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