]> git.lyx.org Git - lyx.git/blob - src/insets/figinset.C
4a798fc42d09aae9242efeda32e3aed2271bce91
[lyx.git] / src / insets / figinset.C
1 /*
2  *      figinset.C - part of LyX project
3  */
4
5 extern int      reverse_video;
6 extern long int background_pixels;
7
8 /*  Rework of path-handling (Matthias 04.07.1996 )
9  * ------------------------------------------------
10  *   figinsets keep an absolute path to the eps-file.
11  *   For the user alway a relative path appears
12  *   (in lyx-file, latex-file and edit-popup).
13  *   To calculate this relative path the path to the
14  *   document where the figinset is in is needed. 
15  *   This is done by a reference to the buffer, called
16  *   figinset::cbuffer. To be up to date the cbuffer
17  *   is sometimes set to the current buffer 
18  *   bufferlist.current(), when it can be assumed that
19  *   this operation happens in the current buffer. 
20  *   This is true for InsetFig::Edit(...), 
21  *   InsetFig::InsetFig(...), InsetFig::Read(...),
22  *   InsetFig::Write and InsetFig::Latex(...).
23  *   Therefore the bufferlist has to make sure that
24  *   during these operations bufferlist.current() 
25  *   returns the buffer where the figinsets are in.
26  *   This made few changes in buffer.C necessary.
27  *
28  * The above is not totally valid anymore. (Lgb)
29  */
30
31
32 #include <config.h>
33
34 #include <unistd.h>
35 #include <csignal>
36 #include <sys/wait.h>
37
38 #include FORMS_H_LOCATION
39 #include <cstdlib>
40 #include <cctype>
41 #include <cmath>
42 #include <fstream>
43 #include <queue>
44 #include <list>
45 #include <algorithm>
46 using std::ofstream;
47 using std::ifstream;
48 using std::queue;
49 using std::list;
50 using std::find;
51 using std::flush;
52
53 #include "figinset.h"
54 #include "lyx.h"
55 #include "lyx_main.h"
56 #include "buffer.h"
57 #include "filedlg.h"
58 #include "support/filetools.h"
59 #include "LyXView.h" // just because of form_main
60 #include "debug.h"
61 #include "lyxdraw.h"
62 #include "LaTeXFeatures.h"
63 #include "lyxrc.h"
64 #include "gettext.h"
65 #include "lyx_gui_misc.h" // CancelCloseBoxCB
66 #include "support/FileInfo.h"
67 #include "support/lyxlib.h"
68 #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 (figure && figure->data && figure->data->bitmap &&
1105             !figure->data->reading && !figure->data->broken) {
1106                 // draw the bitmap
1107                 pain.pixmap(int(x + 1), baseline - hgh,
1108                             wid, hgh, figure->data->bitmap);
1109
1110                 if (flags & 4)
1111                         pain.rectangle(int(x), baseline - hgh - 1,
1112                                        wid + 1, hgh + 1);
1113                 
1114         } else {
1115                 char * msg = 0;
1116                 // draw frame
1117                 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1118
1119                 if (figure && figure->data) {
1120                         if (figure->data->broken)  msg = _("[render error]");
1121                         else if (figure->data->reading) msg = _("[rendering ... ]");
1122                 } else 
1123                         if (fname.empty()) msg = _("[no file]");
1124                         else if ((flags & 3) == 0) msg = _("[not displayed]");
1125                         else if (lyxrc->ps_command.empty()) msg = _("[no ghostscript]");
1126                 
1127                 if (!msg) msg = _("[unknown error]");
1128                 
1129                 font.setFamily(LyXFont::SANS_FAMILY);
1130                 font.setSize(LyXFont::SIZE_FOOTNOTE);
1131                 string justname = OnlyFilename (fname);
1132                 pain.text(int(x + 8), baseline - font.maxAscent() - 4,
1133                           justname, font);
1134                 
1135                 font.setSize(LyXFont::SIZE_TINY);
1136                 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1137         }
1138         x += width(pain, font);    // ?
1139 }
1140 #else
1141 void InsetFig::Draw(LyXFont font, LyXScreen & scr, int baseline, float & x)
1142 {
1143         if (bitmap_waiting) getbitmaps();
1144
1145         // I wish that I didn't have to use this
1146         // but the figinset code is so complicated so
1147         // I don't want to fiddle with it now.
1148         unsigned long pm = scr.getForeground();
1149         
1150         if (figure && figure->data && figure->data->bitmap &&
1151             !figure->data->reading && !figure->data->broken) {
1152                 // draw the bitmap
1153                 XCopyArea(fl_display, figure->data->bitmap, pm, local_gc_copy,
1154                           0, 0, wid, hgh, int(x+1), baseline-hgh);
1155                 XFlush(fl_display);
1156                 if (flags & 4) XDrawRectangle(fl_display, pm, local_gc_copy,
1157                                               int(x), baseline - hgh - 1,
1158                                               wid+1, hgh+1);
1159         } else {
1160                 char * msg = 0;
1161                 // draw frame
1162                 XDrawRectangle(fl_display, pm, local_gc_copy,
1163                                int(x),
1164                                baseline - hgh - 1, wid+1, hgh+1);
1165                 if (figure && figure->data) {
1166                         if (figure->data->broken)  msg = _("[render error]");
1167                         else if (figure->data->reading) msg = _("[rendering ... ]");
1168                 } else 
1169                         if (fname.empty()) msg = _("[no file]");
1170                         else if ((flags & 3) == 0) msg = _("[not displayed]");
1171                         else if (lyxrc->ps_command.empty()) msg = _("[no ghostscript]");
1172
1173                 if (!msg) msg = _("[unknown error]");
1174                 
1175                 font.setFamily (LyXFont::SANS_FAMILY);
1176                 font.setSize (LyXFont::SIZE_FOOTNOTE);
1177                 string justname = OnlyFilename (fname);
1178                 font.drawString(justname, pm,
1179                                 baseline - font.maxAscent() - 4,
1180                                 int(x) + 8);
1181                 font.setSize (LyXFont::SIZE_TINY);
1182                 font.drawText (msg, strlen(msg), pm,
1183                                baseline - 4,
1184                                int(x) + 8);
1185
1186         }
1187         x += Width(font);    // ?
1188 }
1189 #endif
1190
1191
1192 void InsetFig::Write(ostream & os)
1193 {
1194         Regenerate();
1195         os << "Figure size " << wid << " " << hgh << "\n";
1196         if (!fname.empty()) {
1197                 string buf1 = OnlyPath(owner->fileName());
1198                 string fname2 = MakeRelPath(fname, buf1);
1199                 os << "file " << fname2 << "\n";
1200         }
1201         if (!subcaption.empty())
1202                 os << "subcaption " << subcaption << "\n";
1203         if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1204         if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1205         if (angle != 0) os << "angle " << angle << "\n";
1206         os << "flags " << flags << "\n";
1207         if (subfigure) os << "subfigure\n";
1208 }
1209
1210
1211 void InsetFig::Read(LyXLex & lex)
1212 {
1213         string buf;
1214         bool finished = false;
1215         
1216         while (lex.IsOK() && !finished) {
1217                 lex.next();
1218
1219                 string const token = lex.GetString();
1220                 lyxerr.debug() << "Token: " << token << endl;
1221                 
1222                 if (token.empty())
1223                         continue;
1224                 else if (token == "\\end_inset") {
1225                         finished = true;
1226                 } else if (token == "file") {
1227                         if (lex.next()) {
1228                                 buf = lex.GetString();
1229                                 string buf1 = OnlyPath(owner->fileName());
1230                                 fname = MakeAbsPath(buf, buf1);
1231                                 changedfname = true;
1232                         }
1233                 } else if (token == "extra") {
1234                         if (lex.next());
1235                         // kept for backwards compability. Delete in 0.13.x
1236                 } else if (token == "subcaption") {
1237                         if (lex.EatLine())
1238                                 subcaption = lex.GetString();
1239                 } else if (token == "label") {
1240                         if (lex.next());
1241                         // kept for backwards compability. Delete in 0.13.x
1242                 } else if (token == "angle") {
1243                         if (lex.next())
1244                                 angle = lex.GetFloat();
1245                 } else if (token == "size") {
1246                         if (lex.next())
1247                                 wid = lex.GetInteger();
1248                         if (lex.next())
1249                                 hgh = lex.GetInteger();
1250                 } else if (token == "flags") {
1251                         if (lex.next())
1252                                 flags = pflags = lex.GetInteger();
1253                 } else if (token == "subfigure") {
1254                         subfigure = psubfigure = true;
1255                 } else if (token == "width") {
1256                         int typ = 0;
1257                         if (lex.next())
1258                                 typ = lex.GetInteger();
1259                         if (lex.next())
1260                                 xwid = lex.GetFloat();
1261                         switch (typ) {
1262                         case DEF: wtype = DEF; break;
1263                         case CM: wtype = CM; break;
1264                         case IN: wtype = IN; break;
1265                         case PER_PAGE: wtype = PER_PAGE; break;
1266                         case PER_COL: wtype = PER_COL; break;
1267                         default:
1268                                 lyxerr.debug() << "Unknown type!" << endl;
1269                                 break;
1270                         }
1271                         twtype = wtype;
1272                 } else if (token == "height") {
1273                         int typ = 0;
1274                         if (lex.next())
1275                                 typ = lex.GetInteger();
1276                         if (lex.next())
1277                                 xhgh = lex.GetFloat();
1278                         switch (typ) {
1279                         case DEF: htype = DEF; break;
1280                         case CM: htype = CM; break;
1281                         case IN: htype = IN; break;
1282                         case PER_PAGE: htype = PER_PAGE; break;
1283                         default:
1284                                 lyxerr.debug() << "Unknown type!" << endl;
1285                                 break;
1286                         }
1287                         thtype = htype;
1288                 }
1289         }
1290         Regenerate();
1291         Recompute();
1292 }
1293
1294
1295 int InsetFig::Latex(ostream & os, signed char /* fragile*/ )
1296 {
1297         Regenerate();
1298         if (!cmd.empty()) os << cmd << " ";
1299         return 0;
1300 }
1301
1302
1303 int InsetFig::Latex(string & file, signed char /* fragile*/ )
1304 {
1305         Regenerate();
1306         file += cmd + ' ';
1307         return 0;
1308 }
1309
1310
1311 int InsetFig::Linuxdoc(string &/*file*/)
1312 {
1313         return 0;
1314 }
1315
1316
1317 int InsetFig::DocBook(string & file)
1318 {
1319         string figurename = fname;
1320
1321         if(suffixIs(figurename, ".eps"))
1322                 figurename.erase(fname.length() - 5);
1323
1324         file += "@<graphic fileref=\"" + figurename + "\"></graphic>";
1325         return 0;
1326 }
1327
1328
1329 void InsetFig::Validate(LaTeXFeatures & features) const
1330 {
1331         features.graphics = true;
1332         if (subfigure) features.subfigure = true;
1333 }
1334
1335
1336 unsigned char InsetFig::Editable() const
1337 {
1338         return 1;
1339 }
1340
1341
1342 bool InsetFig::Deletable() const
1343 {
1344         return false;
1345 }
1346
1347
1348 void InsetFig::Edit(int, int)
1349 {
1350         lyxerr.debug() << "Editing InsetFig." << endl;
1351         Regenerate();
1352
1353         // We should have RO-versions of the form instead.
1354         // The actual prevention of altering a readonly doc
1355         // is done in CallbackFig()
1356         if(current_view->buffer()->isReadonly()) 
1357                 WarnReadonly(current_view->buffer()->fileName());
1358
1359         if (!form) {
1360                 form = create_form_Figure();
1361                 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1362                 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1363                 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1364                 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1365         }
1366         RestoreForm();
1367         if (form->Figure->visible) {
1368                 fl_raise_form(form->Figure);
1369         } else {
1370                 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1371                              FL_FULLBORDER, _("Figure"));
1372         }
1373 }
1374
1375
1376 Inset * InsetFig::Clone() const
1377 {
1378         InsetFig * tmp = new InsetFig(100, 100, owner);
1379
1380         if (lyxerr.debugging()) {
1381                 lyxerr << "Clone Figure: buffer:["
1382                        << current_view->buffer()
1383                        << "], cbuffer:[xx]" << endl;
1384         }
1385
1386         tmp->wid = wid;
1387         tmp->hgh = hgh;
1388         tmp->raw_wid = raw_wid;
1389         tmp->raw_hgh = raw_hgh;
1390         tmp->angle = angle;
1391         tmp->xwid = xwid;
1392         tmp->xhgh = xhgh;
1393         tmp->flags = flags;
1394         tmp->pflags = pflags;
1395         tmp->subfigure = subfigure;
1396         tmp->psubfigure = psubfigure;
1397         tmp->wtype = wtype;
1398         tmp->htype = htype;
1399         tmp->psx = psx;
1400         tmp->psy = psy;
1401         tmp->pswid = pswid;
1402         tmp->pshgh = pshgh;
1403         tmp->fname = fname;
1404         if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) { 
1405                 // do not display if there is
1406                 // "do not display" chosen (Matthias 260696)
1407                 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1408                                                pswid, pshgh, raw_wid, raw_hgh,
1409                                                angle, flags & (3|8));
1410         } else tmp->figure->data = 0;
1411         tmp->subcaption = subcaption;
1412         tmp->changedfname = false;
1413         tmp->owner = owner;
1414         tmp->Regenerate();
1415         return tmp;
1416 }
1417
1418
1419 Inset::Code InsetFig::LyxCode() const
1420 {
1421         return Inset::GRAPHICS_CODE;
1422 }
1423
1424
1425 void InsetFig::Regenerate()
1426 {
1427         string cmdbuf;
1428         string resizeW, resizeH;
1429         string rotate, recmd;
1430
1431         if (fname.empty()) {
1432                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1433                 cmd += _("empty figure path");
1434                 cmd += '}';
1435                 return;
1436         }
1437
1438         string buf1 = OnlyPath(owner->fileName());
1439         string fname2 = MakeRelPath(fname, buf1);
1440
1441         string gcmd = "\\includegraphics{" + fname2 + '}';
1442         
1443         switch (wtype) {
1444         case DEF:
1445                 break;
1446         case CM:{// \resizebox*{h-length}{v-length}{text}
1447                 char buf[10];
1448                 sprintf(buf, "%g", xwid); // should find better
1449                 resizeW = buf;
1450                 resizeW += "cm";
1451                 break;
1452         }
1453         case IN: {
1454                 char buf[10];
1455                 sprintf(buf, "%g", xwid);
1456                 resizeW = buf;
1457                 resizeW += "in";
1458                 break;
1459         }
1460         case PER_PAGE:{
1461                 char buf[10];
1462                 sprintf(buf, "%g", xwid/100);
1463                 resizeW = buf;
1464                 resizeW += "\\textwidth";
1465                 break;
1466         }
1467         case PER_COL:{
1468                 char buf[10];
1469                 sprintf(buf, "%g", xwid/100);
1470                 resizeW = buf;
1471                 resizeW += "\\columnwidth";
1472                 break;
1473         }
1474         }
1475
1476         switch (htype) {
1477         case DEF:
1478                 break;
1479         case CM: {
1480                 char buf[10];
1481                 sprintf(buf, "%g", xhgh);
1482                 resizeH = buf;
1483                 resizeH += "cm";
1484                 break;
1485         }
1486         case IN:{
1487                 char buf[10];
1488                 sprintf(buf, "%g", xhgh);
1489                 resizeH = buf;
1490                 resizeH += "in";
1491                 break;
1492         }
1493         case PER_PAGE: {
1494                 char buf[10];
1495                 sprintf(buf, "%g", xhgh/100);
1496                 resizeH = buf;
1497                 resizeH += "\\textheight";
1498                 break;
1499         }
1500         case PER_COL: {
1501                 // Doesn't occur; case exists to suppress compiler warnings.
1502                 break;
1503         }
1504         }
1505
1506         if (!resizeW.empty() || !resizeH.empty()) {
1507                 recmd = "\\resizebox*{";
1508                 if (!resizeW.empty())
1509                         recmd += resizeW;
1510                 else
1511                         recmd += '!';
1512                 recmd += "}{";
1513                 if (!resizeH.empty())
1514                         recmd += resizeH;
1515                 else
1516                         recmd += '!';
1517                 recmd += "}{";
1518         }
1519         
1520         
1521         if (angle != 0) {
1522                 char buf[10];
1523                 sprintf(buf, "%g", angle);
1524                 // \rotatebox{angle}{text}
1525                 rotate = "\\rotatebox{";
1526                 rotate += buf;
1527                 rotate += "}{";
1528         }
1529
1530         cmdbuf = recmd;
1531         cmdbuf += rotate;
1532         cmdbuf += gcmd;
1533         if (!rotate.empty()) cmdbuf += '}';
1534         if (!recmd.empty()) cmdbuf += '}';
1535         if (subfigure) {
1536                 if (!subcaption.empty())
1537                         cmdbuf = "\\subfigure[" + subcaption +
1538                                 "]{" + cmdbuf + "}";
1539                 else
1540                         cmdbuf = "\\subfigure{" + cmdbuf + "}";
1541         }
1542         
1543         cmd = cmdbuf;
1544 }
1545
1546
1547 void InsetFig::TempRegenerate()
1548 {
1549         string cmdbuf;
1550         string resizeW, resizeH;
1551         string rotate, recmd;
1552         
1553         char const * tfname = fl_get_input(form->EpsFile);
1554         string tsubcap = fl_get_input(form->Subcaption);
1555         float tangle = atof(fl_get_input(form->Angle));
1556         float txwid = atof(fl_get_input(form->Width));
1557         float txhgh = atof(fl_get_input(form->Height));
1558
1559         if (!tfname || !*tfname) {
1560                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1561                 cmd += _("empty figure path");
1562                 cmd += '}';
1563                 return;
1564         }
1565
1566         string buf1 = OnlyPath(owner->fileName());
1567         string fname2 = MakeRelPath(tfname, buf1);
1568         // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1569         string gcmd = "\\includegraphics{" + fname2 + '}';
1570         
1571         switch (twtype) {
1572         case DEF:
1573                 break;
1574         case CM: {// \resizebox*{h-length}{v-length}{text}
1575                 char buf[10];
1576                 sprintf(buf, "%g", txwid); // should find better
1577                 resizeW = buf;
1578                 resizeW += "cm";
1579                 break;
1580         }
1581         case IN: {
1582                 char buf[10];
1583                 sprintf(buf, "%g", txwid);
1584                 resizeW = buf;
1585                 resizeW += "in";
1586                 break;
1587         }
1588         case PER_PAGE: {
1589                 char buf[10];
1590                 sprintf(buf, "%g", txwid/100);
1591                 resizeW = buf;
1592                 resizeW += "\\textwidth";
1593                 break;
1594         }
1595         case PER_COL: {
1596                 char buf[10];
1597                 sprintf(buf, "%g", txwid/100);
1598                 resizeW = buf;
1599                 resizeW += "\\columnwidth";
1600                 break;
1601         }
1602         }
1603
1604         switch (thtype) {
1605         case DEF:
1606                 break;
1607         case CM: {
1608                 char buf[10];
1609                 sprintf(buf, "%g", txhgh);
1610                 resizeH = buf;
1611                 resizeH += "cm";
1612                 break;
1613         }
1614         case IN: {
1615                 char buf[10];
1616                 sprintf(buf, "%g", txhgh);
1617                 resizeH = buf;
1618                 resizeH += "in";
1619                 break;
1620         }
1621         case PER_PAGE: {
1622                 char buf[10];
1623                 sprintf(buf, "%g", txhgh/100);
1624                 resizeH = buf;
1625                 resizeH += "\\textheight";
1626                 break;
1627         }
1628         case PER_COL: {
1629                 // Doesn't occur; case exists to suppress compiler warnings.
1630                 break;
1631         }
1632         }
1633
1634         // \resizebox*{h-length}{v-length}{text}
1635         if (!resizeW.empty() || !resizeH.empty()) {
1636                 recmd = "\\resizebox*{";
1637                 if (!resizeW.empty())
1638                         recmd += resizeW;
1639                 else
1640                         recmd += '!';
1641                 recmd += "}{";
1642                 if (!resizeH.empty())
1643                         recmd += resizeH;
1644                 else
1645                         recmd += '!';
1646                 recmd += "}{";
1647         }
1648         
1649         if (tangle != 0) {
1650                 char buf[10];
1651                 sprintf(buf, "%g", tangle);
1652                 // \rotatebox{angle}{text}
1653                 rotate = "\\rotatebox{";
1654                 rotate += buf;
1655                 rotate += "}{";
1656         }
1657
1658         cmdbuf = recmd;
1659         cmdbuf += rotate;
1660         cmdbuf += gcmd;
1661         if (!rotate.empty()) cmdbuf += '}';
1662         if (!recmd.empty()) cmdbuf += '}';
1663         if (psubfigure && !tsubcap.empty()) {
1664                 cmdbuf = string("\\subfigure{") + tsubcap
1665                         + string("}{") + cmdbuf + "}";
1666         }
1667 }
1668
1669
1670 void InsetFig::Recompute()
1671 {
1672         bool changed = changedfname;
1673         int newx, newy, nraw_x, nraw_y;
1674
1675         if (changed) GetPSSizes();
1676
1677         float sin_a = sin (angle / DEG2PI);  /* rotation; H. Zeller 021296 */
1678         float cos_a = cos (angle / DEG2PI);
1679         int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1680         int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1681
1682         /* now recompute wid and hgh, and if that is changed, set changed */
1683         /* this depends on chosen size of the picture and its bbox */
1684         // This will be redone in 0.13 ... (hen)
1685         if (!fname.empty()) {
1686                 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1687
1688                 newx = frame_wid;
1689                 newy = frame_hgh;
1690                 switch (wtype) {
1691                 case DEF:
1692                         break;
1693                 case CM:        /* cm */
1694                         newx = int(28.346 * xwid);
1695                         break;
1696                 case IN: /* in */
1697                         newx = int(72 * xwid);
1698                         break;
1699                 case PER_PAGE:  /* % of page */
1700                         newx = int(5.95 * xwid);
1701                         break;
1702                 case PER_COL:   /* % of col */
1703                         newx = int(2.975 * xwid);
1704                         break;
1705                 }
1706                 
1707                 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1708                 
1709                 switch (htype) {
1710                 case DEF:
1711                         //lyxerr << "This should not happen!" << endl;
1712                         break;
1713                 case CM:        /* cm */
1714                         newy = int(28.346 * xhgh);
1715                         break;
1716                 case IN: /* in */
1717                         newy = int(72 * xhgh);
1718                         break;
1719                 case PER_PAGE:  /* % of page */
1720                         newy = int(8.42 * xhgh);
1721                         break;
1722                 case PER_COL: 
1723                         // Doesn't occur; case exists to suppress
1724                         // compiler warnings.  
1725                         break;
1726                 }
1727                 if (htype && !wtype && frame_hgh)
1728                         newx = newy*frame_wid/frame_hgh;
1729         } else {
1730                 newx = wid;
1731                 newy = hgh;
1732         }
1733
1734         if (frame_wid == 0)
1735                 nraw_x = 5;
1736         else
1737                 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1738
1739         if (frame_hgh == 0)
1740                 nraw_y = 5;
1741         else
1742                 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1743
1744         // cannot be zero, actually, set it to some minimum, so its clickable
1745         if (newx < 5) newx = 5;
1746         if (newy < 5) newy = 5;
1747
1748         if (newx   != wid     || newy   != hgh     || 
1749             nraw_x != raw_wid || nraw_y != raw_hgh ||
1750             flags  != pflags  || subfigure != psubfigure) 
1751                 changed = true;
1752        
1753         raw_wid = nraw_x;
1754         raw_hgh = nraw_y;
1755         wid = newx;
1756         hgh = newy;
1757         flags = pflags;
1758         subfigure = psubfigure;
1759
1760         if (changed) {
1761                 figdata * pf = figure->data;
1762
1763                 // get new data
1764                 if (!fname.empty() && (flags & 3)
1765                     && !lyxrc->ps_command.empty()) {
1766                         // do not display if there is "do not display"
1767                         // chosen (Matthias 260696)
1768                         figure->data = getfigdata(wid, hgh, fname,
1769                                                   psx, psy, pswid, pshgh,
1770                                                   raw_wid, raw_hgh,
1771                                                   angle, flags & (3|8));
1772                 } else figure->data = 0;
1773
1774                 // free the old data
1775                 if (pf) freefigdata(pf);
1776         }
1777
1778         changedfname = false;
1779 }
1780
1781
1782 void InsetFig::GetPSSizes()
1783 {
1784         /* get %%BoundingBox: from postscript file */
1785         
1786         /* defaults to associated size
1787          * ..just in case the PS-file is not readable (Henner, 24-Aug-97) 
1788          */
1789         psx = 0;
1790         psy = 0;
1791         pswid = wid;
1792         pshgh = hgh;
1793
1794         if (fname.empty()) return;
1795         string p;
1796         ifstream ifs(fname.c_str());
1797
1798         if (!ifs) return;       // file not found !!!!
1799
1800         /* defaults to A4 page */
1801         psx = 0;
1802         psy = 0;
1803         pswid = 595;
1804         pshgh = 842;
1805
1806         char lastchar = 0; ifs.get(lastchar);
1807         for (;;) {
1808                 char c = 0; ifs.get(c);
1809                 if (ifs.eof()) {
1810                         lyxerr.debug() << "End of (E)PS file reached and"
1811                                 " no BoundingBox!" << endl;
1812                         break;
1813                 }
1814                 if (c == '%' && lastchar == '%') {
1815                         p = NextToken(ifs);
1816                         if (p.empty()) break;
1817                         // we should not use this, with it we cannot
1818                         // discover bounding box and end of file.
1819                         //if (strcmp(p, "EndComments") == 0) break;
1820                         lyxerr.debug() << "Token: `" << p << "'" << endl;
1821                         if (p == "BoundingBox:") {
1822                                 float fpsx, fpsy, fpswid, fpshgh;
1823                                 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1824                                         psx = int(fpsx);
1825                                         psy = int(fpsy);
1826                                         pswid = int(fpswid);
1827                                         pshgh = int(fpshgh);
1828                                 }
1829                                 if (lyxerr.debugging()) {
1830                                         lyxerr << "%%%%BoundingBox:"
1831                                                << psx << ' '
1832                                                << psy << ' '
1833                                                << pswid << ' '
1834                                                << pshgh << endl;
1835                                 }
1836                                 break;
1837                         }
1838                         c = 0;
1839                 }
1840                 lastchar = c;
1841         }
1842         pswid -= psx;
1843         pshgh -= psy;
1844
1845 }
1846
1847
1848 void InsetFig::CallbackFig(long arg)
1849 {
1850         bool regen = false;
1851         char const * p;
1852
1853         if (lyxerr.debugging()) {
1854                 lyxerr << "Figure callback, arg " << arg << endl;
1855         }
1856
1857         switch (arg) {
1858         case 10:
1859         case 11:
1860         case 12:        /* width type */
1861         case 13:
1862         case 14:
1863                 switch (arg - 10) {
1864                 case DEF:
1865                         twtype = DEF;
1866                         // put disable here
1867                         fl_deactivate_object(form->Width);
1868                         break;
1869                 case CM:
1870                         twtype = CM;
1871                         // put enable here
1872                         fl_activate_object(form->Width);
1873                         break;
1874                 case IN:
1875                         twtype = IN;
1876                         // put enable here
1877                         fl_activate_object(form->Width);
1878                         break;
1879                 case PER_PAGE:
1880                         twtype = PER_PAGE;
1881                         // put enable here
1882                         fl_activate_object(form->Width);
1883                         break;
1884                 case PER_COL:
1885                         twtype = PER_COL;
1886                         // put enable here
1887                         fl_activate_object(form->Width);
1888                         break;
1889                 default:
1890                         lyxerr.debug() << "Unknown type!" << endl;
1891                         break;
1892                 }
1893                 regen = true;
1894                 break;
1895         case 20:
1896         case 21:
1897         case 22:        /* height type */
1898         case 23:
1899                 switch (arg - 20) {
1900                 case DEF:
1901                         thtype = DEF;
1902                         // put disable here
1903                         fl_deactivate_object(form->Height);
1904                         break;
1905                 case CM:
1906                         thtype = CM;
1907                         // put enable here
1908                         fl_activate_object(form->Height);
1909                         break;
1910                 case IN:
1911                         thtype = IN;
1912                         // put enable here
1913                         fl_activate_object(form->Height);
1914                         break;
1915                 case PER_PAGE:
1916                         thtype = PER_PAGE;
1917                         // put enable here
1918                         fl_activate_object(form->Height);
1919                         break;
1920                 default:
1921                         lyxerr.debug() << "Unknown type!" << endl;
1922                         break;
1923                 }
1924                 regen = true;
1925                 break;
1926         case 3:
1927                 pflags = pflags & ~3;           /* wysiwyg0 */
1928                 break;
1929         case 33:
1930                 pflags = (pflags & ~3) | 1;     /* wysiwyg1 */
1931                 break;
1932         case 43:
1933                 pflags = (pflags & ~3) | 2;     /* wysiwyg2 */
1934                 break;
1935         case 63:
1936                 pflags = (pflags & ~3) | 3;     /* wysiwyg3 */
1937                 break;
1938         case 53:
1939                 pflags ^= 4;    /* frame */
1940                 break;
1941         case 54:
1942                 pflags ^= 8;    /* do translations */
1943                 break;
1944         case 70:
1945                 psubfigure = !psubfigure;       /* This is a subfigure */
1946                 break;
1947         case 2:
1948                 regen = true;           /* regenerate command */
1949                 break;
1950         case 0:                         /* browse file */
1951                 BrowseFile();
1952                 regen = true;
1953                 break;
1954         case 1:                         /* preview */
1955                 p = fl_get_input(form->EpsFile);
1956                 Preview(p);
1957                 break;
1958         case 7:                         /* apply */
1959         case 8:                         /* ok (apply and close) */
1960                 if(!current_view->buffer()->isReadonly()) {
1961                         wtype = twtype;
1962                         htype = thtype;
1963                         xwid = atof(fl_get_input(form->Width));
1964                         xhgh = atof(fl_get_input(form->Height));
1965                         angle = atof(fl_get_input(form->Angle));
1966                         p = fl_get_input(form->EpsFile);
1967                         if (p && *p) {
1968                                 string buf1 = OnlyPath(owner->fileName());
1969                                 fname = MakeAbsPath(p, buf1);
1970                                 changedfname = true;
1971                         } else {
1972                                 if (!fname.empty()) {
1973                                         changedfname = true;
1974                                         fname.clear();
1975                                 }
1976                         }
1977                         subcaption = fl_get_input(form->Subcaption);
1978         
1979                         Regenerate();
1980                         Recompute();
1981                         /* now update inset */
1982                         if (lyxerr.debugging()) {
1983                                 lyxerr << "Update: ["
1984                                        << wid << 'x' << hgh << ']' << endl;
1985                         }
1986                         UpdateInset(current_view, this);
1987                         if (arg == 8) {
1988                                 fl_set_focus_object(form->Figure, form->OkBtn);
1989                                 fl_hide_form(form->Figure);
1990 #if FL_REVISION == 89
1991 #warning Reactivate this free_form calls
1992 #else
1993                                 fl_free_form(form->Figure);
1994                                 free(form); // Why free?
1995                                 form = 0;
1996 #endif
1997                         }
1998                         break;
1999                 } //if not readonly
2000                 //  The user has already been informed about RO in ::Edit
2001                 if(arg == 7) // if 'Apply'
2002                         break;
2003                 // fall through
2004         case 9:                         /* cancel = restore and close */
2005                 fl_set_focus_object(form->Figure, form->OkBtn);
2006                 fl_hide_form(form->Figure);
2007 #if FL_REVISION == 89
2008 #warning Reactivate this free_form calls
2009 #warning Jug, is this still a problem?
2010 #else
2011                 fl_free_form(form->Figure);
2012                 free(form); // Why free?
2013                 form = 0;
2014 #endif
2015                 break;
2016         }
2017
2018         if (regen) TempRegenerate();
2019 }
2020
2021
2022 inline void DisableFigurePanel(FD_Figure * const form)
2023 {
2024         fl_deactivate_object(form->EpsFile);
2025         fl_deactivate_object(form->Browse);
2026         fl_deactivate_object(form->Width);
2027         fl_deactivate_object(form->Height);
2028         fl_deactivate_object(form->Frame);
2029         fl_deactivate_object(form->Translations);
2030         fl_deactivate_object(form->Angle);
2031         fl_deactivate_object(form->HeightGrp);
2032         fl_deactivate_object(form->page2);
2033         fl_deactivate_object(form->Default2);
2034         fl_deactivate_object(form->cm2);
2035         fl_deactivate_object(form->in2);
2036         fl_deactivate_object(form->HeightLabel);
2037         fl_deactivate_object(form->WidthLabel);
2038         fl_deactivate_object(form->DisplayGrp);
2039         fl_deactivate_object(form->Wysiwyg3);
2040         fl_deactivate_object(form->Wysiwyg0);
2041         fl_deactivate_object(form->Wysiwyg2);
2042         fl_deactivate_object(form->Wysiwyg1);
2043         fl_deactivate_object(form->WidthGrp);
2044         fl_deactivate_object(form->Default1);
2045         fl_deactivate_object(form->cm1);
2046         fl_deactivate_object(form->in1);
2047         fl_deactivate_object(form->page1);
2048         fl_deactivate_object(form->column1);
2049         fl_deactivate_object(form->Subcaption);
2050         fl_deactivate_object(form->Subfigure);
2051         fl_deactivate_object (form->OkBtn);
2052         fl_deactivate_object (form->ApplyBtn);
2053         fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
2054         fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
2055 }
2056
2057
2058 inline void EnableFigurePanel(FD_Figure * const form)
2059 {
2060         fl_activate_object(form->EpsFile);
2061         fl_activate_object(form->Browse);
2062         fl_activate_object(form->Width);
2063         fl_activate_object(form->Height);
2064         fl_activate_object(form->Frame);
2065         fl_activate_object(form->Translations);
2066         fl_activate_object(form->Angle);
2067         fl_activate_object(form->HeightGrp);
2068         fl_activate_object(form->page2);
2069         fl_activate_object(form->Default2);
2070         fl_activate_object(form->cm2);
2071         fl_activate_object(form->in2);
2072         fl_activate_object(form->HeightLabel);
2073         fl_activate_object(form->WidthLabel);
2074         fl_activate_object(form->DisplayGrp);
2075         fl_activate_object(form->Wysiwyg3);
2076         fl_activate_object(form->Wysiwyg0);
2077         fl_activate_object(form->Wysiwyg2);
2078         fl_activate_object(form->Wysiwyg1);
2079         fl_activate_object(form->WidthGrp);
2080         fl_activate_object(form->Default1);
2081         fl_activate_object(form->cm1);
2082         fl_activate_object(form->in1);
2083         fl_activate_object(form->page1);
2084         fl_activate_object(form->column1);
2085         fl_activate_object(form->Subcaption);
2086         fl_activate_object(form->Subfigure);
2087         fl_activate_object (form->OkBtn);
2088         fl_activate_object (form->ApplyBtn);
2089         fl_set_object_lcol (form->OkBtn, FL_BLACK);
2090         fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
2091 }
2092
2093
2094 void InsetFig::RestoreForm()
2095 {
2096         char buf[32];
2097
2098         EnableFigurePanel(form);
2099
2100         twtype = wtype;
2101         fl_set_button(form->Default1, (wtype == 0));
2102         fl_set_button(form->cm1, (wtype == 1));
2103         fl_set_button(form->in1, (wtype == 2));
2104         fl_set_button(form->page1, (wtype == 3));
2105         fl_set_button(form->column1, (wtype == 4));
2106         if (wtype == 0) {
2107                 fl_deactivate_object(form->Width);
2108         } else {
2109                 fl_activate_object(form->Width);
2110         }
2111                 
2112         // enable and disable should be put here.
2113         thtype = htype;
2114         fl_set_button(form->Default2, (htype == 0));
2115         fl_set_button(form->cm2, (htype == 1));
2116         fl_set_button(form->in2, (htype == 2));
2117         fl_set_button(form->page2, (htype == 3));
2118         // enable and disable should be put here.
2119         if (htype == 0) {
2120                 fl_deactivate_object(form->Height);
2121         } else {
2122                 fl_activate_object(form->Height);
2123         }
2124
2125         int pflags = flags & 3;
2126         fl_set_button(form->Wysiwyg0, (pflags == 0));
2127         fl_set_button(form->Wysiwyg1, (pflags == 1));
2128         fl_set_button(form->Wysiwyg2, (pflags == 2));
2129         fl_set_button(form->Wysiwyg3, (pflags == 3));
2130         fl_set_button(form->Frame, ((flags & 4) != 0));
2131         fl_set_button(form->Translations, ((flags & 8) != 0));
2132         fl_set_button(form->Subfigure, (subfigure != 0));
2133         pflags = flags;
2134         psubfigure = subfigure;
2135         sprintf(buf, "%g", xwid);
2136         fl_set_input(form->Width, buf);
2137         sprintf(buf, "%g", xhgh);
2138         fl_set_input(form->Height, buf);
2139         sprintf(buf, "%g", angle);
2140         fl_set_input(form->Angle, buf);
2141         if (!fname.empty()){
2142                 string buf1 = OnlyPath(owner->fileName());
2143                 string fname2 = MakeRelPath(fname, buf1);
2144                 fl_set_input(form->EpsFile, fname2.c_str());
2145         }
2146         else fl_set_input(form->EpsFile, "");
2147         fl_set_input(form->Subcaption, subcaption.c_str());
2148         if(current_view->buffer()->isReadonly()) 
2149                 DisableFigurePanel(form);
2150
2151         TempRegenerate();
2152 }
2153
2154
2155 void InsetFig::Preview(char const * p)
2156 {
2157         int pid = fork();
2158
2159         if (pid == -1) {
2160                 lyxerr << "Cannot fork process!" << endl;
2161                 return;         // error
2162         }
2163         if (pid > 0) {
2164                 addpidwait(pid);
2165                 return;         // parent process
2166         }
2167
2168         string buf1 = OnlyPath(owner->fileName());
2169         string buf2 = MakeAbsPath(p, buf1);
2170         
2171         lyxerr << "Error during rendering "
2172                << execlp(lyxrc->view_pspic_command.c_str(),
2173                          lyxrc->view_pspic_command.c_str(),
2174                          buf2.c_str(), 0)
2175                << endl;
2176         _exit(0);
2177 }
2178
2179
2180 void InsetFig::BrowseFile()
2181 {
2182         static string current_figure_path;
2183         static int once = 0;
2184         LyXFileDlg fileDlg;
2185
2186         if (lyxerr.debugging()) {
2187                 lyxerr << "Filename: "
2188                        << owner->fileName() << endl;
2189         }
2190         string p = fl_get_input(form->EpsFile);
2191
2192         string buf = MakeAbsPath(owner->fileName());
2193         string buf2 = OnlyPath(buf);
2194         if (!p.empty()) {
2195                 buf = MakeAbsPath(p, buf2);
2196                 buf = OnlyPath(buf);
2197         } else {
2198                 buf = OnlyPath(owner->fileName().c_str());
2199         }
2200         
2201         // Does user clipart directory exist?
2202         string bufclip = AddName (user_lyxdir, "clipart");      
2203         FileInfo fileInfo(bufclip);
2204         if (!(fileInfo.isOK() && fileInfo.isDir()))
2205                 // No - bail out to system clipart directory
2206                 bufclip = AddName (system_lyxdir, "clipart");   
2207
2208
2209         fileDlg.SetButton(0, _("Clipart"), bufclip); 
2210         fileDlg.SetButton(1, _("Document"), buf); 
2211
2212         bool error = false;
2213         do {
2214                 ProhibitInput();
2215                 if (once) {
2216                         p = fileDlg.Select(_("EPS Figure"),
2217                                            current_figure_path,
2218                                            "*ps", string());
2219                 } else {
2220                         p = fileDlg.Select(_("EPS Figure"), buf,
2221                                            "*ps", string());
2222                 }
2223                 AllowInput();
2224
2225                 if (p.empty()) return;
2226
2227                 buf = MakeRelPath(p, buf2);
2228                 current_figure_path = OnlyPath(p);
2229                 once = 1;
2230                 
2231                 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2232                     || contains(p, "%") || contains(p, " ")) 
2233                         {
2234                                 WriteAlert(_("Filename can't contain any "
2235                                              "of these characters:"),
2236                                            // xgettext:no-c-format
2237                                            _("space, '#', '~', '$' or '%'.")); 
2238                                 error = true;
2239                         }
2240         } while (error);
2241
2242         if (form) fl_set_input(form->EpsFile, buf.c_str());
2243 }
2244
2245
2246 void GraphicsCB(FL_OBJECT * obj, long arg)
2247 {
2248         /* obj->form contains the form */
2249
2250         if (lyxerr.debugging()) {
2251                 lyxerr << "GraphicsCB callback: " << arg << endl;
2252         }
2253
2254         /* find inset we were reacting to */
2255         for (int i = 0; i < figinsref; ++i)
2256                 if (figures[i]->inset->form && figures[i]->inset->form->Figure
2257                     == obj->form) {
2258             
2259                         if (lyxerr.debugging()) {
2260                                 lyxerr << "Calling back figure " << i << endl;
2261                         }
2262                         figures[i]->inset->CallbackFig(arg);
2263                         return;
2264                 }
2265 }
2266
2267
2268 void HideFiguresPopups()
2269 {
2270         for (int i = 0; i < figinsref; ++i)
2271                 if (figures[i]->inset->form 
2272                     && figures[i]->inset->form->Figure->visible) {
2273                         if (lyxerr.debugging()) {
2274                                 lyxerr << "Hiding figure " << i << endl;
2275                         }
2276                         // hide and free the form
2277                         figures[i]->inset->CallbackFig(9);
2278                 }
2279 }