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