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