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