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