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