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