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