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