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