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