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