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