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