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