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