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