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