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