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