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