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