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