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