]> git.lyx.org Git - lyx.git/blob - src/insets/figinset.C
411f7c12dd62e143bfc23e7bf6d76776e6aef77e
[lyx.git] / src / insets / figinset.C
1 /*
2  *      figinset.C - part of LyX project
3  */
4
5 extern int      reverse_video;
6 extern long int background_pixels;
7
8 /*  Rework of path-handling (Matthias 04.07.1996 )
9  * ------------------------------------------------
10  *   figinsets keep an absolute path to the eps-file.
11  *   For the user alway a relative path appears
12  *   (in lyx-file, latex-file and edit-popup).
13  *   To calculate this relative path the path to the
14  *   document where the figinset is in is needed. 
15  *   This is done by a reference to the buffer, called
16  *   figinset::cbuffer. To be up to date the cbuffer
17  *   is sometimes set to the current buffer 
18  *   bufferlist.current(), when it can be assumed that
19  *   this operation happens in the current buffer. 
20  *   This is true for InsetFig::Edit(...), 
21  *   InsetFig::InsetFig(...), InsetFig::Read(...),
22  *   InsetFig::Write and InsetFig::Latex(...).
23  *   Therefore the bufferlist has to make sure that
24  *   during these operations bufferlist.current() 
25  *   returns the buffer where the figinsets are in.
26  *   This made few changes in buffer.C necessary.
27  *
28  * The above is not totally valid anymore. (Lgb)
29  */
30
31
32 #include <config.h>
33
34 #include <unistd.h>
35 #include <csignal>
36 #include <sys/wait.h>
37
38 #include FORMS_H_LOCATION
39 #include <cstdlib>
40 #include <cctype>
41 #include <cmath>
42 #include <fstream>
43 using std::ofstream;
44
45 #include "form1.h"
46 #include "figinset.h"
47 #include "lyx.h"
48 #include "lyx_main.h"
49 #include "buffer.h"
50 #include "filedlg.h"
51 #include "support/filetools.h"
52 #include "LyXView.h" // just because of form_main
53 #include "debug.h"
54 #include "lyxdraw.h"
55 #include "LaTeXFeatures.h"
56 #include "lyxrc.h"
57 #include "gettext.h"
58 #include "lyx_gui_misc.h" // CancelCloseBoxCB
59 #include "support/FileInfo.h"
60
61 extern BufferView * current_view;
62 #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 = new queue;
718         p->ofsx = psx;
719         p->ofsy = psy;
720         p->rx = ((float)data->raw_wid*72)/pswid;
721         p->ry = ((float)data->raw_hgh*72)/pshgh;
722
723         p->data = data;
724         p->next = 0;
725
726         // now put into queue
727         queue * p2 = gsqueue;
728         if (!gsqueue) gsqueue = p;
729         else {
730                 while (p2->next) p2 = p2->next;
731                 p2->next = p;
732         }
733
734         // if possible, run the queue
735         runqueue();
736 }
737
738
739 static figdata * getfigdata(int wid, int hgh, string const & fname, 
740                             int psx, int psy, int pswid, int pshgh, 
741                             int raw_wid, int raw_hgh, float angle, char flags)
742 {
743         /* first search for an exact match with fname and width/height */
744
745         if (fname.empty()) return 0;
746
747         int i = 0;
748         while (i < bmpinsref) {
749                 if (bitmaps[i]->wid == wid && bitmaps[i]->hgh == hgh &&
750                     bitmaps[i]->flags == flags && bitmaps[i]->fname == fname &&
751                     bitmaps[i]->angle == angle) {
752                         bitmaps[i]->ref++;
753                         return bitmaps[i];
754                 }
755                 ++i;
756         }
757         /* not found -> create new record or return 0 if no record */
758         ++bmpinsref;
759         if (bmpinsref > bmparrsize) {
760                 // allocate more space
761                 bmparrsize += figallocchunk;
762                 figdata ** tmp = (figdata**) malloc(sizeof(figdata*)*bmparrsize);
763                 memcpy(tmp, bitmaps, sizeof(figdata*)*(bmparrsize-figallocchunk));
764                 free(bitmaps);
765                 bitmaps = tmp;
766         }
767         figdata * p = new figdata;
768         bitmaps[bmpinsref-1] = p;
769         p->wid = wid;
770         p->hgh = hgh;
771         p->raw_wid = raw_wid;
772         p->raw_hgh = raw_hgh;
773         p->angle = angle;
774         p->fname = fname;
775         p->flags = flags;
776         XWindowAttributes wa;
777         XGetWindowAttributes(fl_display, fl_get_canvas_id(
778                 figinset_canvas), &wa);
779
780         if (lyxerr.debugging()) {
781                 lyxerr << "Create pixmap disp:" << fl_display
782                        << " scr:" << DefaultScreen(fl_display)
783                        << " w:" << wid
784                        << " h:" << hgh
785                        << " depth:" << wa.depth << endl;
786         }
787         
788         p->ref = 1;
789         p->reading = false;
790         p->broken = false;
791         p->gspid = -1;
792         if (flags) {
793                 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
794                         figinset_canvas), wid, hgh, wa.depth);
795                 p->gsdone = false;
796                 // initialize reading of .eps file with correct sizes and stuff
797                 addwait(psx, psy, pswid, pshgh, p);
798                 p->reading = true;
799         } else {
800                 p->bitmap = None;
801                 p->gsdone = true;
802         }
803
804         return p;
805 }
806
807
808 static void getbitmap(figdata *p)
809 {
810         p->gspid = -1;
811 }
812
813
814 static void makeupdatelist(figdata *p)
815 {
816         for (int i = 0; i < figinsref; ++i)
817                 if (figures[i]->data == p) {
818                         if (lyxerr.debugging()) {
819                                 lyxerr << "Updating inset "
820                                        << figures[i]->inset
821                                        << endl;
822                         }
823                         //UpdateInset(figures[i]->inset);
824                         // add inset figures[i]->inset into to_update list
825                         PutInsetIntoInsetUpdateList(figures[i]->inset);
826                 }
827 }
828
829
830 void sigchldchecker(pid_t pid, int * status)
831 {
832         lyxerr.debug() << "Got pid = " << pid << endl;
833         bool pid_handled = false;
834         for (int i = bmpinsref - 1; i >= 0; --i) {
835                 if (bitmaps[i]->reading && pid == bitmaps[i]->gspid) {
836                         lyxerr.debug() << "Found pid in bitmaps" << endl;
837                         // now read the file and remove it from disk
838                         figdata * p = bitmaps[i];
839                         p->reading = false;
840                         if (bitmaps[i]->gsdone) *status = 0;
841                         if (*status == 0) {
842                                 lyxerr.debug() << "GS [" << pid
843                                                << "] exit OK." << endl;
844                         } else {
845                                 lyxerr << "GS [" << pid  << "] error "
846                                        << *status << " E:"
847                                        << WIFEXITED(*status)
848                                        << " " << WEXITSTATUS(*status)
849                                        << " S:" << WIFSIGNALED(*status)
850                                        << " " << WTERMSIG(*status) << endl;
851                         }
852                         if (*status == 0) {
853                                 bitmap_waiting = true;
854                                 p->broken = false;
855                         } else {
856                                 // remove temporary files
857                                 char tmp[128];
858                                 sprintf(tmp, "%s/~lyxgs%d.ps", 
859                                         system_tempdir.c_str(),
860                                         p->gspid);
861                                 unlink(tmp);
862                                 p->gspid = -1;
863                                 p->broken = true;
864                         }
865                         makeupdatelist(bitmaps[i]);
866                         gsrunning--;
867                         runqueue();
868                         pid_handled = true;
869                 }
870         }
871         if (!pid_handled) {
872                 lyxerr.debug() << "Checking pid in pidwait" << endl;
873                 pidwait * p = pw, * prev = 0;
874                 while (p) {
875                         if (pid == p->pid) {
876                                 lyxerr.debug() << "Found pid in pidwait" << endl;
877                                 lyxerr.debug() << "Caught child pid of recompute routine " << pid << endl;
878                                 if (prev)
879                                         prev->next = p->next;
880                                 else
881                                         pw = p->next;
882                                 free(p);
883                                 break;
884                         }
885                         prev = p;
886                         p = p->next;
887                 }
888         }
889
890         if (pid == -1) {
891                 lyxerr.debug() << "waitpid error" << endl;
892                 switch (errno) {
893                 case ECHILD:
894                         lyxerr << "The process or process group specified by "
895                                 "pid does  not exist or is not a child of "
896                                 "the calling process or can never be in the "
897                                 "states specified by options." << endl;
898                         break;
899                 case EINTR:
900                         lyxerr << "waitpid() was interrupted due to the "
901                                 "receipt of a signal sent by the calling "
902                                 "process." << endl;
903                         break;
904                 case EINVAL:
905                         lyxerr << "An invalid value was specified for "
906                                 "options." << endl;
907                         break;
908                 default:
909                         lyxerr << "Unknown error from waitpid" << endl;
910                         break;
911                 }
912         } else if (pid == 0) {
913                 lyxerr << "waitpid nohang" << endl;;
914         } else {
915                 lyxerr.debug() << "normal exit from childhandler" << endl;
916         }
917 }
918
919
920 static void getbitmaps()
921 {
922         bitmap_waiting = false;
923         for (int i = 0; i < bmpinsref; ++i)
924                 if (bitmaps[i]->gspid > 0 && !bitmaps[i]->reading)
925                         getbitmap(bitmaps[i]);
926 }
927
928
929 static void RegisterFigure(InsetFig *fi)
930 {
931         if (figinsref == 0) InitFigures();
932         fi->form = 0;
933         ++figinsref;
934         if (figinsref > figarrsize) {
935                 // allocate more space
936                 figarrsize += figallocchunk;
937                 Figref **tmp = (Figref**) malloc(sizeof(Figref*)*figarrsize);
938                 memcpy(tmp, figures, sizeof(Figref*)*(figarrsize-figallocchunk));
939                 free(figures);
940                 figures = tmp;
941         }
942         Figref * tmpfig = new Figref;
943         tmpfig->data = 0;
944         tmpfig->inset = fi;
945         figures[figinsref-1] = tmpfig;
946         fi->figure = tmpfig;
947
948         if (lyxerr.debugging()) {
949                 lyxerr << "Register Figure: buffer:["
950                        << current_view->buffer() << "]" << endl;
951         }
952 }
953
954
955 int FindFigIndex(Figref * tmpfig)
956 {
957         int i = 0;
958         while (i < figinsref) {
959                 if (figures[i] == tmpfig) return i;
960                 ++i;
961         }
962         return i;
963 }
964
965
966 static void UnregisterFigure(InsetFig * fi)
967 {
968         Figref * tmpfig = fi->figure;
969
970         if (tmpfig->data) freefigdata(tmpfig->data);
971         if (tmpfig->inset->form) {
972                 if (tmpfig->inset->form->Figure->visible) {
973                         fl_set_focus_object(tmpfig->inset->form->Figure,
974                                             tmpfig->inset->form->OkBtn);
975                         fl_hide_form(tmpfig->inset->form->Figure);
976                 }
977 #if FL_REVISION == 89
978 #warning Reactivate this free_form calls
979 #else
980                 fl_free_form(tmpfig->inset->form->Figure);
981                 free(tmpfig->inset->form);
982                 tmpfig->inset->form = 0;
983 #endif
984         }
985         int i = FindFigIndex(tmpfig);
986         --figinsref;
987         while (i < figinsref) {
988                 figures[i] = figures[i+1];
989                 ++i;
990         }
991         delete tmpfig;
992
993         if (figinsref == 0) DoneFigures();
994 }
995
996
997 static char * NextToken(FILE * myfile)
998 {
999         char * token = 0;
1000         char c;
1001         int i = 0;
1002    
1003         if (!feof(myfile)) {
1004                 token = new char[256];
1005                 do {
1006                         c = fgetc(myfile);
1007                         token[i++]= c;
1008                 } while (!feof(myfile) && !isspace(c));
1009       
1010                 token[i-1]= '\0';         /* just the end of a command  */
1011         }
1012         return token;
1013 }
1014
1015
1016 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
1017         : owner(o)
1018 {
1019         wid = tmpx;
1020         hgh = tmpy;
1021         wtype = DEF;
1022         htype = DEF;
1023         twtype = DEF;
1024         thtype = DEF;
1025         pflags = flags = 9;
1026         psubfigure = subfigure = false;
1027         xwid = xhgh = angle = 0;
1028         raw_wid = raw_hgh = 0;
1029         changedfname = false;
1030         RegisterFigure(this);
1031 }
1032
1033
1034 InsetFig::~InsetFig()
1035 {
1036         if (lyxerr.debugging()) {
1037                 lyxerr << "Figure destructor called" << endl;
1038         }
1039         UnregisterFigure(this);
1040 }
1041
1042
1043 int InsetFig::Ascent(LyXFont const &) const
1044 {
1045         return hgh + 3;
1046 }
1047
1048
1049 int InsetFig::Descent(LyXFont const &) const
1050 {
1051         return 1;
1052 }
1053
1054
1055 int InsetFig::Width(LyXFont const &) const
1056 {
1057         return wid + 2;
1058 }
1059
1060
1061 void InsetFig::Draw(LyXFont font, LyXScreen & scr, int baseline, float & x)
1062 {
1063         if (bitmap_waiting) getbitmaps();
1064
1065         // I wish that I didn't have to use this
1066         // but the figinset code is so complicated so
1067         // I don't want to fiddle with it now.
1068         unsigned long pm = scr.getForeground();
1069         
1070         if (figure && figure->data && figure->data->bitmap &&
1071             !figure->data->reading && !figure->data->broken) {
1072                 // draw the bitmap
1073                 XCopyArea(fl_display, figure->data->bitmap, pm, getGC(gc_copy),
1074                           0, 0, wid, hgh, int(x+1), baseline-hgh);
1075                 XFlush(fl_display);
1076                 if (flags & 4) XDrawRectangle(fl_display, pm, getGC(gc_copy),
1077                                               int(x), baseline - hgh - 1,
1078                                               wid+1, hgh+1);
1079         } else {
1080                 char * msg = 0;
1081                 // draw frame
1082                 XDrawRectangle(fl_display, pm, getGC(gc_copy),
1083                                (int) x,
1084                                baseline - hgh - 1, wid+1, hgh+1);
1085                 if (figure && figure->data) {
1086                   if (figure->data->broken)  msg = _("[render error]");
1087                   else if (figure->data->reading) msg = _("[rendering ... ]");
1088                 } else 
1089                   if (fname.empty()) msg = _("[no file]");
1090                   else if ((flags & 3) == 0) msg = _("[not displayed]");
1091                   else if (lyxrc->ps_command.empty()) msg = _("[no ghostscript]");
1092
1093                 if (!msg) msg = _("[unknown error]");
1094                 
1095                 font.setFamily (LyXFont::SANS_FAMILY);
1096                 font.setSize (LyXFont::SIZE_FOOTNOTE);
1097                 string justname = OnlyFilename (fname);
1098                 font.drawString(justname, pm,
1099                                baseline - font.maxAscent() - 4,
1100                                (int) x + 8);
1101                 font.setSize (LyXFont::SIZE_TINY);
1102                 font.drawText (msg, strlen(msg), pm,
1103                                baseline - 4,
1104                                (int) x + 8);
1105
1106         }
1107         x += Width(font);    // ?
1108 }
1109
1110
1111 void InsetFig::Write(FILE * file)
1112 {
1113         Regenerate();
1114         fprintf(file, "Figure size %d %d\n", wid, hgh);
1115         if (!fname.empty()) {
1116           string buf1 = OnlyPath(owner->getFileName());
1117           string fname2 = MakeRelPath(fname, buf1);
1118           fprintf(file, "file %s\n", fname2.c_str());
1119         }
1120         if (!subcaption.empty())
1121           fprintf(file, "subcaption %s\n", subcaption.c_str());
1122         if (wtype) fprintf(file, "width %d %g\n", wtype, xwid);
1123         if (htype) fprintf(file, "height %d %g\n", htype, xhgh);
1124         if (angle != 0) fprintf(file, "angle %g\n", angle);
1125         fprintf(file, "flags %d\n", flags);
1126         if (subfigure) fprintf(file, "subfigure\n");
1127 }
1128
1129
1130 void InsetFig::Read(LyXLex & lex)
1131 {
1132         string buf;
1133         bool finished = false;
1134         
1135         while (lex.IsOK() && !finished) {
1136                 lex.next();
1137
1138                 string const token = lex.GetString();
1139                 lyxerr.debug() << "Token: " << token << endl;
1140                 
1141                 if (token.empty())
1142                         continue;
1143                 else if (token == "\\end_inset") {
1144                         finished = true;
1145                 } else if (token == "file") {
1146                         if (lex.next()) {
1147                                 buf = lex.GetString();
1148                                 string buf1 = OnlyPath(owner->getFileName());
1149                                 fname = MakeAbsPath(buf, buf1);
1150                                 changedfname = true;
1151                         }
1152                 } else if (token == "extra") {
1153                         if (lex.next());
1154                         // kept for backwards compability. Delete in 0.13.x
1155                 } else if (token == "subcaption") {
1156                         if (lex.EatLine())
1157                                 subcaption = lex.GetString();
1158                 } else if (token == "label") {
1159                         if (lex.next());
1160                         // kept for backwards compability. Delete in 0.13.x
1161                 } else if (token == "angle") {
1162                         if (lex.next())
1163                                 angle = lex.GetFloat();
1164                 } else if (token == "size") {
1165                         if (lex.next())
1166                                 wid = lex.GetInteger();
1167                         if (lex.next())
1168                                 hgh = lex.GetInteger();
1169                 } else if (token == "flags") {
1170                         if (lex.next())
1171                                 flags = pflags = lex.GetInteger();
1172                 } else if (token == "subfigure") {
1173                         subfigure = psubfigure = true;
1174                 } else if (token == "width") {
1175                         int typ = 0;
1176                         if (lex.next())
1177                                 typ = lex.GetInteger();
1178                         if (lex.next())
1179                                 xwid = lex.GetFloat();
1180                         switch (typ) {
1181                         case DEF: wtype = DEF; break;
1182                         case CM: wtype = CM; break;
1183                         case IN: wtype = IN; break;
1184                         case PER_PAGE: wtype = PER_PAGE; break;
1185                         case PER_COL: wtype = PER_COL; break;
1186                         default:
1187                                 lyxerr.debug() << "Unknown type!" << endl;
1188                                 break;
1189                         }
1190                         twtype = wtype;
1191                 } else if (token == "height") {
1192                         int typ = 0;
1193                         if (lex.next())
1194                                 typ = lex.GetInteger();
1195                         if (lex.next())
1196                                 xhgh = lex.GetFloat();
1197                         switch (typ) {
1198                         case DEF: htype = DEF; break;
1199                         case CM: htype = CM; break;
1200                         case IN: htype = IN; break;
1201                         case PER_PAGE: htype = PER_PAGE; break;
1202                         default:
1203                                 lyxerr.debug() << "Unknown type!" << endl;
1204                                 break;
1205                         }
1206                         thtype = htype;
1207                 }
1208         }
1209         Regenerate();
1210         Recompute();
1211 }
1212
1213
1214 int InsetFig::Latex(FILE * file, signed char /* fragile*/ )
1215 {
1216         Regenerate();
1217         if (!cmd.empty()) fprintf(file, "%s ", cmd.c_str());
1218         return 0;
1219 }
1220
1221
1222 int InsetFig::Latex(string & file, signed char /* fragile*/ )
1223 {
1224         Regenerate();
1225         file += cmd + ' ';
1226         return 0;
1227 }
1228
1229
1230 int InsetFig::Linuxdoc(string &/*file*/)
1231 {
1232         return 0;
1233 }
1234
1235
1236 int InsetFig::DocBook(string & file)
1237 {
1238         string figurename= fname;
1239
1240         if(suffixIs(figurename, ".eps"))
1241                 figurename.erase(fname.length() - 5);
1242
1243         file += "@<graphic fileref=\"" + figurename + "\"></graphic>";
1244         return 0;
1245 }
1246
1247
1248 void InsetFig::Validate(LaTeXFeatures & features) const
1249 {
1250         features.graphics = true;
1251         if (subfigure) features.subfigure = true;
1252 }
1253
1254
1255 unsigned char InsetFig::Editable() const
1256 {
1257         return 1;
1258 }
1259
1260
1261 bool InsetFig::Deletable() const
1262 {
1263         return false;
1264 }
1265
1266
1267 void InsetFig::Edit(int, int)
1268 {
1269         lyxerr.debug() << "Editing InsetFig." << endl;
1270         Regenerate();
1271
1272         // We should have RO-versions of the form instead.
1273         // The actual prevention of altering a readonly doc
1274         // is done in CallbackFig()
1275         if(current_view->buffer()->isReadonly()) 
1276                 WarnReadonly();
1277
1278         if (!form) {
1279                 form = create_form_Figure();
1280                 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1281                 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1282                 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1283                 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1284         }
1285         RestoreForm();
1286         if (form->Figure->visible) {
1287                 fl_raise_form(form->Figure);
1288         } else {
1289                 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1290                              FL_FULLBORDER, _("Figure"));
1291         }
1292 }
1293
1294
1295 Inset * InsetFig::Clone() const
1296 {
1297         InsetFig * tmp = new InsetFig(100, 100, owner);
1298
1299         if (lyxerr.debugging()) {
1300                 lyxerr << "Clone Figure: buffer:["
1301                        << current_view->buffer()
1302                        << "], cbuffer:[xx]" << endl;
1303         }
1304
1305         tmp->wid = wid;
1306         tmp->hgh = hgh;
1307         tmp->raw_wid = raw_wid;
1308         tmp->raw_hgh = raw_hgh;
1309         tmp->angle = angle;
1310         tmp->xwid = xwid;
1311         tmp->xhgh = xhgh;
1312         tmp->flags = flags;
1313         tmp->pflags = pflags;
1314         tmp->subfigure = subfigure;
1315         tmp->psubfigure = psubfigure;
1316         tmp->wtype = wtype;
1317         tmp->htype = htype;
1318         tmp->psx = psx;
1319         tmp->psy = psy;
1320         tmp->pswid = pswid;
1321         tmp->pshgh = pshgh;
1322         tmp->fname = fname;
1323         if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) { 
1324           // do not display if there is "do not display" chosen (Matthias 260696)
1325                 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1326                                                pswid, pshgh, raw_wid, raw_hgh,
1327                                                angle, flags & (3|8));
1328         } else tmp->figure->data = 0;
1329         tmp->subcaption = subcaption;
1330         tmp->changedfname = false;
1331         tmp->owner = owner;
1332         tmp->Regenerate();
1333         return tmp;
1334 }
1335
1336
1337 Inset::Code InsetFig::LyxCode() const
1338 {
1339         return Inset::GRAPHICS_CODE;
1340 }
1341
1342
1343 void InsetFig::Regenerate()
1344 {
1345         string cmdbuf;
1346         string resizeW, resizeH;
1347         string rotate, recmd;
1348
1349         if (fname.empty()) {
1350                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1351                 cmd += _("empty figure path");
1352                 cmd += '}';
1353                 //if (form) fl_set_object_label(form->cmd, "");
1354                 return;
1355         }
1356
1357         string buf1 = OnlyPath(owner->getFileName());
1358         string fname2 = MakeRelPath(fname, buf1);
1359
1360         string gcmd = "\\includegraphics{" + fname2 + '}';
1361         
1362         switch (wtype) {
1363         case DEF:
1364                 break;
1365         case CM:{// \resizebox*{h-length}{v-length}{text}
1366                 char buf[10];
1367                 sprintf(buf, "%g", xwid); // should find better
1368                 resizeW = buf;
1369                 resizeW += "cm";
1370                 break;
1371         }
1372         case IN: {
1373                 char buf[10];
1374                 sprintf(buf, "%g", xwid);
1375                 resizeW = buf;
1376                 resizeW += "in";
1377                 break;
1378         }
1379         case PER_PAGE:{
1380                 char buf[10];
1381                 sprintf(buf, "%g", xwid/100);
1382                 resizeW = buf;
1383                 resizeW += "\\textwidth";
1384                 break;
1385         }
1386         case PER_COL:{
1387                 char buf[10];
1388                 sprintf(buf, "%g", xwid/100);
1389                 resizeW = buf;
1390                 resizeW += "\\columnwidth";
1391                 break;
1392         }
1393         }
1394
1395         switch (htype) {
1396         case DEF:
1397                 break;
1398         case CM: {
1399                 char buf[10];
1400                 sprintf(buf, "%g", xhgh);
1401                 resizeH = buf;
1402                 resizeH += "cm";
1403                 break;
1404         }
1405         case IN:{
1406                 char buf[10];
1407                 sprintf(buf, "%g", xhgh);
1408                 resizeH = buf;
1409                 resizeH += "in";
1410                 break;
1411         }
1412         case PER_PAGE: {
1413                 char buf[10];
1414                 sprintf(buf, "%g", xhgh/100);
1415                 resizeH = buf;
1416                 resizeH += "\\textheight";
1417                 break;
1418         }
1419         case PER_COL: {
1420                 // Doesn't occur; case exists to suppress compiler warnings.
1421                 break;
1422         }
1423         }
1424
1425         if (!resizeW.empty() || !resizeH.empty()) {
1426                 recmd = "\\resizebox*{";
1427                 if (!resizeW.empty())
1428                         recmd += resizeW;
1429                 else
1430                         recmd += '!';
1431                 recmd += "}{";
1432                 if (!resizeH.empty())
1433                         recmd += resizeH;
1434                 else
1435                         recmd += '!';
1436                 recmd += "}{";
1437         }
1438         
1439         
1440         if (angle != 0) {
1441                 char buf[10];
1442                 sprintf(buf, "%g", angle);
1443                 // \rotatebox{angle}{text}
1444                 rotate = "\\rotatebox{";
1445                 rotate += buf;
1446                 rotate += "}{";
1447         }
1448
1449         cmdbuf = recmd;
1450         cmdbuf += rotate;
1451         cmdbuf += gcmd;
1452         if (!rotate.empty()) cmdbuf += '}';
1453         if (!recmd.empty()) cmdbuf += '}';
1454         if (subfigure) {
1455                 if (!subcaption.empty())
1456                         cmdbuf = "\\subfigure[" + subcaption +
1457                           "]{" + cmdbuf + "}";
1458                 else
1459                         cmdbuf = "\\subfigure{" + cmdbuf + "}";
1460         }
1461         
1462         cmd = cmdbuf;
1463
1464         //if (form) fl_set_object_label(form->cmd, cmd.c_str());
1465 }
1466
1467
1468 void InsetFig::TempRegenerate()
1469 {
1470         string cmdbuf;
1471         string resizeW, resizeH;
1472         string rotate, recmd;
1473         
1474         char const * tfname = fl_get_input(form->EpsFile);
1475         string tsubcap = fl_get_input(form->Subcaption);
1476         float tangle = atof(fl_get_input(form->Angle));
1477         float txwid = atof(fl_get_input(form->Width));
1478         float txhgh = atof(fl_get_input(form->Height));
1479
1480         if (!tfname || !*tfname) {
1481                 //fl_set_object_label(form->cmd, "");
1482                 //fl_redraw_object(form->cmd);
1483                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1484                 cmd += _("empty figure path");
1485                 cmd += '}';
1486                 return;
1487         }
1488
1489         string buf1 = OnlyPath(owner->getFileName());
1490         string fname2 = MakeRelPath(tfname, buf1);
1491         // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1492         string gcmd = "\\includegraphics{" + fname2 + '}';
1493         
1494         switch (twtype) {
1495         case DEF:
1496                 break;
1497         case CM: {// \resizebox*{h-length}{v-length}{text}
1498                 char buf[10];
1499                 sprintf(buf, "%g", txwid); // should find better
1500                 resizeW = buf;
1501                 resizeW += "cm";
1502                 break;
1503         }
1504         case IN: {
1505                 char buf[10];
1506                 sprintf(buf, "%g", txwid);
1507                 resizeW = buf;
1508                 resizeW += "in";
1509                 break;
1510         }
1511         case PER_PAGE: {
1512                 char buf[10];
1513                 sprintf(buf, "%g", txwid/100);
1514                 resizeW = buf;
1515                 resizeW += "\\textwidth";
1516                 break;
1517         }
1518         case PER_COL: {
1519                 char buf[10];
1520                 sprintf(buf, "%g", txwid/100);
1521                 resizeW = buf;
1522                 resizeW += "\\columnwidth";
1523                 break;
1524         }
1525         }
1526
1527         switch (thtype) {
1528         case DEF:
1529                 break;
1530         case CM: {
1531                 char buf[10];
1532                 sprintf(buf, "%g", txhgh);
1533                 resizeH = buf;
1534                 resizeH += "cm";
1535                 break;
1536         }
1537         case IN: {
1538                 char buf[10];
1539                 sprintf(buf, "%g", txhgh);
1540                 resizeH = buf;
1541                 resizeH += "in";
1542                 break;
1543         }
1544         case PER_PAGE: {
1545                 char buf[10];
1546                 sprintf(buf, "%g", txhgh/100);
1547                 resizeH = buf;
1548                 resizeH += "\\textheight";
1549                 break;
1550         }
1551         case PER_COL: {
1552                 // Doesn't occur; case exists to suppress compiler warnings.
1553                 break;
1554         }
1555         }
1556
1557         // \resizebox*{h-length}{v-length}{text}
1558         if (!resizeW.empty() || !resizeH.empty()) {
1559                 recmd = "\\resizebox*{";
1560                 if (!resizeW.empty())
1561                         recmd += resizeW;
1562                 else
1563                         recmd += '!';
1564                 recmd += "}{";
1565                 if (!resizeH.empty())
1566                         recmd += resizeH;
1567                 else
1568                         recmd += '!';
1569                 recmd += "}{";
1570         }
1571         
1572         if (tangle != 0) {
1573                 char buf[10];
1574                 sprintf(buf, "%g", tangle);
1575                 // \rotatebox{angle}{text}
1576                 rotate = "\\rotatebox{";
1577                 rotate += buf;
1578                 rotate += "}{";
1579         }
1580
1581         cmdbuf = recmd;
1582         cmdbuf += rotate;
1583         cmdbuf += gcmd;
1584         if (!rotate.empty()) cmdbuf += '}';
1585         if (!recmd.empty()) cmdbuf += '}';
1586         if (psubfigure && !tsubcap.empty()) {
1587                 cmdbuf = string("\\subfigure{") + tsubcap
1588                   + string("}{") + cmdbuf + "}";
1589         }
1590 }
1591
1592
1593 void InsetFig::Recompute()
1594 {
1595         bool changed = changedfname;
1596         int newx, newy, nraw_x, nraw_y;
1597
1598         if (changed) GetPSSizes();
1599
1600         float sin_a = sin (angle / DEG2PI);  /* rotation; H. Zeller 021296 */
1601         float cos_a = cos (angle / DEG2PI);
1602         int frame_wid = (int) ceil (fabs(cos_a * pswid) + fabs(sin_a * pshgh));
1603         int frame_hgh= (int) ceil (fabs(cos_a * pshgh) + fabs(sin_a * pswid));
1604
1605         /* now recompute wid and hgh, and if that is changed, set changed */
1606         /* this depends on chosen size of the picture and its bbox */
1607         // This will be redone in 0.13 ... (hen)
1608         if (!fname.empty()) {
1609                 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1610
1611                 newx = frame_wid;
1612                 newy = frame_hgh;
1613                 switch (wtype) {
1614                 case DEF:
1615                         break;
1616                 case CM:        /* cm */
1617                         newx = (int) (28.346*xwid);
1618                         break;
1619                 case IN: /* in */
1620                         newx = (int) (72*xwid);
1621                         break;
1622                 case PER_PAGE:  /* % of page */
1623                         newx = (int) (5.95*xwid);
1624                         break;
1625                 case PER_COL:   /* % of col */
1626                         newx = (int) (2.975*xwid);
1627                         break;
1628                 }
1629                 
1630                 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1631                 
1632                 switch (htype) {
1633                 case DEF:
1634                         //lyxerr << "This should not happen!" << endl;
1635                         break;
1636                 case CM:        /* cm */
1637                         newy = (int) (28.346*xhgh);
1638                         break;
1639                 case IN: /* in */
1640                         newy = (int) (72*xhgh);
1641                         break;
1642                 case PER_PAGE:  /* % of page */
1643                         newy = (int) (8.42*xhgh);
1644                         break;
1645                 case PER_COL: 
1646                         // Doesn't occur; case exists to suppress
1647                         // compiler warnings.  
1648                         break;
1649                 }
1650                 if (htype && !wtype && frame_hgh) newx = newy*frame_wid/frame_hgh;
1651         } else {
1652                 newx = wid;
1653                 newy = hgh;
1654         }
1655
1656         if (frame_wid == 0)
1657                 nraw_x = 5;
1658         else
1659                 nraw_x = (int) ((1.0 * pswid * newx)/frame_wid);
1660
1661         if (frame_hgh == 0)
1662                 nraw_y = 5;
1663         else
1664                 nraw_y = (int) ((1.0 * pshgh * newy)/frame_hgh);
1665
1666         // cannot be zero, actually, set it to some minimum, so its clickable
1667         if (newx < 5) newx = 5;
1668         if (newy < 5) newy = 5;
1669
1670         if (newx   != wid     || newy   != hgh     || 
1671             nraw_x != raw_wid || nraw_y != raw_hgh ||
1672             flags  != pflags  || subfigure != psubfigure) 
1673                 changed = true;
1674        
1675         raw_wid = nraw_x;
1676         raw_hgh = nraw_y;
1677         wid = newx;
1678         hgh = newy;
1679         flags = pflags;
1680         subfigure = psubfigure;
1681
1682         if (changed) {
1683                 figdata * pf = figure->data;
1684
1685                 // get new data
1686                 if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) {
1687                         // do not display if there is "do not display"
1688                         // chosen (Matthias 260696)
1689                         figure->data = getfigdata(wid, hgh, fname,
1690                                                   psx, psy, pswid, pshgh,
1691                                                   raw_wid, raw_hgh,
1692                                                   angle, flags & (3|8));
1693                 } else figure->data = 0;
1694
1695                 // free the old data
1696                 if (pf) freefigdata(pf);
1697         }
1698
1699         changedfname = false;
1700 }
1701
1702
1703 void InsetFig::GetPSSizes()
1704 {
1705 #ifdef WITH_WARNINGS
1706 #warning rewrite this method to use ifstream
1707 #endif
1708         /* get %%BoundingBox: from postscript file */
1709         char * p = 0;
1710         
1711         /* defaults to associated size
1712          * ..just in case the PS-file is not readable (Henner, 24-Aug-97) 
1713          */
1714         psx = 0;
1715         psy = 0;
1716         pswid = wid;
1717         pshgh = hgh;
1718
1719         if (fname.empty()) return;
1720
1721         FilePtr f(fname, FilePtr::read);
1722
1723         if (!f()) return;       // file not found !!!!
1724
1725         /* defaults to A4 page */
1726         psx = 0;
1727         psy = 0;
1728         pswid = 595;
1729         pshgh = 842;
1730
1731         int lastchar = fgetc(f);
1732         for (;;) {
1733                 int c = fgetc(f);
1734                 if (c == EOF) {
1735                         lyxerr.debug() << "End of (E)PS file reached and"
1736                                 " no BoundingBox!" << endl;
1737                         break;
1738                 }
1739                 if (c == '%' && lastchar == '%') {
1740                         p = NextToken(f);
1741                         if (!p) break;
1742                         // we should not use this, with it we cannot
1743                         // discover bounding box and end of file.
1744                         //if (strcmp(p, "EndComments") == 0) break;
1745                         if (strcmp(p, "BoundingBox:") == 0) {
1746                                 float fpsx, fpsy, fpswid, fpshgh;
1747                                 if (fscanf(f, "%f %f %f %f", &fpsx, &fpsy,
1748                                            &fpswid, &fpshgh) == 4) {
1749                                         psx = (int) fpsx;
1750                                         psy = (int) fpsy;
1751                                         pswid = (int) fpswid;
1752                                         pshgh = (int) fpshgh;
1753                                 } 
1754
1755                                 if (lyxerr.debugging()) {
1756                                         lyxerr << "%%%%BoundingBox:"
1757                                                << psx << ' '
1758                                                << psy << ' '
1759                                                << pswid << ' '
1760                                                << pshgh << endl;
1761                                 }
1762                                 break;
1763                         }
1764                         c = 0;
1765                         delete[] p;
1766                         p = 0;
1767                 }
1768                 lastchar = c;
1769         }
1770         if (p) delete[] p;
1771         pswid -= psx;
1772         pshgh -= psy;
1773
1774 }
1775
1776
1777 void InsetFig::CallbackFig(long arg)
1778 {
1779         bool regen = false;
1780         char const * p;
1781
1782         if (lyxerr.debugging()) {
1783                 printf("Figure callback, arg %ld\n", arg);
1784         }
1785
1786         switch (arg) {
1787         case 10:
1788         case 11:
1789         case 12:        /* width type */
1790         case 13:
1791         case 14:
1792                 switch (arg - 10) {
1793                 case DEF:
1794                         twtype = DEF;
1795                         // put disable here
1796                         fl_deactivate_object(form->Width);
1797                         break;
1798                 case CM:
1799                         twtype = CM;
1800                         // put enable here
1801                         fl_activate_object(form->Width);
1802                         break;
1803                 case IN:
1804                         twtype = IN;
1805                         // put enable here
1806                         fl_activate_object(form->Width);
1807                         break;
1808                 case PER_PAGE:
1809                         twtype = PER_PAGE;
1810                         // put enable here
1811                         fl_activate_object(form->Width);
1812                         break;
1813                 case PER_COL:
1814                         twtype = PER_COL;
1815                         // put enable here
1816                         fl_activate_object(form->Width);
1817                         break;
1818                 default:
1819                         lyxerr.debug() << "Unknown type!" << endl;
1820                         break;
1821                 }
1822                 regen = true;
1823                 break;
1824         case 20:
1825         case 21:
1826         case 22:        /* height type */
1827         case 23:
1828                 switch (arg - 20) {
1829                 case DEF:
1830                         thtype = DEF;
1831                         // put disable here
1832                         fl_deactivate_object(form->Height);
1833                         break;
1834                 case CM:
1835                         thtype = CM;
1836                         // put enable here
1837                         fl_activate_object(form->Height);
1838                         break;
1839                 case IN:
1840                         thtype = IN;
1841                         // put enable here
1842                         fl_activate_object(form->Height);
1843                         break;
1844                 case PER_PAGE:
1845                         thtype = PER_PAGE;
1846                         // put enable here
1847                         fl_activate_object(form->Height);
1848                         break;
1849                 default:
1850                         lyxerr.debug() << "Unknown type!" << endl;
1851                         break;
1852                 }
1853                 regen = true;
1854                 break;
1855         case 3:
1856                 pflags = pflags & ~3;           /* wysiwyg0 */
1857                 break;
1858         case 33:
1859                 pflags = (pflags & ~3) | 1;     /* wysiwyg1 */
1860                 break;
1861         case 43:
1862                 pflags = (pflags & ~3) | 2;     /* wysiwyg2 */
1863                 break;
1864         case 63:
1865                 pflags = (pflags & ~3) | 3;     /* wysiwyg3 */
1866                 break;
1867         case 53:
1868                 pflags ^= 4;    /* frame */
1869                 break;
1870         case 54:
1871                 pflags ^= 8;    /* do translations */
1872                 break;
1873         case 70:
1874                 psubfigure = !psubfigure;       /* This is a subfigure */
1875                 break;
1876         case 2:
1877                 regen = true;           /* regenerate command */
1878                 break;
1879         case 0:                         /* browse file */
1880                 BrowseFile();
1881                 regen = true;
1882                 break;
1883         case 1:                         /* preview */
1884                 p = fl_get_input(form->EpsFile);
1885                 Preview(p);
1886                 break;
1887         case 7:                         /* apply */
1888         case 8:                         /* ok (apply and close) */
1889                 if(!current_view->buffer()->isReadonly()) {
1890                         wtype = twtype;
1891                         htype = thtype;
1892                         xwid = atof(fl_get_input(form->Width));
1893                         xhgh = atof(fl_get_input(form->Height));
1894                         angle = atof(fl_get_input(form->Angle));
1895                         p = fl_get_input(form->EpsFile);
1896                         if (p && *p) {
1897                                 string buf1 = OnlyPath(owner->getFileName());
1898                                 fname = MakeAbsPath(p, buf1);
1899                                 changedfname = true;
1900                         } else {
1901                                 if (!fname.empty()) {
1902                                         changedfname = true;
1903                                         fname.clear();
1904                                 }
1905                         }
1906                         subcaption = fl_get_input(form->Subcaption);
1907         
1908                         Regenerate();
1909                         Recompute();
1910                         /* now update inset */
1911                         if (lyxerr.debugging()) {
1912                                 lyxerr << "Update: ["
1913                                        << wid << 'x' << hgh << ']' << endl;
1914                         }
1915                         UpdateInset(this);
1916                         if (arg == 8) {
1917                                 fl_set_focus_object(form->Figure, form->OkBtn);
1918                                 fl_hide_form(form->Figure);
1919 #if FL_REVISION == 89
1920 #warning Reactivate this free_form calls
1921 #else
1922                                 fl_free_form(form->Figure);
1923                                 free(form);
1924                                 form = 0;
1925 #endif
1926                         }
1927                         break;
1928                 } //if not readonly
1929                 //  The user has already been informed about RO in ::Edit
1930                 if(arg == 7) // if 'Apply'
1931                         break;
1932                 // fall through
1933         case 9:                         /* cancel = restore and close */
1934                 fl_set_focus_object(form->Figure, form->OkBtn);
1935                 fl_hide_form(form->Figure);
1936 #if FL_REVISION == 89
1937 #warning Reactivate this free_form calls
1938 #else
1939                 fl_free_form(form->Figure);
1940                 free(form);
1941                 form = 0;
1942 #endif
1943                 break;
1944         }
1945
1946         if (regen) TempRegenerate();
1947 }
1948
1949
1950 inline void DisableFigurePanel(FD_Figure * const form)
1951 {
1952         fl_deactivate_object(form->EpsFile);
1953         fl_deactivate_object(form->Browse);
1954         fl_deactivate_object(form->Width);
1955         fl_deactivate_object(form->Height);
1956         fl_deactivate_object(form->Frame);
1957         fl_deactivate_object(form->Translations);
1958         fl_deactivate_object(form->Angle);
1959         fl_deactivate_object(form->HeightGrp);
1960         fl_deactivate_object(form->page2);
1961         fl_deactivate_object(form->Default2);
1962         fl_deactivate_object(form->cm2);
1963         fl_deactivate_object(form->in2);
1964         fl_deactivate_object(form->HeightLabel);
1965         fl_deactivate_object(form->WidthLabel);
1966         fl_deactivate_object(form->DisplayGrp);
1967         fl_deactivate_object(form->Wysiwyg3);
1968         fl_deactivate_object(form->Wysiwyg0);
1969         fl_deactivate_object(form->Wysiwyg2);
1970         fl_deactivate_object(form->Wysiwyg1);
1971         fl_deactivate_object(form->WidthGrp);
1972         fl_deactivate_object(form->Default1);
1973         fl_deactivate_object(form->cm1);
1974         fl_deactivate_object(form->in1);
1975         fl_deactivate_object(form->page1);
1976         fl_deactivate_object(form->column1);
1977         fl_deactivate_object(form->Subcaption);
1978         fl_deactivate_object(form->Subfigure);
1979         fl_deactivate_object (form->OkBtn);
1980         fl_deactivate_object (form->ApplyBtn);
1981         fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1982         fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1983 }
1984
1985
1986 inline void EnableFigurePanel(FD_Figure * const form)
1987 {
1988         fl_activate_object(form->EpsFile);
1989         fl_activate_object(form->Browse);
1990         fl_activate_object(form->Width);
1991         fl_activate_object(form->Height);
1992         fl_activate_object(form->Frame);
1993         fl_activate_object(form->Translations);
1994         fl_activate_object(form->Angle);
1995         fl_activate_object(form->HeightGrp);
1996         fl_activate_object(form->page2);
1997         fl_activate_object(form->Default2);
1998         fl_activate_object(form->cm2);
1999         fl_activate_object(form->in2);
2000         fl_activate_object(form->HeightLabel);
2001         fl_activate_object(form->WidthLabel);
2002         fl_activate_object(form->DisplayGrp);
2003         fl_activate_object(form->Wysiwyg3);
2004         fl_activate_object(form->Wysiwyg0);
2005         fl_activate_object(form->Wysiwyg2);
2006         fl_activate_object(form->Wysiwyg1);
2007         fl_activate_object(form->WidthGrp);
2008         fl_activate_object(form->Default1);
2009         fl_activate_object(form->cm1);
2010         fl_activate_object(form->in1);
2011         fl_activate_object(form->page1);
2012         fl_activate_object(form->column1);
2013         fl_activate_object(form->Subcaption);
2014         fl_activate_object(form->Subfigure);
2015         fl_activate_object (form->OkBtn);
2016         fl_activate_object (form->ApplyBtn);
2017         fl_set_object_lcol (form->OkBtn, FL_BLACK);
2018         fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
2019 }
2020
2021
2022 void InsetFig::RestoreForm()
2023 {
2024         char buf[32];
2025
2026         EnableFigurePanel(form);
2027
2028         twtype = wtype;
2029         fl_set_button(form->Default1, (wtype == 0));
2030         fl_set_button(form->cm1, (wtype == 1));
2031         fl_set_button(form->in1, (wtype == 2));
2032         fl_set_button(form->page1, (wtype == 3));
2033         fl_set_button(form->column1, (wtype == 4));
2034         if (wtype == 0) {
2035                 fl_deactivate_object(form->Width);
2036         } else {
2037                 fl_activate_object(form->Width);
2038         }
2039                 
2040         // enable and disable should be put here.
2041         thtype = htype;
2042         fl_set_button(form->Default2, (htype == 0));
2043         fl_set_button(form->cm2, (htype == 1));
2044         fl_set_button(form->in2, (htype == 2));
2045         fl_set_button(form->page2, (htype == 3));
2046         // enable and disable should be put here.
2047         if (htype == 0) {
2048                 fl_deactivate_object(form->Height);
2049         } else {
2050                 fl_activate_object(form->Height);
2051         }
2052
2053         int pflags = flags & 3;
2054         fl_set_button(form->Wysiwyg0, (pflags == 0));
2055         fl_set_button(form->Wysiwyg1, (pflags == 1));
2056         fl_set_button(form->Wysiwyg2, (pflags == 2));
2057         fl_set_button(form->Wysiwyg3, (pflags == 3));
2058         fl_set_button(form->Frame, ((flags & 4) != 0));
2059         fl_set_button(form->Translations, ((flags & 8) != 0));
2060         fl_set_button(form->Subfigure, (subfigure != 0));
2061         pflags = flags;
2062         psubfigure = subfigure;
2063         sprintf(buf, "%g", xwid);
2064         fl_set_input(form->Width, buf);
2065         sprintf(buf, "%g", xhgh);
2066         fl_set_input(form->Height, buf);
2067         sprintf(buf, "%g", angle);
2068         fl_set_input(form->Angle, buf);
2069         if (!fname.empty()){
2070                 string buf1 = OnlyPath(owner->getFileName());
2071                 string fname2 = MakeRelPath(fname, buf1);
2072                 fl_set_input(form->EpsFile, fname2.c_str());
2073         }
2074         else fl_set_input(form->EpsFile, "");
2075         fl_set_input(form->Subcaption, subcaption.c_str());
2076         if(current_view->buffer()->isReadonly()) 
2077                 DisableFigurePanel(form);
2078
2079         TempRegenerate();
2080 }
2081
2082
2083 void InsetFig::Preview(char const * p)
2084 {
2085         int pid = fork();
2086
2087         if (pid == -1) {
2088                 lyxerr << "Cannot fork process!" << endl;
2089                 return;         // error
2090         }
2091         if (pid > 0) {
2092                 addpidwait(pid);
2093                 return;         // parent process
2094         }
2095
2096         string buf1 = OnlyPath(owner->getFileName());
2097         string buf2 = MakeAbsPath(p, buf1);
2098         
2099         lyxerr << "Error during rendering "
2100                << execlp(lyxrc->view_pspic_command.c_str(),
2101                          lyxrc->view_pspic_command.c_str(),
2102                          buf2.c_str(), 0)
2103                << endl;
2104         _exit(0);
2105 }
2106
2107
2108 void InsetFig::BrowseFile()
2109 {
2110         static string current_figure_path;
2111         static int once = 0;
2112         LyXFileDlg fileDlg;
2113
2114         if (lyxerr.debugging()) {
2115                 lyxerr << "Filename: "
2116                        << owner->getFileName() << endl;
2117         }
2118         string p = fl_get_input(form->EpsFile);
2119
2120         string buf = MakeAbsPath(owner->getFileName());
2121         string buf2 = OnlyPath(buf);
2122         if (!p.empty()) {
2123                 buf = MakeAbsPath(p, buf2);
2124                 buf = OnlyPath(buf);
2125         } else {
2126           buf = OnlyPath(owner->getFileName().c_str());
2127         }
2128         
2129         // Does user clipart directory exist?
2130         string bufclip = AddName (user_lyxdir, "clipart");      
2131         FileInfo fileInfo(bufclip);
2132         if (!(fileInfo.isOK() && fileInfo.isDir()))
2133           // No - bail out to system clipart directory
2134           bufclip = AddName (system_lyxdir, "clipart"); 
2135
2136
2137         fileDlg.SetButton(0, _("Clipart"), bufclip); 
2138         fileDlg.SetButton(1, _("Document"), buf); 
2139
2140         bool error = false;
2141         do {
2142                 ProhibitInput();
2143                 if (once) {
2144                         p = fileDlg.Select(_("EPS Figure"), current_figure_path,
2145                                            "*ps", string());
2146                 } else {
2147                         p = fileDlg.Select(_("EPS Figure"), buf,
2148                                            "*ps", string());
2149                 }
2150                 AllowInput();
2151
2152                 if (p.empty()) return;
2153
2154                 buf = MakeRelPath(p, buf2);
2155                 current_figure_path = OnlyPath(p);
2156                 once = 1;
2157                 
2158                 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2159                     || contains(p, "%") || contains(p, " ")) 
2160                 {
2161                         WriteAlert(_("Filename can't contain any of these characters:"), // xgettext:no-c-format
2162                                    _("space, '#', '~', '$' or '%'.")); 
2163                         error = true;
2164                 }
2165         } while (error);
2166
2167         if (form) fl_set_input(form->EpsFile, buf.c_str());
2168 }
2169
2170
2171 void GraphicsCB(FL_OBJECT * obj, long arg)
2172 {
2173         /* obj->form contains the form */
2174
2175         if (lyxerr.debugging()) {
2176                 lyxerr << "GraphicsCB callback: " << arg << endl;
2177         }
2178
2179         /* find inset we were reacting to */
2180         for (int i = 0; i < figinsref; ++i)
2181                 if (figures[i]->inset->form && figures[i]->inset->form->Figure
2182                     == obj->form) {
2183             
2184                         if (lyxerr.debugging()) {
2185                                 lyxerr << "Calling back figure " << i << endl;
2186                         }
2187                         figures[i]->inset->CallbackFig(arg);
2188                         return;
2189                 }
2190 }
2191
2192
2193 void HideFiguresPopups()
2194 {
2195         for (int i = 0; i < figinsref; ++i)
2196                 if (figures[i]->inset->form 
2197                     && figures[i]->inset->form->Figure->visible) {
2198                         if (lyxerr.debugging()) {
2199                                 lyxerr << "Hiding figure " << i << endl;
2200                         }
2201                         // hide and free the form
2202                         figures[i]->inset->CallbackFig(9);
2203                 }
2204 }