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