]> git.lyx.org Git - lyx.git/blob - src/insets/figinset.C
Andres fixes to sstrem problems
[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()->getMainForm());
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                                                 break;
596                                         }
597                                         XFree(p);
598                                 }
599                                 XFree(reinterpret_cast<char *>(prop)); // jc:
600                                 if (err) break;
601                                 // ok, property found, we must wait until
602                                 // ghostscript deletes it
603                                 if (lyxerr.debugging()) {
604                                         lyxerr << "Releasing the server\n["
605                                                << getpid()
606                                                << "] GHOSTVIEW property"
607                                                 " found. Waiting." << endl;
608                                 }
609                                 XUngrabServer(tempdisp);
610                                 XFlush(tempdisp);
611                                 ::sleep(1);
612                                 XGrabServer(tempdisp);
613                         }
614                         XChangeProperty(tempdisp, 
615                                         fl_get_canvas_id(figinset_canvas),
616                                         XInternAtom(tempdisp, "GHOSTVIEW", false),
617                                         XInternAtom(tempdisp, "STRING", false),
618                                         8, PropModeAppend, 
619 #ifdef HAVE_SSTREAM
620                                         reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
621                                         t1.str().size()
622 #else
623                                         reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str())),
624                                         strlen(t1.str())
625 #endif
626                                 );
627                         XUngrabServer(tempdisp);
628                         XFlush(tempdisp);
629
630 #ifdef HAVE_SSTREAM
631                         ostringstream t3;
632 #else
633                         char tbuf3[384];
634                         ostrstream t3(tbuf3, sizeof(tbuf3));
635 #endif
636                         switch (p->data->flags & 3) {
637                         case 0: t3 << 'H'; break; // Hidden
638                         case 1: t3 << 'M'; break; // Mono
639                         case 2: t3 << 'G'; break; // Gray
640                         case 3:
641                                 if (color_visual) 
642                                         t3 << 'C'; // Color
643                                 else 
644                                         t3 << 'G'; // Gray
645                                 break;
646                         }
647         
648                         t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
649                            << ' ' << background_pixel;
650 #ifndef HAVE_SSTREAM
651                         t3 << '\0';
652 #endif
653
654                         XGrabServer(tempdisp);
655                         XChangeProperty(tempdisp, 
656                                         fl_get_canvas_id(figinset_canvas),
657                                         XInternAtom(tempdisp,
658                                                     "GHOSTVIEW_COLORS", false),
659                                         XInternAtom(tempdisp, "STRING", false),
660                                         8, PropModeReplace, 
661 #ifdef HAVE_SSTREAM
662                                         reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
663                                         t3.str().size()
664 #else
665                                         reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str())),
666                                         strlen(t3.str())
667 #endif
668                                 );
669                         XUngrabServer(tempdisp);
670                         XFlush(tempdisp);
671                         
672                         if (lyxerr.debugging()) {
673                                 lyxerr << "Releasing the server" << endl;
674                         }
675                         XCloseDisplay(tempdisp);
676
677                         // set up environment
678                         while (environ[ne])
679                                 ++ne;
680                         typedef char * char_p;
681                         env = new char_p[ne + 2];
682 #ifdef HAVE_SSTREAM
683                         string tmp = t2.str().c_str();
684                         env[0] = new char[tmp.size() + 1];
685                         std::copy(tmp.begin(), tmp.end(), env[0]);
686                         env[0][tmp.size()] = '\0';
687 #else
688                         env[0] = tbuf2;
689 #endif
690                         ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
691                         environ = env;
692
693                         // now make gs command
694                         // close(0);
695                         // close(1); do NOT close. If GS writes out
696                         // errors it would hang. (Matthias 290596) 
697
698                         string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
699                         string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
700
701                         // now chdir into dir with .eps file, to be on the safe
702                         // side
703                         ::chdir(OnlyPath(p->data->fname).c_str());
704                         // make temp file name
705                         string tmpf = make_tmp(getpid());
706                         if (lyxerr.debugging()) {
707                                 lyxerr << "starting gs " << tmpf << " "
708                                        << p->data->fname
709                                        << ", pid: " << getpid() << endl;
710                         }
711
712                         int err = ::execlp(lyxrc.ps_command.c_str(), 
713                                          lyxrc.ps_command.c_str(), 
714                                          "-sDEVICE=x11",
715                                          "-dNOPAUSE", "-dQUIET",
716                                          "-dSAFER", 
717                                          rbuf.c_str(), gbuf.c_str(), tmpf.c_str(), 
718                                          p->data->fname.c_str(), 
719                                          "showpage.ps", "quit.ps", "-", 0);
720                         // if we are still there, an error occurred.
721                         lyxerr << "Error executing ghostscript. "
722                                << "Code: " << err << endl;
723                         lyxerr.debug() << "Cmd: " 
724                                        << lyxrc.ps_command
725                                        << " -sDEVICE=x11 "
726                                        << tmpf.c_str() << ' '
727                                        << p->data->fname << endl;
728                         _exit(0);       // no gs?
729                 }
730                 // normal process (parent)
731                 if (lyxerr.debugging()) {
732                         lyxerr << "GS ["  << pid << "] started" << endl;
733                 }
734
735                 p->data->gspid = pid;
736                 ++gsrunning;
737                 gsqueue.pop();
738         }
739 }
740
741
742 static
743 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
744 {
745         // recompute the stuff and put in the queue
746         queue_element p;
747         p.ofsx = psx;
748         p.ofsy = psy;
749         p.rx = (float(data->raw_wid) * 72.0) / pswid;
750         p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
751
752         p.data = data;
753
754         gsqueue.push(p);
755
756         // if possible, run the queue
757         runqueue();
758 }
759
760
761 static
762 figdata * getfigdata(int wid, int hgh, string const & fname, 
763                      int psx, int psy, int pswid, int pshgh, 
764                      int raw_wid, int raw_hgh, float angle, char flags)
765 {
766         /* first search for an exact match with fname and width/height */
767
768         if (fname.empty()) return 0;
769
770         for (bitmaps_type::iterator it = bitmaps.begin();
771              it != bitmaps.end(); ++it) {
772                 if ((*it)->wid == wid && (*it)->hgh == hgh &&
773                     (*it)->flags == flags && (*it)->fname == fname &&
774                     (*it)->angle == angle) {
775                         (*it)->ref++;
776                         return (*it);
777                 }
778         }
779         figdata * p = new figdata;
780         p->wid = wid;
781         p->hgh = hgh;
782         p->raw_wid = raw_wid;
783         p->raw_hgh = raw_hgh;
784         p->angle = angle;
785         p->fname = fname;
786         p->flags = flags;
787         bitmaps.push_back(p);
788         XWindowAttributes wa;
789         XGetWindowAttributes(fl_display, fl_get_canvas_id(
790                 figinset_canvas), &wa);
791
792         if (lyxerr.debugging()) {
793                 lyxerr << "Create pixmap disp:" << fl_display
794                        << " scr:" << DefaultScreen(fl_display)
795                        << " w:" << wid
796                        << " h:" << hgh
797                        << " depth:" << wa.depth << endl;
798         }
799         
800         p->ref = 1;
801         p->reading = false;
802         p->broken = false;
803         p->gspid = -1;
804         if (flags) {
805                 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
806                         figinset_canvas), wid, hgh, wa.depth);
807                 p->gsdone = false;
808                 // initialize reading of .eps file with correct sizes and stuff
809                 addwait(psx, psy, pswid, pshgh, p);
810                 p->reading = true;
811         } else {
812                 p->bitmap = None;
813                 p->gsdone = true;
814         }
815
816         return p;
817 }
818
819
820 static
821 void getbitmap(figdata * p)
822 {
823         p->gspid = -1;
824 }
825
826
827 static
828 void makeupdatelist(figdata * p)
829 {
830         for(figures_type::iterator it = figures.begin();
831             it != figures.end(); ++it)
832                 if ((*it)->data == p) {
833                         if (lyxerr.debugging()) {
834                                 lyxerr << "Updating inset "
835                                        << (*it)->inset
836                                        << endl;
837                         }
838                         // add inset figures[i]->inset into to_update list
839                         current_view->pushIntoUpdateList((*it)->inset);
840                 }
841 }
842
843
844 // this func is only "called" in spellchecker.C
845 void sigchldchecker(pid_t pid, int * status)
846 {
847         lyxerr.debug() << "Got pid = " << pid << endl;
848         bool pid_handled = false;
849         for (bitmaps_type::iterator it = bitmaps.begin();
850              it != bitmaps.end(); ++it) {
851                 if ((*it)->reading && pid == (*it)->gspid) {
852                         lyxerr.debug() << "Found pid in bitmaps" << endl;
853                         // now read the file and remove it from disk
854                         figdata * p = (*it);
855                         p->reading = false;
856                         if ((*it)->gsdone) *status = 0;
857                         if (*status == 0) {
858                                 lyxerr.debug() << "GS [" << pid
859                                                << "] exit OK." << endl;
860                         } else {
861                                 lyxerr << "GS [" << pid  << "] error "
862                                        << *status << " E:"
863                                        << WIFEXITED(*status)
864                                        << " " << WEXITSTATUS(*status)
865                                        << " S:" << WIFSIGNALED(*status)
866                                        << " " << WTERMSIG(*status) << endl;
867                         }
868                         if (*status == 0) {
869                                 bitmap_waiting = true;
870                                 p->broken = false;
871                         } else {
872                                 // remove temporary files
873                                 unlink(make_tmp(p->gspid).c_str());
874                                 p->gspid = -1;
875                                 p->broken = true;
876                         }
877                         makeupdatelist((*it));
878                         --gsrunning;
879                         runqueue();
880                         pid_handled = true;
881                 }
882         }
883         if (!pid_handled) {
884                 lyxerr.debug() << "Checking pid in pidwait" << endl;
885                 list<int>::iterator it = find(pidwaitlist.begin(),
886                                               pidwaitlist.end(), pid);
887                 if (it != pidwaitlist.end()) {
888                         lyxerr.debug() << "Found pid in pidwait\n"
889                                        << "Caught child pid of recompute "
890                                 "routine" << pid << endl;
891                         pidwaitlist.erase(it);
892                 }
893         }
894         if (pid == -1) {
895                 lyxerr.debug() << "waitpid error" << endl;
896                 switch (errno) {
897                 case ECHILD:
898                         lyxerr << "The process or process group specified by "
899                                 "pid does  not exist or is not a child of "
900                                 "the calling process or can never be in the "
901                                 "states specified by options." << endl;
902                         break;
903                 case EINTR:
904                         lyxerr << "waitpid() was interrupted due to the "
905                                 "receipt of a signal sent by the calling "
906                                 "process." << endl;
907                         break;
908                 case EINVAL:
909                         lyxerr << "An invalid value was specified for "
910                                 "options." << endl;
911                         break;
912                 default:
913                         lyxerr << "Unknown error from waitpid" << endl;
914                         break;
915                 }
916         } else if (pid == 0) {
917                 lyxerr << "waitpid nohang" << endl;;
918         } else {
919                 lyxerr.debug() << "normal exit from childhandler" << endl;
920         }
921 }
922
923
924 static
925 void getbitmaps()
926 {
927         bitmap_waiting = false;
928         for (bitmaps_type::iterator it = bitmaps.begin();
929              it != bitmaps.end(); ++it)
930                 if ((*it)->gspid > 0 && !(*it)->reading)
931                         getbitmap((*it));
932 }
933
934
935 static
936 void RegisterFigure(InsetFig * fi)
937 {
938         if (figures.empty()) InitFigures();
939         fi->form = 0;
940         Figref * tmpfig = new Figref;
941         tmpfig->data = 0;
942         tmpfig->inset = fi;
943         figures.push_back(tmpfig);
944         fi->figure = tmpfig;
945
946         if (lyxerr.debugging()) {
947                 lyxerr << "Register Figure: buffer:["
948                        << current_view->buffer() << "]" << endl;
949         }
950 }
951
952
953 static
954 void UnregisterFigure(InsetFig * fi)
955 {
956         Figref * tmpfig = fi->figure;
957
958         if (tmpfig->data) freefigdata(tmpfig->data);
959         if (tmpfig->inset->form) {
960                 if (tmpfig->inset->form->Figure->visible) {
961                         fl_set_focus_object(tmpfig->inset->form->Figure,
962                                             tmpfig->inset->form->OkBtn);
963                         fl_hide_form(tmpfig->inset->form->Figure);
964                 }
965 #if FL_REVISION == 89
966 #warning Reactivate this free_form calls
967 #else
968                 fl_free_form(tmpfig->inset->form->Figure);
969                 free(tmpfig->inset->form); // Why free?
970                 tmpfig->inset->form = 0;
971 #endif
972         }
973         figures.erase(find(figures.begin(), figures.end(), tmpfig));
974         delete tmpfig;
975
976         if (figures.empty()) DoneFigures();
977 }
978
979
980 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
981         : owner(o)
982 {
983         wid = tmpx;
984         hgh = tmpy;
985         wtype = DEF;
986         htype = DEF;
987         twtype = DEF;
988         thtype = DEF;
989         pflags = flags = 9;
990         psubfigure = subfigure = false;
991         xwid = xhgh = angle = 0;
992         pswid = pshgh = 0;
993         raw_wid = raw_hgh = 0;
994         changedfname = false;
995         RegisterFigure(this);
996 }
997
998
999 InsetFig::~InsetFig()
1000 {
1001         if (lyxerr.debugging()) {
1002                 lyxerr << "Figure destructor called" << endl;
1003         }
1004         UnregisterFigure(this);
1005 }
1006
1007
1008 int InsetFig::ascent(Painter &, LyXFont const &) const
1009 {
1010         return hgh + 3;
1011 }
1012
1013
1014 int InsetFig::descent(Painter &, LyXFont const &) const
1015 {
1016         return 1;
1017 }
1018
1019
1020 int InsetFig::width(Painter &, LyXFont const &) const
1021 {
1022         return wid + 2;
1023 }
1024
1025
1026 void InsetFig::draw(Painter & pain, LyXFont const & f,
1027                     int baseline, float & x) const
1028 {
1029         LyXFont font(f);
1030         
1031         if (bitmap_waiting) getbitmaps();
1032         
1033         // I wish that I didn't have to use this
1034         // but the figinset code is so complicated so
1035         // I don't want to fiddle with it now.
1036
1037         if (figure && figure->data && figure->data->bitmap &&
1038             !figure->data->reading && !figure->data->broken) {
1039                 // draw the bitmap
1040                 pain.pixmap(int(x + 1), baseline - hgh,
1041                             wid, hgh, figure->data->bitmap);
1042
1043                 if (flags & 4)
1044                         pain.rectangle(int(x), baseline - hgh - 1,
1045                                        wid + 1, hgh + 1);
1046                 
1047         } else {
1048                 char * msg = 0;
1049                 // draw frame
1050                 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1051
1052                 if (figure && figure->data) {
1053                         if (figure->data->broken)  msg = _("[render error]");
1054                         else if (figure->data->reading) msg = _("[rendering ... ]");
1055                 } else 
1056                         if (fname.empty()) msg = _("[no file]");
1057                         else if ((flags & 3) == 0) msg = _("[not displayed]");
1058                         else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1059                 
1060                 if (!msg) msg = _("[unknown error]");
1061                 
1062                 font.setFamily(LyXFont::SANS_FAMILY);
1063                 font.setSize(LyXFont::SIZE_FOOTNOTE);
1064                 string justname = OnlyFilename (fname);
1065                 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1066                           justname, font);
1067                 
1068                 font.setSize(LyXFont::SIZE_TINY);
1069                 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1070         }
1071         x += width(pain, font);    // ?
1072 }
1073
1074
1075 void InsetFig::Write(ostream & os) const
1076 {
1077         Regenerate();
1078         os << "Figure size " << wid << " " << hgh << "\n";
1079         if (!fname.empty()) {
1080                 string buf1 = OnlyPath(owner->fileName());
1081                 string fname2 = MakeRelPath(fname, buf1);
1082                 os << "file " << fname2 << "\n";
1083         }
1084         if (!subcaption.empty())
1085                 os << "subcaption " << subcaption << "\n";
1086         if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1087         if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1088         if (angle != 0) os << "angle " << angle << "\n";
1089         os << "flags " << flags << "\n";
1090         if (subfigure) os << "subfigure\n";
1091 }
1092
1093
1094 void InsetFig::Read(LyXLex & lex)
1095 {
1096         string buf;
1097         bool finished = false;
1098         
1099         while (lex.IsOK() && !finished) {
1100                 lex.next();
1101
1102                 string const token = lex.GetString();
1103                 lyxerr.debug() << "Token: " << token << endl;
1104                 
1105                 if (token.empty())
1106                         continue;
1107                 else if (token == "\\end_inset") {
1108                         finished = true;
1109                 } else if (token == "file") {
1110                         if (lex.next()) {
1111                                 buf = lex.GetString();
1112                                 string buf1 = OnlyPath(owner->fileName());
1113                                 fname = MakeAbsPath(buf, buf1);
1114                                 changedfname = true;
1115                         }
1116                 } else if (token == "extra") {
1117                         if (lex.next());
1118                         // kept for backwards compability. Delete in 0.13.x
1119                 } else if (token == "subcaption") {
1120                         if (lex.EatLine())
1121                                 subcaption = lex.GetString();
1122                 } else if (token == "label") {
1123                         if (lex.next());
1124                         // kept for backwards compability. Delete in 0.13.x
1125                 } else if (token == "angle") {
1126                         if (lex.next())
1127                                 angle = lex.GetFloat();
1128                 } else if (token == "size") {
1129                         if (lex.next())
1130                                 wid = lex.GetInteger();
1131                         if (lex.next())
1132                                 hgh = lex.GetInteger();
1133                 } else if (token == "flags") {
1134                         if (lex.next())
1135                                 flags = pflags = lex.GetInteger();
1136                 } else if (token == "subfigure") {
1137                         subfigure = psubfigure = true;
1138                 } else if (token == "width") {
1139                         int typ = 0;
1140                         if (lex.next())
1141                                 typ = lex.GetInteger();
1142                         if (lex.next())
1143                                 xwid = lex.GetFloat();
1144                         switch (typ) {
1145                         case DEF: wtype = DEF; break;
1146                         case CM: wtype = CM; break;
1147                         case IN: wtype = IN; break;
1148                         case PER_PAGE: wtype = PER_PAGE; break;
1149                         case PER_COL: wtype = PER_COL; break;
1150                         default:
1151                                 lyxerr.debug() << "Unknown type!" << endl;
1152                                 break;
1153                         }
1154                         twtype = wtype;
1155                 } else if (token == "height") {
1156                         int typ = 0;
1157                         if (lex.next())
1158                                 typ = lex.GetInteger();
1159                         if (lex.next())
1160                                 xhgh = lex.GetFloat();
1161                         switch (typ) {
1162                         case DEF: htype = DEF; break;
1163                         case CM: htype = CM; break;
1164                         case IN: htype = IN; break;
1165                         case PER_PAGE: htype = PER_PAGE; break;
1166                         default:
1167                                 lyxerr.debug() << "Unknown type!" << endl;
1168                                 break;
1169                         }
1170                         thtype = htype;
1171                 }
1172         }
1173         Regenerate();
1174         Recompute();
1175 }
1176
1177
1178 int InsetFig::Latex(ostream & os,
1179                     bool /* fragile*/, bool /* fs*/) const
1180 {
1181         Regenerate();
1182         if (!cmd.empty()) os << cmd << " ";
1183         return 0;
1184 }
1185
1186
1187 int InsetFig::Ascii(ostream &) const
1188 {
1189         return 0;
1190 }
1191
1192
1193 int InsetFig::Linuxdoc(ostream &) const
1194 {
1195         return 0;
1196 }
1197
1198
1199 int InsetFig::DocBook(ostream & os) const
1200 {
1201         string figurename = fname;
1202
1203         if(suffixIs(figurename, ".eps"))
1204                 figurename.erase(fname.length() - 4);
1205
1206         os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1207         return 0;
1208 }
1209
1210
1211 void InsetFig::Validate(LaTeXFeatures & features) const
1212 {
1213         features.graphics = true;
1214         if (subfigure) features.subfigure = true;
1215 }
1216
1217
1218 Inset::EDITABLE InsetFig::Editable() const
1219 {
1220         return IS_EDITABLE;
1221 }
1222
1223
1224 bool InsetFig::Deletable() const
1225 {
1226         return false;
1227 }
1228
1229
1230 char const * InsetFig::EditMessage() const 
1231 {
1232         return _("Opened figure");
1233 }
1234
1235
1236 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1237 {
1238         lyxerr.debug() << "Editing InsetFig." << endl;
1239         Regenerate();
1240
1241         // We should have RO-versions of the form instead.
1242         // The actual prevention of altering a readonly doc
1243         // is done in CallbackFig()
1244         if(bv->buffer()->isReadonly()) 
1245                 WarnReadonly(bv->buffer()->fileName());
1246
1247         if (!form) {
1248                 form = create_form_Figure();
1249                 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1250                 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1251                 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1252                 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1253         }
1254         RestoreForm();
1255         if (form->Figure->visible) {
1256                 fl_raise_form(form->Figure);
1257         } else {
1258                 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1259                              FL_FULLBORDER, _("Figure"));
1260         }
1261 }
1262
1263
1264 Inset * InsetFig::Clone() const
1265 {
1266         InsetFig * tmp = new InsetFig(100, 100, owner);
1267
1268         if (lyxerr.debugging()) {
1269                 lyxerr << "Clone Figure: buffer:["
1270                        << current_view->buffer()
1271                        << "], cbuffer:[xx]" << endl;
1272         }
1273
1274         tmp->wid = wid;
1275         tmp->hgh = hgh;
1276         tmp->raw_wid = raw_wid;
1277         tmp->raw_hgh = raw_hgh;
1278         tmp->angle = angle;
1279         tmp->xwid = xwid;
1280         tmp->xhgh = xhgh;
1281         tmp->flags = flags;
1282         tmp->pflags = pflags;
1283         tmp->subfigure = subfigure;
1284         tmp->psubfigure = psubfigure;
1285         tmp->wtype = wtype;
1286         tmp->htype = htype;
1287         tmp->psx = psx;
1288         tmp->psy = psy;
1289         tmp->pswid = pswid;
1290         tmp->pshgh = pshgh;
1291         tmp->fname = fname;
1292         if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1293             && lyxrc.use_gui) { 
1294                 // do not display if there is
1295                 // "do not display" chosen (Matthias 260696)
1296                 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1297                                                pswid, pshgh, raw_wid, raw_hgh,
1298                                                angle, flags & (3|8));
1299         } else tmp->figure->data = 0;
1300         tmp->subcaption = subcaption;
1301         tmp->changedfname = false;
1302         tmp->owner = owner;
1303         tmp->Regenerate();
1304         return tmp;
1305 }
1306
1307
1308 Inset::Code InsetFig::LyxCode() const
1309 {
1310         return Inset::GRAPHICS_CODE;
1311 }
1312
1313
1314 static
1315 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1316 {
1317         string res;
1318         switch (hw) {
1319                 case InsetFig::DEF:
1320                         break;
1321                 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1322                         res = tostr(f) + "cm";
1323                         break;
1324                 case InsetFig::IN: 
1325                         res = tostr(f) + "in";
1326                         break;
1327                 case InsetFig::PER_PAGE:
1328                         res = tostr(f/100) + "\\text" + suffix;
1329                         break;
1330                 case InsetFig::PER_COL:
1331                         // Doesn't occur for htype...
1332                         res = tostr(f/100) + "\\column" + suffix;
1333                         break;
1334         }
1335         return res;
1336 }
1337
1338
1339 void InsetFig::Regenerate() const
1340 {
1341         string cmdbuf;
1342         string resizeW, resizeH;
1343         string rotate, recmd;
1344
1345         if (fname.empty()) {
1346                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1347                 cmd += _("empty figure path");
1348                 cmd += '}';
1349                 return;
1350         }
1351
1352         string buf1 = OnlyPath(owner->fileName());
1353         string fname2 = MakeRelPath(fname, buf1);
1354
1355         string gcmd = "\\includegraphics{" + fname2 + '}';
1356         resizeW = stringify(wtype, xwid, "width");
1357         resizeH = stringify(htype, xhgh, "height");
1358
1359         if (!resizeW.empty() || !resizeH.empty()) {
1360                 recmd = "\\resizebox*{";
1361                 if (!resizeW.empty())
1362                         recmd += resizeW;
1363                 else
1364                         recmd += '!';
1365                 recmd += "}{";
1366                 if (!resizeH.empty())
1367                         recmd += resizeH;
1368                 else
1369                         recmd += '!';
1370                 recmd += "}{";
1371         }
1372         
1373         
1374         if (angle != 0) {
1375                 // \rotatebox{angle}{text}
1376                 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1377         }
1378
1379         cmdbuf = recmd;
1380         cmdbuf += rotate;
1381         cmdbuf += gcmd;
1382         if (!rotate.empty()) cmdbuf += '}';
1383         if (!recmd.empty()) cmdbuf += '}';
1384         if (subfigure) {
1385                 if (!subcaption.empty())
1386                         cmdbuf = "\\subfigure[" + subcaption +
1387                                 "]{" + cmdbuf + "}";
1388                 else
1389                         cmdbuf = "\\subfigure{" + cmdbuf + "}";
1390         }
1391         
1392         cmd = cmdbuf;
1393 }
1394
1395
1396 void InsetFig::TempRegenerate()
1397 {
1398         string cmdbuf;
1399         string resizeW, resizeH;
1400         string rotate, recmd;
1401         
1402         char const * tfname = fl_get_input(form->EpsFile);
1403         string tsubcap = fl_get_input(form->Subcaption);
1404         float tangle = atof(fl_get_input(form->Angle));
1405         float txwid = atof(fl_get_input(form->Width));
1406         float txhgh = atof(fl_get_input(form->Height));
1407
1408         if (!tfname || !*tfname) {
1409                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1410                 cmd += _("empty figure path");
1411                 cmd += '}';
1412                 return;
1413         }
1414
1415         string buf1 = OnlyPath(owner->fileName());
1416         string fname2 = MakeRelPath(tfname, buf1);
1417         // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1418         string gcmd = "\\includegraphics{" + fname2 + '}';
1419
1420         resizeW = stringify(twtype, txwid, "width");    
1421         resizeH = stringify(thtype, txhgh, "height");   
1422
1423         // \resizebox*{h-length}{v-length}{text}
1424         if (!resizeW.empty() || !resizeH.empty()) {
1425                 recmd = "\\resizebox*{";
1426                 if (!resizeW.empty())
1427                         recmd += resizeW;
1428                 else
1429                         recmd += '!';
1430                 recmd += "}{";
1431                 if (!resizeH.empty())
1432                         recmd += resizeH;
1433                 else
1434                         recmd += '!';
1435                 recmd += "}{";
1436         }
1437         
1438         if (tangle != 0) {
1439                 // \rotatebox{angle}{text}
1440                 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1441         }
1442
1443         cmdbuf = recmd + rotate + gcmd;
1444         if (!rotate.empty()) cmdbuf += '}';
1445         if (!recmd.empty()) cmdbuf += '}';
1446         if (psubfigure && !tsubcap.empty()) {
1447                 cmdbuf = string("\\subfigure{") + tsubcap
1448                         + string("}{") + cmdbuf + "}";
1449         }
1450 }
1451
1452
1453 void InsetFig::Recompute()
1454 {
1455         bool changed = changedfname;
1456         int newx, newy, nraw_x, nraw_y;
1457
1458         if (changed) GetPSSizes();
1459
1460         float sin_a = sin (angle / DEG2PI);  /* rotation; H. Zeller 021296 */
1461         float cos_a = cos (angle / DEG2PI);
1462         int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1463         int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1464
1465         /* now recompute wid and hgh, and if that is changed, set changed */
1466         /* this depends on chosen size of the picture and its bbox */
1467         // This will be redone in 0.13 ... (hen)
1468         if (!fname.empty()) {
1469                 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1470
1471                 newx = frame_wid;
1472                 newy = frame_hgh;
1473                 switch (wtype) {
1474                 case DEF:
1475                         break;
1476                 case CM:        /* cm */
1477                         newx = int(28.346 * xwid);
1478                         break;
1479                 case IN: /* in */
1480                         newx = int(72 * xwid);
1481                         break;
1482                 case PER_PAGE:  /* % of page */
1483                         newx = int(5.95 * xwid);
1484                         break;
1485                 case PER_COL:   /* % of col */
1486                         newx = int(2.975 * xwid);
1487                         break;
1488                 }
1489                 
1490                 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1491                 
1492                 switch (htype) {
1493                 case DEF:
1494                         //lyxerr << "This should not happen!" << endl;
1495                         break;
1496                 case CM:        /* cm */
1497                         newy = int(28.346 * xhgh);
1498                         break;
1499                 case IN: /* in */
1500                         newy = int(72 * xhgh);
1501                         break;
1502                 case PER_PAGE:  /* % of page */
1503                         newy = int(8.42 * xhgh);
1504                         break;
1505                 case PER_COL: 
1506                         // Doesn't occur; case exists to suppress
1507                         // compiler warnings.  
1508                         break;
1509                 }
1510                 if (htype && !wtype && frame_hgh)
1511                         newx = newy*frame_wid/frame_hgh;
1512         } else {
1513                 newx = wid;
1514                 newy = hgh;
1515         }
1516
1517         if (frame_wid == 0)
1518                 nraw_x = 5;
1519         else
1520                 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1521
1522         if (frame_hgh == 0)
1523                 nraw_y = 5;
1524         else
1525                 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1526
1527         // cannot be zero, actually, set it to some minimum, so its clickable
1528         if (newx < 5) newx = 5;
1529         if (newy < 5) newy = 5;
1530
1531         if (newx   != wid     || newy   != hgh     || 
1532             nraw_x != raw_wid || nraw_y != raw_hgh ||
1533             flags  != pflags  || subfigure != psubfigure) 
1534                 changed = true;
1535        
1536         raw_wid = nraw_x;
1537         raw_hgh = nraw_y;
1538         wid = newx;
1539         hgh = newy;
1540         flags = pflags;
1541         subfigure = psubfigure;
1542
1543         if (changed) {
1544                 figdata * pf = figure->data;
1545
1546                 // get new data
1547                 if (!fname.empty() && (flags & 3)
1548                     && !lyxrc.ps_command.empty()) {
1549                         // do not display if there is "do not display"
1550                         // chosen (Matthias 260696)
1551                         figure->data = getfigdata(wid, hgh, fname,
1552                                                   psx, psy, pswid, pshgh,
1553                                                   raw_wid, raw_hgh,
1554                                                   angle, flags & (3|8));
1555                 } else figure->data = 0;
1556
1557                 // free the old data
1558                 if (pf) freefigdata(pf);
1559         }
1560
1561         changedfname = false;
1562 }
1563
1564
1565 void InsetFig::GetPSSizes()
1566 {
1567         /* get %%BoundingBox: from postscript file */
1568         
1569         /* defaults to associated size
1570          * ..just in case the PS-file is not readable (Henner, 24-Aug-97) 
1571          */
1572         psx = 0;
1573         psy = 0;
1574         pswid = wid;
1575         pshgh = hgh;
1576
1577         if (fname.empty()) return;
1578         string p;
1579         ifstream ifs(fname.c_str());
1580
1581         if (!ifs) return;       // file not found !!!!
1582
1583         /* defaults to A4 page */
1584         psx = 0;
1585         psy = 0;
1586         pswid = 595;
1587         pshgh = 842;
1588
1589         char lastchar = 0; ifs.get(lastchar);
1590         for (;;) {
1591                 char c = 0; ifs.get(c);
1592                 if (ifs.eof()) {
1593                         lyxerr.debug() << "End of (E)PS file reached and"
1594                                 " no BoundingBox!" << endl;
1595                         break;
1596                 }
1597                 if (c == '%' && lastchar == '%') {
1598                         ifs >> p;
1599                         if (p.empty()) break;
1600                         lyxerr.debug() << "Token: `" << p << "'" << endl;
1601                         if (p == "BoundingBox:") {
1602                                 float fpsx, fpsy, fpswid, fpshgh;
1603                                 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1604                                         psx = int(fpsx);
1605                                         psy = int(fpsy);
1606                                         pswid = int(fpswid);
1607                                         pshgh = int(fpshgh);
1608                                 }
1609                                 if (lyxerr.debugging()) {
1610                                         lyxerr << "%%%%BoundingBox:"
1611                                                << psx << ' '
1612                                                << psy << ' '
1613                                                << pswid << ' '
1614                                                << pshgh << endl;
1615                                 }
1616                                 break;
1617                         }
1618                         c = 0;
1619                 }
1620                 lastchar = c;
1621         }
1622         pswid -= psx;
1623         pshgh -= psy;
1624
1625 }
1626
1627
1628 void InsetFig::CallbackFig(long arg)
1629 {
1630         bool regen = false;
1631         char const * p;
1632
1633         if (lyxerr.debugging()) {
1634                 lyxerr << "Figure callback, arg " << arg << endl;
1635         }
1636
1637         switch (arg) {
1638         case 10:
1639         case 11:
1640         case 12:        /* width type */
1641         case 13:
1642         case 14:
1643                 switch (arg - 10) {
1644                 case DEF:
1645                         twtype = DEF;
1646                         // put disable here
1647                         fl_deactivate_object(form->Width);
1648                         break;
1649                 case CM:
1650                         twtype = CM;
1651                         // put enable here
1652                         fl_activate_object(form->Width);
1653                         break;
1654                 case IN:
1655                         twtype = IN;
1656                         // put enable here
1657                         fl_activate_object(form->Width);
1658                         break;
1659                 case PER_PAGE:
1660                         twtype = PER_PAGE;
1661                         // put enable here
1662                         fl_activate_object(form->Width);
1663                         break;
1664                 case PER_COL:
1665                         twtype = PER_COL;
1666                         // put enable here
1667                         fl_activate_object(form->Width);
1668                         break;
1669                 default:
1670                         lyxerr.debug() << "Unknown type!" << endl;
1671                         break;
1672                 }
1673                 regen = true;
1674                 break;
1675         case 20:
1676         case 21:
1677         case 22:        /* height type */
1678         case 23:
1679                 switch (arg - 20) {
1680                 case DEF:
1681                         thtype = DEF;
1682                         // put disable here
1683                         fl_deactivate_object(form->Height);
1684                         break;
1685                 case CM:
1686                         thtype = CM;
1687                         // put enable here
1688                         fl_activate_object(form->Height);
1689                         break;
1690                 case IN:
1691                         thtype = IN;
1692                         // put enable here
1693                         fl_activate_object(form->Height);
1694                         break;
1695                 case PER_PAGE:
1696                         thtype = PER_PAGE;
1697                         // put enable here
1698                         fl_activate_object(form->Height);
1699                         break;
1700                 default:
1701                         lyxerr.debug() << "Unknown type!" << endl;
1702                         break;
1703                 }
1704                 regen = true;
1705                 break;
1706         case 3:
1707                 pflags = pflags & ~3;           /* wysiwyg0 */
1708                 break;
1709         case 33:
1710                 pflags = (pflags & ~3) | 1;     /* wysiwyg1 */
1711                 break;
1712         case 43:
1713                 pflags = (pflags & ~3) | 2;     /* wysiwyg2 */
1714                 break;
1715         case 63:
1716                 pflags = (pflags & ~3) | 3;     /* wysiwyg3 */
1717                 break;
1718         case 53:
1719                 pflags ^= 4;    /* frame */
1720                 break;
1721         case 54:
1722                 pflags ^= 8;    /* do translations */
1723                 break;
1724         case 70:
1725                 psubfigure = !psubfigure;       /* This is a subfigure */
1726                 break;
1727         case 2:
1728                 regen = true;           /* regenerate command */
1729                 break;
1730         case 0:                         /* browse file */
1731                 BrowseFile();
1732                 regen = true;
1733                 break;
1734         case 1:                         /* preview */
1735                 p = fl_get_input(form->EpsFile);
1736                 Preview(p);
1737                 break;
1738         case 7:                         /* apply */
1739         case 8:                         /* ok (apply and close) */
1740                 if(!current_view->buffer()->isReadonly()) {
1741                         wtype = twtype;
1742                         htype = thtype;
1743                         xwid = atof(fl_get_input(form->Width));
1744                         xhgh = atof(fl_get_input(form->Height));
1745                         angle = atof(fl_get_input(form->Angle));
1746                         p = fl_get_input(form->EpsFile);
1747                         if (p && *p) {
1748                                 string buf1 = OnlyPath(owner->fileName());
1749                                 fname = MakeAbsPath(p, buf1);
1750                                 changedfname = true;
1751                         } else {
1752                                 if (!fname.empty()) {
1753                                         changedfname = true;
1754                                         fname.clear();
1755                                 }
1756                         }
1757                         subcaption = fl_get_input(form->Subcaption);
1758         
1759                         Regenerate();
1760                         Recompute();
1761                         /* now update inset */
1762                         if (lyxerr.debugging()) {
1763                                 lyxerr << "Update: ["
1764                                        << wid << 'x' << hgh << ']' << endl;
1765                         }
1766                         current_view->updateInset(this, true);
1767                         if (arg == 8) {
1768                                 fl_set_focus_object(form->Figure, form->OkBtn);
1769                                 fl_hide_form(form->Figure);
1770 #if FL_REVISION == 89
1771 #warning Reactivate this free_form calls
1772 #else
1773                                 fl_free_form(form->Figure);
1774                                 free(form); // Why free?
1775                                 form = 0;
1776 #endif
1777                         }
1778                         break;
1779                 } //if not readonly
1780                 //  The user has already been informed about RO in ::Edit
1781                 if(arg == 7) // if 'Apply'
1782                         break;
1783                 // fall through
1784         case 9:                         /* cancel = restore and close */
1785                 fl_set_focus_object(form->Figure, form->OkBtn);
1786                 fl_hide_form(form->Figure);
1787 #if FL_REVISION == 89
1788 #warning Reactivate this free_form calls
1789 #warning Jug, is this still a problem?
1790 #else
1791                 fl_free_form(form->Figure);
1792                 free(form); // Why free?
1793                 form = 0;
1794 #endif
1795                 break;
1796         }
1797
1798         if (regen) TempRegenerate();
1799 }
1800
1801
1802 inline
1803 void DisableFigurePanel(FD_Figure * const form)
1804 {
1805         fl_deactivate_object(form->EpsFile);
1806         fl_deactivate_object(form->Browse);
1807         fl_deactivate_object(form->Width);
1808         fl_deactivate_object(form->Height);
1809         fl_deactivate_object(form->Frame);
1810         fl_deactivate_object(form->Translations);
1811         fl_deactivate_object(form->Angle);
1812         fl_deactivate_object(form->HeightGrp);
1813         fl_deactivate_object(form->page2);
1814         fl_deactivate_object(form->Default2);
1815         fl_deactivate_object(form->cm2);
1816         fl_deactivate_object(form->in2);
1817         fl_deactivate_object(form->HeightLabel);
1818         fl_deactivate_object(form->WidthLabel);
1819         fl_deactivate_object(form->DisplayGrp);
1820         fl_deactivate_object(form->Wysiwyg3);
1821         fl_deactivate_object(form->Wysiwyg0);
1822         fl_deactivate_object(form->Wysiwyg2);
1823         fl_deactivate_object(form->Wysiwyg1);
1824         fl_deactivate_object(form->WidthGrp);
1825         fl_deactivate_object(form->Default1);
1826         fl_deactivate_object(form->cm1);
1827         fl_deactivate_object(form->in1);
1828         fl_deactivate_object(form->page1);
1829         fl_deactivate_object(form->column1);
1830         fl_deactivate_object(form->Subcaption);
1831         fl_deactivate_object(form->Subfigure);
1832         fl_deactivate_object (form->OkBtn);
1833         fl_deactivate_object (form->ApplyBtn);
1834         fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1835         fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1836 }
1837
1838
1839 inline
1840 void EnableFigurePanel(FD_Figure * const form)
1841 {
1842         fl_activate_object(form->EpsFile);
1843         fl_activate_object(form->Browse);
1844         fl_activate_object(form->Width);
1845         fl_activate_object(form->Height);
1846         fl_activate_object(form->Frame);
1847         fl_activate_object(form->Translations);
1848         fl_activate_object(form->Angle);
1849         fl_activate_object(form->HeightGrp);
1850         fl_activate_object(form->page2);
1851         fl_activate_object(form->Default2);
1852         fl_activate_object(form->cm2);
1853         fl_activate_object(form->in2);
1854         fl_activate_object(form->HeightLabel);
1855         fl_activate_object(form->WidthLabel);
1856         fl_activate_object(form->DisplayGrp);
1857         fl_activate_object(form->Wysiwyg3);
1858         fl_activate_object(form->Wysiwyg0);
1859         fl_activate_object(form->Wysiwyg2);
1860         fl_activate_object(form->Wysiwyg1);
1861         fl_activate_object(form->WidthGrp);
1862         fl_activate_object(form->Default1);
1863         fl_activate_object(form->cm1);
1864         fl_activate_object(form->in1);
1865         fl_activate_object(form->page1);
1866         fl_activate_object(form->column1);
1867         fl_activate_object(form->Subcaption);
1868         fl_activate_object(form->Subfigure);
1869         fl_activate_object (form->OkBtn);
1870         fl_activate_object (form->ApplyBtn);
1871         fl_set_object_lcol (form->OkBtn, FL_BLACK);
1872         fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1873 }
1874
1875
1876 void InsetFig::RestoreForm()
1877 {
1878         EnableFigurePanel(form);
1879
1880         twtype = wtype;
1881         fl_set_button(form->Default1, (wtype == 0));
1882         fl_set_button(form->cm1, (wtype == 1));
1883         fl_set_button(form->in1, (wtype == 2));
1884         fl_set_button(form->page1, (wtype == 3));
1885         fl_set_button(form->column1, (wtype == 4));
1886         if (wtype == 0) {
1887                 fl_deactivate_object(form->Width);
1888         } else {
1889                 fl_activate_object(form->Width);
1890         }
1891                 
1892         // enable and disable should be put here.
1893         thtype = htype;
1894         fl_set_button(form->Default2, (htype == 0));
1895         fl_set_button(form->cm2, (htype == 1));
1896         fl_set_button(form->in2, (htype == 2));
1897         fl_set_button(form->page2, (htype == 3));
1898         // enable and disable should be put here.
1899         if (htype == 0) {
1900                 fl_deactivate_object(form->Height);
1901         } else {
1902                 fl_activate_object(form->Height);
1903         }
1904
1905         int pflags = flags & 3;
1906         fl_set_button(form->Wysiwyg0, (pflags == 0));
1907         fl_set_button(form->Wysiwyg1, (pflags == 1));
1908         fl_set_button(form->Wysiwyg2, (pflags == 2));
1909         fl_set_button(form->Wysiwyg3, (pflags == 3));
1910         fl_set_button(form->Frame, ((flags & 4) != 0));
1911         fl_set_button(form->Translations, ((flags & 8) != 0));
1912         fl_set_button(form->Subfigure, (subfigure != 0));
1913         pflags = flags;
1914         psubfigure = subfigure;
1915         fl_set_input(form->Width, tostr(xwid).c_str());
1916         fl_set_input(form->Height, tostr(xhgh).c_str());
1917         fl_set_input(form->Angle, tostr(angle).c_str());
1918         if (!fname.empty()){
1919                 string buf1 = OnlyPath(owner->fileName());
1920                 string fname2 = MakeRelPath(fname, buf1);
1921                 fl_set_input(form->EpsFile, fname2.c_str());
1922         }
1923         else fl_set_input(form->EpsFile, "");
1924         fl_set_input(form->Subcaption, subcaption.c_str());
1925         if(current_view->buffer()->isReadonly()) 
1926                 DisableFigurePanel(form);
1927
1928         TempRegenerate();
1929 }
1930
1931
1932 void InsetFig::Preview(char const * p)
1933 {
1934         int pid = fork();
1935
1936         if (pid == -1) {
1937                 lyxerr << "Cannot fork process!" << endl;
1938                 return;         // error
1939         }
1940         if (pid > 0) {
1941                 addpidwait(pid);
1942                 return;         // parent process
1943         }
1944
1945         string buf1 = OnlyPath(owner->fileName());
1946         string buf2 = MakeAbsPath(p, buf1);
1947         
1948         lyxerr << "Error during rendering "
1949                << execlp(lyxrc.view_pspic_command.c_str(),
1950                          lyxrc.view_pspic_command.c_str(),
1951                          buf2.c_str(), 0)
1952                << endl;
1953         _exit(0);
1954 }
1955
1956
1957 void InsetFig::BrowseFile()
1958 {
1959         static string current_figure_path;
1960         static int once = 0;
1961         LyXFileDlg fileDlg;
1962
1963         if (lyxerr.debugging()) {
1964                 lyxerr << "Filename: "
1965                        << owner->fileName() << endl;
1966         }
1967         string p = fl_get_input(form->EpsFile);
1968
1969         string buf = MakeAbsPath(owner->fileName());
1970         string buf2 = OnlyPath(buf);
1971         if (!p.empty()) {
1972                 buf = MakeAbsPath(p, buf2);
1973                 buf = OnlyPath(buf);
1974         } else {
1975                 buf = OnlyPath(owner->fileName().c_str());
1976         }
1977         
1978         // Does user clipart directory exist?
1979         string bufclip = AddName (user_lyxdir, "clipart");      
1980         FileInfo fileInfo(bufclip);
1981         if (!(fileInfo.isOK() && fileInfo.isDir()))
1982                 // No - bail out to system clipart directory
1983                 bufclip = AddName (system_lyxdir, "clipart");   
1984
1985
1986         fileDlg.SetButton(0, _("Clipart"), bufclip); 
1987         fileDlg.SetButton(1, _("Document"), buf); 
1988
1989         bool error = false;
1990         do {
1991                 ProhibitInput(current_view);
1992                 if (once) {
1993                         p = fileDlg.Select(_("EPS Figure"),
1994                                            current_figure_path,
1995                                            "*ps", string());
1996                 } else {
1997                         p = fileDlg.Select(_("EPS Figure"), buf,
1998                                            "*ps", string());
1999                 }
2000                 AllowInput(current_view);
2001
2002                 if (p.empty()) return;
2003
2004                 buf = MakeRelPath(p, buf2);
2005                 current_figure_path = OnlyPath(p);
2006                 once = 1;
2007                 
2008                 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2009                     || contains(p, "%") || contains(p, " ")) {
2010                         WriteAlert(_("Filename can't contain any "
2011                                      "of these characters:"),
2012                                    // xgettext:no-c-format
2013                                    _("space, '#', '~', '$' or '%'.")); 
2014                         error = true;
2015                 }
2016         } while (error);
2017
2018         if (form) fl_set_input(form->EpsFile, buf.c_str());
2019 }
2020
2021
2022 void GraphicsCB(FL_OBJECT * obj, long arg)
2023 {
2024         /* obj->form contains the form */
2025
2026         if (lyxerr.debugging()) {
2027                 lyxerr << "GraphicsCB callback: " << arg << endl;
2028         }
2029
2030         /* find inset we were reacting to */
2031         for (figures_type::iterator it = figures.begin();
2032              it != figures.end(); ++it)
2033                 if ((*it)->inset->form && (*it)->inset->form->Figure
2034                     == obj->form) {
2035                         if (lyxerr.debugging()) {
2036                                 lyxerr << "Calling back figure "
2037                                        << (*it) << endl;
2038                         }
2039                         (*it)->inset->CallbackFig(arg);
2040                         return;
2041                 }
2042 }
2043
2044
2045 void HideFiguresPopups()
2046 {
2047         for (figures_type::iterator it = figures.begin();
2048              it != figures.end(); ++it)
2049                 if ((*it)->inset->form 
2050                     && (*it)->inset->form->Figure->visible) {
2051                         if (lyxerr.debugging()) {
2052                                 lyxerr << "Hiding figure " << (*it) << endl;
2053                         }
2054                         // hide and free the form
2055                         (*it)->inset->CallbackFig(9);
2056                 }
2057 }