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