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