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