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;
79 extern BufferView * current_view;
80 extern FL_OBJECT * figinset_canvas;
82 extern char ** environ; // is this only redundtant on linux systems? Lgb.
84 static float const DEG2PI = 57.295779513;
86 struct queue_element {
87 float rx, ry; // resolution x and y
88 int ofsx, ofsy; // x and y translation
89 figdata * data; // we are doing it for this data
92 static int const MAXGS = 3; /* maximum 3 gs's at a time */
94 typedef vector<Figref *> figures_type;
95 typedef vector<figdata *> bitmaps_type;
96 static figures_type figures; // all figures
97 static bitmaps_type bitmaps; // all bitmaps
99 static queue<queue_element> gsqueue; // queue for ghostscripting
101 static int gsrunning = 0; /* currently so many gs's are running */
102 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
104 static bool gs_color; // do we allocate colors for gs?
105 static bool color_visual; // is the visual color?
106 static bool gs_xcolor = false; // allocated extended colors
107 static unsigned long gs_pixels[128]; // allocated pixels
108 static int gs_spc; // shades per color
109 static int gs_allcolors; // number of all colors
111 static list<int> pidwaitlist; // pid wait list
117 val.foreground = BlackPixel(fl_get_display(),
118 DefaultScreen(fl_get_display()));
121 val.graphics_exposures = false;
122 val.line_style = LineSolid;
124 return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0),
125 GCForeground | GCFunction | GCGraphicsExposures
126 | GCLineWidth | GCLineStyle , &val);
134 void addpidwait(int pid)
136 // adds pid to pid wait list
137 pidwaitlist.push_back(pid);
139 if (lyxerr.debugging()) {
140 lyxerr << "Pids to wait for: \n";
141 copy(pidwaitlist.begin(), pidwaitlist.end(),
142 ostream_iterator<int>(lyxerr, "\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_get_display(),
206 XFlush(fl_get_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_get_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_get_display(),
321 fl_state[fl_get_vclass()].colormap, &xcol)) {
322 if (i) XFreeColors(fl_get_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 = short(65535 * i / (num - 1));
357 xcol.flags = DoRed | DoGreen | DoBlue;
358 if (!XAllocColor(fl_get_display(),
359 fl_state[fl_get_vclass()].colormap, &xcol)) {
360 if (i) XFreeColors(fl_get_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
383 // allocate color cube on pseudo-color display
387 fl_add_canvas_handler(figinset_canvas, ClientMessage,
389 current_view->owner()->getForm());
391 local_gc_copy = createGC();
393 Visual * vi = DefaultVisual(fl_get_display(),
394 DefaultScreen(fl_get_display()));
395 if (lyxerr.debugging()) {
396 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
397 vi->visualid, vi->c_class,
398 vi->bits_per_rgb, vi->map_entries);
400 color_visual = ( (vi->c_class == StaticColor) ||
401 (vi->c_class == PseudoColor) ||
402 (vi->c_class == TrueColor) ||
403 (vi->c_class == DirectColor) );
404 if ((vi->c_class & 1) == 0) return;
405 // now allocate colors
406 if (vi->c_class == GrayScale) {
407 // allocate grayscale
408 AllocGrays(vi->map_entries/2);
410 // allocate normal color
412 while (i * i * i * 2 > vi->map_entries) --i;
415 gs_allcolors = vi->map_entries;
423 // if bitmaps and figures are not empty we will leak mem
427 lyxerr.debug() << "Unregistering figures..." << endl;
429 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
435 void freefigdata(figdata * tmpdata)
438 if (tmpdata->ref) return;
440 if (tmpdata->gspid > 0) {
441 int pid = tmpdata->gspid;
442 // kill ghostscript and unlink it's files
444 kill_gs(pid, SIGKILL);
447 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
448 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
456 // This _have_ to be set before the fork!
457 unsigned long background_pixel =
458 lyxColorHandler->colorPixel(LColor::background);
460 // run queued requests for ghostscript, if any
461 if (!gsrunning && gs_color && !gs_xcolor) {
462 // here alloc all colors, so that gs will use only
463 // those we allocated for it
468 while (gsrunning < MAXGS) {
469 //char tbuf[384]; //, tbuf2[80];
473 if (gsqueue.empty()) {
474 if (!gsrunning && gs_xcolor) {
475 // de-allocate rest of colors
481 queue_element * p = &gsqueue.front();
490 if (lyxerr.debugging()) {
491 lyxerr << "GS start error! Cannot fork."
494 p->data->broken = true;
495 p->data->reading = false;
498 if (pid == 0) { // child
501 Display * tempdisp = XOpenDisplay(XDisplayName(0));
503 // create translation file
505 ofs.open(make_tmp(getpid()).c_str());
506 ofs << "gsave clippath pathbbox grestore\n"
508 << "/ury exch def /urx exch def /lly exch def "
510 << p->data->wid / 2.0 << " "
511 << p->data->hgh / 2.0 << " translate\n"
512 << p->data->angle << " rotate\n"
513 << -(p->data->raw_wid / 2.0) << " "
514 << -(p->data->raw_hgh / 2.0) << " translate\n"
515 << p->rx / 72.0 << " " << p->ry / 72.0
517 << -p->ofsx << " " << -p->ofsy << " translate\n"
519 ofs.close(); // Don't remove this.
521 // gs process - set ghostview environment first
523 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
524 << ' ' << p->data->bitmap;
525 // now set up ghostview property on a window
526 // #warning BUG seems that the only bug here
527 // might be the hardcoded dpi.. Bummer!
529 t1 << "0 0 0 0 " << p->data->wid << ' '
530 << p->data->hgh << " 72 72 0 0 0 0";
532 if (lyxerr.debugging()) {
533 lyxerr << "Will set GHOSTVIEW property to ["
534 << t1.str() << "]" << endl;
536 // wait until property is deleted if executing multiple
538 XGrabServer(tempdisp);
540 // grab server to prevent other child
541 // interfering with setting GHOSTVIEW property
542 // The grabbing goes on for too long, is it
543 // really needed? (Lgb)
544 // I moved most of the grabs... (Lgb)
545 if (lyxerr.debugging()) {
546 lyxerr << "Grabbing the server"
549 prop = XListProperties(tempdisp,
551 figinset_canvas), &nprop);
555 for (i = 0; i < nprop; ++i) {
556 char * p = XGetAtomName(tempdisp,
558 if (strcmp(p, "GHOSTVIEW") == 0) {
560 // We free it when we leave so we don't leak.
566 XFree(reinterpret_cast<char *>(prop)); // jc:
568 // ok, property found, we must wait until
569 // ghostscript deletes it
570 if (lyxerr.debugging()) {
571 lyxerr << "Releasing the server\n["
573 << "] GHOSTVIEW property"
574 " found. Waiting." << endl;
576 XUngrabServer(tempdisp);
579 XGrabServer(tempdisp);
581 XChangeProperty(tempdisp,
582 fl_get_canvas_id(figinset_canvas),
583 XInternAtom(tempdisp, "GHOSTVIEW", false),
584 XInternAtom(tempdisp, "STRING", false),
586 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
587 int(t1.str().size()));
588 XUngrabServer(tempdisp);
593 switch (p->data->flags & 3) {
594 case 0: t3 << 'H'; break; // Hidden
595 case 1: t3 << 'M'; break; // Mono
596 case 2: t3 << 'G'; break; // Gray
605 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
606 << ' ' << background_pixel;
608 XGrabServer(tempdisp);
609 XChangeProperty(tempdisp,
610 fl_get_canvas_id(figinset_canvas),
611 XInternAtom(tempdisp,
612 "GHOSTVIEW_COLORS", false),
613 XInternAtom(tempdisp, "STRING", false),
615 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
616 int(t3.str().size()));
617 XUngrabServer(tempdisp);
620 if (lyxerr.debugging()) {
621 lyxerr << "Releasing the server" << endl;
623 XCloseDisplay(tempdisp);
625 // set up environment
628 typedef char * char_p;
629 env = new char_p[ne + 2];
630 string tmp = t2.str().c_str();
631 env[0] = new char[tmp.size() + 1];
632 std::copy(tmp.begin(), tmp.end(), env[0]);
633 env[0][tmp.size()] = '\0';
634 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
637 // now make gs command
639 // close(1); do NOT close. If GS writes out
640 // errors it would hang. (Matthias 290596)
642 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
643 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
645 // now chdir into dir with .eps file, to be on the safe
647 lyx::chdir(OnlyPath(p->data->fname));
648 // make temp file name
649 string tmpf = make_tmp(getpid());
650 if (lyxerr.debugging()) {
651 lyxerr << "starting gs " << tmpf << " "
653 << ", pid: " << getpid() << endl;
656 int err = ::execlp(lyxrc.ps_command.c_str(),
657 lyxrc.ps_command.c_str(),
659 "-dNOPAUSE", "-dQUIET",
661 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
662 p->data->fname.c_str(),
663 "showpage.ps", "quit.ps", "-", 0);
664 // if we are still there, an error occurred.
665 lyxerr << "Error executing ghostscript. "
666 << "Code: " << err << endl;
667 lyxerr.debug() << "Cmd: "
671 << p->data->fname << endl;
674 // normal process (parent)
675 if (lyxerr.debugging()) {
676 lyxerr << "GS [" << pid << "] started" << endl;
679 p->data->gspid = pid;
687 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
689 // recompute the stuff and put in the queue
693 p.rx = (float(data->raw_wid) * 72.0) / pswid;
694 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
700 // if possible, run the queue
706 figdata * getfigdata(int wid, int hgh, string const & fname,
707 int psx, int psy, int pswid, int pshgh,
708 int raw_wid, int raw_hgh, float angle, char flags)
710 /* first search for an exact match with fname and width/height */
712 if (fname.empty() || !IsFileReadable(fname))
715 for (bitmaps_type::iterator it = bitmaps.begin();
716 it != bitmaps.end(); ++it) {
717 if ((*it)->wid == wid && (*it)->hgh == hgh &&
718 (*it)->flags == flags && (*it)->fname == fname &&
719 (*it)->angle == angle) {
724 figdata * p = new figdata;
727 p->raw_wid = raw_wid;
728 p->raw_hgh = raw_hgh;
732 bitmaps.push_back(p);
733 XWindowAttributes wa;
734 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
735 figinset_canvas), &wa);
737 if (lyxerr.debugging()) {
738 lyxerr << "Create pixmap disp:" << fl_get_display()
739 << " scr:" << DefaultScreen(fl_get_display())
742 << " depth:" << wa.depth << endl;
750 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
751 figinset_canvas), wid, hgh, wa.depth);
753 // initialize reading of .eps file with correct sizes and stuff
754 addwait(psx, psy, pswid, pshgh, p);
766 void getbitmap(figdata * p)
773 void makeupdatelist(figdata * p)
775 for(figures_type::iterator it = figures.begin();
776 it != figures.end(); ++it)
777 if ((*it)->data == p) {
778 if (lyxerr.debugging()) {
779 lyxerr << "Updating inset "
783 // add inset figures[i]->inset into to_update list
784 current_view->pushIntoUpdateList((*it)->inset);
789 // this func is only "called" in spellchecker.C
790 void sigchldchecker(pid_t pid, int * status)
792 lyxerr.debug() << "Got pid = " << pid << endl;
793 bool pid_handled = false;
794 for (bitmaps_type::iterator it = bitmaps.begin();
795 it != bitmaps.end(); ++it) {
796 if ((*it)->reading && pid == (*it)->gspid) {
797 lyxerr.debug() << "Found pid in bitmaps" << endl;
798 // now read the file and remove it from disk
801 if ((*it)->gsdone) *status = 0;
803 lyxerr.debug() << "GS [" << pid
804 << "] exit OK." << endl;
806 lyxerr << "GS [" << pid << "] error "
808 << WIFEXITED(*status)
809 << " " << WEXITSTATUS(*status)
810 << " S:" << WIFSIGNALED(*status)
811 << " " << WTERMSIG(*status) << endl;
814 bitmap_waiting = true;
817 // remove temporary files
818 lyx::unlink(make_tmp(p->gspid));
822 makeupdatelist((*it));
829 lyxerr.debug() << "Checking pid in pidwait" << endl;
830 list<int>::iterator it = find(pidwaitlist.begin(),
831 pidwaitlist.end(), pid);
832 if (it != pidwaitlist.end()) {
833 lyxerr.debug() << "Found pid in pidwait\n"
834 << "Caught child pid of recompute "
835 "routine" << pid << endl;
836 pidwaitlist.erase(it);
840 lyxerr.debug() << "waitpid error" << endl;
843 lyxerr << "The process or process group specified by "
844 "pid does not exist or is not a child of "
845 "the calling process or can never be in the "
846 "states specified by options." << endl;
849 lyxerr << "waitpid() was interrupted due to the "
850 "receipt of a signal sent by the calling "
854 lyxerr << "An invalid value was specified for "
858 lyxerr << "Unknown error from waitpid" << endl;
861 } else if (pid == 0) {
862 lyxerr << "waitpid nohang" << endl;;
864 lyxerr.debug() << "normal exit from childhandler" << endl;
872 bitmap_waiting = false;
873 for (bitmaps_type::iterator it = bitmaps.begin();
874 it != bitmaps.end(); ++it)
875 if ((*it)->gspid > 0 && !(*it)->reading)
881 void RegisterFigure(InsetFig * fi)
883 if (figures.empty()) InitFigures();
885 Figref * tmpfig = new Figref;
888 figures.push_back(tmpfig);
891 if (lyxerr.debugging()) {
892 lyxerr << "Register Figure: buffer:["
893 << current_view->buffer() << "]" << endl;
899 void UnregisterFigure(InsetFig * fi)
904 Figref * tmpfig = fi->figure;
906 if (tmpfig->data) freefigdata(tmpfig->data);
907 if (tmpfig->inset->form) {
908 if (tmpfig->inset->form->Figure->visible) {
909 fl_set_focus_object(tmpfig->inset->form->Figure,
910 tmpfig->inset->form->OkBtn);
911 fl_hide_form(tmpfig->inset->form->Figure);
913 #if FL_REVISION == 89
914 // CHECK Reactivate this free_form calls
916 fl_free_form(tmpfig->inset->form->Figure);
917 free(tmpfig->inset->form); // Why free?
918 tmpfig->inset->form = 0;
921 figures.erase(find(figures.begin(), figures.end(), tmpfig));
924 if (figures.empty()) DoneFigures();
928 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
938 psubfigure = subfigure = false;
939 xwid = xhgh = angle = 0;
941 raw_wid = raw_hgh = 0;
942 changedfname = false;
943 RegisterFigure(this);
947 InsetFig::~InsetFig()
949 if (lyxerr.debugging()) {
950 lyxerr << "Figure destructor called" << endl;
952 UnregisterFigure(this);
956 int InsetFig::ascent(BufferView *, LyXFont const &) const
962 int InsetFig::descent(BufferView *, LyXFont const &) const
968 int InsetFig::width(BufferView *, LyXFont const &) const
974 void InsetFig::draw(BufferView * bv, LyXFont const & f,
975 int baseline, float & x, bool) const
978 Painter & pain = bv->painter();
980 if (bitmap_waiting) getbitmaps();
982 // I wish that I didn't have to use this
983 // but the figinset code is so complicated so
984 // I don't want to fiddle with it now.
986 if (figure && figure->data && figure->data->bitmap &&
987 !figure->data->reading && !figure->data->broken) {
989 pain.pixmap(int(x + 1), baseline - hgh,
990 wid, hgh, figure->data->bitmap);
993 pain.rectangle(int(x), baseline - hgh - 1,
997 char const * msg = 0;
998 string lfname = fname;
999 if (!fname.empty() && GetExtension(fname).empty())
1002 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1004 if (figure && figure->data) {
1005 if (figure->data->broken) msg = _("[render error]");
1006 else if (figure->data->reading) msg = _("[rendering ... ]");
1008 else if (fname.empty())
1009 msg = _("[no file]");
1010 else if (!IsFileReadable(lfname))
1011 msg = _("[bad file name]");
1012 else if ((flags & 3) == 0)
1013 msg = _("[not displayed]");
1014 else if (lyxrc.ps_command.empty())
1015 msg = _("[no ghostscript]");
1017 if (!msg) msg = _("[unknown error]");
1019 font.setFamily(LyXFont::SANS_FAMILY);
1020 font.setSize(LyXFont::SIZE_FOOTNOTE);
1021 string justname = OnlyFilename (fname);
1022 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1025 font.setSize(LyXFont::SIZE_TINY);
1026 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1028 x += width(bv, font); // ?
1032 void InsetFig::Write(Buffer const *, ostream & os) const
1035 os << "Figure size " << wid << " " << hgh << "\n";
1036 if (!fname.empty()) {
1037 string buf1 = OnlyPath(owner->fileName());
1038 string fname2 = MakeRelPath(fname, buf1);
1039 os << "file " << fname2 << "\n";
1041 if (!subcaption.empty())
1042 os << "subcaption " << subcaption << "\n";
1043 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1044 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1045 if (angle != 0) os << "angle " << angle << "\n";
1046 os << "flags " << flags << "\n";
1047 if (subfigure) os << "subfigure\n";
1051 void InsetFig::Read(Buffer const *, LyXLex & lex)
1054 bool finished = false;
1056 while (lex.IsOK() && !finished) {
1059 string const token = lex.GetString();
1060 lyxerr.debug() << "Token: " << token << endl;
1064 else if (token == "\\end_inset") {
1066 } else if (token == "file") {
1068 buf = lex.GetString();
1069 string buf1 = OnlyPath(owner->fileName());
1070 fname = MakeAbsPath(buf, buf1);
1071 changedfname = true;
1073 } else if (token == "extra") {
1075 // kept for backwards compability. Delete in 0.13.x
1076 } else if (token == "subcaption") {
1078 subcaption = lex.GetString();
1079 } else if (token == "label") {
1081 // kept for backwards compability. Delete in 0.13.x
1082 } else if (token == "angle") {
1084 angle = lex.GetFloat();
1085 } else if (token == "size") {
1087 wid = lex.GetInteger();
1089 hgh = lex.GetInteger();
1090 } else if (token == "flags") {
1092 flags = pflags = lex.GetInteger();
1093 } else if (token == "subfigure") {
1094 subfigure = psubfigure = true;
1095 } else if (token == "width") {
1098 typ = lex.GetInteger();
1100 xwid = lex.GetFloat();
1102 case DEF: wtype = DEF; break;
1103 case CM: wtype = CM; break;
1104 case IN: wtype = IN; break;
1105 case PER_PAGE: wtype = PER_PAGE; break;
1106 case PER_COL: wtype = PER_COL; break;
1108 lyxerr.debug() << "Unknown type!" << endl;
1112 } else if (token == "height") {
1115 typ = lex.GetInteger();
1117 xhgh = lex.GetFloat();
1119 case DEF: htype = DEF; break;
1120 case CM: htype = CM; break;
1121 case IN: htype = IN; break;
1122 case PER_PAGE: htype = PER_PAGE; break;
1124 lyxerr.debug() << "Unknown type!" << endl;
1135 int InsetFig::Latex(Buffer const *, ostream & os,
1136 bool /* fragile*/, bool /* fs*/) const
1139 if (!cmd.empty()) os << cmd << " ";
1144 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1150 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1156 int InsetFig::DocBook(Buffer const *, ostream & os) const
1158 string buf1 = OnlyPath(owner->fileName());
1159 string figurename = MakeRelPath(fname, buf1);
1161 if(suffixIs(figurename, ".eps"))
1162 figurename.erase(figurename.length() - 4);
1164 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1169 void InsetFig::Validate(LaTeXFeatures & features) const
1171 features.graphics = true;
1172 if (subfigure) features.subfigure = true;
1176 Inset::EDITABLE InsetFig::Editable() const
1182 bool InsetFig::Deletable() const
1188 string const InsetFig::EditMessage() const
1190 return _("Opened figure");
1194 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1196 lyxerr.debug() << "Editing InsetFig." << endl;
1199 // We should have RO-versions of the form instead.
1200 // The actual prevention of altering a readonly doc
1201 // is done in CallbackFig()
1202 if(bv->buffer()->isReadonly())
1203 WarnReadonly(bv->buffer()->fileName());
1206 form = create_form_Figure();
1207 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1208 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1209 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1210 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1213 if (form->Figure->visible) {
1214 fl_raise_form(form->Figure);
1216 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1217 FL_FULLBORDER, _("Figure"));
1222 Inset * InsetFig::Clone(Buffer const & buffer) const
1224 InsetFig * tmp = new InsetFig(100, 100, buffer);
1226 if (lyxerr.debugging()) {
1227 lyxerr << "Clone Figure: buffer:["
1229 << "], cbuffer:[xx]" << endl;
1234 tmp->raw_wid = raw_wid;
1235 tmp->raw_hgh = raw_hgh;
1240 tmp->pflags = pflags;
1241 tmp->subfigure = subfigure;
1242 tmp->psubfigure = psubfigure;
1250 if (!fname.empty() && IsFileReadable(fname)
1251 && (flags & 3) && !lyxrc.ps_command.empty()
1253 // do not display if there is
1254 // "do not display" chosen (Matthias 260696)
1255 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1256 pswid, pshgh, raw_wid, raw_hgh,
1257 angle, flags & (3|8));
1258 } else tmp->figure->data = 0;
1259 tmp->subcaption = subcaption;
1260 tmp->changedfname = false;
1267 Inset::Code InsetFig::LyxCode() const
1269 return Inset::GRAPHICS_CODE;
1274 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1280 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1281 res = tostr(f) + "cm";
1284 res = tostr(f) + "in";
1286 case InsetFig::PER_PAGE:
1287 res = tostr(f/100) + "\\text" + suffix;
1289 case InsetFig::PER_COL:
1290 // Doesn't occur for htype...
1291 res = tostr(f/100) + "\\column" + suffix;
1298 void InsetFig::Regenerate() const
1301 string resizeW, resizeH;
1302 string rotate, recmd;
1304 if (fname.empty()) {
1305 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1306 cmd += _("empty figure path");
1311 string buf1 = OnlyPath(owner->fileName());
1312 string fname2 = MakeRelPath(fname, buf1);
1314 string gcmd = "\\includegraphics{" + fname2 + '}';
1315 resizeW = stringify(wtype, xwid, "width");
1316 resizeH = stringify(htype, xhgh, "height");
1318 if (!resizeW.empty() || !resizeH.empty()) {
1319 recmd = "\\resizebox*{";
1320 if (!resizeW.empty())
1325 if (!resizeH.empty())
1334 // \rotatebox{angle}{text}
1335 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1341 if (!rotate.empty()) cmdbuf += '}';
1342 if (!recmd.empty()) cmdbuf += '}';
1344 if (!subcaption.empty())
1345 cmdbuf = "\\subfigure[" + subcaption +
1346 "]{" + cmdbuf + "}";
1348 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1355 void InsetFig::TempRegenerate()
1358 string resizeW, resizeH;
1359 string rotate, recmd;
1361 char const * tfname = fl_get_input(form->EpsFile);
1362 string tsubcap = fl_get_input(form->Subcaption);
1363 float tangle = atof(fl_get_input(form->Angle));
1364 float txwid = atof(fl_get_input(form->Width));
1365 float txhgh = atof(fl_get_input(form->Height));
1367 if (!tfname || !*tfname) {
1368 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1369 cmd += _("empty figure path");
1374 string buf1 = OnlyPath(owner->fileName());
1375 string fname2 = MakeRelPath(tfname, buf1);
1376 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1377 string gcmd = "\\includegraphics{" + fname2 + '}';
1379 resizeW = stringify(twtype, txwid, "width");
1380 resizeH = stringify(thtype, txhgh, "height");
1382 // \resizebox*{h-length}{v-length}{text}
1383 if (!resizeW.empty() || !resizeH.empty()) {
1384 recmd = "\\resizebox*{";
1385 if (!resizeW.empty())
1390 if (!resizeH.empty())
1398 // \rotatebox{angle}{text}
1399 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1402 cmdbuf = recmd + rotate + gcmd;
1403 if (!rotate.empty()) cmdbuf += '}';
1404 if (!recmd.empty()) cmdbuf += '}';
1405 if (psubfigure && !tsubcap.empty()) {
1406 cmdbuf = string("\\subfigure{") + tsubcap
1407 + string("}{") + cmdbuf + "}";
1412 void InsetFig::Recompute()
1417 bool changed = changedfname;
1418 int newx, newy, nraw_x, nraw_y;
1420 if (changed) GetPSSizes();
1422 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1423 float cos_a = cos (angle / DEG2PI);
1424 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1425 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1427 string lfname = fname;
1428 if (GetExtension(fname).empty())
1431 /* now recompute wid and hgh, and if that is changed, set changed */
1432 /* this depends on chosen size of the picture and its bbox */
1433 // This will be redone in 0.13 ... (hen)
1434 if (!lfname.empty() && IsFileReadable(lfname)) {
1435 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1443 newx = int(28.346 * xwid);
1446 newx = int(72 * xwid);
1448 case PER_PAGE: /* % of page */
1449 newx = int(5.95 * xwid);
1451 case PER_COL: /* % of col */
1452 newx = int(2.975 * xwid);
1456 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1460 //lyxerr << "This should not happen!" << endl;
1463 newy = int(28.346 * xhgh);
1466 newy = int(72 * xhgh);
1468 case PER_PAGE: /* % of page */
1469 newy = int(8.42 * xhgh);
1472 // Doesn't occur; case exists to suppress
1473 // compiler warnings.
1476 if (htype && !wtype && frame_hgh)
1477 newx = newy*frame_wid/frame_hgh;
1486 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1491 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1493 // cannot be zero, actually, set it to some minimum, so its clickable
1494 if (newx < 5) newx = 5;
1495 if (newy < 5) newy = 5;
1497 if (newx != wid || newy != hgh ||
1498 nraw_x != raw_wid || nraw_y != raw_hgh ||
1499 flags != pflags || subfigure != psubfigure)
1507 subfigure = psubfigure;
1510 figdata * pf = figure->data;
1513 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1514 && !lyxrc.ps_command.empty()) {
1515 // do not display if there is "do not display"
1516 // chosen (Matthias 260696)
1517 figure->data = getfigdata(wid, hgh, lfname,
1518 psx, psy, pswid, pshgh,
1520 angle, flags & (3|8));
1521 } else figure->data = 0;
1523 // free the old data
1524 if (pf) freefigdata(pf);
1527 changedfname = false;
1531 void InsetFig::GetPSSizes()
1533 /* get %%BoundingBox: from postscript file */
1535 /* defaults to associated size
1536 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1543 if (fname.empty()) return;
1545 ifstream ifs(fname.c_str());
1547 if (!ifs) return; // file not found !!!!
1549 /* defaults to A4 page */
1555 char lastchar = 0; ifs.get(lastchar);
1557 char c = 0; ifs.get(c);
1559 lyxerr.debug() << "End of (E)PS file reached and"
1560 " no BoundingBox!" << endl;
1563 if (c == '%' && lastchar == '%') {
1565 if (p.empty()) break;
1566 lyxerr.debug() << "Token: `" << p << "'" << endl;
1567 if (p == "BoundingBox:") {
1568 float fpsx, fpsy, fpswid, fpshgh;
1569 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1572 pswid = int(fpswid);
1573 pshgh = int(fpshgh);
1575 if (lyxerr.debugging()) {
1576 lyxerr << "%%%%BoundingBox:"
1594 void InsetFig::CallbackFig(long arg)
1599 if (lyxerr.debugging()) {
1600 lyxerr << "Figure callback, arg " << arg << endl;
1606 case 12: /* width type */
1613 fl_deactivate_object(form->Width);
1618 fl_activate_object(form->Width);
1623 fl_activate_object(form->Width);
1628 fl_activate_object(form->Width);
1633 fl_activate_object(form->Width);
1636 lyxerr.debug() << "Unknown type!" << endl;
1643 case 22: /* height type */
1649 fl_deactivate_object(form->Height);
1654 fl_activate_object(form->Height);
1659 fl_activate_object(form->Height);
1664 fl_activate_object(form->Height);
1667 lyxerr.debug() << "Unknown type!" << endl;
1673 pflags = pflags & ~3; /* wysiwyg0 */
1676 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1679 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1682 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1685 pflags ^= 4; /* frame */
1688 pflags ^= 8; /* do translations */
1691 psubfigure = !psubfigure; /* This is a subfigure */
1694 regen = true; /* regenerate command */
1696 case 0: /* browse file */
1700 case 1: /* preview */
1701 p = fl_get_input(form->EpsFile);
1705 case 8: /* ok (apply and close) */
1706 if(!current_view->buffer()->isReadonly()) {
1709 xwid = atof(fl_get_input(form->Width));
1710 xhgh = atof(fl_get_input(form->Height));
1711 angle = atof(fl_get_input(form->Angle));
1712 p = fl_get_input(form->EpsFile);
1714 string buf1 = OnlyPath(owner->fileName());
1715 fname = MakeAbsPath(p, buf1);
1716 changedfname = true;
1718 if (!fname.empty()) {
1719 changedfname = true;
1723 subcaption = fl_get_input(form->Subcaption);
1727 /* now update inset */
1728 if (lyxerr.debugging()) {
1729 lyxerr << "Update: ["
1730 << wid << 'x' << hgh << ']' << endl;
1732 current_view->updateInset(this, true);
1734 fl_set_focus_object(form->Figure, form->OkBtn);
1735 fl_hide_form(form->Figure);
1736 #if FL_REVISION == 89
1737 // CHECK Reactivate this free_form calls
1739 fl_free_form(form->Figure);
1740 free(form); // Why free?
1746 // The user has already been informed about RO in ::Edit
1747 if(arg == 7) // if 'Apply'
1750 case 9: /* cancel = restore and close */
1751 fl_set_focus_object(form->Figure, form->OkBtn);
1752 fl_hide_form(form->Figure);
1753 #if FL_REVISION == 89
1754 // CHECK Reactivate this free_form calls
1755 // Jug, is this still a problem?
1757 fl_free_form(form->Figure);
1758 free(form); // Why free?
1764 if (regen) TempRegenerate();
1769 void DisableFigurePanel(FD_Figure * const form)
1771 fl_deactivate_object(form->EpsFile);
1772 fl_deactivate_object(form->Browse);
1773 fl_deactivate_object(form->Width);
1774 fl_deactivate_object(form->Height);
1775 fl_deactivate_object(form->Frame);
1776 fl_deactivate_object(form->Translations);
1777 fl_deactivate_object(form->Angle);
1778 fl_deactivate_object(form->HeightGrp);
1779 fl_deactivate_object(form->page2);
1780 fl_deactivate_object(form->Default2);
1781 fl_deactivate_object(form->cm2);
1782 fl_deactivate_object(form->in2);
1783 fl_deactivate_object(form->HeightLabel);
1784 fl_deactivate_object(form->WidthLabel);
1785 fl_deactivate_object(form->DisplayGrp);
1786 fl_deactivate_object(form->Wysiwyg3);
1787 fl_deactivate_object(form->Wysiwyg0);
1788 fl_deactivate_object(form->Wysiwyg2);
1789 fl_deactivate_object(form->Wysiwyg1);
1790 fl_deactivate_object(form->WidthGrp);
1791 fl_deactivate_object(form->Default1);
1792 fl_deactivate_object(form->cm1);
1793 fl_deactivate_object(form->in1);
1794 fl_deactivate_object(form->page1);
1795 fl_deactivate_object(form->column1);
1796 fl_deactivate_object(form->Subcaption);
1797 fl_deactivate_object(form->Subfigure);
1798 fl_deactivate_object (form->OkBtn);
1799 fl_deactivate_object (form->ApplyBtn);
1800 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1801 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1806 void EnableFigurePanel(FD_Figure * const form)
1808 fl_activate_object(form->EpsFile);
1809 fl_activate_object(form->Browse);
1810 fl_activate_object(form->Width);
1811 fl_activate_object(form->Height);
1812 fl_activate_object(form->Frame);
1813 fl_activate_object(form->Translations);
1814 fl_activate_object(form->Angle);
1815 fl_activate_object(form->HeightGrp);
1816 fl_activate_object(form->page2);
1817 fl_activate_object(form->Default2);
1818 fl_activate_object(form->cm2);
1819 fl_activate_object(form->in2);
1820 fl_activate_object(form->HeightLabel);
1821 fl_activate_object(form->WidthLabel);
1822 fl_activate_object(form->DisplayGrp);
1823 fl_activate_object(form->Wysiwyg3);
1824 fl_activate_object(form->Wysiwyg0);
1825 fl_activate_object(form->Wysiwyg2);
1826 fl_activate_object(form->Wysiwyg1);
1827 fl_activate_object(form->WidthGrp);
1828 fl_activate_object(form->Default1);
1829 fl_activate_object(form->cm1);
1830 fl_activate_object(form->in1);
1831 fl_activate_object(form->page1);
1832 fl_activate_object(form->column1);
1833 fl_activate_object(form->Subcaption);
1834 fl_activate_object(form->Subfigure);
1835 fl_activate_object (form->OkBtn);
1836 fl_activate_object (form->ApplyBtn);
1837 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1838 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1842 void InsetFig::RestoreForm()
1844 EnableFigurePanel(form);
1847 fl_set_button(form->Default1, (wtype == 0));
1848 fl_set_button(form->cm1, (wtype == 1));
1849 fl_set_button(form->in1, (wtype == 2));
1850 fl_set_button(form->page1, (wtype == 3));
1851 fl_set_button(form->column1, (wtype == 4));
1853 fl_deactivate_object(form->Width);
1855 fl_activate_object(form->Width);
1858 // enable and disable should be put here.
1860 fl_set_button(form->Default2, (htype == 0));
1861 fl_set_button(form->cm2, (htype == 1));
1862 fl_set_button(form->in2, (htype == 2));
1863 fl_set_button(form->page2, (htype == 3));
1864 // enable and disable should be put here.
1866 fl_deactivate_object(form->Height);
1868 fl_activate_object(form->Height);
1871 int piflags = flags & 3;
1872 fl_set_button(form->Wysiwyg0, (piflags == 0));
1873 fl_set_button(form->Wysiwyg1, (piflags == 1));
1874 fl_set_button(form->Wysiwyg2, (piflags == 2));
1875 fl_set_button(form->Wysiwyg3, (piflags == 3));
1876 fl_set_button(form->Frame, ((flags & 4) != 0));
1877 fl_set_button(form->Translations, ((flags & 8) != 0));
1878 fl_set_button(form->Subfigure, (subfigure != 0));
1880 psubfigure = subfigure;
1881 fl_set_input(form->Width, tostr(xwid).c_str());
1882 fl_set_input(form->Height, tostr(xhgh).c_str());
1883 fl_set_input(form->Angle, tostr(angle).c_str());
1884 if (!fname.empty()){
1885 string buf1 = OnlyPath(owner->fileName());
1886 string fname2 = MakeRelPath(fname, buf1);
1887 fl_set_input(form->EpsFile, fname2.c_str());
1889 else fl_set_input(form->EpsFile, "");
1890 fl_set_input(form->Subcaption, subcaption.c_str());
1891 if(current_view->buffer()->isReadonly())
1892 DisableFigurePanel(form);
1898 void InsetFig::Preview(string const & p)
1901 if (GetExtension(tfname).empty())
1903 string buf1 = OnlyPath(owner->fileName());
1904 string buf2 = MakeAbsPath(tfname, buf1);
1905 if (!Formats::View(owner, buf2))
1906 lyxerr << "Can't view " << buf2 << endl;
1909 void InsetFig::BrowseFile()
1911 static string current_figure_path;
1912 static int once = 0;
1915 if (lyxerr.debugging()) {
1916 lyxerr << "Filename: "
1917 << owner->fileName() << endl;
1919 string p = fl_get_input(form->EpsFile);
1921 string buf = MakeAbsPath(owner->fileName());
1922 string buf2 = OnlyPath(buf);
1924 buf = MakeAbsPath(p, buf2);
1925 buf = OnlyPath(buf);
1927 buf = OnlyPath(owner->fileName());
1930 // Does user clipart directory exist?
1931 string bufclip = AddName (user_lyxdir, "clipart");
1932 FileInfo fileInfo(bufclip);
1933 if (!(fileInfo.isOK() && fileInfo.isDir()))
1934 // No - bail out to system clipart directory
1935 bufclip = AddName (system_lyxdir, "clipart");
1938 fileDlg.SetButton(0, _("Clipart"), bufclip);
1939 fileDlg.SetButton(1, _("Document"), buf);
1943 ProhibitInput(current_view);
1945 p = fileDlg.Select(_("EPS Figure"),
1946 current_figure_path,
1949 p = fileDlg.Select(_("EPS Figure"), buf,
1952 AllowInput(current_view);
1954 if (p.empty()) return;
1956 buf = MakeRelPath(p, buf2);
1957 current_figure_path = OnlyPath(p);
1960 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1961 || contains(p, "%") || contains(p, " ")) {
1962 WriteAlert(_("Filename can't contain any "
1963 "of these characters:"),
1964 // xgettext:no-c-format
1965 _("space, '#', '~', '$' or '%'."));
1970 if (form) fl_set_input(form->EpsFile, buf.c_str());
1974 void GraphicsCB(FL_OBJECT * obj, long arg)
1976 /* obj->form contains the form */
1978 if (lyxerr.debugging()) {
1979 lyxerr << "GraphicsCB callback: " << arg << endl;
1982 /* find inset we were reacting to */
1983 for (figures_type::iterator it = figures.begin();
1984 it != figures.end(); ++it)
1985 if ((*it)->inset->form && (*it)->inset->form->Figure
1987 if (lyxerr.debugging()) {
1988 lyxerr << "Calling back figure "
1991 (*it)->inset->CallbackFig(arg);
1997 void HideFiguresPopups()
1999 for (figures_type::iterator it = figures.begin();
2000 it != figures.end(); ++it)
2001 if ((*it)->inset->form
2002 && (*it)->inset->form->Figure->visible) {
2003 if (lyxerr.debugging()) {
2004 lyxerr << "Hiding figure " << (*it) << endl;
2006 // hide and free the form
2007 (*it)->inset->CallbackFig(9);