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