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