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