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)
41 #include FORMS_H_LOCATION
51 #include "support/filetools.h"
52 #include "LyXView.h" // just because of form_main
54 #include "LaTeXFeatures.h"
57 #include "lyx_gui_misc.h" // CancelCloseBoxCB
58 #include "support/FileInfo.h"
59 #include "support/lyxlib.h"
62 #include "bufferview_funcs.h"
63 #include "ColorHandler.h"
75 using std::ostringstream;
77 extern BufferView * current_view;
78 extern FL_OBJECT * figinset_canvas;
80 extern char ** environ; // is this only redundtant on linux systems? Lgb.
82 static float const DEG2PI = 57.295779513;
84 struct queue_element {
85 float rx, ry; // resolution x and y
86 int ofsx, ofsy; // x and y translation
87 figdata * data; // we are doing it for this data
90 static int const MAXGS = 3; /* maximum 3 gs's at a time */
92 typedef vector<Figref *> figures_type;
93 typedef vector<figdata *> bitmaps_type;
94 static figures_type figures; // all figures
95 static bitmaps_type bitmaps; // all bitmaps
97 static queue<queue_element> gsqueue; // queue for ghostscripting
99 static int gsrunning = 0; /* currently so many gs's are running */
100 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
102 static bool gs_color; // do we allocate colors for gs?
103 static bool color_visual; // is the visual color?
104 static bool gs_xcolor = false; // allocated extended colors
105 static unsigned long gs_pixels[128]; // allocated pixels
106 static int gs_spc; // shades per color
107 static int gs_allcolors; // number of all colors
109 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 string make_tmp(int pid)
151 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
156 void kill_gs(int pid, int sig)
158 if (lyxerr.debugging())
159 lyxerr << "Killing gs " << pid << endl;
161 lyx::unlink(make_tmp(pid));
166 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
169 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
171 if(lyxerr.debugging()) {
172 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
173 << "] pm:[" << e->data.l[1] << "]" << endl;
176 // just kill gs, that way it will work for sure
177 // This loop looks like S**T so it probably is...
178 for (bitmaps_type::iterator it = bitmaps.begin();
179 it != bitmaps.end(); ++it)
180 if (static_cast<long>((*it)->bitmap) ==
181 static_cast<long>(e->data.l[1])) {
186 // first update p->bitmap, if necessary
187 if (p->bitmap != None
188 && p->flags > (1|8) && gs_color && p->wid) {
189 // query current colormap and re-render
190 // the pixmap with proper colors
191 XWindowAttributes wa;
192 register XImage * im;
195 int spc1 = gs_spc - 1;
196 int spc2 = gs_spc * gs_spc;
200 GC gc = local_gc_copy;
202 XGetWindowAttributes(fl_display,
207 if (lyxerr.debugging()) {
208 lyxerr << "Starting image translation "
211 << p->wid << "x" << p->hgh
213 << " " << XYPixmap << endl;
215 // now fork rendering process
217 if (forkstat == -1) {
219 << "Cannot fork, using slow "
220 "method for pixmap translation." << endl;
221 tmpdisp = fl_display;
222 } else if (forkstat > 0) { // parent
224 if (lyxerr.debugging()) {
225 lyxerr << "Spawned child "
228 addpidwait(forkstat);
231 tmpdisp = XOpenDisplay(XDisplayName(0));
234 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
235 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
237 if (lyxerr.debugging()) {
238 lyxerr << "Got the image" << endl;
241 if (lyxerr.debugging()) {
242 lyxerr << "Error getting the image" << endl;
247 // query current colormap
248 XColor * cmap = new XColor[gs_allcolors];
249 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
250 XQueryColors(tmpdisp,
251 fl_state[fl_get_vclass()]
255 // now we process all the image
256 for (y = 0; y < p->hgh; ++y) {
257 for (int x = 0; x < wid; ++x) {
262 gs_pixels[((pc->red+6553)*
263 spc1/65535)*spc2+((pc->green+6553)*
264 spc1/65535)*gs_spc+((pc->blue+6553)*
269 // This must be correct.
271 if (lyxerr.debugging()) {
272 lyxerr << "Putting image back"
275 XPutImage(tmpdisp, p->bitmap,
277 0, 0, p->wid, p->hgh);
279 if (lyxerr.debugging()) {
280 lyxerr << "Done translation"
285 kill_gs(p->gspid, SIGHUP);
287 XCloseDisplay(tmpdisp);
291 kill_gs(p->gspid, SIGHUP);
300 void AllocColors(int num)
301 // allocate color cube numxnumxnum, if possible
303 if (lyxerr.debugging()) {
304 lyxerr << "Allocating color cube " << num
305 << 'x' << num << 'x' << num << endl;
309 lyxerr << "Error allocating color colormap." << endl;
313 if (num > 5) num = 5;
315 for (int i = 0; i < num * num * num; ++i) {
316 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
317 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
318 xcol.blue = short(65535 * (i % num) / (num - 1));
319 xcol.flags = DoRed | DoGreen | DoBlue;
320 if (!XAllocColor(fl_display,
321 fl_state[fl_get_vclass()].colormap, &xcol)) {
322 if (i) XFreeColors(fl_display,
323 fl_state[fl_get_vclass()].colormap,
325 if(lyxerr.debugging()) {
326 lyxerr << "Cannot allocate color cube "
329 AllocColors(num - 1);
332 gs_pixels[i] = xcol.pixel;
339 // allocate grayscale ramp
341 void AllocGrays(int num)
343 if (lyxerr.debugging()) {
344 lyxerr << "Allocating grayscale colormap "
349 lyxerr << "Error allocating grayscale colormap." << endl;
353 if (num > 128) num = 128;
355 for (int i = 0; i < num; ++i) {
356 xcol.red = xcol.green = xcol.blue = 65535 * i / (num - 1);
357 xcol.flags = DoRed | DoGreen | DoBlue;
358 if (!XAllocColor(fl_display,
359 fl_state[fl_get_vclass()].colormap, &xcol)) {
360 if (i) XFreeColors(fl_display,
361 fl_state[fl_get_vclass()].colormap,
363 if (lyxerr.debugging()) {
364 lyxerr << "Cannot allocate grayscale "
370 gs_pixels[i] = xcol.pixel;
379 // if bitmaps and figures are not empty we will leak mem
384 for (unsigned int i = 0; i < 256; ++i) {
386 for (unsigned int j = 0; j < 8; ++j)
387 if (i & (1 << (7-j))) k |= 1 << j;
390 // allocate color cube on pseudo-color display
394 fl_add_canvas_handler(figinset_canvas, ClientMessage,
396 current_view->owner()->getForm());
398 local_gc_copy = createGC();
400 Visual * vi = DefaultVisual(fl_display,
401 DefaultScreen(fl_display));
402 if (lyxerr.debugging()) {
403 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
404 vi->visualid, vi->c_class,
405 vi->bits_per_rgb, vi->map_entries);
407 color_visual = ( (vi->c_class == StaticColor) ||
408 (vi->c_class == PseudoColor) ||
409 (vi->c_class == TrueColor) ||
410 (vi->c_class == DirectColor) );
411 if ((vi->c_class & 1) == 0) return;
412 // now allocate colors
413 if (vi->c_class == GrayScale) {
414 // allocate grayscale
415 AllocGrays(vi->map_entries/2);
417 // allocate normal color
419 while (i * i * i * 2 > vi->map_entries) --i;
422 gs_allcolors = vi->map_entries;
430 // if bitmaps and figures are not empty we will leak mem
434 lyxerr.debug() << "Unregistering figures..." << endl;
436 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
442 void freefigdata(figdata * tmpdata)
445 if (tmpdata->ref) return;
447 if (tmpdata->gspid > 0) {
448 int pid = tmpdata->gspid;
449 // kill ghostscript and unlink it's files
451 kill_gs(pid, SIGKILL);
454 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
455 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
463 // This _have_ to be set before the fork!
464 unsigned long background_pixel =
465 lyxColorHandler->colorPixel(LColor::background);
467 // run queued requests for ghostscript, if any
468 if (!gsrunning && gs_color && !gs_xcolor) {
469 // here alloc all colors, so that gs will use only
470 // those we allocated for it
475 while (gsrunning < MAXGS) {
476 //char tbuf[384]; //, tbuf2[80];
480 if (gsqueue.empty()) {
481 if (!gsrunning && gs_xcolor) {
482 // de-allocate rest of colors
488 queue_element * p = &gsqueue.front();
497 if (lyxerr.debugging()) {
498 lyxerr << "GS start error! Cannot fork."
501 p->data->broken = true;
502 p->data->reading = false;
505 if (pid == 0) { // child
508 Display * tempdisp = XOpenDisplay(XDisplayName(0));
510 // create translation file
512 ofs.open(make_tmp(getpid()).c_str());
513 ofs << "gsave clippath pathbbox grestore\n"
515 << "/ury exch def /urx exch def /lly exch def "
517 << p->data->wid / 2.0 << " "
518 << p->data->hgh / 2.0 << " translate\n"
519 << p->data->angle << " rotate\n"
520 << -(p->data->raw_wid / 2.0) << " "
521 << -(p->data->raw_hgh / 2.0) << " translate\n"
522 << p->rx / 72.0 << " " << p->ry / 72.0
524 << -p->ofsx << " " << -p->ofsy << " translate\n"
526 ofs.close(); // Don't remove this.
528 // gs process - set ghostview environment first
530 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
531 << ' ' << p->data->bitmap;
532 // now set up ghostview property on a window
533 // #warning BUG seems that the only bug here
534 // might be the hardcoded dpi.. Bummer!
536 t1 << "0 0 0 0 " << p->data->wid << ' '
537 << p->data->hgh << " 72 72 0 0 0 0";
539 if (lyxerr.debugging()) {
540 lyxerr << "Will set GHOSTVIEW property to ["
541 << t1.str() << "]" << endl;
543 // wait until property is deleted if executing multiple
545 XGrabServer(tempdisp);
547 // grab server to prevent other child
548 // interfering with setting GHOSTVIEW property
549 // The grabbing goes on for too long, is it
550 // really needed? (Lgb)
551 // I moved most of the grabs... (Lgb)
552 if (lyxerr.debugging()) {
553 lyxerr << "Grabbing the server"
556 prop = XListProperties(tempdisp,
558 figinset_canvas), &nprop);
562 for (i = 0; i < nprop; ++i) {
563 char * p = XGetAtomName(tempdisp,
565 if (strcmp(p, "GHOSTVIEW") == 0) {
567 // We free it when we leave so we don't leak.
573 XFree(reinterpret_cast<char *>(prop)); // jc:
575 // ok, property found, we must wait until
576 // ghostscript deletes it
577 if (lyxerr.debugging()) {
578 lyxerr << "Releasing the server\n["
580 << "] GHOSTVIEW property"
581 " found. Waiting." << endl;
583 XUngrabServer(tempdisp);
586 XGrabServer(tempdisp);
588 XChangeProperty(tempdisp,
589 fl_get_canvas_id(figinset_canvas),
590 XInternAtom(tempdisp, "GHOSTVIEW", false),
591 XInternAtom(tempdisp, "STRING", false),
593 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
595 XUngrabServer(tempdisp);
600 switch (p->data->flags & 3) {
601 case 0: t3 << 'H'; break; // Hidden
602 case 1: t3 << 'M'; break; // Mono
603 case 2: t3 << 'G'; break; // Gray
612 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
613 << ' ' << background_pixel;
615 XGrabServer(tempdisp);
616 XChangeProperty(tempdisp,
617 fl_get_canvas_id(figinset_canvas),
618 XInternAtom(tempdisp,
619 "GHOSTVIEW_COLORS", false),
620 XInternAtom(tempdisp, "STRING", false),
622 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
624 XUngrabServer(tempdisp);
627 if (lyxerr.debugging()) {
628 lyxerr << "Releasing the server" << endl;
630 XCloseDisplay(tempdisp);
632 // set up environment
635 typedef char * char_p;
636 env = new char_p[ne + 2];
637 string tmp = t2.str().c_str();
638 env[0] = new char[tmp.size() + 1];
639 std::copy(tmp.begin(), tmp.end(), env[0]);
640 env[0][tmp.size()] = '\0';
641 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
644 // now make gs command
646 // close(1); do NOT close. If GS writes out
647 // errors it would hang. (Matthias 290596)
649 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
650 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
652 // now chdir into dir with .eps file, to be on the safe
654 lyx::chdir(OnlyPath(p->data->fname));
655 // make temp file name
656 string tmpf = make_tmp(getpid());
657 if (lyxerr.debugging()) {
658 lyxerr << "starting gs " << tmpf << " "
660 << ", pid: " << getpid() << endl;
663 int err = ::execlp(lyxrc.ps_command.c_str(),
664 lyxrc.ps_command.c_str(),
666 "-dNOPAUSE", "-dQUIET",
668 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
669 p->data->fname.c_str(),
670 "showpage.ps", "quit.ps", "-", 0);
671 // if we are still there, an error occurred.
672 lyxerr << "Error executing ghostscript. "
673 << "Code: " << err << endl;
674 lyxerr.debug() << "Cmd: "
678 << p->data->fname << endl;
681 // normal process (parent)
682 if (lyxerr.debugging()) {
683 lyxerr << "GS [" << pid << "] started" << endl;
686 p->data->gspid = pid;
694 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
696 // recompute the stuff and put in the queue
700 p.rx = (float(data->raw_wid) * 72.0) / pswid;
701 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
707 // if possible, run the queue
713 figdata * getfigdata(int wid, int hgh, string const & fname,
714 int psx, int psy, int pswid, int pshgh,
715 int raw_wid, int raw_hgh, float angle, char flags)
717 /* first search for an exact match with fname and width/height */
719 if (fname.empty() || !IsFileReadable(fname))
722 for (bitmaps_type::iterator it = bitmaps.begin();
723 it != bitmaps.end(); ++it) {
724 if ((*it)->wid == wid && (*it)->hgh == hgh &&
725 (*it)->flags == flags && (*it)->fname == fname &&
726 (*it)->angle == angle) {
731 figdata * p = new figdata;
734 p->raw_wid = raw_wid;
735 p->raw_hgh = raw_hgh;
739 bitmaps.push_back(p);
740 XWindowAttributes wa;
741 XGetWindowAttributes(fl_display, fl_get_canvas_id(
742 figinset_canvas), &wa);
744 if (lyxerr.debugging()) {
745 lyxerr << "Create pixmap disp:" << fl_display
746 << " scr:" << DefaultScreen(fl_display)
749 << " depth:" << wa.depth << endl;
757 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
758 figinset_canvas), wid, hgh, wa.depth);
760 // initialize reading of .eps file with correct sizes and stuff
761 addwait(psx, psy, pswid, pshgh, p);
773 void getbitmap(figdata * p)
780 void makeupdatelist(figdata * p)
782 for(figures_type::iterator it = figures.begin();
783 it != figures.end(); ++it)
784 if ((*it)->data == p) {
785 if (lyxerr.debugging()) {
786 lyxerr << "Updating inset "
790 // add inset figures[i]->inset into to_update list
791 current_view->pushIntoUpdateList((*it)->inset);
796 // this func is only "called" in spellchecker.C
797 void sigchldchecker(pid_t pid, int * status)
799 lyxerr.debug() << "Got pid = " << pid << endl;
800 bool pid_handled = false;
801 for (bitmaps_type::iterator it = bitmaps.begin();
802 it != bitmaps.end(); ++it) {
803 if ((*it)->reading && pid == (*it)->gspid) {
804 lyxerr.debug() << "Found pid in bitmaps" << endl;
805 // now read the file and remove it from disk
808 if ((*it)->gsdone) *status = 0;
810 lyxerr.debug() << "GS [" << pid
811 << "] exit OK." << endl;
813 lyxerr << "GS [" << pid << "] error "
815 << WIFEXITED(*status)
816 << " " << WEXITSTATUS(*status)
817 << " S:" << WIFSIGNALED(*status)
818 << " " << WTERMSIG(*status) << endl;
821 bitmap_waiting = true;
824 // remove temporary files
825 lyx::unlink(make_tmp(p->gspid));
829 makeupdatelist((*it));
836 lyxerr.debug() << "Checking pid in pidwait" << endl;
837 list<int>::iterator it = find(pidwaitlist.begin(),
838 pidwaitlist.end(), pid);
839 if (it != pidwaitlist.end()) {
840 lyxerr.debug() << "Found pid in pidwait\n"
841 << "Caught child pid of recompute "
842 "routine" << pid << endl;
843 pidwaitlist.erase(it);
847 lyxerr.debug() << "waitpid error" << endl;
850 lyxerr << "The process or process group specified by "
851 "pid does not exist or is not a child of "
852 "the calling process or can never be in the "
853 "states specified by options." << endl;
856 lyxerr << "waitpid() was interrupted due to the "
857 "receipt of a signal sent by the calling "
861 lyxerr << "An invalid value was specified for "
865 lyxerr << "Unknown error from waitpid" << endl;
868 } else if (pid == 0) {
869 lyxerr << "waitpid nohang" << endl;;
871 lyxerr.debug() << "normal exit from childhandler" << endl;
879 bitmap_waiting = false;
880 for (bitmaps_type::iterator it = bitmaps.begin();
881 it != bitmaps.end(); ++it)
882 if ((*it)->gspid > 0 && !(*it)->reading)
888 void RegisterFigure(InsetFig * fi)
890 if (figures.empty()) InitFigures();
892 Figref * tmpfig = new Figref;
895 figures.push_back(tmpfig);
898 if (lyxerr.debugging()) {
899 lyxerr << "Register Figure: buffer:["
900 << current_view->buffer() << "]" << endl;
906 void UnregisterFigure(InsetFig * fi)
908 Figref * tmpfig = fi->figure;
910 if (tmpfig->data) freefigdata(tmpfig->data);
911 if (tmpfig->inset->form) {
912 if (tmpfig->inset->form->Figure->visible) {
913 fl_set_focus_object(tmpfig->inset->form->Figure,
914 tmpfig->inset->form->OkBtn);
915 fl_hide_form(tmpfig->inset->form->Figure);
917 #if FL_REVISION == 89
918 // CHECK Reactivate this free_form calls
920 fl_free_form(tmpfig->inset->form->Figure);
921 free(tmpfig->inset->form); // Why free?
922 tmpfig->inset->form = 0;
925 figures.erase(find(figures.begin(), figures.end(), tmpfig));
928 if (figures.empty()) DoneFigures();
932 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
942 psubfigure = subfigure = false;
943 xwid = xhgh = angle = 0;
945 raw_wid = raw_hgh = 0;
946 changedfname = false;
947 RegisterFigure(this);
951 InsetFig::~InsetFig()
953 if (lyxerr.debugging()) {
954 lyxerr << "Figure destructor called" << endl;
956 UnregisterFigure(this);
960 int InsetFig::ascent(BufferView *, LyXFont const &) const
966 int InsetFig::descent(BufferView *, LyXFont const &) const
972 int InsetFig::width(BufferView *, LyXFont const &) const
978 void InsetFig::draw(BufferView * bv, LyXFont const & f,
979 int baseline, float & x, bool) const
982 Painter & pain = bv->painter();
984 if (bitmap_waiting) getbitmaps();
986 // I wish that I didn't have to use this
987 // but the figinset code is so complicated so
988 // I don't want to fiddle with it now.
990 if (figure && figure->data && figure->data->bitmap &&
991 !figure->data->reading && !figure->data->broken) {
993 pain.pixmap(int(x + 1), baseline - hgh,
994 wid, hgh, figure->data->bitmap);
997 pain.rectangle(int(x), baseline - hgh - 1,
1002 string lfname = fname;
1003 if (!fname.empty() && GetExtension(fname).empty())
1006 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1008 if (figure && figure->data) {
1009 if (figure->data->broken) msg = _("[render error]");
1010 else if (figure->data->reading) msg = _("[rendering ... ]");
1012 else if (fname.empty())
1013 msg = _("[no file]");
1014 else if (!IsFileReadable(lfname))
1015 msg = _("[bad file name]");
1016 else if ((flags & 3) == 0)
1017 msg = _("[not displayed]");
1018 else if (lyxrc.ps_command.empty())
1019 msg = _("[no ghostscript]");
1021 if (!msg) msg = _("[unknown error]");
1023 font.setFamily(LyXFont::SANS_FAMILY);
1024 font.setSize(LyXFont::SIZE_FOOTNOTE);
1025 string justname = OnlyFilename (fname);
1026 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1029 font.setSize(LyXFont::SIZE_TINY);
1030 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1032 x += width(bv, font); // ?
1036 void InsetFig::Write(Buffer const *, ostream & os) const
1039 os << "Figure size " << wid << " " << hgh << "\n";
1040 if (!fname.empty()) {
1041 string buf1 = OnlyPath(owner->fileName());
1042 string fname2 = MakeRelPath(fname, buf1);
1043 os << "file " << fname2 << "\n";
1045 if (!subcaption.empty())
1046 os << "subcaption " << subcaption << "\n";
1047 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1048 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1049 if (angle != 0) os << "angle " << angle << "\n";
1050 os << "flags " << flags << "\n";
1051 if (subfigure) os << "subfigure\n";
1055 void InsetFig::Read(Buffer const *, LyXLex & lex)
1058 bool finished = false;
1060 while (lex.IsOK() && !finished) {
1063 string const token = lex.GetString();
1064 lyxerr.debug() << "Token: " << token << endl;
1068 else if (token == "\\end_inset") {
1070 } else if (token == "file") {
1072 buf = lex.GetString();
1073 string buf1 = OnlyPath(owner->fileName());
1074 fname = MakeAbsPath(buf, buf1);
1075 changedfname = true;
1077 } else if (token == "extra") {
1079 // kept for backwards compability. Delete in 0.13.x
1080 } else if (token == "subcaption") {
1082 subcaption = lex.GetString();
1083 } else if (token == "label") {
1085 // kept for backwards compability. Delete in 0.13.x
1086 } else if (token == "angle") {
1088 angle = lex.GetFloat();
1089 } else if (token == "size") {
1091 wid = lex.GetInteger();
1093 hgh = lex.GetInteger();
1094 } else if (token == "flags") {
1096 flags = pflags = lex.GetInteger();
1097 } else if (token == "subfigure") {
1098 subfigure = psubfigure = true;
1099 } else if (token == "width") {
1102 typ = lex.GetInteger();
1104 xwid = lex.GetFloat();
1106 case DEF: wtype = DEF; break;
1107 case CM: wtype = CM; break;
1108 case IN: wtype = IN; break;
1109 case PER_PAGE: wtype = PER_PAGE; break;
1110 case PER_COL: wtype = PER_COL; break;
1112 lyxerr.debug() << "Unknown type!" << endl;
1116 } else if (token == "height") {
1119 typ = lex.GetInteger();
1121 xhgh = lex.GetFloat();
1123 case DEF: htype = DEF; break;
1124 case CM: htype = CM; break;
1125 case IN: htype = IN; break;
1126 case PER_PAGE: htype = PER_PAGE; break;
1128 lyxerr.debug() << "Unknown type!" << endl;
1139 int InsetFig::Latex(Buffer const *, ostream & os,
1140 bool /* fragile*/, bool /* fs*/) const
1143 if (!cmd.empty()) os << cmd << " ";
1148 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1154 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1160 int InsetFig::DocBook(Buffer const *, ostream & os) const
1162 string buf1 = OnlyPath(owner->fileName());
1163 string figurename = MakeRelPath(fname, buf1);
1165 if(suffixIs(figurename, ".eps"))
1166 figurename.erase(figurename.length() - 4);
1168 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1173 void InsetFig::Validate(LaTeXFeatures & features) const
1175 features.graphics = true;
1176 if (subfigure) features.subfigure = true;
1180 Inset::EDITABLE InsetFig::Editable() const
1186 bool InsetFig::Deletable() const
1192 string const InsetFig::EditMessage() const
1194 return _("Opened figure");
1198 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1200 lyxerr.debug() << "Editing InsetFig." << endl;
1203 // We should have RO-versions of the form instead.
1204 // The actual prevention of altering a readonly doc
1205 // is done in CallbackFig()
1206 if(bv->buffer()->isReadonly())
1207 WarnReadonly(bv->buffer()->fileName());
1210 form = create_form_Figure();
1211 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1212 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1213 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1214 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1217 if (form->Figure->visible) {
1218 fl_raise_form(form->Figure);
1220 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1221 FL_FULLBORDER, _("Figure"));
1226 Inset * InsetFig::Clone() const
1228 InsetFig * tmp = new InsetFig(100, 100, owner);
1230 if (lyxerr.debugging()) {
1231 lyxerr << "Clone Figure: buffer:["
1232 << current_view->buffer()
1233 << "], cbuffer:[xx]" << endl;
1238 tmp->raw_wid = raw_wid;
1239 tmp->raw_hgh = raw_hgh;
1244 tmp->pflags = pflags;
1245 tmp->subfigure = subfigure;
1246 tmp->psubfigure = psubfigure;
1254 if (!fname.empty() && IsFileReadable(fname)
1255 && (flags & 3) && !lyxrc.ps_command.empty()
1257 // do not display if there is
1258 // "do not display" chosen (Matthias 260696)
1259 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1260 pswid, pshgh, raw_wid, raw_hgh,
1261 angle, flags & (3|8));
1262 } else tmp->figure->data = 0;
1263 tmp->subcaption = subcaption;
1264 tmp->changedfname = false;
1271 Inset::Code InsetFig::LyxCode() const
1273 return Inset::GRAPHICS_CODE;
1278 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1284 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1285 res = tostr(f) + "cm";
1288 res = tostr(f) + "in";
1290 case InsetFig::PER_PAGE:
1291 res = tostr(f/100) + "\\text" + suffix;
1293 case InsetFig::PER_COL:
1294 // Doesn't occur for htype...
1295 res = tostr(f/100) + "\\column" + suffix;
1302 void InsetFig::Regenerate() const
1305 string resizeW, resizeH;
1306 string rotate, recmd;
1308 if (fname.empty()) {
1309 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1310 cmd += _("empty figure path");
1315 string buf1 = OnlyPath(owner->fileName());
1316 string fname2 = MakeRelPath(fname, buf1);
1318 string gcmd = "\\includegraphics{" + fname2 + '}';
1319 resizeW = stringify(wtype, xwid, "width");
1320 resizeH = stringify(htype, xhgh, "height");
1322 if (!resizeW.empty() || !resizeH.empty()) {
1323 recmd = "\\resizebox*{";
1324 if (!resizeW.empty())
1329 if (!resizeH.empty())
1338 // \rotatebox{angle}{text}
1339 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1345 if (!rotate.empty()) cmdbuf += '}';
1346 if (!recmd.empty()) cmdbuf += '}';
1348 if (!subcaption.empty())
1349 cmdbuf = "\\subfigure[" + subcaption +
1350 "]{" + cmdbuf + "}";
1352 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1359 void InsetFig::TempRegenerate()
1362 string resizeW, resizeH;
1363 string rotate, recmd;
1365 char const * tfname = fl_get_input(form->EpsFile);
1366 string tsubcap = fl_get_input(form->Subcaption);
1367 float tangle = atof(fl_get_input(form->Angle));
1368 float txwid = atof(fl_get_input(form->Width));
1369 float txhgh = atof(fl_get_input(form->Height));
1371 if (!tfname || !*tfname) {
1372 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1373 cmd += _("empty figure path");
1378 string buf1 = OnlyPath(owner->fileName());
1379 string fname2 = MakeRelPath(tfname, buf1);
1380 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1381 string gcmd = "\\includegraphics{" + fname2 + '}';
1383 resizeW = stringify(twtype, txwid, "width");
1384 resizeH = stringify(thtype, txhgh, "height");
1386 // \resizebox*{h-length}{v-length}{text}
1387 if (!resizeW.empty() || !resizeH.empty()) {
1388 recmd = "\\resizebox*{";
1389 if (!resizeW.empty())
1394 if (!resizeH.empty())
1402 // \rotatebox{angle}{text}
1403 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1406 cmdbuf = recmd + rotate + gcmd;
1407 if (!rotate.empty()) cmdbuf += '}';
1408 if (!recmd.empty()) cmdbuf += '}';
1409 if (psubfigure && !tsubcap.empty()) {
1410 cmdbuf = string("\\subfigure{") + tsubcap
1411 + string("}{") + cmdbuf + "}";
1416 void InsetFig::Recompute()
1418 bool changed = changedfname;
1419 int newx, newy, nraw_x, nraw_y;
1421 if (changed) GetPSSizes();
1423 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1424 float cos_a = cos (angle / DEG2PI);
1425 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1426 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1428 string lfname = fname;
1429 if (GetExtension(fname).empty())
1432 /* now recompute wid and hgh, and if that is changed, set changed */
1433 /* this depends on chosen size of the picture and its bbox */
1434 // This will be redone in 0.13 ... (hen)
1435 if (!lfname.empty() && IsFileReadable(lfname)) {
1436 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1444 newx = int(28.346 * xwid);
1447 newx = int(72 * xwid);
1449 case PER_PAGE: /* % of page */
1450 newx = int(5.95 * xwid);
1452 case PER_COL: /* % of col */
1453 newx = int(2.975 * xwid);
1457 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1461 //lyxerr << "This should not happen!" << endl;
1464 newy = int(28.346 * xhgh);
1467 newy = int(72 * xhgh);
1469 case PER_PAGE: /* % of page */
1470 newy = int(8.42 * xhgh);
1473 // Doesn't occur; case exists to suppress
1474 // compiler warnings.
1477 if (htype && !wtype && frame_hgh)
1478 newx = newy*frame_wid/frame_hgh;
1487 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1492 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1494 // cannot be zero, actually, set it to some minimum, so its clickable
1495 if (newx < 5) newx = 5;
1496 if (newy < 5) newy = 5;
1498 if (newx != wid || newy != hgh ||
1499 nraw_x != raw_wid || nraw_y != raw_hgh ||
1500 flags != pflags || subfigure != psubfigure)
1508 subfigure = psubfigure;
1511 figdata * pf = figure->data;
1514 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1515 && !lyxrc.ps_command.empty()) {
1516 // do not display if there is "do not display"
1517 // chosen (Matthias 260696)
1518 figure->data = getfigdata(wid, hgh, lfname,
1519 psx, psy, pswid, pshgh,
1521 angle, flags & (3|8));
1522 } else figure->data = 0;
1524 // free the old data
1525 if (pf) freefigdata(pf);
1528 changedfname = false;
1532 void InsetFig::GetPSSizes()
1534 /* get %%BoundingBox: from postscript file */
1536 /* defaults to associated size
1537 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1544 if (fname.empty()) return;
1546 ifstream ifs(fname.c_str());
1548 if (!ifs) return; // file not found !!!!
1550 /* defaults to A4 page */
1556 char lastchar = 0; ifs.get(lastchar);
1558 char c = 0; ifs.get(c);
1560 lyxerr.debug() << "End of (E)PS file reached and"
1561 " no BoundingBox!" << endl;
1564 if (c == '%' && lastchar == '%') {
1566 if (p.empty()) break;
1567 lyxerr.debug() << "Token: `" << p << "'" << endl;
1568 if (p == "BoundingBox:") {
1569 float fpsx, fpsy, fpswid, fpshgh;
1570 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1573 pswid = int(fpswid);
1574 pshgh = int(fpshgh);
1576 if (lyxerr.debugging()) {
1577 lyxerr << "%%%%BoundingBox:"
1595 void InsetFig::CallbackFig(long arg)
1600 if (lyxerr.debugging()) {
1601 lyxerr << "Figure callback, arg " << arg << endl;
1607 case 12: /* width type */
1614 fl_deactivate_object(form->Width);
1619 fl_activate_object(form->Width);
1624 fl_activate_object(form->Width);
1629 fl_activate_object(form->Width);
1634 fl_activate_object(form->Width);
1637 lyxerr.debug() << "Unknown type!" << endl;
1644 case 22: /* height type */
1650 fl_deactivate_object(form->Height);
1655 fl_activate_object(form->Height);
1660 fl_activate_object(form->Height);
1665 fl_activate_object(form->Height);
1668 lyxerr.debug() << "Unknown type!" << endl;
1674 pflags = pflags & ~3; /* wysiwyg0 */
1677 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1680 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1683 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1686 pflags ^= 4; /* frame */
1689 pflags ^= 8; /* do translations */
1692 psubfigure = !psubfigure; /* This is a subfigure */
1695 regen = true; /* regenerate command */
1697 case 0: /* browse file */
1701 case 1: /* preview */
1702 p = fl_get_input(form->EpsFile);
1706 case 8: /* ok (apply and close) */
1707 if(!current_view->buffer()->isReadonly()) {
1710 xwid = atof(fl_get_input(form->Width));
1711 xhgh = atof(fl_get_input(form->Height));
1712 angle = atof(fl_get_input(form->Angle));
1713 p = fl_get_input(form->EpsFile);
1715 string buf1 = OnlyPath(owner->fileName());
1716 fname = MakeAbsPath(p, buf1);
1717 changedfname = true;
1719 if (!fname.empty()) {
1720 changedfname = true;
1724 subcaption = fl_get_input(form->Subcaption);
1728 /* now update inset */
1729 if (lyxerr.debugging()) {
1730 lyxerr << "Update: ["
1731 << wid << 'x' << hgh << ']' << endl;
1733 current_view->updateInset(this, true);
1735 fl_set_focus_object(form->Figure, form->OkBtn);
1736 fl_hide_form(form->Figure);
1737 #if FL_REVISION == 89
1738 // CHECK Reactivate this free_form calls
1740 fl_free_form(form->Figure);
1741 free(form); // Why free?
1747 // The user has already been informed about RO in ::Edit
1748 if(arg == 7) // if 'Apply'
1751 case 9: /* cancel = restore and close */
1752 fl_set_focus_object(form->Figure, form->OkBtn);
1753 fl_hide_form(form->Figure);
1754 #if FL_REVISION == 89
1755 // CHECK Reactivate this free_form calls
1756 // Jug, is this still a problem?
1758 fl_free_form(form->Figure);
1759 free(form); // Why free?
1765 if (regen) TempRegenerate();
1770 void DisableFigurePanel(FD_Figure * const form)
1772 fl_deactivate_object(form->EpsFile);
1773 fl_deactivate_object(form->Browse);
1774 fl_deactivate_object(form->Width);
1775 fl_deactivate_object(form->Height);
1776 fl_deactivate_object(form->Frame);
1777 fl_deactivate_object(form->Translations);
1778 fl_deactivate_object(form->Angle);
1779 fl_deactivate_object(form->HeightGrp);
1780 fl_deactivate_object(form->page2);
1781 fl_deactivate_object(form->Default2);
1782 fl_deactivate_object(form->cm2);
1783 fl_deactivate_object(form->in2);
1784 fl_deactivate_object(form->HeightLabel);
1785 fl_deactivate_object(form->WidthLabel);
1786 fl_deactivate_object(form->DisplayGrp);
1787 fl_deactivate_object(form->Wysiwyg3);
1788 fl_deactivate_object(form->Wysiwyg0);
1789 fl_deactivate_object(form->Wysiwyg2);
1790 fl_deactivate_object(form->Wysiwyg1);
1791 fl_deactivate_object(form->WidthGrp);
1792 fl_deactivate_object(form->Default1);
1793 fl_deactivate_object(form->cm1);
1794 fl_deactivate_object(form->in1);
1795 fl_deactivate_object(form->page1);
1796 fl_deactivate_object(form->column1);
1797 fl_deactivate_object(form->Subcaption);
1798 fl_deactivate_object(form->Subfigure);
1799 fl_deactivate_object (form->OkBtn);
1800 fl_deactivate_object (form->ApplyBtn);
1801 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1802 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1807 void EnableFigurePanel(FD_Figure * const form)
1809 fl_activate_object(form->EpsFile);
1810 fl_activate_object(form->Browse);
1811 fl_activate_object(form->Width);
1812 fl_activate_object(form->Height);
1813 fl_activate_object(form->Frame);
1814 fl_activate_object(form->Translations);
1815 fl_activate_object(form->Angle);
1816 fl_activate_object(form->HeightGrp);
1817 fl_activate_object(form->page2);
1818 fl_activate_object(form->Default2);
1819 fl_activate_object(form->cm2);
1820 fl_activate_object(form->in2);
1821 fl_activate_object(form->HeightLabel);
1822 fl_activate_object(form->WidthLabel);
1823 fl_activate_object(form->DisplayGrp);
1824 fl_activate_object(form->Wysiwyg3);
1825 fl_activate_object(form->Wysiwyg0);
1826 fl_activate_object(form->Wysiwyg2);
1827 fl_activate_object(form->Wysiwyg1);
1828 fl_activate_object(form->WidthGrp);
1829 fl_activate_object(form->Default1);
1830 fl_activate_object(form->cm1);
1831 fl_activate_object(form->in1);
1832 fl_activate_object(form->page1);
1833 fl_activate_object(form->column1);
1834 fl_activate_object(form->Subcaption);
1835 fl_activate_object(form->Subfigure);
1836 fl_activate_object (form->OkBtn);
1837 fl_activate_object (form->ApplyBtn);
1838 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1839 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1843 void InsetFig::RestoreForm()
1845 EnableFigurePanel(form);
1848 fl_set_button(form->Default1, (wtype == 0));
1849 fl_set_button(form->cm1, (wtype == 1));
1850 fl_set_button(form->in1, (wtype == 2));
1851 fl_set_button(form->page1, (wtype == 3));
1852 fl_set_button(form->column1, (wtype == 4));
1854 fl_deactivate_object(form->Width);
1856 fl_activate_object(form->Width);
1859 // enable and disable should be put here.
1861 fl_set_button(form->Default2, (htype == 0));
1862 fl_set_button(form->cm2, (htype == 1));
1863 fl_set_button(form->in2, (htype == 2));
1864 fl_set_button(form->page2, (htype == 3));
1865 // enable and disable should be put here.
1867 fl_deactivate_object(form->Height);
1869 fl_activate_object(form->Height);
1872 int piflags = flags & 3;
1873 fl_set_button(form->Wysiwyg0, (piflags == 0));
1874 fl_set_button(form->Wysiwyg1, (piflags == 1));
1875 fl_set_button(form->Wysiwyg2, (piflags == 2));
1876 fl_set_button(form->Wysiwyg3, (piflags == 3));
1877 fl_set_button(form->Frame, ((flags & 4) != 0));
1878 fl_set_button(form->Translations, ((flags & 8) != 0));
1879 fl_set_button(form->Subfigure, (subfigure != 0));
1881 psubfigure = subfigure;
1882 fl_set_input(form->Width, tostr(xwid).c_str());
1883 fl_set_input(form->Height, tostr(xhgh).c_str());
1884 fl_set_input(form->Angle, tostr(angle).c_str());
1885 if (!fname.empty()){
1886 string buf1 = OnlyPath(owner->fileName());
1887 string fname2 = MakeRelPath(fname, buf1);
1888 fl_set_input(form->EpsFile, fname2.c_str());
1890 else fl_set_input(form->EpsFile, "");
1891 fl_set_input(form->Subcaption, subcaption.c_str());
1892 if(current_view->buffer()->isReadonly())
1893 DisableFigurePanel(form);
1899 void InsetFig::Preview(string const & p)
1904 lyxerr << "Cannot fork process!" << endl;
1909 return; // parent process
1913 if (GetExtension(tfname).empty())
1915 string buf1 = OnlyPath(owner->fileName());
1916 string buf2 = MakeAbsPath(tfname, buf1);
1918 lyxerr << "Error during rendering "
1919 << execlp(lyxrc.view_pspic_command.c_str(),
1920 lyxrc.view_pspic_command.c_str(),
1927 void InsetFig::BrowseFile()
1929 static string current_figure_path;
1930 static int once = 0;
1933 if (lyxerr.debugging()) {
1934 lyxerr << "Filename: "
1935 << owner->fileName() << endl;
1937 string p = fl_get_input(form->EpsFile);
1939 string buf = MakeAbsPath(owner->fileName());
1940 string buf2 = OnlyPath(buf);
1942 buf = MakeAbsPath(p, buf2);
1943 buf = OnlyPath(buf);
1945 buf = OnlyPath(owner->fileName());
1948 // Does user clipart directory exist?
1949 string bufclip = AddName (user_lyxdir, "clipart");
1950 FileInfo fileInfo(bufclip);
1951 if (!(fileInfo.isOK() && fileInfo.isDir()))
1952 // No - bail out to system clipart directory
1953 bufclip = AddName (system_lyxdir, "clipart");
1956 fileDlg.SetButton(0, _("Clipart"), bufclip);
1957 fileDlg.SetButton(1, _("Document"), buf);
1961 ProhibitInput(current_view);
1963 p = fileDlg.Select(_("EPS Figure"),
1964 current_figure_path,
1967 p = fileDlg.Select(_("EPS Figure"), buf,
1970 AllowInput(current_view);
1972 if (p.empty()) return;
1974 buf = MakeRelPath(p, buf2);
1975 current_figure_path = OnlyPath(p);
1978 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1979 || contains(p, "%") || contains(p, " ")) {
1980 WriteAlert(_("Filename can't contain any "
1981 "of these characters:"),
1982 // xgettext:no-c-format
1983 _("space, '#', '~', '$' or '%'."));
1988 if (form) fl_set_input(form->EpsFile, buf.c_str());
1992 void GraphicsCB(FL_OBJECT * obj, long arg)
1994 /* obj->form contains the form */
1996 if (lyxerr.debugging()) {
1997 lyxerr << "GraphicsCB callback: " << arg << endl;
2000 /* find inset we were reacting to */
2001 for (figures_type::iterator it = figures.begin();
2002 it != figures.end(); ++it)
2003 if ((*it)->inset->form && (*it)->inset->form->Figure
2005 if (lyxerr.debugging()) {
2006 lyxerr << "Calling back figure "
2009 (*it)->inset->CallbackFig(arg);
2015 void HideFiguresPopups()
2017 for (figures_type::iterator it = figures.begin();
2018 it != figures.end(); ++it)
2019 if ((*it)->inset->form
2020 && (*it)->inset->form->Figure->visible) {
2021 if (lyxerr.debugging()) {
2022 lyxerr << "Hiding figure " << (*it) << endl;
2024 // hide and free the form
2025 (*it)->inset->CallbackFig(9);