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