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