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