2 * figinset.C - part of LyX project
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.
25 * The above is not totally valid anymore. (Lgb)
35 #include FORMS_H_LOCATION
59 #include "support/filetools.h"
60 #include "LyXView.h" // just because of form_main
62 #include "LaTeXFeatures.h"
65 #include "lyx_gui_misc.h" // CancelCloseBoxCB
66 #include "support/FileInfo.h"
67 #include "support/lyxlib.h"
70 extern BufferView * current_view;
71 extern FL_OBJECT * figinset_canvas;
73 extern char ** environ; // is this only redundtant on linux systems? Lgb.
75 extern void ProhibitInput();
76 extern void AllowInput();
78 static float const DEG2PI = 57.295779513;
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
86 static int const MAXGS = 3; /* maximum 3 gs's at a time */
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
93 static queue<queue_element> gsqueue; // queue for ghostscripting
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 */
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
108 static list<int> pidwaitlist; // pid wait list
115 val.foreground = BlackPixel(fl_display,
116 DefaultScreen(fl_display));
119 val.graphics_exposures = false;
120 val.line_style = LineSolid;
122 return XCreateGC(fl_display, RootWindow(fl_display, 0),
123 GCForeground | GCFunction | GCGraphicsExposures
124 | GCLineWidth | GCLineStyle , &val);
132 void addpidwait(int pid)
134 // adds pid to pid wait list
135 pidwaitlist.push_back(pid);
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';
149 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
154 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
156 if(lyxerr.debugging()) {
157 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
158 << "] pm:[" << e->data.l[1] << "]" << endl;
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])) {
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;
182 int spc1 = gs_spc - 1;
183 int spc2 = gs_spc * gs_spc;
187 GC gc = local_gc_copy;
189 XGetWindowAttributes(fl_display,
194 if (lyxerr.debugging()) {
195 lyxerr << "Starting image translation "
198 << p->wid << "x" << p->hgh
200 << " " << XYPixmap << endl;
202 // now fork rendering process
204 if (forkstat == -1) {
206 << "Cannot fork, using slow "
207 "method for pixmap translation." << endl;
208 tmpdisp = fl_display;
209 } else if (forkstat > 0) { // parent
211 if (lyxerr.debugging()) {
212 lyxerr << "Spawned child "
215 addpidwait(forkstat);
218 tmpdisp = XOpenDisplay(XDisplayName(0));
221 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
222 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
224 if (lyxerr.debugging()) {
225 lyxerr << "Got the image" << endl;
228 if (lyxerr.debugging()) {
229 lyxerr << "Error getting the image" << endl;
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()]
243 // now we process all the image
244 for (y = 0; y < p->hgh; ++y) {
245 for (int x = 0; x < wid; ++x) {
250 gs_pixels[((pc->red+6553)*
251 spc1/65535)*spc2+((pc->green+6553)*
252 spc1/65535)*gs_spc+((pc->blue+6553)*
257 // This must be correct.
259 if (lyxerr.debugging()) {
260 lyxerr << "Putting image back"
263 XPutImage(tmpdisp, p->bitmap,
265 0, 0, p->wid, p->hgh);
267 if (lyxerr.debugging()) {
268 lyxerr << "Done translation"
273 if (lyxerr.debugging()) {
274 lyxerr << "Killing gs "
277 lyx::kill(p->gspid, SIGHUP);
279 sprintf(tmp, "%s/~lyxgs%d.ps",
280 system_tempdir.c_str(),
284 XCloseDisplay(tmpdisp);
288 if (lyxerr.debugging()) {
289 lyxerr << "Killing gs "
292 lyx::kill(p->gspid, SIGHUP);
294 sprintf(tmp, "%s/~lyxgs%d.ps",
295 system_tempdir.c_str(),
306 void AllocColors(int num)
307 // allocate color cube numxnumxnum, if possible
309 if (lyxerr.debugging()) {
310 lyxerr << "Allocating color cube " << num
311 << 'x' << num << 'x' << num << endl;
315 lyxerr << "Error allocating color colormap." << endl;
319 if (num > 5) num = 5;
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,
331 if(lyxerr.debugging()) {
332 lyxerr << "Cannot allocate color cube "
335 AllocColors(num - 1);
338 gs_pixels[i] = xcol.pixel;
343 gs_num_pixels = num * num * num;
347 // allocate grayscale ramp
349 void AllocGrays(int num)
351 if (lyxerr.debugging()) {
352 lyxerr << "Allocating grayscale colormap "
357 lyxerr << "Error allocating grayscale colormap." << endl;
361 if (num > 128) num = 128;
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,
371 if (lyxerr.debugging()) {
372 lyxerr << "Cannot allocate grayscale "
378 gs_pixels[i] = xcol.pixel;
389 // if bitmaps and figures are not empty we will leak mem
394 for (unsigned int i = 0; i < 256; ++i) {
396 for (unsigned int j = 0; j < 8; ++j)
397 if (i & (1 << (7-j))) k |= 1 << j;
398 bittable[i] = char(~k);
401 // allocate color cube on pseudo-color display
405 fl_add_canvas_handler(figinset_canvas, ClientMessage,
406 GhostscriptMsg, current_view->owner()->getMainForm());
408 local_gc_copy = createGC();
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);
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);
426 // allocate normal color
428 while (i * i * i * 2 > vi->map_entries) --i;
431 gs_allcolors = vi->map_entries;
439 // if bitmaps and figures are not empty we will leak mem
443 lyxerr.debug() << "Unregistering figures..." << endl;
445 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
451 void freefigdata(figdata * tmpdata)
454 if (tmpdata->ref) return;
456 if (tmpdata->gspid > 0) {
457 int pid = tmpdata->gspid;
459 // kill ghostscript and unlink it's files
461 lyx::kill(pid, SIGKILL);
462 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
466 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
467 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
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
483 while (gsrunning < MAXGS) {
484 char tbuf[384], tbuf2[80];
488 if (gsqueue.empty()) {
489 if (!gsrunning && gs_xcolor) {
490 // de-allocate rest of colors
496 queue_element * p = &gsqueue.front();
505 if (lyxerr.debugging()) {
506 lyxerr << "GS start error! Cannot fork."
509 p->data->broken = true;
510 p->data->reading = false;
513 if (pid == 0) { // child
514 char ** env, rbuf[80], gbuf[40];
516 Display * tempdisp = XOpenDisplay(XDisplayName(0));
518 // create translation file
519 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
523 ofs << "gsave clippath pathbbox grestore\n"
525 << "/ury exch def /urx exch def /lly exch def "
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
534 << -p->ofsx << " " << -p->ofsy << " translate\n"
536 ofs.close(); // Don't remove this.
538 // gs process - set ghostview environment first
539 sprintf(tbuf2, "GHOSTVIEW=%ld %ld", fl_get_canvas_id(
540 figinset_canvas), p->data->bitmap);
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!
548 if (lyxerr.debugging()) {
549 lyxerr << "Will set GHOSTVIEW property to ["
550 << tbuf << "]" << endl;
552 // wait until property is deleted if executing multiple
555 // grab server to prevent other child
556 // interfering with setting GHOSTVIEW property
557 if (lyxerr.debugging()) {
558 lyxerr << "Grabbing the server"
561 XGrabServer(tempdisp);
562 prop = XListProperties(tempdisp,
564 figinset_canvas), &nprop);
568 for (i = 0; i < nprop; ++i) {
569 char * p = XGetAtomName(tempdisp,
571 if (strcmp(p, "GHOSTVIEW") == 0) {
577 XFree(reinterpret_cast<char *>(prop)); // jc:
579 // release the server
580 XUngrabServer(tempdisp);
582 // ok, property found, we must wait until
583 // ghostscript deletes it
584 if (lyxerr.debugging()) {
585 lyxerr << "Releasing the server\n["
587 << "] GHOSTVIEW property"
588 " found. Waiting." << endl;
594 XChangeProperty(tempdisp,
595 fl_get_canvas_id(figinset_canvas),
596 XInternAtom(tempdisp, "GHOSTVIEW", false),
597 XInternAtom(tempdisp, "STRING", false),
599 reinterpret_cast<unsigned char*>(tbuf),
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
608 tbuf[0] = 'C'; // Color
610 tbuf[0] = 'G'; // Gray
614 sprintf(tbuf+1, " %ld %ld", BlackPixelOfScreen(
615 DefaultScreenOfDisplay(fl_display)),
616 fl_get_pixel(FL_WHITE));
618 XChangeProperty(tempdisp,
619 fl_get_canvas_id(figinset_canvas),
620 XInternAtom(tempdisp,
621 "GHOSTVIEW_COLORS", false),
622 XInternAtom(tempdisp, "STRING", false),
624 reinterpret_cast<unsigned char*>(tbuf),
626 XUngrabServer(tempdisp);
628 if (lyxerr.debugging()) {
629 lyxerr << "Releasing the server" << endl;
631 XCloseDisplay(tempdisp);
633 // set up environment
634 while (environ[ne]) ++ne;
635 typedef char * char_p;
636 env = new char_p[ne + 2];
638 memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
641 // now make gs command
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
649 chdir(OnlyPath(p->data->fname).c_str());
650 // make temp file name
651 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
653 if (lyxerr.debugging()) {
654 lyxerr << "starting gs " << tbuf << " "
656 << ", pid: " << getpid() << endl;
659 int err = execlp(lyxrc.ps_command.c_str(),
660 lyxrc.ps_command.c_str(),
662 "-dNOPAUSE", "-dQUIET",
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: "
674 << p->data->fname << endl;
677 // normal process (parent)
678 if (lyxerr.debugging()) {
679 lyxerr << "GS [" << pid << "] started" << endl;
682 p->data->gspid = pid;
690 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
692 // recompute the stuff and put in the queue
696 p.rx = (float(data->raw_wid) * 72.0) / pswid;
697 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
703 // if possible, run the queue
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)
713 /* first search for an exact match with fname and width/height */
715 if (fname.empty()) return 0;
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) {
726 figdata * p = new figdata;
729 p->raw_wid = raw_wid;
730 p->raw_hgh = raw_hgh;
734 bitmaps.push_back(p);
735 XWindowAttributes wa;
736 XGetWindowAttributes(fl_display, fl_get_canvas_id(
737 figinset_canvas), &wa);
739 if (lyxerr.debugging()) {
740 lyxerr << "Create pixmap disp:" << fl_display
741 << " scr:" << DefaultScreen(fl_display)
744 << " depth:" << wa.depth << endl;
752 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
753 figinset_canvas), wid, hgh, wa.depth);
755 // initialize reading of .eps file with correct sizes and stuff
756 addwait(psx, psy, pswid, pshgh, p);
768 void getbitmap(figdata * p)
775 void makeupdatelist(figdata * p)
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 "
785 // add inset figures[i]->inset into to_update list
786 current_view->pushIntoUpdateList((*it)->inset);
791 // this func is only "called" in spellchecker.C
792 void sigchldchecker(pid_t pid, int * status)
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
803 if ((*it)->gsdone) *status = 0;
805 lyxerr.debug() << "GS [" << pid
806 << "] exit OK." << endl;
808 lyxerr << "GS [" << pid << "] error "
810 << WIFEXITED(*status)
811 << " " << WEXITSTATUS(*status)
812 << " S:" << WIFSIGNALED(*status)
813 << " " << WTERMSIG(*status) << endl;
816 bitmap_waiting = true;
819 // remove temporary files
821 sprintf(tmp, "%s/~lyxgs%d.ps",
822 system_tempdir.c_str(),
828 makeupdatelist((*it));
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);
846 lyxerr.debug() << "waitpid error" << endl;
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;
855 lyxerr << "waitpid() was interrupted due to the "
856 "receipt of a signal sent by the calling "
860 lyxerr << "An invalid value was specified for "
864 lyxerr << "Unknown error from waitpid" << endl;
867 } else if (pid == 0) {
868 lyxerr << "waitpid nohang" << endl;;
870 lyxerr.debug() << "normal exit from childhandler" << endl;
878 bitmap_waiting = false;
879 for (bitmaps_type::iterator it = bitmaps.begin();
880 it != bitmaps.end(); ++it)
881 if ((*it)->gspid > 0 && !(*it)->reading)
887 void RegisterFigure(InsetFig * fi)
889 if (figures.empty()) InitFigures();
891 Figref * tmpfig = new Figref;
894 figures.push_back(tmpfig);
897 if (lyxerr.debugging()) {
898 lyxerr << "Register Figure: buffer:["
899 << current_view->buffer() << "]" << endl;
905 void UnregisterFigure(InsetFig * fi)
907 Figref * tmpfig = fi->figure;
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);
916 #if FL_REVISION == 89
917 #warning Reactivate this free_form calls
919 fl_free_form(tmpfig->inset->form->Figure);
920 free(tmpfig->inset->form); // Why free?
921 tmpfig->inset->form = 0;
924 figures.erase(find(figures.begin(), figures.end(), tmpfig));
927 if (figures.empty()) DoneFigures();
932 string NextToken(istream & is)
940 } while (!is.eof() && !isspace(c));
941 token.erase(token.length() - 1); // remove the isspace
947 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
957 psubfigure = subfigure = false;
958 xwid = xhgh = angle = 0;
960 raw_wid = raw_hgh = 0;
961 changedfname = false;
962 RegisterFigure(this);
966 InsetFig::~InsetFig()
968 if (lyxerr.debugging()) {
969 lyxerr << "Figure destructor called" << endl;
971 UnregisterFigure(this);
975 int InsetFig::ascent(Painter &, LyXFont const &) const
981 int InsetFig::descent(Painter &, LyXFont const &) const
987 int InsetFig::width(Painter &, LyXFont const &) const
993 void InsetFig::draw(Painter & pain, LyXFont const & f,
994 int baseline, float & x) const
998 if (bitmap_waiting) getbitmaps();
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.
1004 if (figure && figure->data && figure->data->bitmap &&
1005 !figure->data->reading && !figure->data->broken) {
1007 pain.pixmap(int(x + 1), baseline - hgh,
1008 wid, hgh, figure->data->bitmap);
1011 pain.rectangle(int(x), baseline - hgh - 1,
1017 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1019 if (figure && figure->data) {
1020 if (figure->data->broken) msg = _("[render error]");
1021 else if (figure->data->reading) msg = _("[rendering ... ]");
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]");
1027 if (!msg) msg = _("[unknown error]");
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,
1035 font.setSize(LyXFont::SIZE_TINY);
1036 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1038 x += width(pain, font); // ?
1042 void InsetFig::Write(ostream & os) const
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";
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";
1061 void InsetFig::Read(LyXLex & lex)
1064 bool finished = false;
1066 while (lex.IsOK() && !finished) {
1069 string const token = lex.GetString();
1070 lyxerr.debug() << "Token: " << token << endl;
1074 else if (token == "\\end_inset") {
1076 } else if (token == "file") {
1078 buf = lex.GetString();
1079 string buf1 = OnlyPath(owner->fileName());
1080 fname = MakeAbsPath(buf, buf1);
1081 changedfname = true;
1083 } else if (token == "extra") {
1085 // kept for backwards compability. Delete in 0.13.x
1086 } else if (token == "subcaption") {
1088 subcaption = lex.GetString();
1089 } else if (token == "label") {
1091 // kept for backwards compability. Delete in 0.13.x
1092 } else if (token == "angle") {
1094 angle = lex.GetFloat();
1095 } else if (token == "size") {
1097 wid = lex.GetInteger();
1099 hgh = lex.GetInteger();
1100 } else if (token == "flags") {
1102 flags = pflags = lex.GetInteger();
1103 } else if (token == "subfigure") {
1104 subfigure = psubfigure = true;
1105 } else if (token == "width") {
1108 typ = lex.GetInteger();
1110 xwid = lex.GetFloat();
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;
1118 lyxerr.debug() << "Unknown type!" << endl;
1122 } else if (token == "height") {
1125 typ = lex.GetInteger();
1127 xhgh = lex.GetFloat();
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;
1134 lyxerr.debug() << "Unknown type!" << endl;
1145 int InsetFig::Latex(ostream & os,
1146 signed char /* fragile*/, bool /* fs*/) const
1149 if (!cmd.empty()) os << cmd << " ";
1154 int InsetFig::Linuxdoc(ostream &) const
1160 int InsetFig::DocBook(ostream & os) const
1162 string figurename = fname;
1164 if(suffixIs(figurename, ".eps"))
1165 figurename.erase(fname.length() - 5);
1167 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1172 void InsetFig::Validate(LaTeXFeatures & features) const
1174 features.graphics = true;
1175 if (subfigure) features.subfigure = true;
1179 Inset::EDITABLE InsetFig::Editable() const
1185 bool InsetFig::Deletable() const
1191 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1193 lyxerr.debug() << "Editing InsetFig." << endl;
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());
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);
1210 if (form->Figure->visible) {
1211 fl_raise_form(form->Figure);
1213 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1214 FL_FULLBORDER, _("Figure"));
1219 Inset * InsetFig::Clone() const
1221 InsetFig * tmp = new InsetFig(100, 100, owner);
1223 if (lyxerr.debugging()) {
1224 lyxerr << "Clone Figure: buffer:["
1225 << current_view->buffer()
1226 << "], cbuffer:[xx]" << endl;
1231 tmp->raw_wid = raw_wid;
1232 tmp->raw_hgh = raw_hgh;
1237 tmp->pflags = pflags;
1238 tmp->subfigure = subfigure;
1239 tmp->psubfigure = psubfigure;
1247 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
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;
1263 Inset::Code InsetFig::LyxCode() const
1265 return Inset::GRAPHICS_CODE;
1269 void InsetFig::Regenerate() const
1272 string resizeW, resizeH;
1273 string rotate, recmd;
1275 if (fname.empty()) {
1276 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1277 cmd += _("empty figure path");
1282 string buf1 = OnlyPath(owner->fileName());
1283 string fname2 = MakeRelPath(fname, buf1);
1285 string gcmd = "\\includegraphics{" + fname2 + '}';
1290 case CM:{// \resizebox*{h-length}{v-length}{text}
1292 sprintf(buf, "%g", xwid); // should find better
1299 sprintf(buf, "%g", xwid);
1306 sprintf(buf, "%g", xwid/100);
1308 resizeW += "\\textwidth";
1313 sprintf(buf, "%g", xwid/100);
1315 resizeW += "\\columnwidth";
1325 sprintf(buf, "%g", xhgh);
1332 sprintf(buf, "%g", xhgh);
1339 sprintf(buf, "%g", xhgh/100);
1341 resizeH += "\\textheight";
1345 // Doesn't occur; case exists to suppress compiler warnings.
1350 if (!resizeW.empty() || !resizeH.empty()) {
1351 recmd = "\\resizebox*{";
1352 if (!resizeW.empty())
1357 if (!resizeH.empty())
1367 sprintf(buf, "%g", angle);
1368 // \rotatebox{angle}{text}
1369 rotate = "\\rotatebox{";
1377 if (!rotate.empty()) cmdbuf += '}';
1378 if (!recmd.empty()) cmdbuf += '}';
1380 if (!subcaption.empty())
1381 cmdbuf = "\\subfigure[" + subcaption +
1382 "]{" + cmdbuf + "}";
1384 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1391 void InsetFig::TempRegenerate()
1394 string resizeW, resizeH;
1395 string rotate, recmd;
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));
1403 if (!tfname || !*tfname) {
1404 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1405 cmd += _("empty figure path");
1410 string buf1 = OnlyPath(owner->fileName());
1411 string fname2 = MakeRelPath(tfname, buf1);
1412 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1413 string gcmd = "\\includegraphics{" + fname2 + '}';
1418 case CM: {// \resizebox*{h-length}{v-length}{text}
1420 sprintf(buf, "%g", txwid); // should find better
1427 sprintf(buf, "%g", txwid);
1434 sprintf(buf, "%g", txwid/100);
1436 resizeW += "\\textwidth";
1441 sprintf(buf, "%g", txwid/100);
1443 resizeW += "\\columnwidth";
1453 sprintf(buf, "%g", txhgh);
1460 sprintf(buf, "%g", txhgh);
1467 sprintf(buf, "%g", txhgh/100);
1469 resizeH += "\\textheight";
1473 // Doesn't occur; case exists to suppress compiler warnings.
1478 // \resizebox*{h-length}{v-length}{text}
1479 if (!resizeW.empty() || !resizeH.empty()) {
1480 recmd = "\\resizebox*{";
1481 if (!resizeW.empty())
1486 if (!resizeH.empty())
1495 sprintf(buf, "%g", tangle);
1496 // \rotatebox{angle}{text}
1497 rotate = "\\rotatebox{";
1505 if (!rotate.empty()) cmdbuf += '}';
1506 if (!recmd.empty()) cmdbuf += '}';
1507 if (psubfigure && !tsubcap.empty()) {
1508 cmdbuf = string("\\subfigure{") + tsubcap
1509 + string("}{") + cmdbuf + "}";
1514 void InsetFig::Recompute()
1516 bool changed = changedfname;
1517 int newx, newy, nraw_x, nraw_y;
1519 if (changed) GetPSSizes();
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)));
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" */
1538 newx = int(28.346 * xwid);
1541 newx = int(72 * xwid);
1543 case PER_PAGE: /* % of page */
1544 newx = int(5.95 * xwid);
1546 case PER_COL: /* % of col */
1547 newx = int(2.975 * xwid);
1551 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1555 //lyxerr << "This should not happen!" << endl;
1558 newy = int(28.346 * xhgh);
1561 newy = int(72 * xhgh);
1563 case PER_PAGE: /* % of page */
1564 newy = int(8.42 * xhgh);
1567 // Doesn't occur; case exists to suppress
1568 // compiler warnings.
1571 if (htype && !wtype && frame_hgh)
1572 newx = newy*frame_wid/frame_hgh;
1581 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1586 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
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;
1592 if (newx != wid || newy != hgh ||
1593 nraw_x != raw_wid || nraw_y != raw_hgh ||
1594 flags != pflags || subfigure != psubfigure)
1602 subfigure = psubfigure;
1605 figdata * pf = figure->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,
1615 angle, flags & (3|8));
1616 } else figure->data = 0;
1618 // free the old data
1619 if (pf) freefigdata(pf);
1622 changedfname = false;
1626 void InsetFig::GetPSSizes()
1628 /* get %%BoundingBox: from postscript file */
1630 /* defaults to associated size
1631 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1638 if (fname.empty()) return;
1640 ifstream ifs(fname.c_str());
1642 if (!ifs) return; // file not found !!!!
1644 /* defaults to A4 page */
1650 char lastchar = 0; ifs.get(lastchar);
1652 char c = 0; ifs.get(c);
1654 lyxerr.debug() << "End of (E)PS file reached and"
1655 " no BoundingBox!" << endl;
1658 if (c == '%' && lastchar == '%') {
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) {
1670 pswid = int(fpswid);
1671 pshgh = int(fpshgh);
1673 if (lyxerr.debugging()) {
1674 lyxerr << "%%%%BoundingBox:"
1692 void InsetFig::CallbackFig(long arg)
1697 if (lyxerr.debugging()) {
1698 lyxerr << "Figure callback, arg " << arg << endl;
1704 case 12: /* width type */
1711 fl_deactivate_object(form->Width);
1716 fl_activate_object(form->Width);
1721 fl_activate_object(form->Width);
1726 fl_activate_object(form->Width);
1731 fl_activate_object(form->Width);
1734 lyxerr.debug() << "Unknown type!" << endl;
1741 case 22: /* height type */
1747 fl_deactivate_object(form->Height);
1752 fl_activate_object(form->Height);
1757 fl_activate_object(form->Height);
1762 fl_activate_object(form->Height);
1765 lyxerr.debug() << "Unknown type!" << endl;
1771 pflags = pflags & ~3; /* wysiwyg0 */
1774 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1777 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1780 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1783 pflags ^= 4; /* frame */
1786 pflags ^= 8; /* do translations */
1789 psubfigure = !psubfigure; /* This is a subfigure */
1792 regen = true; /* regenerate command */
1794 case 0: /* browse file */
1798 case 1: /* preview */
1799 p = fl_get_input(form->EpsFile);
1803 case 8: /* ok (apply and close) */
1804 if(!current_view->buffer()->isReadonly()) {
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);
1812 string buf1 = OnlyPath(owner->fileName());
1813 fname = MakeAbsPath(p, buf1);
1814 changedfname = true;
1816 if (!fname.empty()) {
1817 changedfname = true;
1821 subcaption = fl_get_input(form->Subcaption);
1825 /* now update inset */
1826 if (lyxerr.debugging()) {
1827 lyxerr << "Update: ["
1828 << wid << 'x' << hgh << ']' << endl;
1830 current_view->updateInset(this, true);
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
1837 fl_free_form(form->Figure);
1838 free(form); // Why free?
1844 // The user has already been informed about RO in ::Edit
1845 if(arg == 7) // if 'Apply'
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?
1855 fl_free_form(form->Figure);
1856 free(form); // Why free?
1862 if (regen) TempRegenerate();
1867 void DisableFigurePanel(FD_Figure * const form)
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);
1904 void EnableFigurePanel(FD_Figure * const form)
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);
1940 void InsetFig::RestoreForm()
1944 EnableFigurePanel(form);
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));
1953 fl_deactivate_object(form->Width);
1955 fl_activate_object(form->Width);
1958 // enable and disable should be put here.
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.
1966 fl_deactivate_object(form->Height);
1968 fl_activate_object(form->Height);
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));
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());
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);
2001 void InsetFig::Preview(char const * p)
2006 lyxerr << "Cannot fork process!" << endl;
2011 return; // parent process
2014 string buf1 = OnlyPath(owner->fileName());
2015 string buf2 = MakeAbsPath(p, buf1);
2017 lyxerr << "Error during rendering "
2018 << execlp(lyxrc.view_pspic_command.c_str(),
2019 lyxrc.view_pspic_command.c_str(),
2026 void InsetFig::BrowseFile()
2028 static string current_figure_path;
2029 static int once = 0;
2032 if (lyxerr.debugging()) {
2033 lyxerr << "Filename: "
2034 << owner->fileName() << endl;
2036 string p = fl_get_input(form->EpsFile);
2038 string buf = MakeAbsPath(owner->fileName());
2039 string buf2 = OnlyPath(buf);
2041 buf = MakeAbsPath(p, buf2);
2042 buf = OnlyPath(buf);
2044 buf = OnlyPath(owner->fileName().c_str());
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");
2055 fileDlg.SetButton(0, _("Clipart"), bufclip);
2056 fileDlg.SetButton(1, _("Document"), buf);
2062 p = fileDlg.Select(_("EPS Figure"),
2063 current_figure_path,
2066 p = fileDlg.Select(_("EPS Figure"), buf,
2071 if (p.empty()) return;
2073 buf = MakeRelPath(p, buf2);
2074 current_figure_path = OnlyPath(p);
2077 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2078 || contains(p, "%") || contains(p, " "))
2080 WriteAlert(_("Filename can't contain any "
2081 "of these characters:"),
2082 // xgettext:no-c-format
2083 _("space, '#', '~', '$' or '%'."));
2088 if (form) fl_set_input(form->EpsFile, buf.c_str());
2092 void GraphicsCB(FL_OBJECT * obj, long arg)
2094 /* obj->form contains the form */
2096 if (lyxerr.debugging()) {
2097 lyxerr << "GraphicsCB callback: " << arg << endl;
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
2105 if (lyxerr.debugging()) {
2106 lyxerr << "Calling back figure "
2109 (*it)->inset->CallbackFig(arg);
2115 void HideFiguresPopups()
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;
2124 // hide and free the form
2125 (*it)->inset->CallbackFig(9);