]> git.lyx.org Git - lyx.git/blob - src/insets/figinset.C
9c4332024b612fd99576d0491be1ae3cf75066bb
[lyx.git] / src / insets / figinset.C
1 /*
2  *      figinset.C - part of LyX project
3  */
4
5 extern int      reverse_video;
6 extern long int background_pixels;
7
8 /*  Rework of path-handling (Matthias 04.07.1996 )
9  * ------------------------------------------------
10  *   figinsets keep an absolute path to the eps-file.
11  *   For the user alway a relative path appears
12  *   (in lyx-file, latex-file and edit-popup).
13  *   To calculate this relative path the path to the
14  *   document where the figinset is in is needed. 
15  *   This is done by a reference to the buffer, called
16  *   figinset::cbuffer. To be up to date the cbuffer
17  *   is sometimes set to the current buffer 
18  *   bufferlist.current(), when it can be assumed that
19  *   this operation happens in the current buffer. 
20  *   This is true for InsetFig::Edit(...), 
21  *   InsetFig::InsetFig(...), InsetFig::Read(...),
22  *   InsetFig::Write and InsetFig::Latex(...).
23  *   Therefore the bufferlist has to make sure that
24  *   during these operations bufferlist.current() 
25  *   returns the buffer where the figinsets are in.
26  *   This made few changes in buffer.C necessary.
27  *
28  * The above is not totally valid anymore. (Lgb)
29  */
30
31
32 #include <config.h>
33
34 #include <unistd.h>
35 #include <csignal>
36 #include <sys/wait.h>
37
38 #include FORMS_H_LOCATION
39 #include <cstdlib>
40 #include <cctype>
41 #include <cmath>
42 #include <fstream>
43
44 #include "form1.h"
45 #include "figinset.h"
46 #include "lyx.h"
47 #include "lyx_main.h"
48 #include "buffer.h"
49 #include "filedlg.h"
50 #include "support/filetools.h"
51 #include "LyXView.h" // just because of form_main
52 #include "debug.h"
53 #include "lyxdraw.h"
54 #include "LaTeXFeatures.h"
55 #include "lyxrc.h"
56 #include "gettext.h"
57 #include "lyx_gui_misc.h" // CancelCloseBoxCB
58 #include "support/FileInfo.h"
59
60 extern BufferView *current_view;
61 static volatile bool alarmed;
62
63 extern FL_OBJECT *figinset_canvas;
64 //inline
65 extern "C" void waitalarm(int)
66 {
67         alarmed = true;
68 }
69
70 extern char **environ; // is this only redundtant on linux systems? Lgb.
71 extern void UpdateInset(Inset* inset, bool mark_dirty = true);
72 // better for asyncron updating:
73 void PutInsetIntoInsetUpdateList(Inset* inset);
74 extern void ProhibitInput();
75 extern void AllowInput();
76
77 #define DEG2PI 57.295779513
78 #define figallocchunk 32
79
80 static int figinsref = 0;       /* number of figures */
81 static int figarrsize = 0;      /* current max number of figures */
82 static int bmpinsref = 0;       /* number of bitmaps */
83 static int bmparrsize = 0;      /* current max number of bitmaps */
84
85 struct queue {
86         float rx, ry;           /* resolution x and y */
87         int ofsx, ofsy;         /* x and y translation */
88         figdata *data;          /* we are doing it for this data */
89         queue *next;            /* next item in queue */
90 };
91
92 struct pidwait {
93         int pid;                /* pid to wait for */
94         pidwait *next;  /* next */
95 };
96
97 #define MAXGS 3                 /* maximum 3 gs's at a time */
98
99 static Figref **figures;        /* all the figures */
100 static figdata **bitmaps;       /* all the bitmaps */
101 static queue *gsqueue = 0;      /* queue for ghostscripting */
102 static int gsrunning = 0;       /* currently so many gs's are running */
103 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
104 static char bittable[256];      /* bit reversion table */
105
106 static bool gs_color;                   // do we allocate colors for gs?
107 static bool color_visual;               // is the visual color?
108 static bool gs_xcolor = false;          // allocated extended colors
109 static unsigned long gs_pixels[128];    // allocated pixels
110 static int gs_num_pixels;               // number of pixels allocated
111 static int gs_spc;                      // shades per color
112 static bool gs_gray;                    // is grayscale?
113 static int gs_allcolors;                // number of all colors
114
115 static pidwait *pw = 0;         // pid wait list
116
117
118 extern FD_form_main *fd_form_main;
119 extern Colormap color_map;
120
121 void addpidwait(int pid)
122 {
123         // adds pid to pid wait list
124         register pidwait *p = new pidwait;
125
126         p->pid = pid;
127         p->next = pw;
128         pw = p;
129
130         if (lyxerr.debugging()) {
131                 lyxerr << "Pids to wait for: " << p->pid << endl;
132                 while (p->next) {
133                         p = p->next;
134                         lyxerr << p->pid << endl;
135                 }
136         }
137 }
138
139
140 extern "C" int GhostscriptMsg(FL_OBJECT *, Window, int, int,
141                    XEvent *ev, void *)
142 {
143         int i;
144         char tmp[128];
145
146         XClientMessageEvent *e = (XClientMessageEvent*) ev;
147
148         if(lyxerr.debugging()) {
149                 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
150                        << "] pm:[" << e->data.l[1] << "]" << endl;
151         }
152
153         // just kill gs, that way it will work for sure
154         for (i = 0; i < bmpinsref; ++i)
155                 if ((long)bitmaps[i]->bitmap == (long)e->data.l[1]) {
156                         // found the one
157                         figdata *p = bitmaps[i];
158                         p->gsdone = true;
159
160                         // first update p->bitmap, if necessary
161                         if (p->bitmap != None && p->flags > (1|8) && gs_color && p->wid) {
162                                 // query current colormap and re-render
163                                 // the pixmap with proper colors
164                                 XColor *cmap;
165                                 XWindowAttributes wa;
166                                 register XImage *im;
167                                 int i, y, wid1, spc1 = gs_spc-1,
168                                         spc2 = gs_spc*gs_spc, wid = p->wid,
169                                         forkstat;
170                                 Display *tmpdisp;
171                                 GC gc = getGC(gc_copy);
172
173                                 XGetWindowAttributes(fl_display, fl_get_canvas_id(
174                                         figinset_canvas), &wa);
175                                 XFlush(fl_display);
176                                 if (lyxerr.debugging()) {
177                                         lyxerr 
178                                                 << "Starting image translation "
179                                                 << p->bitmap << " "
180                                                 << p->flags << " "
181                                                 << p->wid << "x" << p->hgh
182                                                 << " " << wa.depth
183                                                 << " " << XYPixmap << endl;
184
185                                 }
186                                 // now fork rendering process
187                                 forkstat = fork();
188                                 if (forkstat == -1) {
189                                         lyxerr.debug() << "Cannot fork, using slow "
190                                                 "method for pixmap translation." << endl;
191                                         tmpdisp = fl_display;
192                                 } else if (forkstat > 0) {
193                                         // register child
194                                         if (lyxerr.debugging()) {
195                                                 lyxerr << "Spawned child "
196                                                        << forkstat << endl;
197                                         }
198                                         addpidwait(forkstat);
199                                         break; // in parent process
200                                 } else {
201                                         tmpdisp = XOpenDisplay(XDisplayName(0));
202                                         XFlush(tmpdisp);
203                                 }
204                                 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
205                                                p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
206                                 XFlush(tmpdisp);
207                                 if (lyxerr.debugging()) {
208                                         lyxerr << "Got the image" << endl;
209                                 }
210                                 if (!im) {
211                                         if (lyxerr.debugging()) {
212                                                 lyxerr << "Error getting the image" << endl;
213                                         }
214                                         goto noim;
215                                 }
216                                 // query current colormap
217                                 cmap = (XColor *) malloc(gs_allcolors*sizeof(XColor));
218                                 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
219                                 XQueryColors(tmpdisp, color_map, cmap, gs_allcolors);
220                                 XFlush(tmpdisp);
221                                 wid1 = p->wid - 1;
222                                 // now we process all the image
223                                 for (y = 0; y < p->hgh; ++y) {
224                                         register int x;
225                                         for (x = 0; x < wid; ++x) {
226                                                 register XColor* pc;
227                                                 pc = cmap + XGetPixel(im, x, y);
228                                                 XFlush(tmpdisp);
229                                                 XPutPixel(im, x, y, gs_pixels[((pc->red+6553)*
230                                                                                spc1/65535)*spc2+((pc->green+6553)*
231                                                                                                  spc1/65535)*gs_spc+((pc->blue+6553)*
232                                                                                                                      spc1/65535)]);
233                                                 XFlush(tmpdisp);
234                                         }
235                                 }
236                                 if (lyxerr.debugging()) {
237                                         lyxerr << "Putting image back" << endl;
238                                 }
239                                 XPutImage(tmpdisp, p->bitmap, gc, im, 0, 0,
240                                           0, 0, p->wid, p->hgh);
241                                 XDestroyImage(im);
242                                 if (lyxerr.debugging()) {
243                                         lyxerr << "Done translation" << endl;
244                                 }
245                           noim:
246                                 if (lyxerr.debugging()) {
247                                         lyxerr << "Killing gs " 
248                                                << p->gspid << endl;
249                                 }
250                                 kill(p->gspid, SIGHUP);
251
252                                 sprintf(tmp, "%s/~lyxgs%d.ps",
253                                         system_tempdir.c_str(), 
254                                         p->gspid);
255                                 unlink(tmp);
256                                 if (forkstat == 0) {
257                                         XCloseDisplay(tmpdisp);
258                                         _exit(0);
259                                 }
260                         } else {
261                                 if (lyxerr.debugging()) {
262                                         lyxerr << "Killing gs " 
263                                                << p->gspid << endl;
264                                 }
265                                 kill(p->gspid, SIGHUP);
266
267                                 sprintf(tmp, "%s/~lyxgs%d.ps", 
268                                         system_tempdir.c_str(),
269                                         p->gspid);
270                                 unlink(tmp);
271                         }
272                         break;
273                 }
274         return 0;
275 }
276
277
278 static void AllocColors(int num)
279 // allocate color cube numxnumxnum, if possible
280 {
281         XColor xcol;
282         int i;
283
284         if (lyxerr.debugging()) {
285                 lyxerr << "Allocating color cube " << num
286                        << 'x' << num << 'x' << num << endl;
287         }
288
289         if (num <= 1) {
290                 lyxerr << "Error allocating color colormap." << endl;
291                 gs_color = false;
292                 return;
293         }
294         if (num > 5) num = 5;
295         for (i = 0; i < num*num*num; ++i) {
296                 xcol.red = 65535*(i/(num*num))/(num-1);
297                 xcol.green = 65535*((i/num) % num)/(num-1);
298                 xcol.blue = 65535*(i % num)/(num-1);
299                 xcol.flags = DoRed | DoGreen | DoBlue;
300                 if (!XAllocColor(fl_display, color_map, &xcol)) {
301                         if (i) XFreeColors(fl_display, color_map,
302                                            gs_pixels, i, 0);
303                         if(lyxerr.debugging()) {
304                                 lyxerr << "Cannot allocate color cube "
305                                        << num << endl;;
306                         }
307                         AllocColors(num-1);
308                         return;
309                 }
310                 gs_pixels[i] = xcol.pixel;
311         }
312         gs_color = true;
313         gs_gray = false;
314         gs_spc = num;
315         gs_num_pixels = num*num*num;
316 }
317
318
319 static void AllocGrays(int num)
320 // allocate grayscale ramp
321 {
322         XColor xcol;
323         int i;
324
325         if (lyxerr.debugging()) {
326                 lyxerr << "Allocating grayscale ramp "
327                        << num << endl;
328         }
329
330         if (num < 4) {
331                 lyxerr << "Error allocating grayscale colormap." << endl;
332                 gs_color = false;
333                 return;
334         }
335         if (num > 128) num = 128;
336         for (i = 0; i < num; ++i) {
337                 xcol.red = xcol.green = xcol.blue = 65535*i/(num-1);
338                 xcol.flags = DoRed | DoGreen | DoBlue;
339                 if (!XAllocColor(fl_display, color_map, &xcol)) {
340                         if (i) XFreeColors(fl_display, color_map,
341                                            gs_pixels, i, 0);
342                         if (lyxerr.debugging()) {
343                                 lyxerr << "Cannot allocate grayscale " 
344                                        << num << endl;
345                         }
346                         AllocGrays(num/2);
347                         return;
348                 }
349                 gs_pixels[i] = xcol.pixel;
350         }
351         gs_color = true;
352         gs_gray = false;
353         gs_num_pixels = num;
354 }
355
356
357 void InitFigures()
358 {
359         unsigned int i, j, k;
360         Visual *vi;
361
362         bmparrsize = figarrsize = figallocchunk;
363         figures = (Figref**) malloc(sizeof(Figref*)*figallocchunk);
364         bitmaps = (figdata**) malloc(sizeof(figdata*)*figallocchunk);
365
366         for (i = 0; i < 256; ++i) {
367                 k = 0;
368                 for (j = 0; j < 8; ++j)
369                         if (i & (1 << (7-j))) k |= 1 << j;
370                 bittable[i] = (char) ~k;
371         }
372
373         fl_add_canvas_handler(figinset_canvas, ClientMessage,
374                               GhostscriptMsg, fd_form_main);
375
376         // now we have to init color_map
377         if (!color_map) color_map = DefaultColormap(fl_display,
378                                                     DefaultScreen(fl_display));
379         // allocate color cube on pseudo-color display
380         // first get visual
381         gs_color = false;
382
383         vi = DefaultVisual(fl_display, DefaultScreen(fl_display));
384         if (lyxerr.debugging()) {
385                 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n", 
386                        vi->visualid, vi->c_class, 
387                        vi->bits_per_rgb, vi->map_entries);
388         }
389         color_visual = ( (vi->c_class == StaticColor) ||
390                 (vi->c_class == PseudoColor) ||
391                 (vi->c_class == TrueColor) ||
392                 (vi->c_class == DirectColor) );
393         if ((vi->c_class & 1) == 0) return;
394         // now allocate colors
395         if (vi->c_class == GrayScale) {
396                 // allocate grayscale
397                 AllocGrays(vi->map_entries/2);
398         } else {
399                 // allocate normal color
400                 int i = 5;
401                 while (i*i*i*2 > vi->map_entries) --i;
402                 AllocColors(i);
403         }
404         gs_allcolors = vi->map_entries;
405 }
406
407
408 void DoneFigures()
409 {
410         free(figures);
411         free(bitmaps);
412         figarrsize = 0;
413         bmparrsize = 0;
414
415         lyxerr.debug() << "Unregistering figures..." << endl;
416
417         fl_remove_canvas_handler(figinset_canvas, ClientMessage,
418                                  GhostscriptMsg);
419
420         if (gs_color) {
421                 lyxerr.debug() << "Freeing up the colors..." << endl;
422                 XFreeColors(fl_display, color_map, gs_pixels,
423                             gs_num_pixels, 0);
424                 /******????????????????? what's planes in this case ??????***/
425         }
426 }
427
428
429 int FindBmpIndex(figdata *tmpdata)
430 {
431         int i = 0;
432         while (i < bmpinsref) {
433                 if (bitmaps[i] == tmpdata) return i;
434                 ++i;
435         }
436         return i;
437 }
438
439
440 static void chpixmap(Pixmap, int, int)
441 {
442 #if 0
443         Display * tempdisp = XOpenDisplay(XDisplayName(0));
444
445         // here read the pixmap and change all colors to those we
446         // have allocated
447
448         XCloseDisplay(tempdisp);
449 #endif
450 }
451
452
453 static void freefigdata(figdata *tmpdata)
454 {
455         tmpdata->ref--;
456         if (tmpdata->ref) return;
457
458         if (tmpdata->gspid > 0) {
459                 int pid = tmpdata->gspid;
460                 char buf[128];
461                 // change Pixmap according to our allocated colormap
462                 chpixmap(tmpdata->bitmap, tmpdata->wid, tmpdata->hgh);
463                 // kill ghostscript and unlink it's files
464                 tmpdata->gspid = -1;
465                 kill(pid, SIGKILL);
466                 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
467                 unlink(buf);
468         }
469
470         if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
471         delete tmpdata;
472         int i = FindBmpIndex(tmpdata);
473         --bmpinsref;
474         while (i < bmpinsref) {
475                 bitmaps[i] = bitmaps[i+1];
476                 ++i;
477         }
478 }
479
480
481 static void runqueue()
482 {
483         // run queued requests for ghostscript, if any
484         if (!gsrunning && gs_color && !gs_xcolor) {
485                 // here alloc all colors, so that gs will use only
486                 // those we allocated for it
487                 // *****
488                 gs_xcolor = true;
489         }
490         
491         while (gsrunning < MAXGS) {
492                 char tbuf[384], tbuf2[80];
493                 Atom * prop;
494                 int nprop, i;
495
496                 if (!gsqueue) {
497                         if (!gsrunning && gs_xcolor) {
498                                 // de-allocate rest of colors
499                                 // *****
500                                 gs_xcolor = false;
501                         }
502                         return;
503                 }
504                 queue * p = gsqueue;
505
506                 if (!p->data) {
507                         delete p;
508                         continue;
509                 }
510
511                 int pid = fork();
512                 
513                 if (pid == -1) {
514                         if (lyxerr.debugging()) {
515                                 lyxerr << "GS start error! Cannot fork."
516                                        << endl;
517                         }
518                         p->data->broken = true;
519                         p->data->reading = false;
520                         return;
521                 }
522                 if (pid == 0) { // child
523                         char ** env, rbuf[80], gbuf[40];
524                         int ne = 0;
525                         Display * tempdisp = XOpenDisplay(XDisplayName(0));
526
527                         // create translation file
528                         sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
529                                 int(getpid()));
530                         
531                         ofstream ofs(tbuf);
532                         ofs << "gsave clippath pathbbox grestore\n"
533                             << "4 dict begin\n"
534                             << "/ury exch def /urx exch def /lly exch def "
535                                 "/llx exch def\n"
536                             << p->data->wid / 2.0 << " "
537                             << p->data->hgh / 2.0 << " translate\n"
538                             << p->data->angle << " rotate\n"
539                             << -(p->data->raw_wid / 2.0) << " "
540                             << -(p->data->raw_hgh / 2.0) << " translate\n"
541                             << p->rx / 72.0 << " " << p->ry / 72.0
542                             << " scale\n"
543                             << -p->ofsx << " " << -p->ofsy << " translate\n"
544                             << "end" << endl;
545                         ofs.close(); // Don't remove this.
546
547                         // gs process - set ghostview environment first
548                         sprintf(tbuf2, "GHOSTVIEW=%ld %ld", fl_get_canvas_id(
549                                 figinset_canvas), p->data->bitmap);
550
551                         // now set up ghostview property on a window
552                         sprintf(tbuf, "0 0 0 0 %d %d 72 72 0 0 0 0",
553                                 p->data->wid, p->data->hgh);
554 //#warning BUG seems that the only bug here might be the hardcoded dpi.. Bummer!
555                         
556                         if (lyxerr.debugging()) {
557                                 lyxerr << "Will set GHOSTVIEW property to ["
558                                        << tbuf << "]" << endl;
559                         }
560                         // wait until property is deleted if executing multiple
561                         // ghostscripts
562                         for (;;) {
563                                 // grab server to prevent other child interfering
564                                 // with setting GHOSTVIEW property
565                                 if (lyxerr.debugging()) {
566                                         lyxerr << "Grabbing the server" << endl;
567                                 }
568                                 XGrabServer(tempdisp);
569                                 prop = XListProperties(tempdisp, fl_get_canvas_id(
570                                         figinset_canvas), &nprop);
571                                 if (!prop) break;
572
573                                 bool err = true;
574                                 for (i = 0; i < nprop; ++i) {
575                                         char *p = XGetAtomName(tempdisp, prop[i]);
576                                         if (strcmp(p, "GHOSTVIEW") == 0) {
577                                                 err = false;
578                                                 break;
579                                         }
580                                         XFree(p);
581                                 }
582                                 XFree((char *)prop);    /* jc: */
583                                 if (err) break;
584                                 // release the server
585                                 XUngrabServer(tempdisp);
586                                 XFlush(tempdisp);
587                                 // ok, property found, we must wait until ghostscript
588                                 // deletes it
589                                 if (lyxerr.debugging()) {
590                                         lyxerr << "Releasing the server" << endl;
591                                         lyxerr << "["
592                                                << getpid()
593                                                << "] GHOSTVIEW property"
594                                                 " found. Waiting." << endl;
595                                 }
596 #if 0
597 #ifdef WITH_WARNINGS
598 #warning What is this doing? (wouldn't a sleep(1); work too?')
599 #endif
600                                 alarm(1);
601                                 alarmed = false;
602                                 signal(SIGALRM, waitalarm);
603                                 while (!alarmed) pause();
604 #else
605                                 sleep(1);
606 #endif
607                         }
608
609                         XChangeProperty(tempdisp, 
610                                         fl_get_canvas_id(figinset_canvas),
611                                         XInternAtom(tempdisp, "GHOSTVIEW", false),
612                                         XInternAtom(tempdisp, "STRING", false),
613                                         8, PropModeAppend, 
614                                         reinterpret_cast<unsigned char*>(tbuf),
615                                         strlen(tbuf));
616                         
617                         switch (p->data->flags & 3) {
618                         case 0: tbuf[0] = 'H'; break; // Hidden
619                         case 1: tbuf[0] = 'M'; break; // Mono
620                         case 2: tbuf[0] = 'G'; break; // Gray
621                         case 3:
622                                 if (color_visual) 
623                                         tbuf[0] = 'C'; // Color
624                                 else 
625                                         tbuf[0] = 'G'; // Gray
626                                 break;
627                         }
628
629                         if (reverse_video) {
630                                 sprintf(tbuf+1, " %ld %ld", WhitePixelOfScreen(
631                                         DefaultScreenOfDisplay(fl_display)),
632                                         background_pixels);
633                         } else {
634                                 sprintf(tbuf+1, " %ld %ld", BlackPixelOfScreen(
635                                         DefaultScreenOfDisplay(fl_display)),
636                                         background_pixels);
637                         }
638
639                         XChangeProperty(tempdisp, 
640                                         fl_get_canvas_id(figinset_canvas),
641                                         XInternAtom(tempdisp, "GHOSTVIEW_COLORS", false),
642                                         XInternAtom(tempdisp, "STRING", false),
643                                         8, PropModeReplace, 
644                                         reinterpret_cast<unsigned char*>(tbuf),
645                                         strlen(tbuf));
646                         XUngrabServer(tempdisp);
647                         XFlush(tempdisp);
648                         if (lyxerr.debugging()) {
649                                 lyxerr << "Releasing the server" << endl;
650                         }
651                         XCloseDisplay(tempdisp);
652
653                         // set up environment
654                         while (environ[ne]) ++ne;
655                         env = (char **) malloc(sizeof(char*)*(ne+2));
656                         env[0] = tbuf2;
657                         memcpy(&env[1], environ, sizeof(char*)*(ne+1));
658                         environ = env;
659
660                         // now make gs command
661                         // close(0);
662                         // close(1); do NOT close. If GS writes out
663                         // errors it would hang. (Matthias 290596) 
664                         sprintf(rbuf, "-r%gx%g", p->rx, p->ry);
665                         sprintf(gbuf, "-g%dx%d", p->data->wid, p->data->hgh);
666                         // now chdir into dir with .eps file, to be on the safe
667                         // side
668                         chdir(OnlyPath(p->data->fname).c_str());
669                         // make temp file name
670                         sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
671                                 int(getpid()));
672                         if (lyxerr.debugging()) {
673                                 printf("starting gs %s %s, pid: %d\n", tbuf,
674                                        p->data->fname.c_str(), int(getpid()));
675                         }
676
677                         int err = execlp(lyxrc->ps_command.c_str(), 
678                                          lyxrc->ps_command.c_str(), 
679                                          "-sDEVICE=x11",
680                                          "-dNOPAUSE", "-dQUIET",
681                                          "-dSAFER", 
682                                          rbuf, gbuf, tbuf, 
683                                          p->data->fname.c_str(), 
684                                          "showpage.ps", "quit.ps", "-", 0);
685                         // if we are still there, an error occurred.
686                         lyxerr << "Error executing ghostscript. "
687                                << "Code: " << err << endl;
688                         lyxerr.debug() << "Cmd: " 
689                                        << lyxrc->ps_command
690                                        << " -sDEVICE=x11 "
691                                        << tbuf << ' '
692                                        << p->data->fname << endl;
693                         _exit(0);       // no gs?
694                 }
695                 // normal process (parent)
696                 if (lyxerr.debugging()) {
697                         lyxerr << "GS ["  << pid << "] started" << endl;
698                 }
699                 gsqueue = gsqueue->next;
700                 gsrunning++;
701                 p->data->gspid = pid;
702                 delete p;
703         }
704 }
705
706
707 static void addwait(int psx, int psy, int pswid, int pshgh, figdata *data)
708 {
709         // recompute the stuff and put in the queue
710         queue *p, *p2;
711         p = new queue;
712         p->ofsx = psx;
713         p->ofsy = psy;
714         p->rx = ((float)data->raw_wid*72)/pswid;
715         p->ry = ((float)data->raw_hgh*72)/pshgh;
716
717         p->data = data;
718         p->next = 0;
719
720         // now put into queue
721         p2 = gsqueue;
722         if (!gsqueue) gsqueue = p;
723         else {
724                 while (p2->next) p2 = p2->next;
725                 p2->next = p;
726         }
727
728         // if possible, run the queue
729         runqueue();
730 }
731
732
733 static figdata *getfigdata(int wid, int hgh, string const & fname, 
734                            int psx, int psy, int pswid, int pshgh, 
735                            int raw_wid, int raw_hgh, float angle, char flags)
736 {
737         /* first search for an exact match with fname and width/height */
738         int i = 0;
739         figdata *p;
740         XWindowAttributes wa;
741
742         if (fname.empty()) return 0;
743
744         while (i < bmpinsref) {
745                 if (bitmaps[i]->wid == wid && bitmaps[i]->hgh == hgh &&
746                     bitmaps[i]->flags == flags && bitmaps[i]->fname == fname &&
747                     bitmaps[i]->angle == angle) {
748                         bitmaps[i]->ref++;
749                         return bitmaps[i];
750                 }
751                 ++i;
752         }
753         /* not found -> create new record or return 0 if no record */
754         ++bmpinsref;
755         if (bmpinsref > bmparrsize) {
756                 // allocate more space
757                 bmparrsize += figallocchunk;
758                 figdata **tmp = (figdata**) malloc(sizeof(figdata*)*bmparrsize);
759                 memcpy(tmp, bitmaps, sizeof(figdata*)*(bmparrsize-figallocchunk));
760                 free(bitmaps);
761                 bitmaps = tmp;
762         }
763         p = new figdata;
764         bitmaps[bmpinsref-1] = p;
765         p->wid = wid;
766         p->hgh = hgh;
767         p->raw_wid = raw_wid;
768         p->raw_hgh = raw_hgh;
769         p->angle = angle;
770         p->fname = fname;
771         p->flags = flags;
772         XGetWindowAttributes(fl_display, fl_get_canvas_id(
773                 figinset_canvas), &wa);
774
775         if (lyxerr.debugging()) {
776                 lyxerr << "Create pixmap disp:" << fl_display
777                        << " scr:" << DefaultScreen(fl_display)
778                        << " w:" << wid
779                        << " h:" << hgh
780                        << " depth:" << wa.depth << endl;
781         }
782         
783         p->ref = 1;
784         p->reading = false;
785         p->broken = false;
786         p->gspid = -1;
787         if (flags) {
788                 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
789                         figinset_canvas), wid, hgh, wa.depth);
790                 p->gsdone = false;
791                 // initialize reading of .eps file with correct sizes and stuff
792                 addwait(psx, psy, pswid, pshgh, p);
793                 p->reading = true;
794         } else {
795                 p->bitmap = None;
796                 p->gsdone = true;
797         }
798
799         return p;
800 }
801
802
803 static void getbitmap(figdata *p)
804 {
805         p->gspid = -1;
806 }
807
808
809 static void makeupdatelist(figdata *p)
810 {
811         int i;
812
813         for (i = 0; i < figinsref; ++i) if (figures[i]->data == p) {
814                 if (lyxerr.debugging()) {
815                         lyxerr << "Updating inset " << figures[i]->inset
816                                << endl;
817                 }
818                 //UpdateInset(figures[i]->inset);
819                 // add inset figures[i]->inset into to_update list
820                 PutInsetIntoInsetUpdateList(figures[i]->inset);
821         }
822 }
823
824
825 void sigchldchecker(pid_t pid, int *status)
826 {
827         int i;
828         figdata *p;
829
830         bool pid_handled = false;
831         
832         lyxerr.debug() << "Got pid = " << pid << endl;
833         pid_handled = false;
834         for (i = bmpinsref - 1; i >= 0; --i) {
835                 if (bitmaps[i]->reading && pid == bitmaps[i]->gspid) {
836                         lyxerr.debug() << "Found pid in bitmaps" << endl;
837                         // now read the file and remove it from disk
838                         p = bitmaps[i];
839                         p->reading = false;
840                         if (bitmaps[i]->gsdone) *status = 0;
841                         if (*status == 0) {
842                                 lyxerr.debug() << "GS [" << pid
843                                                << "] exit OK." << endl;
844                         } else {
845                                 lyxerr << "GS [" << pid  << "] error "
846                                        << *status << " E:"
847                                        << WIFEXITED(*status)
848                                        << " " << WEXITSTATUS(*status)
849                                        << " S:" << WIFSIGNALED(*status)
850                                        << " " << WTERMSIG(*status) << endl;
851                         }
852                         if (*status == 0) {
853                                 bitmap_waiting = true;
854                                 p->broken = false;
855                         } else {
856                                 // remove temporary files
857                                 char tmp[128];
858                                 sprintf(tmp, "%s/~lyxgs%d.ps", 
859                                         system_tempdir.c_str(),
860                                         p->gspid);
861                                 unlink(tmp);
862                                 p->gspid = -1;
863                                 p->broken = true;
864                         }
865                         makeupdatelist(bitmaps[i]);
866                         gsrunning--;
867                         runqueue();
868                         pid_handled = true;
869                 }
870         }
871         if (!pid_handled) {
872                 lyxerr.debug() << "Checking pid in pidwait" << endl;
873                 pidwait *p = pw, *prev = 0;
874                 while (p) {
875                         if (pid == p->pid) {
876                                 lyxerr.debug() << "Found pid in pidwait" << endl;
877                                 lyxerr.debug() << "Caught child pid of recompute routine " << pid << endl;
878                                 if (prev)
879                                         prev->next = p->next;
880                                 else
881                                         pw = p->next;
882                                 free(p);
883                                 break;
884                         }
885                         prev = p;
886                         p = p->next;
887                 }
888         }
889
890         if (pid == -1) {
891                 lyxerr.debug() << "waitpid error" << endl;
892                 switch (errno) {
893                 case ECHILD:
894                         lyxerr << "The process or process group specified by "
895                                 "pid does  not exist or is not a child of "
896                                 "the calling process or can never be in the "
897                                 "states specified by options." << endl;
898                         break;
899                 case EINTR:
900                         lyxerr << "waitpid() was interrupted due to the "
901                                 "receipt of a signal sent by the calling "
902                                 "process." << endl;
903                         break;
904                 case EINVAL:
905                         lyxerr << "An invalid value was specified for "
906                                 "options." << endl;
907                         break;
908                 default:
909                         lyxerr << "Unknown error from waitpid" << endl;
910                         break;
911                 }
912         } else if (pid == 0) {
913                 lyxerr << "waitpid nohang" << endl;;
914         } else {
915                 lyxerr.debug() << "normal exit from childhandler" << endl;
916         }
917 }
918
919
920 static void getbitmaps()
921 {
922         int i;
923         bitmap_waiting = false;
924         for (i = 0; i < bmpinsref; ++i)
925                 if (bitmaps[i]->gspid > 0 && !bitmaps[i]->reading)
926                         getbitmap(bitmaps[i]);
927 }
928
929
930 static void RegisterFigure(InsetFig *fi)
931 {
932         Figref *tmpfig;
933
934         if (figinsref == 0) InitFigures();
935         fi->form = 0;
936         ++figinsref;
937         if (figinsref > figarrsize) {
938                 // allocate more space
939                 figarrsize += figallocchunk;
940                 Figref **tmp = (Figref**) malloc(sizeof(Figref*)*figarrsize);
941                 memcpy(tmp, figures, sizeof(Figref*)*(figarrsize-figallocchunk));
942                 free(figures);
943                 figures = tmp;
944         }
945         tmpfig = new Figref;
946         tmpfig->data = 0;
947         tmpfig->inset = fi;
948         figures[figinsref-1] = tmpfig;
949         fi->figure = tmpfig;
950
951         if (lyxerr.debugging()) {
952                 lyxerr << "Register Figure: buffer:["
953                        << current_view->buffer() << "]" << endl;
954         }
955 }
956
957
958 int FindFigIndex(Figref *tmpfig)
959 {
960         int i = 0;
961         while (i < figinsref) {
962                 if (figures[i] == tmpfig) return i;
963                 ++i;
964         }
965         return i;
966 }
967
968
969 static void UnregisterFigure(InsetFig *fi)
970 {
971         Figref *tmpfig = fi->figure;
972         int i;
973
974         if (tmpfig->data) freefigdata(tmpfig->data);
975         if (tmpfig->inset->form) {
976                 if (tmpfig->inset->form->Figure->visible) {
977                         fl_set_focus_object(tmpfig->inset->form->Figure,
978                                             tmpfig->inset->form->OkBtn);
979                         fl_hide_form(tmpfig->inset->form->Figure);
980                 }
981 #if FL_REVISION == 89
982 #warning Reactivate this free_form calls
983 #else
984                 fl_free_form(tmpfig->inset->form->Figure);
985                 free(tmpfig->inset->form);
986                 tmpfig->inset->form = 0;
987 #endif
988         }
989         i = FindFigIndex(tmpfig);
990         --figinsref;
991         while (i < figinsref) {
992                 figures[i] = figures[i+1];
993                 ++i;
994         }
995         delete tmpfig;
996
997         if (figinsref == 0) DoneFigures();
998 }
999
1000
1001 static char* NextToken(FILE *myfile)
1002 {
1003         char* token = 0;
1004         char c;
1005         int i = 0;
1006    
1007         if (!feof(myfile)) {
1008                 token = new char[256];
1009                 do {
1010                         c = fgetc(myfile);
1011                         token[i++]= c;
1012                 } while (!feof(myfile) && !isspace(c));
1013       
1014                 token[i-1]= '\0';         /* just the end of a command  */
1015         }
1016         return token;
1017 }
1018
1019
1020 InsetFig::InsetFig(int tmpx, int tmpy, Buffer *o)
1021         : owner(o)
1022 {
1023         wid = tmpx;
1024         hgh = tmpy;
1025         wtype = DEF;
1026         htype = DEF;
1027         twtype = DEF;
1028         thtype = DEF;
1029         pflags = flags = 9;
1030         psubfigure = subfigure = false;
1031         xwid = xhgh = angle = 0;
1032         raw_wid = raw_hgh = 0;
1033         changedfname = false;
1034         RegisterFigure(this);
1035 }
1036
1037
1038 InsetFig::~InsetFig()
1039 {
1040         if (lyxerr.debugging()) {
1041                 lyxerr << "Figure destructor called" << endl;
1042         }
1043         UnregisterFigure(this);
1044 }
1045
1046
1047 int InsetFig::Ascent(LyXFont const&) const
1048 {
1049         return hgh + 3;
1050 }
1051
1052
1053 int InsetFig::Descent(LyXFont const&) const
1054 {
1055         return 1;
1056 }
1057
1058
1059 int InsetFig::Width(LyXFont const&) const
1060 {
1061         return wid + 2;
1062 }
1063
1064
1065 void InsetFig::Draw(LyXFont font, LyXScreen &scr, int baseline, float &x)
1066 {
1067         if (bitmap_waiting) getbitmaps();
1068
1069         // I wish that I didn't have to use this
1070         // but the figinset code is so complicated so
1071         // I don't want to fiddle with it now.
1072         unsigned long pm = scr.getForeground();
1073         
1074         if (figure && figure->data && figure->data->bitmap &&
1075             !figure->data->reading && !figure->data->broken) {
1076                 // draw the bitmap
1077                 XCopyArea(fl_display, figure->data->bitmap, pm, getGC(gc_copy),
1078                           0, 0, wid, hgh, int(x+1), baseline-hgh);
1079                 XFlush(fl_display);
1080                 if (flags & 4) XDrawRectangle(fl_display, pm, getGC(gc_copy),
1081                                               int(x), baseline - hgh - 1,
1082                                               wid+1, hgh+1);
1083         } else {
1084                 char * msg = 0;
1085                 // draw frame
1086                 XDrawRectangle(fl_display, pm, getGC(gc_copy),
1087                                (int) x,
1088                                baseline - hgh - 1, wid+1, hgh+1);
1089                 if (figure && figure->data) {
1090                   if (figure->data->broken)  msg = _("[render error]");
1091                   else if (figure->data->reading) msg = _("[rendering ... ]");
1092                 } else 
1093                   if (fname.empty()) msg = _("[no file]");
1094                   else if ((flags & 3) == 0) msg = _("[not displayed]");
1095                   else if (lyxrc->ps_command.empty()) msg = _("[no ghostscript]");
1096
1097                 if (!msg) msg = _("[unknown error]");
1098                 
1099                 font.setFamily (LyXFont::SANS_FAMILY);
1100                 font.setSize (LyXFont::SIZE_FOOTNOTE);
1101                 string justname = OnlyFilename (fname);
1102                 font.drawString(justname, pm,
1103                                baseline - font.maxAscent() - 4,
1104                                (int) x + 8);
1105                 font.setSize (LyXFont::SIZE_TINY);
1106                 font.drawText (msg, strlen(msg), pm,
1107                                baseline - 4,
1108                                (int) x + 8);
1109
1110         }
1111         x += Width(font);    // ?
1112 }
1113
1114
1115 void InsetFig::Write(FILE *file)
1116 {
1117         Regenerate();
1118         fprintf(file, "Figure size %d %d\n", wid, hgh);
1119         if (!fname.empty()) {
1120           string buf1 = OnlyPath(owner->getFileName());
1121           string fname2 = MakeRelPath(fname, buf1);
1122           fprintf(file, "file %s\n", fname2.c_str());
1123         }
1124         if (!subcaption.empty())
1125           fprintf(file, "subcaption %s\n", subcaption.c_str());
1126         if (wtype) fprintf(file, "width %d %g\n", wtype, xwid);
1127         if (htype) fprintf(file, "height %d %g\n", htype, xhgh);
1128         if (angle != 0) fprintf(file, "angle %g\n", angle);
1129         fprintf(file, "flags %d\n", flags);
1130         if (subfigure) fprintf(file, "subfigure\n");
1131 }
1132
1133
1134 void InsetFig::Read(LyXLex &lex)
1135 {
1136         string buf;
1137         bool finished = false;
1138         
1139         while (lex.IsOK() && !finished) {
1140                 lex.next();
1141
1142                 string const token = lex.GetString();
1143                 lyxerr.debug() << "Token: " << token << endl;
1144                 
1145                 if (token.empty())
1146                         continue;
1147                 else if (token == "\\end_inset") {
1148                         finished = true;
1149                 } else if (token == "file") {
1150                         if (lex.next()) {
1151                                 buf = lex.GetString();
1152                                 string buf1 = OnlyPath(owner->getFileName());
1153                                 fname = MakeAbsPath(buf, buf1);
1154                                 changedfname = true;
1155                         }
1156                 } else if (token == "extra") {
1157                         if (lex.next());
1158                         // kept for backwards compability. Delete in 0.13.x
1159                 } else if (token == "subcaption") {
1160                         if (lex.EatLine())
1161                                 subcaption = lex.GetString();
1162                 } else if (token == "label") {
1163                         if (lex.next());
1164                         // kept for backwards compability. Delete in 0.13.x
1165                 } else if (token == "angle") {
1166                         if (lex.next())
1167                                 angle = lex.GetFloat();
1168                 } else if (token == "size") {
1169                         if (lex.next())
1170                                 wid = lex.GetInteger();
1171                         if (lex.next())
1172                                 hgh = lex.GetInteger();
1173                 } else if (token == "flags") {
1174                         if (lex.next())
1175                                 flags = pflags = lex.GetInteger();
1176                 } else if (token == "subfigure") {
1177                         subfigure = psubfigure = true;
1178                 } else if (token == "width") {
1179                         int typ = 0;
1180                         if (lex.next())
1181                                 typ = lex.GetInteger();
1182                         if (lex.next())
1183                                 xwid = lex.GetFloat();
1184                         switch (typ) {
1185                         case DEF: wtype = DEF; break;
1186                         case CM: wtype = CM; break;
1187                         case IN: wtype = IN; break;
1188                         case PER_PAGE: wtype = PER_PAGE; break;
1189                         case PER_COL: wtype = PER_COL; break;
1190                         default:
1191                                 lyxerr.debug() << "Unknown type!" << endl;
1192                                 break;
1193                         }
1194                         twtype = wtype;
1195                 } else if (token == "height") {
1196                         int typ = 0;
1197                         if (lex.next())
1198                                 typ = lex.GetInteger();
1199                         if (lex.next())
1200                                 xhgh = lex.GetFloat();
1201                         switch (typ) {
1202                         case DEF: htype = DEF; break;
1203                         case CM: htype = CM; break;
1204                         case IN: htype = IN; break;
1205                         case PER_PAGE: htype = PER_PAGE; break;
1206                         default:
1207                                 lyxerr.debug() << "Unknown type!" << endl;
1208                                 break;
1209                         }
1210                         thtype = htype;
1211                 }
1212         }
1213         Regenerate();
1214         Recompute();
1215 }
1216
1217
1218 int InsetFig::Latex(FILE *file, signed char /* fragile*/ )
1219 {
1220         Regenerate();
1221         if (!cmd.empty()) fprintf(file, "%s ", cmd.c_str());
1222         return 0;
1223 }
1224
1225
1226 int InsetFig::Latex(string &file, signed char /* fragile*/ )
1227 {
1228         Regenerate();
1229         file += cmd + ' ';
1230         return 0;
1231 }
1232
1233
1234 int InsetFig::Linuxdoc(string &/*file*/)
1235 {
1236         return 0;
1237 }
1238
1239
1240 int InsetFig::DocBook(string &file)
1241 {
1242         string figurename= fname;
1243
1244         if(suffixIs(figurename, ".eps"))
1245                 figurename.erase(fname.length() - 5);
1246
1247         file += "@<graphic fileref= \"" + figurename + "\"></graphic>";
1248         return 0;
1249 }
1250
1251
1252 void InsetFig::Validate(LaTeXFeatures &features) const
1253 {
1254         features.graphics = true;
1255         if (subfigure) features.subfigure = true;
1256 }
1257
1258
1259 unsigned char InsetFig::Editable() const
1260 {
1261         return 1;
1262 }
1263
1264
1265 bool InsetFig::Deletable() const
1266 {
1267         return false;
1268 }
1269
1270
1271 void InsetFig::Edit(int, int)
1272 {
1273         lyxerr.debug() << "Editing InsetFig." << endl;
1274         Regenerate();
1275
1276         // We should have RO-versions of the form instead.
1277         // The actual prevention of altering a readonly doc
1278         // is done in CallbackFig()
1279         if(current_view->buffer()->isReadonly()) 
1280                 WarnReadonly();
1281
1282         if (!form) {
1283                 form = create_form_Figure();
1284                 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1285                 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1286                 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1287                 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1288         }
1289         RestoreForm();
1290         if (form->Figure->visible) {
1291                 fl_raise_form(form->Figure);
1292         } else {
1293                 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1294                              FL_FULLBORDER, _("Figure"));
1295         }
1296 }
1297
1298
1299 Inset * InsetFig::Clone() const
1300 {
1301         InsetFig * tmp = new InsetFig(100, 100, owner);
1302
1303         if (lyxerr.debugging()) {
1304                 lyxerr << "Clone Figure: buffer:["
1305                        << current_view->buffer()
1306                        << "], cbuffer:[xx]" << endl;
1307         }
1308
1309         tmp->wid = wid;
1310         tmp->hgh = hgh;
1311         tmp->raw_wid = raw_wid;
1312         tmp->raw_hgh = raw_hgh;
1313         tmp->angle = angle;
1314         tmp->xwid = xwid;
1315         tmp->xhgh = xhgh;
1316         tmp->flags = flags;
1317         tmp->pflags = pflags;
1318         tmp->subfigure = subfigure;
1319         tmp->psubfigure = psubfigure;
1320         tmp->wtype = wtype;
1321         tmp->htype = htype;
1322         tmp->psx = psx;
1323         tmp->psy = psy;
1324         tmp->pswid = pswid;
1325         tmp->pshgh = pshgh;
1326         tmp->fname = fname;
1327         if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) { 
1328           // do not display if there is "do not display" chosen (Matthias 260696)
1329                 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1330                                                pswid, pshgh, raw_wid, raw_hgh,
1331                                                angle, flags & (3|8));
1332         } else tmp->figure->data = 0;
1333         tmp->subcaption = subcaption;
1334         tmp->changedfname = false;
1335         tmp->owner = owner;
1336         tmp->Regenerate();
1337         return tmp;
1338 }
1339
1340
1341 Inset::Code InsetFig::LyxCode() const
1342 {
1343         return Inset::GRAPHICS_CODE;
1344 }
1345
1346
1347 void InsetFig::Regenerate()
1348 {
1349         string cmdbuf;
1350         string gcmd;
1351         string resizeW, resizeH;
1352         string rotate, recmd;
1353
1354         if (fname.empty()) {
1355                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1356                 cmd += _("empty figure path");
1357                 cmd += '}';
1358                 //if (form) fl_set_object_label(form->cmd, "");
1359                 return;
1360         }
1361
1362         string buf1 = OnlyPath(owner->getFileName());
1363         string fname2 = MakeRelPath(fname, buf1);
1364
1365         gcmd = "\\includegraphics{" + fname2 + '}';
1366         
1367         switch (wtype) {
1368         case DEF:
1369                 break;
1370         case CM:{// \resizebox*{h-length}{v-length}{text}
1371                 char buf[10];
1372                 sprintf(buf, "%g", xwid); // should find better
1373                 resizeW = buf;
1374                 resizeW += "cm";
1375                 break;
1376         }
1377         case IN: {
1378                 char buf[10];
1379                 sprintf(buf, "%g", xwid);
1380                 resizeW = buf;
1381                 resizeW += "in";
1382                 break;
1383         }
1384         case PER_PAGE:{
1385                 char buf[10];
1386                 sprintf(buf, "%g", xwid/100);
1387                 resizeW = buf;
1388                 resizeW += "\\textwidth";
1389                 break;
1390         }
1391         case PER_COL:{
1392                 char buf[10];
1393                 sprintf(buf, "%g", xwid/100);
1394                 resizeW = buf;
1395                 resizeW += "\\columnwidth";
1396                 break;
1397         }
1398         }
1399
1400         switch (htype) {
1401         case DEF:
1402                 break;
1403         case CM: {
1404                 char buf[10];
1405                 sprintf(buf, "%g", xhgh);
1406                 resizeH = buf;
1407                 resizeH += "cm";
1408                 break;
1409         }
1410         case IN:{
1411                 char buf[10];
1412                 sprintf(buf, "%g", xhgh);
1413                 resizeH = buf;
1414                 resizeH += "in";
1415                 break;
1416         }
1417         case PER_PAGE: {
1418                 char buf[10];
1419                 sprintf(buf, "%g", xhgh/100);
1420                 resizeH = buf;
1421                 resizeH += "\\textheight";
1422                 break;
1423         }
1424         case PER_COL: {
1425                 // Doesn't occur; case exists to suppress compiler warnings.
1426                 break;
1427         }
1428         }
1429
1430         if (!resizeW.empty() || !resizeH.empty()) {
1431                 recmd = "\\resizebox*{";
1432                 if (!resizeW.empty())
1433                         recmd += resizeW;
1434                 else
1435                         recmd += '!';
1436                 recmd += "}{";
1437                 if (!resizeH.empty())
1438                         recmd += resizeH;
1439                 else
1440                         recmd += '!';
1441                 recmd += "}{";
1442         }
1443         
1444         
1445         if (angle != 0) {
1446                 char buf[10];
1447                 sprintf(buf, "%g", angle);
1448                 // \rotatebox{angle}{text}
1449                 rotate = "\\rotatebox{";
1450                 rotate += buf;
1451                 rotate += "}{";
1452         }
1453
1454         cmdbuf = recmd;
1455         cmdbuf += rotate;
1456         cmdbuf += gcmd;
1457         if (!rotate.empty()) cmdbuf += '}';
1458         if (!recmd.empty()) cmdbuf += '}';
1459         if (subfigure) {
1460                 if (!subcaption.empty())
1461                         cmdbuf = "\\subfigure[" + subcaption +
1462                           "]{" + cmdbuf + "}";
1463                 else
1464                         cmdbuf = "\\subfigure{" + cmdbuf + "}";
1465         }
1466         
1467         cmd = cmdbuf;
1468
1469         //if (form) fl_set_object_label(form->cmd, cmd.c_str());
1470 }
1471
1472
1473 void InsetFig::TempRegenerate()
1474 {
1475         string gcmd;
1476         string cmdbuf;
1477         string resizeW, resizeH;
1478         string rotate, recmd;
1479         string tsubcap;
1480         
1481         char const *tfname; // *textra;
1482         float tangle, txwid, txhgh;
1483
1484         tfname = fl_get_input(form->EpsFile);
1485         tsubcap = fl_get_input(form->Subcaption);
1486         tangle = atof(fl_get_input(form->Angle));
1487         txwid = atof(fl_get_input(form->Width));
1488         txhgh = atof(fl_get_input(form->Height));
1489
1490         if (!tfname || !*tfname) {
1491                 //fl_set_object_label(form->cmd, "");
1492                 //fl_redraw_object(form->cmd);
1493                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1494                 cmd += _("empty figure path");
1495                 cmd += '}';
1496                 return;
1497         }
1498
1499         string buf1 = OnlyPath(owner->getFileName());
1500         string fname2 = MakeRelPath(tfname, buf1);
1501         // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1502         gcmd = "\\includegraphics{" + fname2 + '}';
1503         
1504         switch (twtype) {
1505         case DEF:
1506                 break;
1507         case CM: {// \resizebox*{h-length}{v-length}{text}
1508                 char buf[10];
1509                 sprintf(buf, "%g", txwid); // should find better
1510                 resizeW = buf;
1511                 resizeW += "cm";
1512                 break;
1513         }
1514         case IN: {
1515                 char buf[10];
1516                 sprintf(buf, "%g", txwid);
1517                 resizeW = buf;
1518                 resizeW += "in";
1519                 break;
1520         }
1521         case PER_PAGE: {
1522                 char buf[10];
1523                 sprintf(buf, "%g", txwid/100);
1524                 resizeW = buf;
1525                 resizeW += "\\textwidth";
1526                 break;
1527         }
1528         case PER_COL: {
1529                 char buf[10];
1530                 sprintf(buf, "%g", txwid/100);
1531                 resizeW = buf;
1532                 resizeW += "\\columnwidth";
1533                 break;
1534         }
1535         }
1536
1537         switch (thtype) {
1538         case DEF:
1539                 break;
1540         case CM: {
1541                 char buf[10];
1542                 sprintf(buf, "%g", txhgh);
1543                 resizeH = buf;
1544                 resizeH += "cm";
1545                 break;
1546         }
1547         case IN: {
1548                 char buf[10];
1549                 sprintf(buf, "%g", txhgh);
1550                 resizeH = buf;
1551                 resizeH += "in";
1552                 break;
1553         }
1554         case PER_PAGE: {
1555                 char buf[10];
1556                 sprintf(buf, "%g", txhgh/100);
1557                 resizeH = buf;
1558                 resizeH += "\\textheight";
1559                 break;
1560         }
1561         case PER_COL: {
1562                 // Doesn't occur; case exists to suppress compiler warnings.
1563                 break;
1564         }
1565         }
1566
1567         // \resizebox*{h-length}{v-length}{text}
1568         if (!resizeW.empty() || !resizeH.empty()) {
1569                 recmd = "\\resizebox*{";
1570                 if (!resizeW.empty())
1571                         recmd += resizeW;
1572                 else
1573                         recmd += '!';
1574                 recmd += "}{";
1575                 if (!resizeH.empty())
1576                         recmd += resizeH;
1577                 else
1578                         recmd += '!';
1579                 recmd += "}{";
1580         }
1581         
1582         if (tangle != 0) {
1583                 char buf[10];
1584                 sprintf(buf, "%g", tangle);
1585                 // \rotatebox{angle}{text}
1586                 rotate = "\\rotatebox{";
1587                 rotate += buf;
1588                 rotate += "}{";
1589         }
1590
1591         cmdbuf = recmd;
1592         cmdbuf += rotate;
1593         cmdbuf += gcmd;
1594         if (!rotate.empty()) cmdbuf += '}';
1595         if (!recmd.empty()) cmdbuf += '}';
1596         if (psubfigure && !tsubcap.empty()) {
1597                 cmdbuf = string("\\subfigure{") + tsubcap
1598                   + string("}{") + cmdbuf + "}";
1599         }
1600
1601         
1602         //fl_set_object_label(form->cmd, cmdbuf.c_str());
1603         //fl_redraw_object(form->cmd);
1604 }
1605
1606
1607 void InsetFig::Recompute()
1608 {
1609         bool changed = changedfname;
1610         int newx, newy, nraw_x, nraw_y, frame_wid, frame_hgh;
1611         float sin_a, cos_a;
1612
1613         if (changed) GetPSSizes();
1614
1615         sin_a = sin (angle / DEG2PI);        /* rotation; H. Zeller 021296 */
1616         cos_a = cos (angle / DEG2PI);
1617         frame_wid = (int) ceil (fabs(cos_a * pswid) + fabs(sin_a * pshgh));
1618         frame_hgh= (int) ceil (fabs(cos_a * pshgh) + fabs(sin_a * pswid));
1619
1620         /* now recompute wid and hgh, and if that is changed, set changed */
1621         /* this depends on chosen size of the picture and its bbox */
1622         // This will be redone in 0.13 ... (hen)
1623         if (!fname.empty()) {
1624                 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1625
1626                 newx = frame_wid;
1627                 newy = frame_hgh;
1628                 switch (wtype) {
1629                 case DEF:
1630                         break;
1631                 case CM:        /* cm */
1632                         newx = (int) (28.346*xwid);
1633                         break;
1634                 case IN: /* in */
1635                         newx = (int) (72*xwid);
1636                         break;
1637                 case PER_PAGE:  /* % of page */
1638                         newx = (int) (5.95*xwid);
1639                         break;
1640                 case PER_COL:   /* % of col */
1641                         newx = (int) (2.975*xwid);
1642                         break;
1643                 }
1644                 
1645                 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1646                 
1647                 switch (htype) {
1648                 case DEF:
1649                         //lyxerr << "This should not happen!" << endl;
1650                         break;
1651                 case CM:        /* cm */
1652                         newy = (int) (28.346*xhgh);
1653                         break;
1654                 case IN: /* in */
1655                         newy = (int) (72*xhgh);
1656                         break;
1657                 case PER_PAGE:  /* % of page */
1658                         newy = (int) (8.42*xhgh);
1659                         break;
1660                 case PER_COL: 
1661                         // Doesn't occur; case exists to suppress
1662                         // compiler warnings.  
1663                         break;
1664                 }
1665                 if (htype && !wtype && frame_hgh) newx = newy*frame_wid/frame_hgh;
1666         } else {
1667                 newx = wid;
1668                 newy = hgh;
1669         }
1670
1671         if (frame_wid == 0)
1672                 nraw_x = 5;
1673         else
1674                 nraw_x = (int) ((1.0 * pswid * newx)/frame_wid);
1675
1676         if (frame_hgh == 0)
1677                 nraw_y = 5;
1678         else
1679                 nraw_y = (int) ((1.0 * pshgh * newy)/frame_hgh);
1680
1681         // cannot be zero, actually, set it to some minimum, so its clickable
1682         if (newx < 5) newx = 5;
1683         if (newy < 5) newy = 5;
1684
1685         if (newx   != wid     || newy   != hgh     || 
1686             nraw_x != raw_wid || nraw_y != raw_hgh ||
1687             flags  != pflags  || subfigure != psubfigure) 
1688                 changed = true;
1689        
1690         raw_wid = nraw_x;
1691         raw_hgh = nraw_y;
1692         wid = newx;
1693         hgh = newy;
1694         flags = pflags;
1695         subfigure = psubfigure;
1696
1697         if (changed) {
1698                 figdata *pf = figure->data;
1699
1700                 // get new data
1701                 if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) {
1702                         // do not display if there is "do not display"
1703                         // chosen (Matthias 260696)
1704                         figure->data = getfigdata(wid, hgh, fname,
1705                                                   psx, psy, pswid, pshgh,
1706                                                   raw_wid, raw_hgh,
1707                                                   angle, flags & (3|8));
1708                 } else figure->data = 0;
1709
1710                 // free the old data
1711                 if (pf) freefigdata(pf);
1712         }
1713
1714         changedfname = false;
1715 }
1716
1717
1718 void InsetFig::GetPSSizes()
1719 {
1720 #warning rewrite this method to use ifstream
1721         /* get %%BoundingBox: from postscript file */
1722         int lastchar, c;
1723         char * p = 0;
1724         
1725         /* defaults to associated size
1726          * ..just in case the PS-file is not readable (Henner, 24-Aug-97) 
1727          */
1728         psx = 0;
1729         psy = 0;
1730         pswid = wid;
1731         pshgh = hgh;
1732
1733         if (fname.empty()) return;
1734
1735         FilePtr f(fname, FilePtr::read);
1736
1737         if (!f()) return;       // file not found !!!!
1738
1739         /* defaults to A4 page */
1740         psx = 0;
1741         psy = 0;
1742         pswid = 595;
1743         pshgh = 842;
1744
1745         lastchar = fgetc(f);
1746         for (;;) {
1747                 c = fgetc(f);
1748                 if (c == EOF) {
1749                         lyxerr.debug() << "End of (E)PS file reached and"
1750                                 " no BoundingBox!" << endl;
1751                         break;
1752                 }
1753                 if (c == '%' && lastchar == '%') {
1754                         p = NextToken(f);
1755                         if (!p) break;
1756                         // we should not use this, with it we cannot
1757                         // discover bounding box and end of file.
1758                         //if (strcmp(p, "EndComments") == 0) break;
1759                         if (strcmp(p, "BoundingBox:") == 0) {
1760                                 float fpsx, fpsy, fpswid, fpshgh;
1761                                 if (fscanf(f, "%f %f %f %f", &fpsx, &fpsy,
1762                                            &fpswid, &fpshgh) == 4) {
1763                                         psx = (int) fpsx;
1764                                         psy = (int) fpsy;
1765                                         pswid = (int) fpswid;
1766                                         pshgh = (int) fpshgh;
1767                                 } 
1768
1769                                 if (lyxerr.debugging()) {
1770                                         lyxerr << "%%%%BoundingBox:"
1771                                                << psx << ' '
1772                                                << psy << ' '
1773                                                << pswid << ' '
1774                                                << pshgh << endl;
1775                                 }
1776                                 break;
1777                         }
1778                         c = 0;
1779                         delete[] p;
1780                         p = 0;
1781                 }
1782                 lastchar = c;
1783         }
1784         if (p) delete[] p;
1785         pswid -= psx;
1786         pshgh -= psy;
1787
1788 }
1789
1790
1791 void InsetFig::CallbackFig(long arg)
1792 {
1793         bool regen = false;
1794         char const *p;
1795
1796         if (lyxerr.debugging()) {
1797                 printf("Figure callback, arg %ld\n", arg);
1798         }
1799
1800         switch (arg) {
1801         case 10:
1802         case 11:
1803         case 12:        /* width type */
1804         case 13:
1805         case 14:
1806                 switch (arg - 10) {
1807                 case DEF:
1808                         twtype = DEF;
1809                         // put disable here
1810                         fl_deactivate_object(form->Width);
1811                         break;
1812                 case CM:
1813                         twtype = CM;
1814                         // put enable here
1815                         fl_activate_object(form->Width);
1816                         break;
1817                 case IN:
1818                         twtype = IN;
1819                         // put enable here
1820                         fl_activate_object(form->Width);
1821                         break;
1822                 case PER_PAGE:
1823                         twtype = PER_PAGE;
1824                         // put enable here
1825                         fl_activate_object(form->Width);
1826                         break;
1827                 case PER_COL:
1828                         twtype = PER_COL;
1829                         // put enable here
1830                         fl_activate_object(form->Width);
1831                         break;
1832                 default:
1833                         lyxerr.debug() << "Unknown type!" << endl;
1834                         break;
1835                 }
1836                 regen = true;
1837                 break;
1838         case 20:
1839         case 21:
1840         case 22:        /* height type */
1841         case 23:
1842                 switch (arg - 20) {
1843                 case DEF:
1844                         thtype = DEF;
1845                         // put disable here
1846                         fl_deactivate_object(form->Height);
1847                         break;
1848                 case CM:
1849                         thtype = CM;
1850                         // put enable here
1851                         fl_activate_object(form->Height);
1852                         break;
1853                 case IN:
1854                         thtype = IN;
1855                         // put enable here
1856                         fl_activate_object(form->Height);
1857                         break;
1858                 case PER_PAGE:
1859                         thtype = PER_PAGE;
1860                         // put enable here
1861                         fl_activate_object(form->Height);
1862                         break;
1863                 default:
1864                         lyxerr.debug() << "Unknown type!" << endl;
1865                         break;
1866                 }
1867                 regen = true;
1868                 break;
1869         case 3:
1870                 pflags = pflags & ~3;           /* wysiwyg0 */
1871                 break;
1872         case 33:
1873                 pflags = (pflags & ~3) | 1;     /* wysiwyg1 */
1874                 break;
1875         case 43:
1876                 pflags = (pflags & ~3) | 2;     /* wysiwyg2 */
1877                 break;
1878         case 63:
1879                 pflags = (pflags & ~3) | 3;     /* wysiwyg3 */
1880                 break;
1881         case 53:
1882                 pflags ^= 4;    /* frame */
1883                 break;
1884         case 54:
1885                 pflags ^= 8;    /* do translations */
1886                 break;
1887         case 70:
1888                 psubfigure = !psubfigure;       /* This is a subfigure */
1889                 break;
1890         case 2:
1891                 regen = true;           /* regenerate command */
1892                 break;
1893         case 0:                         /* browse file */
1894                 BrowseFile();
1895                 regen = true;
1896                 break;
1897         case 1:                         /* preview */
1898                 p = fl_get_input(form->EpsFile);
1899                 Preview(p);
1900                 break;
1901         case 7:                         /* apply */
1902         case 8:                         /* ok (apply and close) */
1903                 if(!current_view->buffer()->isReadonly())
1904                 {
1905                         wtype = twtype;
1906                         htype = thtype;
1907                         xwid = atof(fl_get_input(form->Width));
1908                         xhgh = atof(fl_get_input(form->Height));
1909                         angle = atof(fl_get_input(form->Angle));
1910                         p = fl_get_input(form->EpsFile);
1911                         if (p && *p) {
1912                                 string buf1 = OnlyPath(owner->getFileName());
1913                                 fname = MakeAbsPath(p, buf1);
1914                                 changedfname = true;
1915                         } else {
1916                                 if (!fname.empty()) {
1917                                         changedfname = true;
1918                                         fname.clear();
1919                                 }
1920                         }
1921                         subcaption = fl_get_input(form->Subcaption);
1922         
1923                         Regenerate();
1924                         Recompute();
1925                         /* now update inset */
1926                         if (lyxerr.debugging()) {
1927                                 lyxerr << "Update: ["
1928                                        << wid << 'x' << hgh << ']' << endl;
1929                         }
1930                         UpdateInset(this);
1931                         if (arg == 8) {
1932                                 fl_set_focus_object(form->Figure, form->OkBtn);
1933                                 fl_hide_form(form->Figure);
1934 #if FL_REVISION == 89
1935 #warning Reactivate this free_form calls
1936 #else
1937                                 fl_free_form(form->Figure);
1938                                 free(form);
1939                                 form = 0;
1940 #endif
1941                         }
1942                         break;
1943                 } //if not readonly
1944                 //  The user has already been informed about RO in ::Edit
1945                 if(arg == 7) // if 'Apply'
1946                         break;
1947                 // fall through
1948         case 9:                         /* cancel = restore and close */
1949                 fl_set_focus_object(form->Figure, form->OkBtn);
1950                 fl_hide_form(form->Figure);
1951 #if FL_REVISION == 89
1952 #warning Reactivate this free_form calls
1953 #else
1954                 fl_free_form(form->Figure);
1955                 free(form);
1956                 form = 0;
1957 #endif
1958                 break;
1959         }
1960
1961         if (regen) TempRegenerate();
1962 }
1963
1964 inline void DisableFigurePanel(FD_Figure * const form)
1965 {
1966         fl_deactivate_object(form->EpsFile);
1967         fl_deactivate_object(form->Browse);
1968         fl_deactivate_object(form->Width);
1969         fl_deactivate_object(form->Height);
1970         fl_deactivate_object(form->Frame);
1971         fl_deactivate_object(form->Translations);
1972         fl_deactivate_object(form->Angle);
1973         fl_deactivate_object(form->HeightGrp);
1974         fl_deactivate_object(form->page2);
1975         fl_deactivate_object(form->Default2);
1976         fl_deactivate_object(form->cm2);
1977         fl_deactivate_object(form->in2);
1978         fl_deactivate_object(form->HeightLabel);
1979         fl_deactivate_object(form->WidthLabel);
1980         fl_deactivate_object(form->DisplayGrp);
1981         fl_deactivate_object(form->Wysiwyg3);
1982         fl_deactivate_object(form->Wysiwyg0);
1983         fl_deactivate_object(form->Wysiwyg2);
1984         fl_deactivate_object(form->Wysiwyg1);
1985         fl_deactivate_object(form->WidthGrp);
1986         fl_deactivate_object(form->Default1);
1987         fl_deactivate_object(form->cm1);
1988         fl_deactivate_object(form->in1);
1989         fl_deactivate_object(form->page1);
1990         fl_deactivate_object(form->column1);
1991         fl_deactivate_object(form->Subcaption);
1992         fl_deactivate_object(form->Subfigure);
1993         fl_deactivate_object (form->OkBtn);
1994         fl_deactivate_object (form->ApplyBtn);
1995         fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1996         fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1997 }
1998
1999 inline void EnableFigurePanel(FD_Figure * const form)
2000 {
2001         fl_activate_object(form->EpsFile);
2002         fl_activate_object(form->Browse);
2003         fl_activate_object(form->Width);
2004         fl_activate_object(form->Height);
2005         fl_activate_object(form->Frame);
2006         fl_activate_object(form->Translations);
2007         fl_activate_object(form->Angle);
2008         fl_activate_object(form->HeightGrp);
2009         fl_activate_object(form->page2);
2010         fl_activate_object(form->Default2);
2011         fl_activate_object(form->cm2);
2012         fl_activate_object(form->in2);
2013         fl_activate_object(form->HeightLabel);
2014         fl_activate_object(form->WidthLabel);
2015         fl_activate_object(form->DisplayGrp);
2016         fl_activate_object(form->Wysiwyg3);
2017         fl_activate_object(form->Wysiwyg0);
2018         fl_activate_object(form->Wysiwyg2);
2019         fl_activate_object(form->Wysiwyg1);
2020         fl_activate_object(form->WidthGrp);
2021         fl_activate_object(form->Default1);
2022         fl_activate_object(form->cm1);
2023         fl_activate_object(form->in1);
2024         fl_activate_object(form->page1);
2025         fl_activate_object(form->column1);
2026         fl_activate_object(form->Subcaption);
2027         fl_activate_object(form->Subfigure);
2028         fl_activate_object (form->OkBtn);
2029         fl_activate_object (form->ApplyBtn);
2030         fl_set_object_lcol (form->OkBtn, FL_BLACK);
2031         fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
2032 }
2033
2034 void InsetFig::RestoreForm()
2035 {
2036         char buf[32];
2037         int pflags;
2038
2039         EnableFigurePanel(form);
2040
2041         twtype = wtype;
2042         fl_set_button(form->Default1, (wtype == 0));
2043         fl_set_button(form->cm1, (wtype == 1));
2044         fl_set_button(form->in1, (wtype == 2));
2045         fl_set_button(form->page1, (wtype == 3));
2046         fl_set_button(form->column1, (wtype == 4));
2047         if (wtype == 0) {
2048                 fl_deactivate_object(form->Width);
2049         } else {
2050                 fl_activate_object(form->Width);
2051         }
2052                 
2053         // enable and disable should be put here.
2054         thtype = htype;
2055         fl_set_button(form->Default2, (htype == 0));
2056         fl_set_button(form->cm2, (htype == 1));
2057         fl_set_button(form->in2, (htype == 2));
2058         fl_set_button(form->page2, (htype == 3));
2059         // enable and disable should be put here.
2060         if (htype == 0) {
2061                 fl_deactivate_object(form->Height);
2062         } else {
2063                 fl_activate_object(form->Height);
2064         }
2065
2066         pflags = flags & 3;
2067         fl_set_button(form->Wysiwyg0, (pflags == 0));
2068         fl_set_button(form->Wysiwyg1, (pflags == 1));
2069         fl_set_button(form->Wysiwyg2, (pflags == 2));
2070         fl_set_button(form->Wysiwyg3, (pflags == 3));
2071         fl_set_button(form->Frame, ((flags & 4) != 0));
2072         fl_set_button(form->Translations, ((flags & 8) != 0));
2073         fl_set_button(form->Subfigure, (subfigure != 0));
2074         pflags = flags;
2075         psubfigure = subfigure;
2076         sprintf(buf, "%g", xwid);
2077         fl_set_input(form->Width, buf);
2078         sprintf(buf, "%g", xhgh);
2079         fl_set_input(form->Height, buf);
2080         sprintf(buf, "%g", angle);
2081         fl_set_input(form->Angle, buf);
2082         if (!fname.empty()){
2083                 string buf1 = OnlyPath(owner->getFileName());
2084                 string fname2 = MakeRelPath(fname, buf1);
2085                 fl_set_input(form->EpsFile, fname2.c_str());
2086         }
2087         else fl_set_input(form->EpsFile, "");
2088         fl_set_input(form->Subcaption, subcaption.c_str());
2089         if(current_view->buffer()->isReadonly()) 
2090                 DisableFigurePanel(form);
2091
2092         TempRegenerate();
2093 }
2094
2095
2096 void InsetFig::Preview(char const *p)
2097 {
2098         int pid;
2099
2100         pid = fork();
2101
2102         if (pid == -1) {
2103                 lyxerr << "Cannot fork process!" << endl;
2104                 return;         // error
2105         }
2106         if (pid > 0) {
2107                 addpidwait(pid);
2108                 return;         // parent process
2109         }
2110
2111         string buf1 = OnlyPath(owner->getFileName());
2112         string buf2 = MakeAbsPath(p, buf1);
2113         
2114         lyxerr << "Error during rendering "
2115                << execlp(lyxrc->view_pspic_command.c_str(),
2116                          lyxrc->view_pspic_command.c_str(),
2117                          buf2.c_str(), 0)
2118                << endl;
2119         _exit(0);
2120 }
2121
2122
2123 void InsetFig::BrowseFile()
2124 {
2125         string buf, buf2, bufclip;
2126         static string current_figure_path;
2127         static int once = 0;
2128         LyXFileDlg fileDlg;
2129
2130         if (lyxerr.debugging()) {
2131                 lyxerr << "Filename: "
2132                        << owner->getFileName() << endl;
2133         }
2134         string p = fl_get_input(form->EpsFile);
2135
2136         buf = MakeAbsPath(owner->getFileName());
2137         buf2 = OnlyPath(buf);
2138         if (!p.empty()) {
2139                 buf = MakeAbsPath(p, buf2);
2140                 buf = OnlyPath(buf);
2141         } else {
2142           buf = OnlyPath(owner->getFileName().c_str());
2143         }
2144         
2145         // Does user clipart directory exist?
2146         bufclip = AddName (user_lyxdir, "clipart");     
2147         FileInfo fileInfo(bufclip);
2148         if (!(fileInfo.isOK() && fileInfo.isDir()))
2149           // No - bail out to system clipart directory
2150           bufclip = AddName (system_lyxdir, "clipart"); 
2151
2152
2153         fileDlg.SetButton(0, _("Clipart"), bufclip); 
2154         fileDlg.SetButton(1, _("Document"), buf); 
2155
2156         bool error = false;
2157         do {
2158                 ProhibitInput();
2159                 if (once) {
2160                         p = fileDlg.Select(_("EPS Figure"), current_figure_path,
2161                                            "*ps", string());
2162                 } else {
2163                         p = fileDlg.Select(_("EPS Figure"), buf,
2164                                            "*ps", string());
2165                 }
2166                 AllowInput();
2167
2168                 if (p.empty()) return;
2169
2170                 buf = MakeRelPath(p, buf2);
2171                 current_figure_path = OnlyPath(p);
2172                 once = 1;
2173                 
2174                 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2175                     || contains(p, "%") || contains(p, " ")) 
2176                 {
2177                         WriteAlert(_("Filename can't contain any of these characters:"), // xgettext:no-c-format
2178                                    _("space, '#', '~', '$' or '%'.")); 
2179                         error = true;
2180                 }
2181         } while (error);
2182
2183         if (form) fl_set_input(form->EpsFile, buf.c_str());
2184 }
2185
2186
2187 void GraphicsCB(FL_OBJECT *obj, long arg)
2188 {
2189         /* obj->form contains the form */
2190
2191         if (lyxerr.debugging()) {
2192                 lyxerr << "GraphicsCB callback: " << arg << endl;
2193         }
2194
2195         /* find inset we were reacting to */
2196         for (int i = 0; i < figinsref; ++i)
2197                 if (figures[i]->inset->form && figures[i]->inset->form->Figure
2198                     == obj->form) {
2199             
2200                         if (lyxerr.debugging()) {
2201                                 lyxerr << "Calling back figure " << i << endl;
2202                         }
2203                         figures[i]->inset->CallbackFig(arg);
2204                         return;
2205                 }
2206 }
2207
2208
2209 void HideFiguresPopups()
2210 {
2211         for (int i = 0; i < figinsref; ++i)
2212                 if (figures[i]->inset->form 
2213                     && figures[i]->inset->form->Figure->visible) {
2214                         if (lyxerr.debugging()) {
2215                                 lyxerr << "Hiding figure " << i << endl;
2216                         }
2217                         // hide and free the form
2218                         figures[i]->inset->CallbackFig(9);
2219                 }
2220 }