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