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