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"
64 #include "converter.h"
76 using std::ostringstream;
78 extern BufferView * current_view;
79 extern FL_OBJECT * figinset_canvas;
81 extern char ** environ; // is this only redundtant on linux systems? Lgb.
83 static float const DEG2PI = 57.295779513;
85 struct queue_element {
86 float rx, ry; // resolution x and y
87 int ofsx, ofsy; // x and y translation
88 figdata * data; // we are doing it for this data
91 static int const MAXGS = 3; /* maximum 3 gs's at a time */
93 typedef vector<Figref *> figures_type;
94 typedef vector<figdata *> bitmaps_type;
95 static figures_type figures; // all figures
96 static bitmaps_type bitmaps; // all bitmaps
98 static queue<queue_element> gsqueue; // queue for ghostscripting
100 static int gsrunning = 0; /* currently so many gs's are running */
101 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
103 static bool gs_color; // do we allocate colors for gs?
104 static bool color_visual; // is the visual color?
105 static bool gs_xcolor = false; // allocated extended colors
106 static unsigned long gs_pixels[128]; // allocated pixels
107 static int gs_spc; // shades per color
108 static int gs_allcolors; // number of all colors
110 static list<int> pidwaitlist; // pid wait list
116 val.foreground = BlackPixel(fl_display,
117 DefaultScreen(fl_display));
120 val.graphics_exposures = false;
121 val.line_style = LineSolid;
123 return XCreateGC(fl_display, RootWindow(fl_display, 0),
124 GCForeground | GCFunction | GCGraphicsExposures
125 | GCLineWidth | GCLineStyle , &val);
133 void addpidwait(int pid)
135 // adds pid to pid wait list
136 pidwaitlist.push_back(pid);
138 if (lyxerr.debugging()) {
139 lyxerr << "Pids to wait for: \n";
140 for (list<int>::const_iterator cit = pidwaitlist.begin();
141 cit != pidwaitlist.end(); ++cit) {
142 lyxerr << (*cit) << '\n';
150 string make_tmp(int pid)
152 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
157 void kill_gs(int pid, int sig)
159 if (lyxerr.debugging())
160 lyxerr << "Killing gs " << pid << endl;
162 lyx::unlink(make_tmp(pid));
167 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
170 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
172 if(lyxerr.debugging()) {
173 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
174 << "] pm:[" << e->data.l[1] << "]" << endl;
177 // just kill gs, that way it will work for sure
178 // This loop looks like S**T so it probably is...
179 for (bitmaps_type::iterator it = bitmaps.begin();
180 it != bitmaps.end(); ++it)
181 if (static_cast<long>((*it)->bitmap) ==
182 static_cast<long>(e->data.l[1])) {
187 // first update p->bitmap, if necessary
188 if (p->bitmap != None
189 && p->flags > (1|8) && gs_color && p->wid) {
190 // query current colormap and re-render
191 // the pixmap with proper colors
192 XWindowAttributes wa;
193 register XImage * im;
196 int spc1 = gs_spc - 1;
197 int spc2 = gs_spc * gs_spc;
201 GC gc = local_gc_copy;
203 XGetWindowAttributes(fl_display,
208 if (lyxerr.debugging()) {
209 lyxerr << "Starting image translation "
212 << p->wid << "x" << p->hgh
214 << " " << XYPixmap << endl;
216 // now fork rendering process
218 if (forkstat == -1) {
220 << "Cannot fork, using slow "
221 "method for pixmap translation." << endl;
222 tmpdisp = fl_display;
223 } else if (forkstat > 0) { // parent
225 if (lyxerr.debugging()) {
226 lyxerr << "Spawned child "
229 addpidwait(forkstat);
232 tmpdisp = XOpenDisplay(XDisplayName(0));
235 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
236 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
238 if (lyxerr.debugging()) {
239 lyxerr << "Got the image" << endl;
242 if (lyxerr.debugging()) {
243 lyxerr << "Error getting the image" << endl;
248 // query current colormap
249 XColor * cmap = new XColor[gs_allcolors];
250 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
251 XQueryColors(tmpdisp,
252 fl_state[fl_get_vclass()]
256 // now we process all the image
257 for (y = 0; y < p->hgh; ++y) {
258 for (int x = 0; x < wid; ++x) {
263 gs_pixels[((pc->red+6553)*
264 spc1/65535)*spc2+((pc->green+6553)*
265 spc1/65535)*gs_spc+((pc->blue+6553)*
270 // This must be correct.
272 if (lyxerr.debugging()) {
273 lyxerr << "Putting image back"
276 XPutImage(tmpdisp, p->bitmap,
278 0, 0, p->wid, p->hgh);
280 if (lyxerr.debugging()) {
281 lyxerr << "Done translation"
286 kill_gs(p->gspid, SIGHUP);
288 XCloseDisplay(tmpdisp);
292 kill_gs(p->gspid, SIGHUP);
301 void AllocColors(int num)
302 // allocate color cube numxnumxnum, if possible
304 if (lyxerr.debugging()) {
305 lyxerr << "Allocating color cube " << num
306 << 'x' << num << 'x' << num << endl;
310 lyxerr << "Error allocating color colormap." << endl;
314 if (num > 5) num = 5;
316 for (int i = 0; i < num * num * num; ++i) {
317 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
318 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
319 xcol.blue = short(65535 * (i % num) / (num - 1));
320 xcol.flags = DoRed | DoGreen | DoBlue;
321 if (!XAllocColor(fl_display,
322 fl_state[fl_get_vclass()].colormap, &xcol)) {
323 if (i) XFreeColors(fl_display,
324 fl_state[fl_get_vclass()].colormap,
326 if(lyxerr.debugging()) {
327 lyxerr << "Cannot allocate color cube "
330 AllocColors(num - 1);
333 gs_pixels[i] = xcol.pixel;
340 // allocate grayscale ramp
342 void AllocGrays(int num)
344 if (lyxerr.debugging()) {
345 lyxerr << "Allocating grayscale colormap "
350 lyxerr << "Error allocating grayscale colormap." << endl;
354 if (num > 128) num = 128;
356 for (int i = 0; i < num; ++i) {
357 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
358 xcol.flags = DoRed | DoGreen | DoBlue;
359 if (!XAllocColor(fl_display,
360 fl_state[fl_get_vclass()].colormap, &xcol)) {
361 if (i) XFreeColors(fl_display,
362 fl_state[fl_get_vclass()].colormap,
364 if (lyxerr.debugging()) {
365 lyxerr << "Cannot allocate grayscale "
371 gs_pixels[i] = xcol.pixel;
380 // if bitmaps and figures are not empty we will leak mem
384 // allocate color cube on pseudo-color display
388 fl_add_canvas_handler(figinset_canvas, ClientMessage,
390 current_view->owner()->getForm());
392 local_gc_copy = createGC();
394 Visual * vi = DefaultVisual(fl_display,
395 DefaultScreen(fl_display));
396 if (lyxerr.debugging()) {
397 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
398 vi->visualid, vi->c_class,
399 vi->bits_per_rgb, vi->map_entries);
401 color_visual = ( (vi->c_class == StaticColor) ||
402 (vi->c_class == PseudoColor) ||
403 (vi->c_class == TrueColor) ||
404 (vi->c_class == DirectColor) );
405 if ((vi->c_class & 1) == 0) return;
406 // now allocate colors
407 if (vi->c_class == GrayScale) {
408 // allocate grayscale
409 AllocGrays(vi->map_entries/2);
411 // allocate normal color
413 while (i * i * i * 2 > vi->map_entries) --i;
416 gs_allcolors = vi->map_entries;
424 // if bitmaps and figures are not empty we will leak mem
428 lyxerr.debug() << "Unregistering figures..." << endl;
430 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
436 void freefigdata(figdata * tmpdata)
439 if (tmpdata->ref) return;
441 if (tmpdata->gspid > 0) {
442 int pid = tmpdata->gspid;
443 // kill ghostscript and unlink it's files
445 kill_gs(pid, SIGKILL);
448 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
449 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
457 // This _have_ to be set before the fork!
458 unsigned long background_pixel =
459 lyxColorHandler->colorPixel(LColor::background);
461 // run queued requests for ghostscript, if any
462 if (!gsrunning && gs_color && !gs_xcolor) {
463 // here alloc all colors, so that gs will use only
464 // those we allocated for it
469 while (gsrunning < MAXGS) {
470 //char tbuf[384]; //, tbuf2[80];
474 if (gsqueue.empty()) {
475 if (!gsrunning && gs_xcolor) {
476 // de-allocate rest of colors
482 queue_element * p = &gsqueue.front();
491 if (lyxerr.debugging()) {
492 lyxerr << "GS start error! Cannot fork."
495 p->data->broken = true;
496 p->data->reading = false;
499 if (pid == 0) { // child
502 Display * tempdisp = XOpenDisplay(XDisplayName(0));
504 // create translation file
506 ofs.open(make_tmp(getpid()).c_str());
507 ofs << "gsave clippath pathbbox grestore\n"
509 << "/ury exch def /urx exch def /lly exch def "
511 << p->data->wid / 2.0 << " "
512 << p->data->hgh / 2.0 << " translate\n"
513 << p->data->angle << " rotate\n"
514 << -(p->data->raw_wid / 2.0) << " "
515 << -(p->data->raw_hgh / 2.0) << " translate\n"
516 << p->rx / 72.0 << " " << p->ry / 72.0
518 << -p->ofsx << " " << -p->ofsy << " translate\n"
520 ofs.close(); // Don't remove this.
522 // gs process - set ghostview environment first
524 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
525 << ' ' << p->data->bitmap;
526 // now set up ghostview property on a window
527 // #warning BUG seems that the only bug here
528 // might be the hardcoded dpi.. Bummer!
530 t1 << "0 0 0 0 " << p->data->wid << ' '
531 << p->data->hgh << " 72 72 0 0 0 0";
533 if (lyxerr.debugging()) {
534 lyxerr << "Will set GHOSTVIEW property to ["
535 << t1.str() << "]" << endl;
537 // wait until property is deleted if executing multiple
539 XGrabServer(tempdisp);
541 // grab server to prevent other child
542 // interfering with setting GHOSTVIEW property
543 // The grabbing goes on for too long, is it
544 // really needed? (Lgb)
545 // I moved most of the grabs... (Lgb)
546 if (lyxerr.debugging()) {
547 lyxerr << "Grabbing the server"
550 prop = XListProperties(tempdisp,
552 figinset_canvas), &nprop);
556 for (i = 0; i < nprop; ++i) {
557 char * p = XGetAtomName(tempdisp,
559 if (strcmp(p, "GHOSTVIEW") == 0) {
561 // We free it when we leave so we don't leak.
567 XFree(reinterpret_cast<char *>(prop)); // jc:
569 // ok, property found, we must wait until
570 // ghostscript deletes it
571 if (lyxerr.debugging()) {
572 lyxerr << "Releasing the server\n["
574 << "] GHOSTVIEW property"
575 " found. Waiting." << endl;
577 XUngrabServer(tempdisp);
580 XGrabServer(tempdisp);
582 XChangeProperty(tempdisp,
583 fl_get_canvas_id(figinset_canvas),
584 XInternAtom(tempdisp, "GHOSTVIEW", false),
585 XInternAtom(tempdisp, "STRING", false),
587 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
588 int(t1.str().size()));
589 XUngrabServer(tempdisp);
594 switch (p->data->flags & 3) {
595 case 0: t3 << 'H'; break; // Hidden
596 case 1: t3 << 'M'; break; // Mono
597 case 2: t3 << 'G'; break; // Gray
606 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
607 << ' ' << background_pixel;
609 XGrabServer(tempdisp);
610 XChangeProperty(tempdisp,
611 fl_get_canvas_id(figinset_canvas),
612 XInternAtom(tempdisp,
613 "GHOSTVIEW_COLORS", false),
614 XInternAtom(tempdisp, "STRING", false),
616 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
617 int(t3.str().size()));
618 XUngrabServer(tempdisp);
621 if (lyxerr.debugging()) {
622 lyxerr << "Releasing the server" << endl;
624 XCloseDisplay(tempdisp);
626 // set up environment
629 typedef char * char_p;
630 env = new char_p[ne + 2];
631 string tmp = t2.str().c_str();
632 env[0] = new char[tmp.size() + 1];
633 std::copy(tmp.begin(), tmp.end(), env[0]);
634 env[0][tmp.size()] = '\0';
635 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
638 // now make gs command
640 // close(1); do NOT close. If GS writes out
641 // errors it would hang. (Matthias 290596)
643 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
644 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
646 // now chdir into dir with .eps file, to be on the safe
648 lyx::chdir(OnlyPath(p->data->fname));
649 // make temp file name
650 string tmpf = make_tmp(getpid());
651 if (lyxerr.debugging()) {
652 lyxerr << "starting gs " << tmpf << " "
654 << ", pid: " << getpid() << endl;
657 int err = ::execlp(lyxrc.ps_command.c_str(),
658 lyxrc.ps_command.c_str(),
660 "-dNOPAUSE", "-dQUIET",
662 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
663 p->data->fname.c_str(),
664 "showpage.ps", "quit.ps", "-", 0);
665 // if we are still there, an error occurred.
666 lyxerr << "Error executing ghostscript. "
667 << "Code: " << err << endl;
668 lyxerr.debug() << "Cmd: "
672 << p->data->fname << endl;
675 // normal process (parent)
676 if (lyxerr.debugging()) {
677 lyxerr << "GS [" << pid << "] started" << endl;
680 p->data->gspid = pid;
688 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
690 // recompute the stuff and put in the queue
694 p.rx = (float(data->raw_wid) * 72.0) / pswid;
695 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
701 // if possible, run the queue
707 figdata * getfigdata(int wid, int hgh, string const & fname,
708 int psx, int psy, int pswid, int pshgh,
709 int raw_wid, int raw_hgh, float angle, char flags)
711 /* first search for an exact match with fname and width/height */
713 if (fname.empty() || !IsFileReadable(fname))
716 for (bitmaps_type::iterator it = bitmaps.begin();
717 it != bitmaps.end(); ++it) {
718 if ((*it)->wid == wid && (*it)->hgh == hgh &&
719 (*it)->flags == flags && (*it)->fname == fname &&
720 (*it)->angle == angle) {
725 figdata * p = new figdata;
728 p->raw_wid = raw_wid;
729 p->raw_hgh = raw_hgh;
733 bitmaps.push_back(p);
734 XWindowAttributes wa;
735 XGetWindowAttributes(fl_display, fl_get_canvas_id(
736 figinset_canvas), &wa);
738 if (lyxerr.debugging()) {
739 lyxerr << "Create pixmap disp:" << fl_display
740 << " scr:" << DefaultScreen(fl_display)
743 << " depth:" << wa.depth << endl;
751 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
752 figinset_canvas), wid, hgh, wa.depth);
754 // initialize reading of .eps file with correct sizes and stuff
755 addwait(psx, psy, pswid, pshgh, p);
767 void getbitmap(figdata * p)
774 void makeupdatelist(figdata * p)
776 for(figures_type::iterator it = figures.begin();
777 it != figures.end(); ++it)
778 if ((*it)->data == p) {
779 if (lyxerr.debugging()) {
780 lyxerr << "Updating inset "
784 // add inset figures[i]->inset into to_update list
785 current_view->pushIntoUpdateList((*it)->inset);
790 // this func is only "called" in spellchecker.C
791 void sigchldchecker(pid_t pid, int * status)
793 lyxerr.debug() << "Got pid = " << pid << endl;
794 bool pid_handled = false;
795 for (bitmaps_type::iterator it = bitmaps.begin();
796 it != bitmaps.end(); ++it) {
797 if ((*it)->reading && pid == (*it)->gspid) {
798 lyxerr.debug() << "Found pid in bitmaps" << endl;
799 // now read the file and remove it from disk
802 if ((*it)->gsdone) *status = 0;
804 lyxerr.debug() << "GS [" << pid
805 << "] exit OK." << endl;
807 lyxerr << "GS [" << pid << "] error "
809 << WIFEXITED(*status)
810 << " " << WEXITSTATUS(*status)
811 << " S:" << WIFSIGNALED(*status)
812 << " " << WTERMSIG(*status) << endl;
815 bitmap_waiting = true;
818 // remove temporary files
819 lyx::unlink(make_tmp(p->gspid));
823 makeupdatelist((*it));
830 lyxerr.debug() << "Checking pid in pidwait" << endl;
831 list<int>::iterator it = find(pidwaitlist.begin(),
832 pidwaitlist.end(), pid);
833 if (it != pidwaitlist.end()) {
834 lyxerr.debug() << "Found pid in pidwait\n"
835 << "Caught child pid of recompute "
836 "routine" << pid << endl;
837 pidwaitlist.erase(it);
841 lyxerr.debug() << "waitpid error" << endl;
844 lyxerr << "The process or process group specified by "
845 "pid does not exist or is not a child of "
846 "the calling process or can never be in the "
847 "states specified by options." << endl;
850 lyxerr << "waitpid() was interrupted due to the "
851 "receipt of a signal sent by the calling "
855 lyxerr << "An invalid value was specified for "
859 lyxerr << "Unknown error from waitpid" << endl;
862 } else if (pid == 0) {
863 lyxerr << "waitpid nohang" << endl;;
865 lyxerr.debug() << "normal exit from childhandler" << endl;
873 bitmap_waiting = false;
874 for (bitmaps_type::iterator it = bitmaps.begin();
875 it != bitmaps.end(); ++it)
876 if ((*it)->gspid > 0 && !(*it)->reading)
882 void RegisterFigure(InsetFig * fi)
884 if (figures.empty()) InitFigures();
886 Figref * tmpfig = new Figref;
889 figures.push_back(tmpfig);
892 if (lyxerr.debugging()) {
893 lyxerr << "Register Figure: buffer:["
894 << current_view->buffer() << "]" << endl;
900 void UnregisterFigure(InsetFig * fi)
905 Figref * tmpfig = fi->figure;
907 if (tmpfig->data) freefigdata(tmpfig->data);
908 if (tmpfig->inset->form) {
909 if (tmpfig->inset->form->Figure->visible) {
910 fl_set_focus_object(tmpfig->inset->form->Figure,
911 tmpfig->inset->form->OkBtn);
912 fl_hide_form(tmpfig->inset->form->Figure);
914 #if FL_REVISION == 89
915 // CHECK Reactivate this free_form calls
917 fl_free_form(tmpfig->inset->form->Figure);
918 free(tmpfig->inset->form); // Why free?
919 tmpfig->inset->form = 0;
922 figures.erase(find(figures.begin(), figures.end(), tmpfig));
925 if (figures.empty()) DoneFigures();
929 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
939 psubfigure = subfigure = false;
940 xwid = xhgh = angle = 0;
942 raw_wid = raw_hgh = 0;
943 changedfname = false;
944 RegisterFigure(this);
948 InsetFig::~InsetFig()
950 if (lyxerr.debugging()) {
951 lyxerr << "Figure destructor called" << endl;
953 UnregisterFigure(this);
957 int InsetFig::ascent(BufferView *, LyXFont const &) const
963 int InsetFig::descent(BufferView *, LyXFont const &) const
969 int InsetFig::width(BufferView *, LyXFont const &) const
975 void InsetFig::draw(BufferView * bv, LyXFont const & f,
976 int baseline, float & x, bool) const
979 Painter & pain = bv->painter();
981 if (bitmap_waiting) getbitmaps();
983 // I wish that I didn't have to use this
984 // but the figinset code is so complicated so
985 // I don't want to fiddle with it now.
987 if (figure && figure->data && figure->data->bitmap &&
988 !figure->data->reading && !figure->data->broken) {
990 pain.pixmap(int(x + 1), baseline - hgh,
991 wid, hgh, figure->data->bitmap);
994 pain.rectangle(int(x), baseline - hgh - 1,
999 string lfname = fname;
1000 if (!fname.empty() && GetExtension(fname).empty())
1003 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1005 if (figure && figure->data) {
1006 if (figure->data->broken) msg = _("[render error]");
1007 else if (figure->data->reading) msg = _("[rendering ... ]");
1009 else if (fname.empty())
1010 msg = _("[no file]");
1011 else if (!IsFileReadable(lfname))
1012 msg = _("[bad file name]");
1013 else if ((flags & 3) == 0)
1014 msg = _("[not displayed]");
1015 else if (lyxrc.ps_command.empty())
1016 msg = _("[no ghostscript]");
1018 if (!msg) msg = _("[unknown error]");
1020 font.setFamily(LyXFont::SANS_FAMILY);
1021 font.setSize(LyXFont::SIZE_FOOTNOTE);
1022 string justname = OnlyFilename (fname);
1023 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1026 font.setSize(LyXFont::SIZE_TINY);
1027 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1029 x += width(bv, font); // ?
1033 void InsetFig::Write(Buffer const *, ostream & os) const
1036 os << "Figure size " << wid << " " << hgh << "\n";
1037 if (!fname.empty()) {
1038 string buf1 = OnlyPath(owner->fileName());
1039 string fname2 = MakeRelPath(fname, buf1);
1040 os << "file " << fname2 << "\n";
1042 if (!subcaption.empty())
1043 os << "subcaption " << subcaption << "\n";
1044 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1045 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1046 if (angle != 0) os << "angle " << angle << "\n";
1047 os << "flags " << flags << "\n";
1048 if (subfigure) os << "subfigure\n";
1052 void InsetFig::Read(Buffer const *, LyXLex & lex)
1055 bool finished = false;
1057 while (lex.IsOK() && !finished) {
1060 string const token = lex.GetString();
1061 lyxerr.debug() << "Token: " << token << endl;
1065 else if (token == "\\end_inset") {
1067 } else if (token == "file") {
1069 buf = lex.GetString();
1070 string buf1 = OnlyPath(owner->fileName());
1071 fname = MakeAbsPath(buf, buf1);
1072 changedfname = true;
1074 } else if (token == "extra") {
1076 // kept for backwards compability. Delete in 0.13.x
1077 } else if (token == "subcaption") {
1079 subcaption = lex.GetString();
1080 } else if (token == "label") {
1082 // kept for backwards compability. Delete in 0.13.x
1083 } else if (token == "angle") {
1085 angle = lex.GetFloat();
1086 } else if (token == "size") {
1088 wid = lex.GetInteger();
1090 hgh = lex.GetInteger();
1091 } else if (token == "flags") {
1093 flags = pflags = lex.GetInteger();
1094 } else if (token == "subfigure") {
1095 subfigure = psubfigure = true;
1096 } else if (token == "width") {
1099 typ = lex.GetInteger();
1101 xwid = lex.GetFloat();
1103 case DEF: wtype = DEF; break;
1104 case CM: wtype = CM; break;
1105 case IN: wtype = IN; break;
1106 case PER_PAGE: wtype = PER_PAGE; break;
1107 case PER_COL: wtype = PER_COL; break;
1109 lyxerr.debug() << "Unknown type!" << endl;
1113 } else if (token == "height") {
1116 typ = lex.GetInteger();
1118 xhgh = lex.GetFloat();
1120 case DEF: htype = DEF; break;
1121 case CM: htype = CM; break;
1122 case IN: htype = IN; break;
1123 case PER_PAGE: htype = PER_PAGE; break;
1125 lyxerr.debug() << "Unknown type!" << endl;
1136 int InsetFig::Latex(Buffer const *, ostream & os,
1137 bool /* fragile*/, bool /* fs*/) const
1140 if (!cmd.empty()) os << cmd << " ";
1145 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1151 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1157 int InsetFig::DocBook(Buffer const *, ostream & os) const
1159 string buf1 = OnlyPath(owner->fileName());
1160 string figurename = MakeRelPath(fname, buf1);
1162 if(suffixIs(figurename, ".eps"))
1163 figurename.erase(figurename.length() - 4);
1165 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1170 void InsetFig::Validate(LaTeXFeatures & features) const
1172 features.graphics = true;
1173 if (subfigure) features.subfigure = true;
1177 Inset::EDITABLE InsetFig::Editable() const
1183 bool InsetFig::Deletable() const
1189 string const InsetFig::EditMessage() const
1191 return _("Opened figure");
1195 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1197 lyxerr.debug() << "Editing InsetFig." << endl;
1200 // We should have RO-versions of the form instead.
1201 // The actual prevention of altering a readonly doc
1202 // is done in CallbackFig()
1203 if(bv->buffer()->isReadonly())
1204 WarnReadonly(bv->buffer()->fileName());
1207 form = create_form_Figure();
1208 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1209 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1210 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1211 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1214 if (form->Figure->visible) {
1215 fl_raise_form(form->Figure);
1217 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1218 FL_FULLBORDER, _("Figure"));
1223 Inset * InsetFig::Clone() const
1225 InsetFig * tmp = new InsetFig(100, 100, owner);
1227 if (lyxerr.debugging()) {
1228 lyxerr << "Clone Figure: buffer:["
1229 << current_view->buffer()
1230 << "], cbuffer:[xx]" << endl;
1235 tmp->raw_wid = raw_wid;
1236 tmp->raw_hgh = raw_hgh;
1241 tmp->pflags = pflags;
1242 tmp->subfigure = subfigure;
1243 tmp->psubfigure = psubfigure;
1251 if (!fname.empty() && IsFileReadable(fname)
1252 && (flags & 3) && !lyxrc.ps_command.empty()
1254 // do not display if there is
1255 // "do not display" chosen (Matthias 260696)
1256 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1257 pswid, pshgh, raw_wid, raw_hgh,
1258 angle, flags & (3|8));
1259 } else tmp->figure->data = 0;
1260 tmp->subcaption = subcaption;
1261 tmp->changedfname = false;
1268 Inset::Code InsetFig::LyxCode() const
1270 return Inset::GRAPHICS_CODE;
1275 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1281 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1282 res = tostr(f) + "cm";
1285 res = tostr(f) + "in";
1287 case InsetFig::PER_PAGE:
1288 res = tostr(f/100) + "\\text" + suffix;
1290 case InsetFig::PER_COL:
1291 // Doesn't occur for htype...
1292 res = tostr(f/100) + "\\column" + suffix;
1299 void InsetFig::Regenerate() const
1302 string resizeW, resizeH;
1303 string rotate, recmd;
1305 if (fname.empty()) {
1306 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1307 cmd += _("empty figure path");
1312 string buf1 = OnlyPath(owner->fileName());
1313 string fname2 = MakeRelPath(fname, buf1);
1315 string gcmd = "\\includegraphics{" + fname2 + '}';
1316 resizeW = stringify(wtype, xwid, "width");
1317 resizeH = stringify(htype, xhgh, "height");
1319 if (!resizeW.empty() || !resizeH.empty()) {
1320 recmd = "\\resizebox*{";
1321 if (!resizeW.empty())
1326 if (!resizeH.empty())
1335 // \rotatebox{angle}{text}
1336 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1342 if (!rotate.empty()) cmdbuf += '}';
1343 if (!recmd.empty()) cmdbuf += '}';
1345 if (!subcaption.empty())
1346 cmdbuf = "\\subfigure[" + subcaption +
1347 "]{" + cmdbuf + "}";
1349 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1356 void InsetFig::TempRegenerate()
1359 string resizeW, resizeH;
1360 string rotate, recmd;
1362 char const * tfname = fl_get_input(form->EpsFile);
1363 string tsubcap = fl_get_input(form->Subcaption);
1364 float tangle = atof(fl_get_input(form->Angle));
1365 float txwid = atof(fl_get_input(form->Width));
1366 float txhgh = atof(fl_get_input(form->Height));
1368 if (!tfname || !*tfname) {
1369 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1370 cmd += _("empty figure path");
1375 string buf1 = OnlyPath(owner->fileName());
1376 string fname2 = MakeRelPath(tfname, buf1);
1377 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1378 string gcmd = "\\includegraphics{" + fname2 + '}';
1380 resizeW = stringify(twtype, txwid, "width");
1381 resizeH = stringify(thtype, txhgh, "height");
1383 // \resizebox*{h-length}{v-length}{text}
1384 if (!resizeW.empty() || !resizeH.empty()) {
1385 recmd = "\\resizebox*{";
1386 if (!resizeW.empty())
1391 if (!resizeH.empty())
1399 // \rotatebox{angle}{text}
1400 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1403 cmdbuf = recmd + rotate + gcmd;
1404 if (!rotate.empty()) cmdbuf += '}';
1405 if (!recmd.empty()) cmdbuf += '}';
1406 if (psubfigure && !tsubcap.empty()) {
1407 cmdbuf = string("\\subfigure{") + tsubcap
1408 + string("}{") + cmdbuf + "}";
1413 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)
1902 if (GetExtension(tfname).empty())
1904 string buf1 = OnlyPath(owner->fileName());
1905 string buf2 = MakeAbsPath(tfname, buf1);
1906 if (!Formats::View(owner, buf2))
1907 lyxerr << "Can't view " << buf2 << endl;
1910 void InsetFig::BrowseFile()
1912 static string current_figure_path;
1913 static int once = 0;
1916 if (lyxerr.debugging()) {
1917 lyxerr << "Filename: "
1918 << owner->fileName() << endl;
1920 string p = fl_get_input(form->EpsFile);
1922 string buf = MakeAbsPath(owner->fileName());
1923 string buf2 = OnlyPath(buf);
1925 buf = MakeAbsPath(p, buf2);
1926 buf = OnlyPath(buf);
1928 buf = OnlyPath(owner->fileName());
1931 // Does user clipart directory exist?
1932 string bufclip = AddName (user_lyxdir, "clipart");
1933 FileInfo fileInfo(bufclip);
1934 if (!(fileInfo.isOK() && fileInfo.isDir()))
1935 // No - bail out to system clipart directory
1936 bufclip = AddName (system_lyxdir, "clipart");
1939 fileDlg.SetButton(0, _("Clipart"), bufclip);
1940 fileDlg.SetButton(1, _("Document"), buf);
1944 ProhibitInput(current_view);
1946 p = fileDlg.Select(_("EPS Figure"),
1947 current_figure_path,
1950 p = fileDlg.Select(_("EPS Figure"), buf,
1953 AllowInput(current_view);
1955 if (p.empty()) return;
1957 buf = MakeRelPath(p, buf2);
1958 current_figure_path = OnlyPath(p);
1961 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1962 || contains(p, "%") || contains(p, " ")) {
1963 WriteAlert(_("Filename can't contain any "
1964 "of these characters:"),
1965 // xgettext:no-c-format
1966 _("space, '#', '~', '$' or '%'."));
1971 if (form) fl_set_input(form->EpsFile, buf.c_str());
1975 void GraphicsCB(FL_OBJECT * obj, long arg)
1977 /* obj->form contains the form */
1979 if (lyxerr.debugging()) {
1980 lyxerr << "GraphicsCB callback: " << arg << endl;
1983 /* find inset we were reacting to */
1984 for (figures_type::iterator it = figures.begin();
1985 it != figures.end(); ++it)
1986 if ((*it)->inset->form && (*it)->inset->form->Figure
1988 if (lyxerr.debugging()) {
1989 lyxerr << "Calling back figure "
1992 (*it)->inset->CallbackFig(arg);
1998 void HideFiguresPopups()
2000 for (figures_type::iterator it = figures.begin();
2001 it != figures.end(); ++it)
2002 if ((*it)->inset->form
2003 && (*it)->inset->form->Figure->visible) {
2004 if (lyxerr.debugging()) {
2005 lyxerr << "Hiding figure " << (*it) << endl;
2007 // hide and free the form
2008 (*it)->inset->CallbackFig(9);