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