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