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