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