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