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