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