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