]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/xforms_helpers.C
Clean-up yesterday's code-splurge and sort the translated language names.
[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 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "xforms_helpers.h"
16
17 #include "lyxlex.h"
18 #include "gettext.h"
19 #include "lyxlength.h"
20 #include "lyxgluelength.h"
21
22 #include "support/LAssert.h"
23 #include "support/FileInfo.h"
24 #include "support/filetools.h"
25 #include "support/lstrings.h" // frontStrip, strip
26
27 #include <algorithm>
28 #include <fstream>
29 #include <vector>
30
31 using std::ofstream;
32 using std::pair;
33 using std::vector;
34
35 // Extract shortcut from <ident>|<shortcut> string
36 char const * flyx_shortcut_extract(char const * sc)
37 {
38         // Find '|' in the sc and return the string after that.
39         register char const * sd = sc;
40         while (sd[0]!= 0 && sd[0] != '|') ++sd;
41
42         if (sd[0] == '|') {
43                 ++sd;
44                 return sd;
45         }
46         return "";
47 }
48
49
50 // Extract identifier from <ident>|<shortcut> string
51 char const * flyx_ident_extract(char const * sc)
52 {
53         register char const * se = sc;
54         while (se[0]!= 0 && se[0] != '|') ++se;
55
56         if (se[0] == 0) return sc;
57
58         char * sb = new char[se - sc + 1];
59         int index = 0;
60         register char const * sd = sc;
61         while (sd != se) {
62                 sb[index] = sd[0];
63                 ++index; ++sd;
64         }
65         sb[index] = 0;
66         return sb;
67 }
68
69
70 // Set an FL_OBJECT to activated or deactivated
71 void setEnabled(FL_OBJECT * ob, bool enable)
72 {
73         if (enable) {
74                 fl_activate_object(ob);
75                 fl_set_object_lcol(ob, FL_BLACK);
76         } else {
77                 fl_deactivate_object(ob);
78                 fl_set_object_lcol(ob, FL_INACTIVE);
79         }
80 }
81
82
83 // Given an fl_choice, create a vector of its entries
84 vector<string> const getVectorFromChoice(FL_OBJECT * ob)
85 {
86         vector<string> vec;
87         if (!ob || ob->objclass != FL_CHOICE)
88                 return vec;
89
90         for(int i = 0; i < fl_get_choice_maxitems(ob); ++i) {
91                 string const text = fl_get_choice_item_text(ob, i+1);
92                 vec.push_back(strip(frontStrip(text)));
93         }
94
95         return vec;
96 }
97
98
99 /// Given an fl_input, return its contents.
100 string const getStringFromInput(FL_OBJECT * ob)
101 {
102         if (!ob || ob->objclass != FL_INPUT)
103                 return string();
104
105         char const * tmp = fl_get_input(ob);
106         return (tmp) ? tmp : string();
107 }
108
109
110 // Given an fl_browser, return the contents of line
111 string const getStringFromBrowser(FL_OBJECT * ob, int line)
112 {
113         if (!ob || ob->objclass != FL_BROWSER ||
114             line < 1 || line > fl_get_browser_maxline(ob))
115                 return string();
116
117         char const * tmp = fl_get_browser_line(ob, line);
118         return (tmp) ? tmp : string();
119 }
120
121 // Given an fl_browser, return the contents of the currently
122 // highlighted line.
123 // If nothing is selected, return an empty string
124 string const getSelectedStringFromBrowser(FL_OBJECT * ob)
125 {
126         if (!ob || ob->objclass != FL_BROWSER)
127                 return string();
128
129         int const line = fl_get_browser(ob);
130         if (line < 1 || line > fl_get_browser_maxline(ob))
131                 return string();
132
133         if (!fl_isselected_browser_line(ob, line))
134                 return string();
135
136         char const * tmp = fl_get_browser_line(ob, line);
137         return (tmp) ? tmp : string();
138 }
139
140
141 // Given an fl_browser, create a vector of its entries
142 vector<string> const getVectorFromBrowser(FL_OBJECT * ob)
143 {
144         vector<string> vec;
145         if (!ob || ob->objclass != FL_BROWSER)
146                 return vec;
147
148         for(int i = 0; i < fl_get_browser_maxline(ob); ++i) {
149                 string const text = fl_get_browser_line(ob, i+1);
150                 vec.push_back(strip(frontStrip(text)));
151         }
152
153         return vec;
154 }
155
156
157 string getLengthFromWidgets(FL_OBJECT * input, FL_OBJECT * choice)
158 {
159         // Paranoia check
160         lyx::Assert(input  && input->objclass  == FL_INPUT &&
161                     choice && choice->objclass == FL_CHOICE);
162
163         string const length = strip(frontStrip(fl_get_input(input)));
164         if (length.empty())
165                 return string();
166
167         //don't return unit-from-choice if the input(field) contains a unit
168         if (isValidGlueLength(length))
169                 return length;
170
171         string unit = strip(frontStrip(fl_get_choice_text(choice)));
172         unit = subst(unit, "%%", "%");
173
174         return length + unit;
175 }
176
177
178 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
179                                    string const & str,
180                                    string const & default_unit)
181 {
182         // use input field only for gluelengths
183         if (!isValidLength(str) && !isStrDbl(str)) {
184                 fl_set_input(input, str.c_str());
185                 // we assume that "default_unit" is in the choice as "we"
186                 // have control over that!
187                 // No need to check for it's precence in the choice, therefore.
188                 fl_set_choice_text(choice, default_unit.c_str());
189         } else {
190                 updateWidgetsFromLength(input, choice,
191                                 LyXLength(str), default_unit);
192         }
193 }
194
195
196 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
197                              LyXLength const & len,
198                              string const & default_unit)
199 {
200         // Paranoia check
201         lyx::Assert(input  && input->objclass  == FL_INPUT &&
202                     choice && choice->objclass == FL_CHOICE);
203
204         if (len.zero()) {
205                 fl_set_input(input, "");
206                 fl_set_choice_text(choice, default_unit.c_str());
207         } else {
208                 ostringstream buffer;
209                 buffer << len.value();
210                 fl_set_input(input, buffer.str().c_str());
211
212                 // Set the choice to the desired unit, if present in the choice.
213                 // Else set the choice to the default unit.
214                 string const unit = subst(stringFromUnit(len.unit()),"%","%%");
215
216                 vector<string> const vec = getVectorFromChoice(choice);
217                 vector<string>::const_iterator it =
218                         std::find(vec.begin(), vec.end(), unit);
219                 if (it != vec.end()) {
220                         fl_set_choice_text(choice, unit.c_str());
221                 } else {
222                         fl_set_choice_text(choice, default_unit.c_str());
223                 }
224         }
225 }
226
227
228 // Take a string and add breaks so that it fits into a desired label width, w
229 string formatted(string const & sin, int w, int size, int style)
230 {
231         string sout;
232         if (sin.empty()) return sout;
233
234         string::size_type curpos = 0;
235         string line;
236         for(;;) {
237                 string::size_type const nxtpos1 = sin.find(' ',  curpos);
238                 string::size_type const nxtpos2 = sin.find('\n', curpos);
239                 string::size_type const nxtpos = std::min(nxtpos1, nxtpos1);
240
241                 string const word = nxtpos == string::npos ?
242                         sin.substr(curpos) : sin.substr(curpos, nxtpos-curpos);
243
244                 bool const newline = (nxtpos2 != string::npos &&
245                                       nxtpos2 < nxtpos1);
246
247                 string const line_plus_word =
248                         line.empty() ? word : line + ' ' + word;
249
250                 int const length =
251                         fl_get_string_width(style, size,
252                                             line_plus_word.c_str(),
253                                             int(line_plus_word.length()));
254
255                 if (length >= w) {
256                         sout += line + '\n';
257                         if (newline) {
258                                 sout += word + '\n';
259                                 line.erase();
260                         } else {
261                                 line = word;
262                         }
263
264                 } else if (newline) {
265                         sout += line_plus_word + '\n';
266                         line.erase();
267
268                 } else {
269                         if (!line.empty())
270                                 line += ' ';
271                         line += word;
272                 }
273
274                 if (nxtpos == string::npos) {
275                         if (!line.empty())
276                                 sout += line;
277                         break;
278                 }
279
280                 curpos = nxtpos+1;
281         }
282
283         return sout;
284 }
285
286
287 void setCursorColor(int color)
288 {
289         fl_set_cursor_color(FL_DEFAULT_CURSOR, color, FL_WHITE);
290         fl_set_cursor_color(XC_xterm,          color, FL_WHITE);
291         fl_set_cursor_color(XC_watch,          color, FL_WHITE);
292         fl_set_cursor_color(XC_sb_right_arrow, color, FL_WHITE);
293 }
294
295
296 namespace {
297
298 // sorted by hand to prevent LyXLex from complaining on read().
299 keyword_item xformTags[] = {
300         { "\\gui_background",   FL_COL1 },
301         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
302         { "\\gui_buttonleft",   FL_LEFT_BCOL },
303         { "\\gui_buttonright",  FL_RIGHT_BCOL },
304         { "\\gui_buttontop",    FL_TOP_BCOL },
305         { "\\gui_inactive",     FL_INACTIVE },
306         { "\\gui_pointer",      FL_FREE_COL16 },
307         { "\\gui_push_button",  FL_YELLOW },
308         { "\\gui_selected",     FL_MCOL },
309         { "\\gui_text",         FL_BLACK }
310 };
311
312
313 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
314
315 } // namespace anon
316
317
318 bool XformsColor::read(string const & filename)
319 {
320         LyXLex lexrc(xformTags, xformCount);
321         if (!lexrc.setFile(filename))
322                 return false;
323
324         while (lexrc.isOK()) {
325                 int const le = lexrc.lex();
326
327                 switch (le) {
328                 case LyXLex::LEX_UNDEF:
329                         lexrc.printError("Unknown tag `$$Token'");
330                         continue;
331                 case LyXLex::LEX_FEOF:
332                         continue;
333                 default: break;
334                 }
335
336                 string const tag = lexrc.getString();
337
338                 RGBColor col;
339
340                 if (!lexrc.next()) break;
341                 col.r = lexrc.getInteger();
342
343                 if (!lexrc.next()) break;
344                 col.g = lexrc.getInteger();
345
346                 if (!lexrc.next()) break;
347                 col.b = lexrc.getInteger();
348
349                 fl_mapcolor(le, col.r, col.g, col.b);
350
351                 if (tag == "\\gui_pointer") {
352                         setCursorColor(FL_FREE_COL16);
353                 }
354         }
355
356         return true;
357 }
358
359
360 bool XformsColor::write(string const & filename)
361 {
362         ofstream os(filename.c_str());
363         if (!os)
364                 return false;
365
366         os << "### This file is part of\n"
367            << "### ========================================================\n"
368            << "###          LyX, The Document Processor\n"
369            << "###\n"
370            << "###          Copyright 1995 Matthias Ettrich\n"
371            << "###          Copyright 1995-2002 The LyX Team.\n"
372            << "###\n"
373            << "### ========================================================\n"
374            << "\n"
375            << "# This file is written by LyX, if you want to make your own\n"
376            << "# modifications you should do them from inside LyX and save\n"
377            << "\n";
378
379         for (int i = 0; i < xformCount; ++i) {
380                 string const tag  = xformTags[i].tag;
381                 int const colorID = xformTags[i].code;
382                 RGBColor color;
383
384                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
385
386                 os << tag << " "
387                    << color.r << " " << color.g << " " << color.b << "\n";
388         }
389
390         return true;
391 }
392
393
394 string  RWInfo::error_message;
395
396 bool RWInfo::WriteableDir(string const & name)
397 {
398         error_message.erase();
399
400         if (!AbsolutePath(name)) {
401                 error_message = _("The absolute path is required.");
402                 return false;
403         }
404
405         FileInfo const tp(name);
406         if (!tp.isOK() || !tp.isDir()) {
407                 error_message = _("Directory does not exist.");
408                 return false;
409         }
410
411         if (!tp.writable()) {
412                 error_message = _("Cannot write to this directory.");
413                 return false;
414         }
415
416         return true;
417 }
418
419
420 bool RWInfo::ReadableDir(string const & name)
421 {
422         error_message.erase();
423
424         if (!AbsolutePath(name)) {
425                 error_message = _("The absolute path is required.");
426                 return false;
427         }
428
429         FileInfo const tp(name);
430         if (!tp.isOK() || !tp.isDir()) {
431                 error_message = _("Directory does not exist.");
432                 return false;
433         }
434
435         if (!tp.readable()) {
436                 error_message = _("Cannot read this directory.");
437                 return false;
438         }
439
440         return true;
441 }
442
443
444 bool RWInfo::WriteableFile(string const & name)
445 {
446         // A writeable file is either:
447         // * An existing file to which we have write access, or
448         // * A file that doesn't yet exist but that would exist in a writeable
449         //   directory.
450
451         error_message.erase();
452
453         if (name.empty()) {
454                 error_message = _("No file input.");
455                 return false;
456         }
457
458         string const dir = OnlyPath(name);
459         if (!AbsolutePath(dir)) {
460                 error_message = _("The absolute path is required.");
461                 return false;
462         }
463
464         FileInfo d(name);
465
466         if (!d.isOK() || !d.isDir()) {
467                 d.newFile(dir);
468         }
469
470         if (!d.isOK() || !d.isDir()) {
471                 error_message = _("Directory does not exist.");
472                 return false;
473         }
474
475         if (!d.writable()) {
476                 error_message = _("Cannot write to this directory.");
477                 return false;
478         }
479
480         FileInfo f(name);
481         if (dir == name || (f.isOK() && f.isDir())) {
482                 error_message = _("A file is required, not a directory.");
483                 return false;
484         }
485
486         if (f.isOK() && f.exist() && !f.writable()) {
487                 error_message = _("Cannot write to this file.");
488                 return false;
489         }
490
491         return true;
492 }
493
494
495 bool RWInfo::ReadableFile(string const & name)
496 {
497         error_message.erase();
498
499         if (name.empty()) {
500                 error_message = _("No file input.");
501                 return false;
502         }
503
504         string const dir = OnlyPath(name);
505         if (!AbsolutePath(dir)) {
506                 error_message = _("The absolute path is required.");
507                 return false;
508         }
509
510         FileInfo d(name);
511
512         if (!d.isOK() && !d.isDir()) {
513                 d.newFile(dir);
514         }
515
516         if (!d.isOK() || !d.isDir()) {
517                 error_message = _("Directory does not exist.");
518                 return false;
519         }
520
521         if (!d.readable()) {
522                 error_message = _("Cannot read from this directory.");
523                 return false;
524         }
525
526         FileInfo f(name);
527         if (dir == name || (f.isOK() && f.isDir())) {
528                 error_message = _("A file is required, not a directory.");
529                 return false;
530         }
531
532         if (!f.exist()) {
533                 error_message = _("File does not exist.");
534                 return false;
535         }
536
537         if (!f.readable()) {
538                 error_message = _("Cannot read from this file.");
539                 return false;
540         }
541
542         return true;
543 }