]> git.lyx.org Git - lyx.git/blob - src/insets/figinset.C
0210ef4511f3acb44a752b76d0527be0750443e0
[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 //extern Colormap color_map;
113
114
115
116 static
117 GC createGC()
118 {
119         XGCValues val;
120         val.foreground = BlackPixel(fl_display, 
121                                     DefaultScreen(fl_display));
122         
123         val.function=GXcopy;
124         val.graphics_exposures = false;
125         val.line_style = LineSolid;
126         val.line_width = 0;
127         return XCreateGC(fl_display, RootWindow(fl_display, 0), 
128                          GCForeground | GCFunction | GCGraphicsExposures
129                          | GCLineWidth | GCLineStyle , &val);
130 }
131
132 static
133 GC local_gc_copy;
134
135
136 void addpidwait(int pid)
137 {
138         // adds pid to pid wait list
139         pidwaitlist.push_back(pid);
140
141         if (lyxerr.debugging()) {
142                 lyxerr << "Pids to wait for: \n";
143                 for (list<int>::const_iterator cit = pidwaitlist.begin();
144                      cit != pidwaitlist.end(); ++cit) {
145                         lyxerr << (*cit) << '\n';
146                 }
147                 lyxerr << flush;
148         }
149 }
150
151
152 extern "C" int GhostscriptMsg(FL_OBJECT *, Window, int, int,
153                               XEvent * ev, void *)
154 {
155         char tmp[128];
156
157         XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
158
159         if(lyxerr.debugging()) {
160                 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
161                        << "] pm:[" << e->data.l[1] << "]" << endl;
162         }
163
164         // just kill gs, that way it will work for sure
165         // This loop looks like S**T so it probably is...
166         for (int i = 0; i < bmpinsref; ++i)
167                 if ((long)bitmaps[i]->bitmap == (long)e->data.l[1]) {
168                         // found the one
169                         figdata * p = bitmaps[i];
170                         p->gsdone = true;
171
172                         // first update p->bitmap, if necessary
173                         if (p->bitmap != None
174                             && p->flags > (1|8) && gs_color && p->wid) {
175                                 // query current colormap and re-render
176                                 // the pixmap with proper colors
177                                 //XColor * cmap;
178                                 XWindowAttributes wa;
179                                 register XImage * im;
180                                 int i;
181                                 int y;
182                                 int wid1;
183                                 int spc1 = gs_spc-1;
184                                 int spc2 = gs_spc * gs_spc;
185                                 int wid = p->wid;
186                                 int forkstat;
187                                 Display * tmpdisp;
188                                 GC gc = local_gc_copy;
189
190                                 XGetWindowAttributes(fl_display,
191                                                      fl_get_canvas_id(
192                                                              figinset_canvas),
193                                                      &wa);
194                                 XFlush(fl_display);
195                                 if (lyxerr.debugging()) {
196                                         lyxerr << "Starting image translation "
197                                                << p->bitmap << " "
198                                                << p->flags << " "
199                                                << p->wid << "x" << p->hgh
200                                                << " " << wa.depth
201                                                << " " << XYPixmap << endl;
202                                 }
203                                 // now fork rendering process
204                                 forkstat = fork();
205                                 if (forkstat == -1) {
206                                         lyxerr.debug()
207                                                 << "Cannot fork, using slow "
208                                                 "method for pixmap translation." << endl;
209                                         tmpdisp = fl_display;
210                                 } else if (forkstat > 0) { // parent
211                                         // register child
212                                         if (lyxerr.debugging()) {
213                                                 lyxerr << "Spawned child "
214                                                        << forkstat << endl;
215                                         }
216                                         addpidwait(forkstat);
217                                         break;
218                                 } else {  // child
219                                         tmpdisp = XOpenDisplay(XDisplayName(0));
220                                         XFlush(tmpdisp);
221                                 }
222                                 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
223                                                p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
224                                 XFlush(tmpdisp);
225                                 if (lyxerr.debugging()) {
226                                         lyxerr << "Got the image" << endl;
227                                 }
228                                 if (!im) {
229                                         if (lyxerr.debugging()) {
230                                                 lyxerr << "Error getting the image" << endl;
231                                         }
232                                         goto noim;
233                                 }
234                                 {
235                                 // query current colormap
236                                         XColor * cmap = new XColor[gs_allcolors];
237                                         for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
238 #if 1
239                                         XQueryColors(tmpdisp, fl_state[fl_get_vclass()].colormap, cmap, gs_allcolors);
240 #else
241                                         XQueryColors(tmpdisp, color_map, cmap, gs_allcolors);
242 #endif
243                                         XFlush(tmpdisp);
244                                         wid1 = p->wid - 1;
245                                 // now we process all the image
246                                         for (y = 0; y < p->hgh; ++y) {
247                                                 for (int x = 0; x < wid; ++x) {
248                                                         XColor * pc = cmap +
249                                                                 XGetPixel(im, x, y);
250                                                         XFlush(tmpdisp);
251                                                         XPutPixel(im, x, y,
252                                                                   gs_pixels[((pc->red+6553)*
253                                                                              spc1/65535)*spc2+((pc->green+6553)*
254                                                                                                spc1/65535)*gs_spc+((pc->blue+6553)*
255                                                                                                                    spc1/65535)]);
256                                                         XFlush(tmpdisp);
257                                                 }
258                                         }
259                                 // This must be correct.
260                                         delete [] cmap;
261                                         if (lyxerr.debugging()) {
262                                                 lyxerr << "Putting image back"
263                                                        << endl;
264                                         }
265                                         XPutImage(tmpdisp, p->bitmap,
266                                                   gc, im, 0, 0,
267                                                   0, 0, p->wid, p->hgh);
268                                         XDestroyImage(im);
269                                         if (lyxerr.debugging()) {
270                                                 lyxerr << "Done translation"
271                                                        << endl;
272                                         }
273                                 }
274                           noim:
275                                 if (lyxerr.debugging()) {
276                                         lyxerr << "Killing gs " 
277                                                << p->gspid << endl;
278                                 }
279                                 lyx::kill(p->gspid, SIGHUP);
280
281                                 sprintf(tmp, "%s/~lyxgs%d.ps",
282                                         system_tempdir.c_str(), 
283                                         p->gspid);
284                                 unlink(tmp);
285                                 if (forkstat == 0) {
286                                         XCloseDisplay(tmpdisp);
287                                         _exit(0);
288                                 }
289                         } else {
290                                 if (lyxerr.debugging()) {
291                                         lyxerr << "Killing gs " 
292                                                << p->gspid << endl;
293                                 }
294                                 lyx::kill(p->gspid, SIGHUP);
295
296                                 sprintf(tmp, "%s/~lyxgs%d.ps", 
297                                         system_tempdir.c_str(),
298                                         p->gspid);
299                                 unlink(tmp);
300                         }
301                         break;
302                 }
303         return 0;
304 }
305
306
307 static void AllocColors(int num)
308 // allocate color cube numxnumxnum, if possible
309 {
310         if (lyxerr.debugging()) {
311                 lyxerr << "Allocating color cube " << num
312                        << 'x' << num << 'x' << num << endl;
313         }
314
315         if (num <= 1) {
316                 lyxerr << "Error allocating color colormap." << endl;
317                 gs_color = false;
318                 return;
319         }
320         if (num > 5) num = 5;
321         XColor xcol;
322         for (int i = 0; i < num * num * num; ++i) {
323                 xcol.red = 65535 * (i / (num * num)) / (num - 1);
324                 xcol.green = 65535 * ((i / num) % num) / (num - 1);
325                 xcol.blue = 65535 * (i % num) / (num - 1);
326                 xcol.flags = DoRed | DoGreen | DoBlue;
327                 if (!XAllocColor(fl_display,
328                                  fl_state[fl_get_vclass()].colormap, &xcol)) {
329                         if (i) XFreeColors(fl_display,
330                                            fl_state[fl_get_vclass()].colormap,
331                                            gs_pixels, i, 0);
332                         if(lyxerr.debugging()) {
333                                 lyxerr << "Cannot allocate color cube "
334                                        << num << endl;;
335                         }
336                         AllocColors(num - 1);
337                         return;
338                 }
339                 gs_pixels[i] = xcol.pixel;
340         }
341         gs_color = true;
342         gs_gray = false;
343         gs_spc = num;
344         gs_num_pixels = num * num * num;
345 }
346
347
348 // allocate grayscale ramp
349 static
350 void AllocGrays(int num)
351 {
352         if (lyxerr.debugging()) {
353                 lyxerr << "Allocating grayscale colormap "
354                        << num << endl;
355         }
356
357         if (num < 4) {
358                 lyxerr << "Error allocating grayscale colormap." << endl;
359                 gs_color = false;
360                 return;
361         }
362         if (num > 128) num = 128;
363         XColor xcol;
364         for (int i = 0; i < num; ++i) {
365                 xcol.red = xcol.green = xcol.blue = 65535 * i / (num - 1);
366                 xcol.flags = DoRed | DoGreen | DoBlue;
367                 if (!XAllocColor(fl_display,
368                                  fl_state[fl_get_vclass()].colormap, &xcol)) {
369                         if (i) XFreeColors(fl_display,
370                                            fl_state[fl_get_vclass()].colormap,
371                                            gs_pixels, i, 0);
372                         if (lyxerr.debugging()) {
373                                 lyxerr << "Cannot allocate grayscale " 
374                                        << num << endl;
375                         }
376                         AllocGrays(num / 2);
377                         return;
378                 }
379                 gs_pixels[i] = xcol.pixel;
380         }
381         gs_color = true;
382         gs_gray = false;
383         gs_num_pixels = num;
384 }
385
386
387 void InitFigures()
388 {
389         bmparrsize = figarrsize = figallocchunk;
390         typedef Figref * Figref_p;
391         figures = new Figref_p[figallocchunk];
392         typedef figdata * figdata_p;
393         bitmaps = new figdata_p[figallocchunk];
394
395         unsigned int k;
396         for (unsigned int i = 0; i < 256; ++i) {
397                 k = 0;
398                 for (unsigned int j = 0; j < 8; ++j)
399                         if (i & (1 << (7-j))) k |= 1 << j;
400                 bittable[i] = char(~k);
401         }
402
403         fl_add_canvas_handler(figinset_canvas, ClientMessage,
404                               GhostscriptMsg, current_view->owner()->getMainForm());
405
406         // allocate color cube on pseudo-color display
407         // first get visual
408         gs_color = false;
409         local_gc_copy = createGC();
410
411         Visual * vi = DefaultVisual(fl_display, DefaultScreen(fl_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 void DoneFigures()
437 {
438         delete[] figures;
439         delete[] bitmaps;
440         figarrsize = 0;
441         bmparrsize = 0;
442
443         lyxerr.debug() << "Unregistering figures..." << endl;
444
445         fl_remove_canvas_handler(figinset_canvas, ClientMessage,
446                                  GhostscriptMsg);
447 }
448
449
450 int FindBmpIndex(figdata * tmpdata)
451 {
452         int i = 0;
453         while (i < bmpinsref) {
454                 if (bitmaps[i] == tmpdata) return i;
455                 ++i;
456         }
457         return i;
458 }
459
460
461 static void freefigdata(figdata * tmpdata)
462 {
463         tmpdata->ref--;
464         if (tmpdata->ref) return;
465
466         if (tmpdata->gspid > 0) {
467                 int pid = tmpdata->gspid;
468                 char buf[128];
469                 // kill ghostscript and unlink it's files
470                 tmpdata->gspid = -1;
471                 lyx::kill(pid, SIGKILL);
472                 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
473                 unlink(buf);
474         }
475
476         if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
477         delete tmpdata;
478         int i = FindBmpIndex(tmpdata);
479         --bmpinsref;
480         while (i < bmpinsref) {
481                 bitmaps[i] = bitmaps[i + 1];
482                 ++i;
483         }
484 }
485
486
487 static 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 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
704 {
705         // recompute the stuff and put in the queue
706         queue_element p;
707         p.ofsx = psx;
708         p.ofsy = psy;
709         p.rx = (float(data->raw_wid) * 72.0) / pswid;
710         p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
711
712         p.data = data;
713
714         gsqueue.push(p);
715
716         // if possible, run the queue
717         runqueue();
718 }
719
720
721 static figdata * getfigdata(int wid, int hgh, string const & fname, 
722                             int psx, int psy, int pswid, int pshgh, 
723                             int raw_wid, int raw_hgh, float angle, char flags)
724 {
725         /* first search for an exact match with fname and width/height */
726
727         if (fname.empty()) return 0;
728
729         int i = 0;
730         while (i < bmpinsref) {
731                 if (bitmaps[i]->wid == wid && bitmaps[i]->hgh == hgh &&
732                     bitmaps[i]->flags == flags && bitmaps[i]->fname == fname &&
733                     bitmaps[i]->angle == angle) {
734                         bitmaps[i]->ref++;
735                         return bitmaps[i];
736                 }
737                 ++i;
738         }
739         /* not found -> create new record or return 0 if no record */
740         ++bmpinsref;
741         if (bmpinsref > bmparrsize) {
742                 // allocate more space
743                 bmparrsize += figallocchunk;
744                 typedef figdata * figdata_p;
745                 figdata ** tmp = new figdata_p[bmparrsize];
746                 memcpy(tmp, bitmaps,
747                        sizeof(figdata*) * (bmparrsize - figallocchunk));
748                 delete[] bitmaps;
749                 bitmaps = tmp;
750         }
751         figdata * p = new figdata;
752         bitmaps[bmpinsref-1] = p;
753         p->wid = wid;
754         p->hgh = hgh;
755         p->raw_wid = raw_wid;
756         p->raw_hgh = raw_hgh;
757         p->angle = angle;
758         p->fname = fname;
759         p->flags = flags;
760         XWindowAttributes wa;
761         XGetWindowAttributes(fl_display, fl_get_canvas_id(
762                 figinset_canvas), &wa);
763
764         if (lyxerr.debugging()) {
765                 lyxerr << "Create pixmap disp:" << fl_display
766                        << " scr:" << DefaultScreen(fl_display)
767                        << " w:" << wid
768                        << " h:" << hgh
769                        << " depth:" << wa.depth << endl;
770         }
771         
772         p->ref = 1;
773         p->reading = false;
774         p->broken = false;
775         p->gspid = -1;
776         if (flags) {
777                 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
778                         figinset_canvas), wid, hgh, wa.depth);
779                 p->gsdone = false;
780                 // initialize reading of .eps file with correct sizes and stuff
781                 addwait(psx, psy, pswid, pshgh, p);
782                 p->reading = true;
783         } else {
784                 p->bitmap = None;
785                 p->gsdone = true;
786         }
787
788         return p;
789 }
790
791
792 static
793 void getbitmap(figdata * p)
794 {
795         p->gspid = -1;
796 }
797
798
799 static
800 void makeupdatelist(figdata * p)
801 {
802         for (int i = 0; i < figinsref; ++i)
803                 if (figures[i]->data == p) {
804                         if (lyxerr.debugging()) {
805                                 lyxerr << "Updating inset "
806                                        << figures[i]->inset
807                                        << endl;
808                         }
809                         // add inset figures[i]->inset into to_update list
810                         current_view->pushIntoUpdateList(figures[i]->inset);
811                         
812                         //PutInsetIntoInsetUpdateList(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 void getbitmaps()
900 {
901         bitmap_waiting = false;
902         for (int i = 0; i < bmpinsref; ++i)
903                 if (bitmaps[i]->gspid > 0 && !bitmaps[i]->reading)
904                         getbitmap(bitmaps[i]);
905 }
906
907
908 static void RegisterFigure(InsetFig * fi)
909 {
910         if (figinsref == 0) InitFigures();
911         fi->form = 0;
912         ++figinsref;
913         if (figinsref > figarrsize) {
914                 // allocate more space
915                 figarrsize += figallocchunk;
916                 typedef Figref * Figref_p;
917                 Figref ** tmp = new Figref_p[figarrsize];
918                 memcpy(tmp, figures,
919                        sizeof(Figref*)*(figarrsize-figallocchunk));
920                 delete[] figures;
921                 figures = tmp;
922         }
923         Figref * tmpfig = new Figref;
924         tmpfig->data = 0;
925         tmpfig->inset = fi;
926         figures[figinsref-1] = tmpfig;
927         fi->figure = tmpfig;
928
929         if (lyxerr.debugging()) {
930                 lyxerr << "Register Figure: buffer:["
931                        << current_view->buffer() << "]" << endl;
932         }
933 }
934
935
936 int FindFigIndex(Figref * tmpfig)
937 {
938         int i = 0;
939         while (i < figinsref) {
940                 if (figures[i] == tmpfig) return i;
941                 ++i;
942         }
943         return i;
944 }
945
946
947 static void UnregisterFigure(InsetFig * fi)
948 {
949         Figref * tmpfig = fi->figure;
950
951         if (tmpfig->data) freefigdata(tmpfig->data);
952         if (tmpfig->inset->form) {
953                 if (tmpfig->inset->form->Figure->visible) {
954                         fl_set_focus_object(tmpfig->inset->form->Figure,
955                                             tmpfig->inset->form->OkBtn);
956                         fl_hide_form(tmpfig->inset->form->Figure);
957                 }
958 #if FL_REVISION == 89
959 #warning Reactivate this free_form calls
960 #else
961                 fl_free_form(tmpfig->inset->form->Figure);
962                 free(tmpfig->inset->form); // Why free?
963                 tmpfig->inset->form = 0;
964 #endif
965         }
966         int i = FindFigIndex(tmpfig);
967         --figinsref;
968         while (i < figinsref) {
969                 figures[i] = figures[i+1];
970                 ++i;
971         }
972         delete tmpfig;
973
974         if (figinsref == 0) DoneFigures();
975 }
976
977
978 static string NextToken(istream & is)
979 {
980         string token;
981         char c;
982         if (!is.eof()) {
983                 do {
984                         is.get(c);
985                         token += c;
986                 } while (!is.eof() && !isspace(c));
987                 token.erase(token.length() - 1); // remove the isspace
988         }
989         return token;
990 }
991
992
993 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
994         : owner(o)
995 {
996         wid = tmpx;
997         hgh = tmpy;
998         wtype = DEF;
999         htype = DEF;
1000         twtype = DEF;
1001         thtype = DEF;
1002         pflags = flags = 9;
1003         psubfigure = subfigure = false;
1004         xwid = xhgh = angle = 0;
1005         pswid = pshgh = 0;
1006         raw_wid = raw_hgh = 0;
1007         changedfname = false;
1008         RegisterFigure(this);
1009 }
1010
1011
1012 InsetFig::~InsetFig()
1013 {
1014         if (lyxerr.debugging()) {
1015                 lyxerr << "Figure destructor called" << endl;
1016         }
1017         UnregisterFigure(this);
1018 }
1019
1020
1021 int InsetFig::ascent(Painter &, LyXFont const &) const
1022 {
1023         return hgh + 3;
1024 }
1025
1026
1027 int InsetFig::descent(Painter &, LyXFont const &) const
1028 {
1029         return 1;
1030 }
1031
1032
1033 int InsetFig::width(Painter &, LyXFont const &) const
1034 {
1035         return wid + 2;
1036 }
1037
1038
1039 void InsetFig::draw(Painter & pain, LyXFont const & f,
1040                     int baseline, float & x) const
1041 {
1042         LyXFont font(f);
1043         
1044         if (bitmap_waiting) getbitmaps();
1045         
1046         // I wish that I didn't have to use this
1047         // but the figinset code is so complicated so
1048         // I don't want to fiddle with it now.
1049
1050         if (figure && figure->data && figure->data->bitmap &&
1051             !figure->data->reading && !figure->data->broken) {
1052                 // draw the bitmap
1053                 pain.pixmap(int(x + 1), baseline - hgh,
1054                             wid, hgh, figure->data->bitmap);
1055
1056                 if (flags & 4)
1057                         pain.rectangle(int(x), baseline - hgh - 1,
1058                                        wid + 1, hgh + 1);
1059                 
1060         } else {
1061                 char * msg = 0;
1062                 // draw frame
1063                 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1064
1065                 if (figure && figure->data) {
1066                         if (figure->data->broken)  msg = _("[render error]");
1067                         else if (figure->data->reading) msg = _("[rendering ... ]");
1068                 } else 
1069                         if (fname.empty()) msg = _("[no file]");
1070                         else if ((flags & 3) == 0) msg = _("[not displayed]");
1071                         else if (lyxrc->ps_command.empty()) msg = _("[no ghostscript]");
1072                 
1073                 if (!msg) msg = _("[unknown error]");
1074                 
1075                 font.setFamily(LyXFont::SANS_FAMILY);
1076                 font.setSize(LyXFont::SIZE_FOOTNOTE);
1077                 string justname = OnlyFilename (fname);
1078                 pain.text(int(x + 8), baseline - font.maxAscent() - 4,
1079                           justname, font);
1080                 
1081                 font.setSize(LyXFont::SIZE_TINY);
1082                 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1083         }
1084         x += width(pain, font);    // ?
1085 }
1086
1087
1088 void InsetFig::Write(ostream & os) const
1089 {
1090         Regenerate();
1091         os << "Figure size " << wid << " " << hgh << "\n";
1092         if (!fname.empty()) {
1093                 string buf1 = OnlyPath(owner->fileName());
1094                 string fname2 = MakeRelPath(fname, buf1);
1095                 os << "file " << fname2 << "\n";
1096         }
1097         if (!subcaption.empty())
1098                 os << "subcaption " << subcaption << "\n";
1099         if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1100         if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1101         if (angle != 0) os << "angle " << angle << "\n";
1102         os << "flags " << flags << "\n";
1103         if (subfigure) os << "subfigure\n";
1104 }
1105
1106
1107 void InsetFig::Read(LyXLex & lex)
1108 {
1109         string buf;
1110         bool finished = false;
1111         
1112         while (lex.IsOK() && !finished) {
1113                 lex.next();
1114
1115                 string const token = lex.GetString();
1116                 lyxerr.debug() << "Token: " << token << endl;
1117                 
1118                 if (token.empty())
1119                         continue;
1120                 else if (token == "\\end_inset") {
1121                         finished = true;
1122                 } else if (token == "file") {
1123                         if (lex.next()) {
1124                                 buf = lex.GetString();
1125                                 string buf1 = OnlyPath(owner->fileName());
1126                                 fname = MakeAbsPath(buf, buf1);
1127                                 changedfname = true;
1128                         }
1129                 } else if (token == "extra") {
1130                         if (lex.next());
1131                         // kept for backwards compability. Delete in 0.13.x
1132                 } else if (token == "subcaption") {
1133                         if (lex.EatLine())
1134                                 subcaption = lex.GetString();
1135                 } else if (token == "label") {
1136                         if (lex.next());
1137                         // kept for backwards compability. Delete in 0.13.x
1138                 } else if (token == "angle") {
1139                         if (lex.next())
1140                                 angle = lex.GetFloat();
1141                 } else if (token == "size") {
1142                         if (lex.next())
1143                                 wid = lex.GetInteger();
1144                         if (lex.next())
1145                                 hgh = lex.GetInteger();
1146                 } else if (token == "flags") {
1147                         if (lex.next())
1148                                 flags = pflags = lex.GetInteger();
1149                 } else if (token == "subfigure") {
1150                         subfigure = psubfigure = true;
1151                 } else if (token == "width") {
1152                         int typ = 0;
1153                         if (lex.next())
1154                                 typ = lex.GetInteger();
1155                         if (lex.next())
1156                                 xwid = lex.GetFloat();
1157                         switch (typ) {
1158                         case DEF: wtype = DEF; break;
1159                         case CM: wtype = CM; break;
1160                         case IN: wtype = IN; break;
1161                         case PER_PAGE: wtype = PER_PAGE; break;
1162                         case PER_COL: wtype = PER_COL; break;
1163                         default:
1164                                 lyxerr.debug() << "Unknown type!" << endl;
1165                                 break;
1166                         }
1167                         twtype = wtype;
1168                 } else if (token == "height") {
1169                         int typ = 0;
1170                         if (lex.next())
1171                                 typ = lex.GetInteger();
1172                         if (lex.next())
1173                                 xhgh = lex.GetFloat();
1174                         switch (typ) {
1175                         case DEF: htype = DEF; break;
1176                         case CM: htype = CM; break;
1177                         case IN: htype = IN; break;
1178                         case PER_PAGE: htype = PER_PAGE; break;
1179                         default:
1180                                 lyxerr.debug() << "Unknown type!" << endl;
1181                                 break;
1182                         }
1183                         thtype = htype;
1184                 }
1185         }
1186         Regenerate();
1187         Recompute();
1188 }
1189
1190
1191 int InsetFig::Latex(ostream & os, signed char /* fragile*/ ) const
1192 {
1193         Regenerate();
1194         if (!cmd.empty()) os << cmd << " ";
1195         return 0;
1196 }
1197
1198
1199 int InsetFig::Latex(string & file, signed char /* fragile*/ ) const
1200 {
1201         Regenerate();
1202         file += cmd + ' ';
1203         return 0;
1204 }
1205
1206
1207 int InsetFig::Linuxdoc(string &/*file*/) const
1208 {
1209         return 0;
1210 }
1211
1212
1213 int InsetFig::DocBook(string & file) const
1214 {
1215         string figurename = fname;
1216
1217         if(suffixIs(figurename, ".eps"))
1218                 figurename.erase(fname.length() - 5);
1219
1220         file += "@<graphic fileref=\"" + figurename + "\"></graphic>";
1221         return 0;
1222 }
1223
1224
1225 void InsetFig::Validate(LaTeXFeatures & features) const
1226 {
1227         features.graphics = true;
1228         if (subfigure) features.subfigure = true;
1229 }
1230
1231
1232 unsigned char InsetFig::Editable() const
1233 {
1234         return 1;
1235 }
1236
1237
1238 bool InsetFig::Deletable() const
1239 {
1240         return false;
1241 }
1242
1243
1244 void InsetFig::Edit(BufferView * bv, int, int)
1245 {
1246         lyxerr.debug() << "Editing InsetFig." << endl;
1247         Regenerate();
1248
1249         // We should have RO-versions of the form instead.
1250         // The actual prevention of altering a readonly doc
1251         // is done in CallbackFig()
1252         if(bv->buffer()->isReadonly()) 
1253                 WarnReadonly(bv->buffer()->fileName());
1254
1255         if (!form) {
1256                 form = create_form_Figure();
1257                 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1258                 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1259                 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1260                 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1261         }
1262         RestoreForm();
1263         if (form->Figure->visible) {
1264                 fl_raise_form(form->Figure);
1265         } else {
1266                 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1267                              FL_FULLBORDER, _("Figure"));
1268         }
1269 }
1270
1271
1272 Inset * InsetFig::Clone() const
1273 {
1274         InsetFig * tmp = new InsetFig(100, 100, owner);
1275
1276         if (lyxerr.debugging()) {
1277                 lyxerr << "Clone Figure: buffer:["
1278                        << current_view->buffer()
1279                        << "], cbuffer:[xx]" << endl;
1280         }
1281
1282         tmp->wid = wid;
1283         tmp->hgh = hgh;
1284         tmp->raw_wid = raw_wid;
1285         tmp->raw_hgh = raw_hgh;
1286         tmp->angle = angle;
1287         tmp->xwid = xwid;
1288         tmp->xhgh = xhgh;
1289         tmp->flags = flags;
1290         tmp->pflags = pflags;
1291         tmp->subfigure = subfigure;
1292         tmp->psubfigure = psubfigure;
1293         tmp->wtype = wtype;
1294         tmp->htype = htype;
1295         tmp->psx = psx;
1296         tmp->psy = psy;
1297         tmp->pswid = pswid;
1298         tmp->pshgh = pshgh;
1299         tmp->fname = fname;
1300         if (!fname.empty() && (flags & 3) && !lyxrc->ps_command.empty()) { 
1301                 // do not display if there is
1302                 // "do not display" chosen (Matthias 260696)
1303                 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1304                                                pswid, pshgh, raw_wid, raw_hgh,
1305                                                angle, flags & (3|8));
1306         } else tmp->figure->data = 0;
1307         tmp->subcaption = subcaption;
1308         tmp->changedfname = false;
1309         tmp->owner = owner;
1310         tmp->Regenerate();
1311         return tmp;
1312 }
1313
1314
1315 Inset::Code InsetFig::LyxCode() const
1316 {
1317         return Inset::GRAPHICS_CODE;
1318 }
1319
1320
1321 void InsetFig::Regenerate() const
1322 {
1323         string cmdbuf;
1324         string resizeW, resizeH;
1325         string rotate, recmd;
1326
1327         if (fname.empty()) {
1328                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1329                 cmd += _("empty figure path");
1330                 cmd += '}';
1331                 return;
1332         }
1333
1334         string buf1 = OnlyPath(owner->fileName());
1335         string fname2 = MakeRelPath(fname, buf1);
1336
1337         string gcmd = "\\includegraphics{" + fname2 + '}';
1338         
1339         switch (wtype) {
1340         case DEF:
1341                 break;
1342         case CM:{// \resizebox*{h-length}{v-length}{text}
1343                 char buf[10];
1344                 sprintf(buf, "%g", xwid); // should find better
1345                 resizeW = buf;
1346                 resizeW += "cm";
1347                 break;
1348         }
1349         case IN: {
1350                 char buf[10];
1351                 sprintf(buf, "%g", xwid);
1352                 resizeW = buf;
1353                 resizeW += "in";
1354                 break;
1355         }
1356         case PER_PAGE:{
1357                 char buf[10];
1358                 sprintf(buf, "%g", xwid/100);
1359                 resizeW = buf;
1360                 resizeW += "\\textwidth";
1361                 break;
1362         }
1363         case PER_COL:{
1364                 char buf[10];
1365                 sprintf(buf, "%g", xwid/100);
1366                 resizeW = buf;
1367                 resizeW += "\\columnwidth";
1368                 break;
1369         }
1370         }
1371
1372         switch (htype) {
1373         case DEF:
1374                 break;
1375         case CM: {
1376                 char buf[10];
1377                 sprintf(buf, "%g", xhgh);
1378                 resizeH = buf;
1379                 resizeH += "cm";
1380                 break;
1381         }
1382         case IN:{
1383                 char buf[10];
1384                 sprintf(buf, "%g", xhgh);
1385                 resizeH = buf;
1386                 resizeH += "in";
1387                 break;
1388         }
1389         case PER_PAGE: {
1390                 char buf[10];
1391                 sprintf(buf, "%g", xhgh/100);
1392                 resizeH = buf;
1393                 resizeH += "\\textheight";
1394                 break;
1395         }
1396         case PER_COL: {
1397                 // Doesn't occur; case exists to suppress compiler warnings.
1398                 break;
1399         }
1400         }
1401
1402         if (!resizeW.empty() || !resizeH.empty()) {
1403                 recmd = "\\resizebox*{";
1404                 if (!resizeW.empty())
1405                         recmd += resizeW;
1406                 else
1407                         recmd += '!';
1408                 recmd += "}{";
1409                 if (!resizeH.empty())
1410                         recmd += resizeH;
1411                 else
1412                         recmd += '!';
1413                 recmd += "}{";
1414         }
1415         
1416         
1417         if (angle != 0) {
1418                 char buf[10];
1419                 sprintf(buf, "%g", angle);
1420                 // \rotatebox{angle}{text}
1421                 rotate = "\\rotatebox{";
1422                 rotate += buf;
1423                 rotate += "}{";
1424         }
1425
1426         cmdbuf = recmd;
1427         cmdbuf += rotate;
1428         cmdbuf += gcmd;
1429         if (!rotate.empty()) cmdbuf += '}';
1430         if (!recmd.empty()) cmdbuf += '}';
1431         if (subfigure) {
1432                 if (!subcaption.empty())
1433                         cmdbuf = "\\subfigure[" + subcaption +
1434                                 "]{" + cmdbuf + "}";
1435                 else
1436                         cmdbuf = "\\subfigure{" + cmdbuf + "}";
1437         }
1438         
1439         cmd = cmdbuf;
1440 }
1441
1442
1443 void InsetFig::TempRegenerate()
1444 {
1445         string cmdbuf;
1446         string resizeW, resizeH;
1447         string rotate, recmd;
1448         
1449         char const * tfname = fl_get_input(form->EpsFile);
1450         string tsubcap = fl_get_input(form->Subcaption);
1451         float tangle = atof(fl_get_input(form->Angle));
1452         float txwid = atof(fl_get_input(form->Width));
1453         float txhgh = atof(fl_get_input(form->Height));
1454
1455         if (!tfname || !*tfname) {
1456                 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1457                 cmd += _("empty figure path");
1458                 cmd += '}';
1459                 return;
1460         }
1461
1462         string buf1 = OnlyPath(owner->fileName());
1463         string fname2 = MakeRelPath(tfname, buf1);
1464         // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1465         string gcmd = "\\includegraphics{" + fname2 + '}';
1466         
1467         switch (twtype) {
1468         case DEF:
1469                 break;
1470         case CM: {// \resizebox*{h-length}{v-length}{text}
1471                 char buf[10];
1472                 sprintf(buf, "%g", txwid); // should find better
1473                 resizeW = buf;
1474                 resizeW += "cm";
1475                 break;
1476         }
1477         case IN: {
1478                 char buf[10];
1479                 sprintf(buf, "%g", txwid);
1480                 resizeW = buf;
1481                 resizeW += "in";
1482                 break;
1483         }
1484         case PER_PAGE: {
1485                 char buf[10];
1486                 sprintf(buf, "%g", txwid/100);
1487                 resizeW = buf;
1488                 resizeW += "\\textwidth";
1489                 break;
1490         }
1491         case PER_COL: {
1492                 char buf[10];
1493                 sprintf(buf, "%g", txwid/100);
1494                 resizeW = buf;
1495                 resizeW += "\\columnwidth";
1496                 break;
1497         }
1498         }
1499
1500         switch (thtype) {
1501         case DEF:
1502                 break;
1503         case CM: {
1504                 char buf[10];
1505                 sprintf(buf, "%g", txhgh);
1506                 resizeH = buf;
1507                 resizeH += "cm";
1508                 break;
1509         }
1510         case IN: {
1511                 char buf[10];
1512                 sprintf(buf, "%g", txhgh);
1513                 resizeH = buf;
1514                 resizeH += "in";
1515                 break;
1516         }
1517         case PER_PAGE: {
1518                 char buf[10];
1519                 sprintf(buf, "%g", txhgh/100);
1520                 resizeH = buf;
1521                 resizeH += "\\textheight";
1522                 break;
1523         }
1524         case PER_COL: {
1525                 // Doesn't occur; case exists to suppress compiler warnings.
1526                 break;
1527         }
1528         }
1529
1530         // \resizebox*{h-length}{v-length}{text}
1531         if (!resizeW.empty() || !resizeH.empty()) {
1532                 recmd = "\\resizebox*{";
1533                 if (!resizeW.empty())
1534                         recmd += resizeW;
1535                 else
1536                         recmd += '!';
1537                 recmd += "}{";
1538                 if (!resizeH.empty())
1539                         recmd += resizeH;
1540                 else
1541                         recmd += '!';
1542                 recmd += "}{";
1543         }
1544         
1545         if (tangle != 0) {
1546                 char buf[10];
1547                 sprintf(buf, "%g", tangle);
1548                 // \rotatebox{angle}{text}
1549                 rotate = "\\rotatebox{";
1550                 rotate += buf;
1551                 rotate += "}{";
1552         }
1553
1554         cmdbuf = recmd;
1555         cmdbuf += rotate;
1556         cmdbuf += gcmd;
1557         if (!rotate.empty()) cmdbuf += '}';
1558         if (!recmd.empty()) cmdbuf += '}';
1559         if (psubfigure && !tsubcap.empty()) {
1560                 cmdbuf = string("\\subfigure{") + tsubcap
1561                         + string("}{") + cmdbuf + "}";
1562         }
1563 }
1564
1565
1566 void InsetFig::Recompute()
1567 {
1568         bool changed = changedfname;
1569         int newx, newy, nraw_x, nraw_y;
1570
1571         if (changed) GetPSSizes();
1572
1573         float sin_a = sin (angle / DEG2PI);  /* rotation; H. Zeller 021296 */
1574         float cos_a = cos (angle / DEG2PI);
1575         int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1576         int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1577
1578         /* now recompute wid and hgh, and if that is changed, set changed */
1579         /* this depends on chosen size of the picture and its bbox */
1580         // This will be redone in 0.13 ... (hen)
1581         if (!fname.empty()) {
1582                 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1583
1584                 newx = frame_wid;
1585                 newy = frame_hgh;
1586                 switch (wtype) {
1587                 case DEF:
1588                         break;
1589                 case CM:        /* cm */
1590                         newx = int(28.346 * xwid);
1591                         break;
1592                 case IN: /* in */
1593                         newx = int(72 * xwid);
1594                         break;
1595                 case PER_PAGE:  /* % of page */
1596                         newx = int(5.95 * xwid);
1597                         break;
1598                 case PER_COL:   /* % of col */
1599                         newx = int(2.975 * xwid);
1600                         break;
1601                 }
1602                 
1603                 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1604                 
1605                 switch (htype) {
1606                 case DEF:
1607                         //lyxerr << "This should not happen!" << endl;
1608                         break;
1609                 case CM:        /* cm */
1610                         newy = int(28.346 * xhgh);
1611                         break;
1612                 case IN: /* in */
1613                         newy = int(72 * xhgh);
1614                         break;
1615                 case PER_PAGE:  /* % of page */
1616                         newy = int(8.42 * xhgh);
1617                         break;
1618                 case PER_COL: 
1619                         // Doesn't occur; case exists to suppress
1620                         // compiler warnings.  
1621                         break;
1622                 }
1623                 if (htype && !wtype && frame_hgh)
1624                         newx = newy*frame_wid/frame_hgh;
1625         } else {
1626                 newx = wid;
1627                 newy = hgh;
1628         }
1629
1630         if (frame_wid == 0)
1631                 nraw_x = 5;
1632         else
1633                 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1634
1635         if (frame_hgh == 0)
1636                 nraw_y = 5;
1637         else
1638                 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1639
1640         // cannot be zero, actually, set it to some minimum, so its clickable
1641         if (newx < 5) newx = 5;
1642         if (newy < 5) newy = 5;
1643
1644         if (newx   != wid     || newy   != hgh     || 
1645             nraw_x != raw_wid || nraw_y != raw_hgh ||
1646             flags  != pflags  || subfigure != psubfigure) 
1647                 changed = true;
1648        
1649         raw_wid = nraw_x;
1650         raw_hgh = nraw_y;
1651         wid = newx;
1652         hgh = newy;
1653         flags = pflags;
1654         subfigure = psubfigure;
1655
1656         if (changed) {
1657                 figdata * pf = figure->data;
1658
1659                 // get new data
1660                 if (!fname.empty() && (flags & 3)
1661                     && !lyxrc->ps_command.empty()) {
1662                         // do not display if there is "do not display"
1663                         // chosen (Matthias 260696)
1664                         figure->data = getfigdata(wid, hgh, fname,
1665                                                   psx, psy, pswid, pshgh,
1666                                                   raw_wid, raw_hgh,
1667                                                   angle, flags & (3|8));
1668                 } else figure->data = 0;
1669
1670                 // free the old data
1671                 if (pf) freefigdata(pf);
1672         }
1673
1674         changedfname = false;
1675 }
1676
1677
1678 void InsetFig::GetPSSizes()
1679 {
1680         /* get %%BoundingBox: from postscript file */
1681         
1682         /* defaults to associated size
1683          * ..just in case the PS-file is not readable (Henner, 24-Aug-97) 
1684          */
1685         psx = 0;
1686         psy = 0;
1687         pswid = wid;
1688         pshgh = hgh;
1689
1690         if (fname.empty()) return;
1691         string p;
1692         ifstream ifs(fname.c_str());
1693
1694         if (!ifs) return;       // file not found !!!!
1695
1696         /* defaults to A4 page */
1697         psx = 0;
1698         psy = 0;
1699         pswid = 595;
1700         pshgh = 842;
1701
1702         char lastchar = 0; ifs.get(lastchar);
1703         for (;;) {
1704                 char c = 0; ifs.get(c);
1705                 if (ifs.eof()) {
1706                         lyxerr.debug() << "End of (E)PS file reached and"
1707                                 " no BoundingBox!" << endl;
1708                         break;
1709                 }
1710                 if (c == '%' && lastchar == '%') {
1711                         p = NextToken(ifs);
1712                         if (p.empty()) break;
1713                         // we should not use this, with it we cannot
1714                         // discover bounding box and end of file.
1715                         //if (strcmp(p, "EndComments") == 0) break;
1716                         lyxerr.debug() << "Token: `" << p << "'" << endl;
1717                         if (p == "BoundingBox:") {
1718                                 float fpsx, fpsy, fpswid, fpshgh;
1719                                 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1720                                         psx = int(fpsx);
1721                                         psy = int(fpsy);
1722                                         pswid = int(fpswid);
1723                                         pshgh = int(fpshgh);
1724                                 }
1725                                 if (lyxerr.debugging()) {
1726                                         lyxerr << "%%%%BoundingBox:"
1727                                                << psx << ' '
1728                                                << psy << ' '
1729                                                << pswid << ' '
1730                                                << pshgh << endl;
1731                                 }
1732                                 break;
1733                         }
1734                         c = 0;
1735                 }
1736                 lastchar = c;
1737         }
1738         pswid -= psx;
1739         pshgh -= psy;
1740
1741 }
1742
1743
1744 void InsetFig::CallbackFig(long arg)
1745 {
1746         bool regen = false;
1747         char const * p;
1748
1749         if (lyxerr.debugging()) {
1750                 lyxerr << "Figure callback, arg " << arg << endl;
1751         }
1752
1753         switch (arg) {
1754         case 10:
1755         case 11:
1756         case 12:        /* width type */
1757         case 13:
1758         case 14:
1759                 switch (arg - 10) {
1760                 case DEF:
1761                         twtype = DEF;
1762                         // put disable here
1763                         fl_deactivate_object(form->Width);
1764                         break;
1765                 case CM:
1766                         twtype = CM;
1767                         // put enable here
1768                         fl_activate_object(form->Width);
1769                         break;
1770                 case IN:
1771                         twtype = IN;
1772                         // put enable here
1773                         fl_activate_object(form->Width);
1774                         break;
1775                 case PER_PAGE:
1776                         twtype = PER_PAGE;
1777                         // put enable here
1778                         fl_activate_object(form->Width);
1779                         break;
1780                 case PER_COL:
1781                         twtype = PER_COL;
1782                         // put enable here
1783                         fl_activate_object(form->Width);
1784                         break;
1785                 default:
1786                         lyxerr.debug() << "Unknown type!" << endl;
1787                         break;
1788                 }
1789                 regen = true;
1790                 break;
1791         case 20:
1792         case 21:
1793         case 22:        /* height type */
1794         case 23:
1795                 switch (arg - 20) {
1796                 case DEF:
1797                         thtype = DEF;
1798                         // put disable here
1799                         fl_deactivate_object(form->Height);
1800                         break;
1801                 case CM:
1802                         thtype = CM;
1803                         // put enable here
1804                         fl_activate_object(form->Height);
1805                         break;
1806                 case IN:
1807                         thtype = IN;
1808                         // put enable here
1809                         fl_activate_object(form->Height);
1810                         break;
1811                 case PER_PAGE:
1812                         thtype = PER_PAGE;
1813                         // put enable here
1814                         fl_activate_object(form->Height);
1815                         break;
1816                 default:
1817                         lyxerr.debug() << "Unknown type!" << endl;
1818                         break;
1819                 }
1820                 regen = true;
1821                 break;
1822         case 3:
1823                 pflags = pflags & ~3;           /* wysiwyg0 */
1824                 break;
1825         case 33:
1826                 pflags = (pflags & ~3) | 1;     /* wysiwyg1 */
1827                 break;
1828         case 43:
1829                 pflags = (pflags & ~3) | 2;     /* wysiwyg2 */
1830                 break;
1831         case 63:
1832                 pflags = (pflags & ~3) | 3;     /* wysiwyg3 */
1833                 break;
1834         case 53:
1835                 pflags ^= 4;    /* frame */
1836                 break;
1837         case 54:
1838                 pflags ^= 8;    /* do translations */
1839                 break;
1840         case 70:
1841                 psubfigure = !psubfigure;       /* This is a subfigure */
1842                 break;
1843         case 2:
1844                 regen = true;           /* regenerate command */
1845                 break;
1846         case 0:                         /* browse file */
1847                 BrowseFile();
1848                 regen = true;
1849                 break;
1850         case 1:                         /* preview */
1851                 p = fl_get_input(form->EpsFile);
1852                 Preview(p);
1853                 break;
1854         case 7:                         /* apply */
1855         case 8:                         /* ok (apply and close) */
1856                 if(!current_view->buffer()->isReadonly()) {
1857                         wtype = twtype;
1858                         htype = thtype;
1859                         xwid = atof(fl_get_input(form->Width));
1860                         xhgh = atof(fl_get_input(form->Height));
1861                         angle = atof(fl_get_input(form->Angle));
1862                         p = fl_get_input(form->EpsFile);
1863                         if (p && *p) {
1864                                 string buf1 = OnlyPath(owner->fileName());
1865                                 fname = MakeAbsPath(p, buf1);
1866                                 changedfname = true;
1867                         } else {
1868                                 if (!fname.empty()) {
1869                                         changedfname = true;
1870                                         fname.clear();
1871                                 }
1872                         }
1873                         subcaption = fl_get_input(form->Subcaption);
1874         
1875                         Regenerate();
1876                         Recompute();
1877                         /* now update inset */
1878                         if (lyxerr.debugging()) {
1879                                 lyxerr << "Update: ["
1880                                        << wid << 'x' << hgh << ']' << endl;
1881                         }
1882                         current_view->updateInset(this, true);
1883                         if (arg == 8) {
1884                                 fl_set_focus_object(form->Figure, form->OkBtn);
1885                                 fl_hide_form(form->Figure);
1886 #if FL_REVISION == 89
1887 #warning Reactivate this free_form calls
1888 #else
1889                                 fl_free_form(form->Figure);
1890                                 free(form); // Why free?
1891                                 form = 0;
1892 #endif
1893                         }
1894                         break;
1895                 } //if not readonly
1896                 //  The user has already been informed about RO in ::Edit
1897                 if(arg == 7) // if 'Apply'
1898                         break;
1899                 // fall through
1900         case 9:                         /* cancel = restore and close */
1901                 fl_set_focus_object(form->Figure, form->OkBtn);
1902                 fl_hide_form(form->Figure);
1903 #if FL_REVISION == 89
1904 #warning Reactivate this free_form calls
1905 #warning Jug, is this still a problem?
1906 #else
1907                 fl_free_form(form->Figure);
1908                 free(form); // Why free?
1909                 form = 0;
1910 #endif
1911                 break;
1912         }
1913
1914         if (regen) TempRegenerate();
1915 }
1916
1917
1918 inline void DisableFigurePanel(FD_Figure * const form)
1919 {
1920         fl_deactivate_object(form->EpsFile);
1921         fl_deactivate_object(form->Browse);
1922         fl_deactivate_object(form->Width);
1923         fl_deactivate_object(form->Height);
1924         fl_deactivate_object(form->Frame);
1925         fl_deactivate_object(form->Translations);
1926         fl_deactivate_object(form->Angle);
1927         fl_deactivate_object(form->HeightGrp);
1928         fl_deactivate_object(form->page2);
1929         fl_deactivate_object(form->Default2);
1930         fl_deactivate_object(form->cm2);
1931         fl_deactivate_object(form->in2);
1932         fl_deactivate_object(form->HeightLabel);
1933         fl_deactivate_object(form->WidthLabel);
1934         fl_deactivate_object(form->DisplayGrp);
1935         fl_deactivate_object(form->Wysiwyg3);
1936         fl_deactivate_object(form->Wysiwyg0);
1937         fl_deactivate_object(form->Wysiwyg2);
1938         fl_deactivate_object(form->Wysiwyg1);
1939         fl_deactivate_object(form->WidthGrp);
1940         fl_deactivate_object(form->Default1);
1941         fl_deactivate_object(form->cm1);
1942         fl_deactivate_object(form->in1);
1943         fl_deactivate_object(form->page1);
1944         fl_deactivate_object(form->column1);
1945         fl_deactivate_object(form->Subcaption);
1946         fl_deactivate_object(form->Subfigure);
1947         fl_deactivate_object (form->OkBtn);
1948         fl_deactivate_object (form->ApplyBtn);
1949         fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1950         fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1951 }
1952
1953
1954 inline void EnableFigurePanel(FD_Figure * const form)
1955 {
1956         fl_activate_object(form->EpsFile);
1957         fl_activate_object(form->Browse);
1958         fl_activate_object(form->Width);
1959         fl_activate_object(form->Height);
1960         fl_activate_object(form->Frame);
1961         fl_activate_object(form->Translations);
1962         fl_activate_object(form->Angle);
1963         fl_activate_object(form->HeightGrp);
1964         fl_activate_object(form->page2);
1965         fl_activate_object(form->Default2);
1966         fl_activate_object(form->cm2);
1967         fl_activate_object(form->in2);
1968         fl_activate_object(form->HeightLabel);
1969         fl_activate_object(form->WidthLabel);
1970         fl_activate_object(form->DisplayGrp);
1971         fl_activate_object(form->Wysiwyg3);
1972         fl_activate_object(form->Wysiwyg0);
1973         fl_activate_object(form->Wysiwyg2);
1974         fl_activate_object(form->Wysiwyg1);
1975         fl_activate_object(form->WidthGrp);
1976         fl_activate_object(form->Default1);
1977         fl_activate_object(form->cm1);
1978         fl_activate_object(form->in1);
1979         fl_activate_object(form->page1);
1980         fl_activate_object(form->column1);
1981         fl_activate_object(form->Subcaption);
1982         fl_activate_object(form->Subfigure);
1983         fl_activate_object (form->OkBtn);
1984         fl_activate_object (form->ApplyBtn);
1985         fl_set_object_lcol (form->OkBtn, FL_BLACK);
1986         fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1987 }
1988
1989
1990 void InsetFig::RestoreForm()
1991 {
1992         char buf[32];
1993
1994         EnableFigurePanel(form);
1995
1996         twtype = wtype;
1997         fl_set_button(form->Default1, (wtype == 0));
1998         fl_set_button(form->cm1, (wtype == 1));
1999         fl_set_button(form->in1, (wtype == 2));
2000         fl_set_button(form->page1, (wtype == 3));
2001         fl_set_button(form->column1, (wtype == 4));
2002         if (wtype == 0) {
2003                 fl_deactivate_object(form->Width);
2004         } else {
2005                 fl_activate_object(form->Width);
2006         }
2007                 
2008         // enable and disable should be put here.
2009         thtype = htype;
2010         fl_set_button(form->Default2, (htype == 0));
2011         fl_set_button(form->cm2, (htype == 1));
2012         fl_set_button(form->in2, (htype == 2));
2013         fl_set_button(form->page2, (htype == 3));
2014         // enable and disable should be put here.
2015         if (htype == 0) {
2016                 fl_deactivate_object(form->Height);
2017         } else {
2018                 fl_activate_object(form->Height);
2019         }
2020
2021         int pflags = flags & 3;
2022         fl_set_button(form->Wysiwyg0, (pflags == 0));
2023         fl_set_button(form->Wysiwyg1, (pflags == 1));
2024         fl_set_button(form->Wysiwyg2, (pflags == 2));
2025         fl_set_button(form->Wysiwyg3, (pflags == 3));
2026         fl_set_button(form->Frame, ((flags & 4) != 0));
2027         fl_set_button(form->Translations, ((flags & 8) != 0));
2028         fl_set_button(form->Subfigure, (subfigure != 0));
2029         pflags = flags;
2030         psubfigure = subfigure;
2031         sprintf(buf, "%g", xwid);
2032         fl_set_input(form->Width, buf);
2033         sprintf(buf, "%g", xhgh);
2034         fl_set_input(form->Height, buf);
2035         sprintf(buf, "%g", angle);
2036         fl_set_input(form->Angle, buf);
2037         if (!fname.empty()){
2038                 string buf1 = OnlyPath(owner->fileName());
2039                 string fname2 = MakeRelPath(fname, buf1);
2040                 fl_set_input(form->EpsFile, fname2.c_str());
2041         }
2042         else fl_set_input(form->EpsFile, "");
2043         fl_set_input(form->Subcaption, subcaption.c_str());
2044         if(current_view->buffer()->isReadonly()) 
2045                 DisableFigurePanel(form);
2046
2047         TempRegenerate();
2048 }
2049
2050
2051 void InsetFig::Preview(char const * p)
2052 {
2053         int pid = fork();
2054
2055         if (pid == -1) {
2056                 lyxerr << "Cannot fork process!" << endl;
2057                 return;         // error
2058         }
2059         if (pid > 0) {
2060                 addpidwait(pid);
2061                 return;         // parent process
2062         }
2063
2064         string buf1 = OnlyPath(owner->fileName());
2065         string buf2 = MakeAbsPath(p, buf1);
2066         
2067         lyxerr << "Error during rendering "
2068                << execlp(lyxrc->view_pspic_command.c_str(),
2069                          lyxrc->view_pspic_command.c_str(),
2070                          buf2.c_str(), 0)
2071                << endl;
2072         _exit(0);
2073 }
2074
2075
2076 void InsetFig::BrowseFile()
2077 {
2078         static string current_figure_path;
2079         static int once = 0;
2080         LyXFileDlg fileDlg;
2081
2082         if (lyxerr.debugging()) {
2083                 lyxerr << "Filename: "
2084                        << owner->fileName() << endl;
2085         }
2086         string p = fl_get_input(form->EpsFile);
2087
2088         string buf = MakeAbsPath(owner->fileName());
2089         string buf2 = OnlyPath(buf);
2090         if (!p.empty()) {
2091                 buf = MakeAbsPath(p, buf2);
2092                 buf = OnlyPath(buf);
2093         } else {
2094                 buf = OnlyPath(owner->fileName().c_str());
2095         }
2096         
2097         // Does user clipart directory exist?
2098         string bufclip = AddName (user_lyxdir, "clipart");      
2099         FileInfo fileInfo(bufclip);
2100         if (!(fileInfo.isOK() && fileInfo.isDir()))
2101                 // No - bail out to system clipart directory
2102                 bufclip = AddName (system_lyxdir, "clipart");   
2103
2104
2105         fileDlg.SetButton(0, _("Clipart"), bufclip); 
2106         fileDlg.SetButton(1, _("Document"), buf); 
2107
2108         bool error = false;
2109         do {
2110                 ProhibitInput();
2111                 if (once) {
2112                         p = fileDlg.Select(_("EPS Figure"),
2113                                            current_figure_path,
2114                                            "*ps", string());
2115                 } else {
2116                         p = fileDlg.Select(_("EPS Figure"), buf,
2117                                            "*ps", string());
2118                 }
2119                 AllowInput();
2120
2121                 if (p.empty()) return;
2122
2123                 buf = MakeRelPath(p, buf2);
2124                 current_figure_path = OnlyPath(p);
2125                 once = 1;
2126                 
2127                 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2128                     || contains(p, "%") || contains(p, " ")) 
2129                         {
2130                                 WriteAlert(_("Filename can't contain any "
2131                                              "of these characters:"),
2132                                            // xgettext:no-c-format
2133                                            _("space, '#', '~', '$' or '%'.")); 
2134                                 error = true;
2135                         }
2136         } while (error);
2137
2138         if (form) fl_set_input(form->EpsFile, buf.c_str());
2139 }
2140
2141
2142 void GraphicsCB(FL_OBJECT * obj, long arg)
2143 {
2144         /* obj->form contains the form */
2145
2146         if (lyxerr.debugging()) {
2147                 lyxerr << "GraphicsCB callback: " << arg << endl;
2148         }
2149
2150         /* find inset we were reacting to */
2151         for (int i = 0; i < figinsref; ++i)
2152                 if (figures[i]->inset->form && figures[i]->inset->form->Figure
2153                     == obj->form) {
2154             
2155                         if (lyxerr.debugging()) {
2156                                 lyxerr << "Calling back figure " << i << endl;
2157                         }
2158                         figures[i]->inset->CallbackFig(arg);
2159                         return;
2160                 }
2161 }
2162
2163
2164 void HideFiguresPopups()
2165 {
2166         for (int i = 0; i < figinsref; ++i)
2167                 if (figures[i]->inset->form 
2168                     && figures[i]->inset->form->Figure->visible) {
2169                         if (lyxerr.debugging()) {
2170                                 lyxerr << "Hiding figure " << i << endl;
2171                         }
2172                         // hide and free the form
2173                         figures[i]->inset->CallbackFig(9);
2174                 }
2175 }