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