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