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