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