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