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