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"
65 #include "frontends/Dialogs.h" // redrawGUI
67 #ifdef SIGC_CXX_NAMESPACES
81 using std::ostringstream;
84 extern BufferView * current_view;
85 extern FL_OBJECT * figinset_canvas;
87 extern char ** environ; // is this only redundtant on linux systems? Lgb.
89 static float const DEG2PI = 57.295779513;
91 struct queue_element {
92 float rx, ry; // resolution x and y
93 int ofsx, ofsy; // x and y translation
94 figdata * data; // we are doing it for this data
97 static int const MAXGS = 3; /* maximum 3 gs's at a time */
99 typedef vector<Figref *> figures_type;
100 typedef vector<figdata *> bitmaps_type;
101 static figures_type figures; // all figures
102 static bitmaps_type bitmaps; // all bitmaps
104 static queue<queue_element> gsqueue; // queue for ghostscripting
106 static int gsrunning = 0; /* currently so many gs's are running */
107 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
109 static bool gs_color; // do we allocate colors for gs?
110 static bool color_visual; // is the visual color?
111 static bool gs_xcolor = false; // allocated extended colors
112 static unsigned long gs_pixels[128]; // allocated pixels
113 static int gs_spc; // shades per color
114 static int gs_allcolors; // number of all colors
116 static list<int> pidwaitlist; // pid wait list
122 val.foreground = BlackPixel(fl_get_display(),
123 DefaultScreen(fl_get_display()));
126 val.graphics_exposures = false;
127 val.line_style = LineSolid;
129 return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0),
130 GCForeground | GCFunction | GCGraphicsExposures
131 | GCLineWidth | GCLineStyle , &val);
139 void addpidwait(int pid)
141 // adds pid to pid wait list
142 pidwaitlist.push_back(pid);
144 if (lyxerr.debugging()) {
145 lyxerr << "Pids to wait for: \n";
146 copy(pidwaitlist.begin(), pidwaitlist.end(),
147 std::ostream_iterator<int>(lyxerr, "\n"));
154 string make_tmp(int pid)
156 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
161 void kill_gs(int pid, int sig)
163 if (lyxerr.debugging())
164 lyxerr << "Killing gs " << pid << endl;
166 lyx::unlink(make_tmp(pid));
172 int GhostscriptMsg(XEvent * ev, void *)
174 // bin all events not of interest
175 if (ev->type != ClientMessage)
178 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
180 if (lyxerr.debugging()) {
181 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
182 << "] pm:[" << e->data.l[1] << "]" << endl;
185 // just kill gs, that way it will work for sure
186 // This loop looks like S**T so it probably is...
187 for (bitmaps_type::iterator it = bitmaps.begin();
188 it != bitmaps.end(); ++it)
189 if (static_cast<long>((*it)->bitmap) ==
190 static_cast<long>(e->data.l[1])) {
195 // first update p->bitmap, if necessary
196 if (p->bitmap != None
197 && p->flags > (1|8) && gs_color && p->wid) {
198 // query current colormap and re-render
199 // the pixmap with proper colors
200 XWindowAttributes wa;
201 register XImage * im;
204 int spc1 = gs_spc - 1;
205 int spc2 = gs_spc * gs_spc;
209 GC gc = local_gc_copy;
211 XGetWindowAttributes(fl_get_display(),
215 XFlush(fl_get_display());
216 if (lyxerr.debugging()) {
217 lyxerr << "Starting image translation "
220 << p->wid << "x" << p->hgh
222 << " " << XYPixmap << endl;
224 // now fork rendering process
226 if (forkstat == -1) {
228 << "Cannot fork, using slow "
229 "method for pixmap translation." << endl;
230 tmpdisp = fl_get_display();
231 } else if (forkstat > 0) { // parent
233 if (lyxerr.debugging()) {
234 lyxerr << "Spawned child "
237 addpidwait(forkstat);
240 tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
243 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
244 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
246 if (lyxerr.debugging()) {
247 lyxerr << "Got the image" << endl;
250 if (lyxerr.debugging()) {
251 lyxerr << "Error getting the image" << endl;
256 // query current colormap
257 XColor * cmap = new XColor[gs_allcolors];
258 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
259 XQueryColors(tmpdisp,
260 fl_state[fl_get_vclass()]
264 // now we process all the image
265 for (y = 0; y < p->hgh; ++y) {
266 for (int x = 0; x < wid; ++x) {
271 gs_pixels[((pc->red+6553)*
272 spc1/65535)*spc2+((pc->green+6553)*
273 spc1/65535)*gs_spc+((pc->blue+6553)*
278 // This must be correct.
280 if (lyxerr.debugging()) {
281 lyxerr << "Putting image back"
284 XPutImage(tmpdisp, p->bitmap,
286 0, 0, p->wid, p->hgh);
288 if (lyxerr.debugging()) {
289 lyxerr << "Done translation"
294 kill_gs(p->gspid, SIGHUP);
296 XCloseDisplay(tmpdisp);
300 kill_gs(p->gspid, SIGHUP);
310 void AllocColors(int num)
311 // allocate color cube numxnumxnum, if possible
313 if (lyxerr.debugging()) {
314 lyxerr << "Allocating color cube " << num
315 << 'x' << num << 'x' << num << endl;
319 lyxerr << "Error allocating color colormap." << endl;
323 if (num > 5) num = 5;
325 for (int i = 0; i < num * num * num; ++i) {
326 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
327 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
328 xcol.blue = short(65535 * (i % num) / (num - 1));
329 xcol.flags = DoRed | DoGreen | DoBlue;
330 if (!XAllocColor(fl_get_display(),
331 fl_state[fl_get_vclass()].colormap, &xcol)) {
332 if (i) XFreeColors(fl_get_display(),
333 fl_state[fl_get_vclass()].colormap,
335 if (lyxerr.debugging()) {
336 lyxerr << "Cannot allocate color cube "
339 AllocColors(num - 1);
342 gs_pixels[i] = xcol.pixel;
349 // allocate grayscale ramp
351 void AllocGrays(int num)
353 if (lyxerr.debugging()) {
354 lyxerr << "Allocating grayscale colormap "
359 lyxerr << "Error allocating grayscale colormap." << endl;
363 if (num > 128) num = 128;
365 for (int i = 0; i < num; ++i) {
366 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
367 xcol.flags = DoRed | DoGreen | DoBlue;
368 if (!XAllocColor(fl_get_display(),
369 fl_state[fl_get_vclass()].colormap, &xcol)) {
370 if (i) XFreeColors(fl_get_display(),
371 fl_state[fl_get_vclass()].colormap,
373 if (lyxerr.debugging()) {
374 lyxerr << "Cannot allocate grayscale "
380 gs_pixels[i] = xcol.pixel;
386 // xforms doesn't define this
387 extern "C" FL_APPEVENT_CB fl_set_preemptive_callback(Window, FL_APPEVENT_CB, void *);
392 // if bitmaps and figures are not empty we will leak mem
396 // allocate color cube on pseudo-color display
400 /* we want to capture every event, in order to work around an
403 fl_set_preemptive_callback(fl_get_canvas_id(figinset_canvas), GhostscriptMsg, 0);
405 local_gc_copy = createGC();
407 Visual * vi = DefaultVisual(fl_get_display(),
408 DefaultScreen(fl_get_display()));
409 if (lyxerr.debugging()) {
410 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
411 vi->visualid, vi->c_class,
412 vi->bits_per_rgb, vi->map_entries);
414 color_visual = ( (vi->c_class == StaticColor) ||
415 (vi->c_class == PseudoColor) ||
416 (vi->c_class == TrueColor) ||
417 (vi->c_class == DirectColor) );
418 if ((vi->c_class & 1) == 0) return;
419 // now allocate colors
420 if (vi->c_class == GrayScale) {
421 // allocate grayscale
422 AllocGrays(vi->map_entries/2);
424 // allocate normal color
426 while (i * i * i * 2 > vi->map_entries) --i;
429 gs_allcolors = vi->map_entries;
437 // if bitmaps and figures are not empty we will leak mem
441 lyxerr.debug() << "Unregistering figures..." << endl;
446 void freefigdata(figdata * tmpdata)
449 if (tmpdata->ref) return;
451 if (tmpdata->gspid > 0) {
452 int pid = tmpdata->gspid;
453 // kill ghostscript and unlink it's files
455 kill_gs(pid, SIGKILL);
458 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
459 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
467 // This _have_ to be set before the fork!
468 unsigned long background_pixel =
469 lyxColorHandler->colorPixel(LColor::background);
471 // run queued requests for ghostscript, if any
472 if (!gsrunning && gs_color && !gs_xcolor) {
473 // here alloc all colors, so that gs will use only
474 // those we allocated for it
479 while (gsrunning < MAXGS) {
480 //char tbuf[384]; //, tbuf2[80];
484 if (gsqueue.empty()) {
485 if (!gsrunning && gs_xcolor) {
486 // de-allocate rest of colors
492 queue_element * p = &gsqueue.front();
501 if (lyxerr.debugging()) {
502 lyxerr << "GS start error! Cannot fork."
505 p->data->broken = true;
506 p->data->reading = false;
509 if (pid == 0) { // child
512 Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
514 // create translation file
516 ofs.open(make_tmp(getpid()).c_str());
517 ofs << "gsave clippath pathbbox grestore\n"
519 << "/ury exch def /urx exch def /lly exch def "
521 << p->data->wid / 2.0 << " "
522 << p->data->hgh / 2.0 << " translate\n"
523 << p->data->angle << " rotate\n"
524 << -(p->data->raw_wid / 2.0) << " "
525 << -(p->data->raw_hgh / 2.0) << " translate\n"
526 << p->rx / 72.0 << " " << p->ry / 72.0
528 << -p->ofsx << " " << -p->ofsy << " translate\n"
530 ofs.close(); // Don't remove this.
532 // gs process - set ghostview environment first
534 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
535 << ' ' << p->data->bitmap;
536 // now set up ghostview property on a window
537 // #warning BUG seems that the only bug here
538 // might be the hardcoded dpi.. Bummer!
540 t1 << "0 0 0 0 " << p->data->wid << ' '
541 << p->data->hgh << " 72 72 0 0 0 0";
543 if (lyxerr.debugging()) {
544 lyxerr << "Will set GHOSTVIEW property to ["
545 << t1.str() << "]" << endl;
547 // wait until property is deleted if executing multiple
549 XGrabServer(tempdisp);
551 // grab server to prevent other child
552 // interfering with setting GHOSTVIEW property
553 // The grabbing goes on for too long, is it
554 // really needed? (Lgb)
555 // I moved most of the grabs... (Lgb)
556 if (lyxerr.debugging()) {
557 lyxerr << "Grabbing the server"
560 prop = XListProperties(tempdisp,
562 figinset_canvas), &nprop);
566 for (i = 0; i < nprop; ++i) {
567 char * p = XGetAtomName(tempdisp,
569 if (strcmp(p, "GHOSTVIEW") == 0) {
571 // We free it when we leave so we don't leak.
577 XFree(reinterpret_cast<char *>(prop)); // jc:
579 // ok, property found, we must wait until
580 // ghostscript deletes it
581 if (lyxerr.debugging()) {
582 lyxerr << "Releasing the server\n["
584 << "] GHOSTVIEW property"
585 " found. Waiting." << endl;
587 XUngrabServer(tempdisp);
590 XGrabServer(tempdisp);
592 XChangeProperty(tempdisp,
593 fl_get_canvas_id(figinset_canvas),
594 XInternAtom(tempdisp, "GHOSTVIEW", false),
595 XInternAtom(tempdisp, "STRING", false),
597 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
598 int(t1.str().size()));
599 XUngrabServer(tempdisp);
604 switch (p->data->flags & 3) {
605 case 0: t3 << 'H'; break; // Hidden
606 case 1: t3 << 'M'; break; // Mono
607 case 2: t3 << 'G'; break; // Gray
616 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
617 << ' ' << background_pixel;
619 XGrabServer(tempdisp);
620 XChangeProperty(tempdisp,
621 fl_get_canvas_id(figinset_canvas),
622 XInternAtom(tempdisp,
623 "GHOSTVIEW_COLORS", false),
624 XInternAtom(tempdisp, "STRING", false),
626 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
627 int(t3.str().size()));
628 XUngrabServer(tempdisp);
631 if (lyxerr.debugging()) {
632 lyxerr << "Releasing the server" << endl;
634 XCloseDisplay(tempdisp);
636 // set up environment
639 typedef char * char_p;
640 env = new char_p[ne + 2];
641 string tmp = t2.str().c_str();
642 env[0] = new char[tmp.size() + 1];
643 std::copy(tmp.begin(), tmp.end(), env[0]);
644 env[0][tmp.size()] = '\0';
645 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
648 // now make gs command
650 // close(1); do NOT close. If GS writes out
651 // errors it would hang. (Matthias 290596)
653 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
654 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
656 // now chdir into dir with .eps file, to be on the safe
658 lyx::chdir(OnlyPath(p->data->fname));
659 // make temp file name
660 string tmpf = make_tmp(getpid());
661 if (lyxerr.debugging()) {
662 lyxerr << "starting gs " << tmpf << " "
664 << ", pid: " << getpid() << endl;
667 int err = ::execlp(lyxrc.ps_command.c_str(),
668 lyxrc.ps_command.c_str(),
670 "-dNOPAUSE", "-dQUIET",
672 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
673 p->data->fname.c_str(),
674 "showpage.ps", "quit.ps", "-", 0);
675 // if we are still there, an error occurred.
676 lyxerr << "Error executing ghostscript. "
677 << "Code: " << err << endl;
678 lyxerr.debug() << "Cmd: "
682 << p->data->fname << endl;
685 // normal process (parent)
686 if (lyxerr.debugging()) {
687 lyxerr << "GS [" << pid << "] started" << endl;
690 p->data->gspid = pid;
698 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
700 // recompute the stuff and put in the queue
704 p.rx = (float(data->raw_wid) * 72.0) / pswid;
705 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
711 // if possible, run the queue
717 figdata * getfigdata(int wid, int hgh, string const & fname,
718 int psx, int psy, int pswid, int pshgh,
719 int raw_wid, int raw_hgh, float angle, char flags)
721 /* first search for an exact match with fname and width/height */
723 if (fname.empty() || !IsFileReadable(fname))
726 for (bitmaps_type::iterator it = bitmaps.begin();
727 it != bitmaps.end(); ++it) {
728 if ((*it)->wid == wid && (*it)->hgh == hgh &&
729 (*it)->flags == flags && (*it)->fname == fname &&
730 (*it)->angle == angle) {
735 figdata * p = new figdata;
738 p->raw_wid = raw_wid;
739 p->raw_hgh = raw_hgh;
743 bitmaps.push_back(p);
744 XWindowAttributes wa;
745 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
746 figinset_canvas), &wa);
748 if (lyxerr.debugging()) {
749 lyxerr << "Create pixmap disp:" << fl_get_display()
750 << " scr:" << DefaultScreen(fl_get_display())
753 << " depth:" << wa.depth << endl;
761 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
762 figinset_canvas), wid, hgh, wa.depth);
764 // initialize reading of .eps file with correct sizes and stuff
765 addwait(psx, psy, pswid, pshgh, p);
777 void getbitmap(figdata * p)
784 void makeupdatelist(figdata * p)
786 for (figures_type::iterator it = figures.begin();
787 it != figures.end(); ++it)
788 if ((*it)->data == p) {
789 if (lyxerr.debugging()) {
790 lyxerr << "Updating inset "
794 // add inset figures[i]->inset into to_update list
795 current_view->pushIntoUpdateList((*it)->inset);
800 // this func is only "called" in spellchecker.C
801 void sigchldchecker(pid_t pid, int * status)
803 lyxerr.debug() << "Got pid = " << pid << endl;
804 bool pid_handled = false;
805 for (bitmaps_type::iterator it = bitmaps.begin();
806 it != bitmaps.end(); ++it) {
807 if ((*it)->reading && pid == (*it)->gspid) {
808 lyxerr.debug() << "Found pid in bitmaps" << endl;
809 // now read the file and remove it from disk
812 if ((*it)->gsdone) *status = 0;
814 lyxerr.debug() << "GS [" << pid
815 << "] exit OK." << endl;
817 lyxerr << "GS [" << pid << "] error "
819 << WIFEXITED(*status)
820 << " " << WEXITSTATUS(*status)
821 << " S:" << WIFSIGNALED(*status)
822 << " " << WTERMSIG(*status) << endl;
825 bitmap_waiting = true;
828 // remove temporary files
829 lyx::unlink(make_tmp(p->gspid));
833 makeupdatelist((*it));
840 lyxerr.debug() << "Checking pid in pidwait" << endl;
841 list<int>::iterator it = find(pidwaitlist.begin(),
842 pidwaitlist.end(), pid);
843 if (it != pidwaitlist.end()) {
844 lyxerr.debug() << "Found pid in pidwait\n"
845 << "Caught child pid of recompute "
846 "routine" << pid << endl;
847 pidwaitlist.erase(it);
851 lyxerr.debug() << "waitpid error" << endl;
854 lyxerr << "The process or process group specified by "
855 "pid does not exist or is not a child of "
856 "the calling process or can never be in the "
857 "states specified by options." << endl;
860 lyxerr << "waitpid() was interrupted due to the "
861 "receipt of a signal sent by the calling "
865 lyxerr << "An invalid value was specified for "
869 lyxerr << "Unknown error from waitpid" << endl;
872 } else if (pid == 0) {
873 lyxerr << "waitpid nohang" << endl;;
875 lyxerr.debug() << "normal exit from childhandler" << endl;
883 bitmap_waiting = false;
884 for (bitmaps_type::iterator it = bitmaps.begin();
885 it != bitmaps.end(); ++it)
886 if ((*it)->gspid > 0 && !(*it)->reading)
892 void RegisterFigure(InsetFig * fi)
894 if (figures.empty()) InitFigures();
896 Figref * tmpfig = new Figref;
899 figures.push_back(tmpfig);
902 if (lyxerr.debugging()) {
903 lyxerr << "Register Figure: buffer:["
904 << current_view->buffer() << "]" << endl;
910 void UnregisterFigure(InsetFig * fi)
915 Figref * tmpfig = fi->figure;
917 if (tmpfig->data) freefigdata(tmpfig->data);
918 if (tmpfig->inset->form) {
919 if (tmpfig->inset->form->Figure->visible) {
920 fl_set_focus_object(tmpfig->inset->form->Figure,
921 tmpfig->inset->form->OkBtn);
922 fl_hide_form(tmpfig->inset->form->Figure);
924 #if FL_REVISION == 89
925 // CHECK Reactivate this free_form calls
927 fl_free_form(tmpfig->inset->form->Figure);
928 free(tmpfig->inset->form); // Why free?
929 tmpfig->inset->form = 0;
932 figures.erase(find(figures.begin(), figures.end(), tmpfig));
935 if (figures.empty()) DoneFigures();
939 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
949 psubfigure = subfigure = false;
950 xwid = xhgh = angle = 0;
952 raw_wid = raw_hgh = 0;
953 changedfname = false;
954 RegisterFigure(this);
955 r_ = Dialogs::redrawGUI.connect(slot(this, &InsetFig::redraw));
959 InsetFig::~InsetFig()
961 if (lyxerr.debugging()) {
962 lyxerr << "Figure destructor called" << endl;
964 UnregisterFigure(this);
969 void InsetFig::redraw()
971 if (form && form->Figure->visible)
972 fl_redraw_form(form->Figure);
976 int InsetFig::ascent(BufferView *, LyXFont const &) const
982 int InsetFig::descent(BufferView *, LyXFont const &) const
988 int InsetFig::width(BufferView *, LyXFont const &) const
994 void InsetFig::draw(BufferView * bv, LyXFont const & f,
995 int baseline, float & x, bool) const
998 Painter & pain = bv->painter();
1000 if (bitmap_waiting) getbitmaps();
1002 // I wish that I didn't have to use this
1003 // but the figinset code is so complicated so
1004 // I don't want to fiddle with it now.
1006 if (figure && figure->data && figure->data->bitmap &&
1007 !figure->data->reading && !figure->data->broken) {
1009 pain.pixmap(int(x + 1), baseline - hgh,
1010 wid, hgh, figure->data->bitmap);
1013 pain.rectangle(int(x), baseline - hgh - 1,
1017 char const * msg = 0;
1018 string lfname = fname;
1019 if (!fname.empty() && GetExtension(fname).empty())
1022 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1024 if (figure && figure->data) {
1025 if (figure->data->broken) msg = _("[render error]");
1026 else if (figure->data->reading) msg = _("[rendering ... ]");
1028 else if (fname.empty())
1029 msg = _("[no file]");
1030 else if (!IsFileReadable(lfname))
1031 msg = _("[bad file name]");
1032 else if ((flags & 3) == 0)
1033 msg = _("[not displayed]");
1034 else if (lyxrc.ps_command.empty())
1035 msg = _("[no ghostscript]");
1037 if (!msg) msg = _("[unknown error]");
1039 font.setFamily(LyXFont::SANS_FAMILY);
1040 font.setSize(LyXFont::SIZE_FOOTNOTE);
1041 string justname = OnlyFilename (fname);
1042 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1045 font.setSize(LyXFont::SIZE_TINY);
1046 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1048 x += width(bv, font); // ?
1052 void InsetFig::Write(Buffer const *, ostream & os) const
1055 os << "Figure size " << wid << " " << hgh << "\n";
1056 if (!fname.empty()) {
1057 string buf1 = OnlyPath(owner->fileName());
1058 string fname2 = MakeRelPath(fname, buf1);
1059 os << "file " << fname2 << "\n";
1061 if (!subcaption.empty())
1062 os << "subcaption " << subcaption << "\n";
1063 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1064 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1065 if (angle != 0) os << "angle " << angle << "\n";
1066 os << "flags " << flags << "\n";
1067 if (subfigure) os << "subfigure\n";
1071 void InsetFig::Read(Buffer const *, LyXLex & lex)
1074 bool finished = false;
1076 while (lex.IsOK() && !finished) {
1079 string const token = lex.GetString();
1080 lyxerr.debug() << "Token: " << token << endl;
1084 else if (token == "\\end_inset") {
1086 } else if (token == "file") {
1088 buf = lex.GetString();
1089 string buf1 = OnlyPath(owner->fileName());
1090 fname = MakeAbsPath(buf, buf1);
1091 changedfname = true;
1093 } else if (token == "extra") {
1095 // kept for backwards compability. Delete in 0.13.x
1096 } else if (token == "subcaption") {
1098 subcaption = lex.GetString();
1099 } else if (token == "label") {
1101 // kept for backwards compability. Delete in 0.13.x
1102 } else if (token == "angle") {
1104 angle = lex.GetFloat();
1105 } else if (token == "size") {
1107 wid = lex.GetInteger();
1109 hgh = lex.GetInteger();
1110 } else if (token == "flags") {
1112 flags = pflags = lex.GetInteger();
1113 } else if (token == "subfigure") {
1114 subfigure = psubfigure = true;
1115 } else if (token == "width") {
1118 typ = lex.GetInteger();
1120 xwid = lex.GetFloat();
1122 case DEF: wtype = DEF; break;
1123 case CM: wtype = CM; break;
1124 case IN: wtype = IN; break;
1125 case PER_PAGE: wtype = PER_PAGE; break;
1126 case PER_COL: wtype = PER_COL; break;
1128 lyxerr.debug() << "Unknown type!" << endl;
1132 } else if (token == "height") {
1135 typ = lex.GetInteger();
1137 xhgh = lex.GetFloat();
1139 case DEF: htype = DEF; break;
1140 case CM: htype = CM; break;
1141 case IN: htype = IN; break;
1142 case PER_PAGE: htype = PER_PAGE; break;
1144 lyxerr.debug() << "Unknown type!" << endl;
1155 int InsetFig::Latex(Buffer const *, ostream & os,
1156 bool /* fragile*/, bool /* fs*/) const
1159 if (!cmd.empty()) os << cmd << " ";
1164 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1170 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1176 int InsetFig::DocBook(Buffer const *, ostream & os) const
1178 string buf1 = OnlyPath(owner->fileName());
1179 string figurename = MakeRelPath(fname, buf1);
1181 if (suffixIs(figurename, ".eps"))
1182 figurename.erase(figurename.length() - 4);
1184 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1189 void InsetFig::Validate(LaTeXFeatures & features) const
1191 features.graphics = true;
1192 if (subfigure) features.subfigure = true;
1196 Inset::EDITABLE InsetFig::Editable() const
1202 bool InsetFig::Deletable() const
1208 string const InsetFig::EditMessage() const
1210 return _("Opened figure");
1214 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1216 lyxerr.debug() << "Editing InsetFig." << endl;
1219 // We should have RO-versions of the form instead.
1220 // The actual prevention of altering a readonly doc
1221 // is done in CallbackFig()
1222 if (bv->buffer()->isReadonly())
1223 WarnReadonly(bv->buffer()->fileName());
1226 form = create_form_Figure();
1227 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1228 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1229 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1230 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1233 if (form->Figure->visible) {
1234 fl_raise_form(form->Figure);
1236 fl_show_form(form->Figure,
1237 FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
1243 Inset * InsetFig::Clone(Buffer const & buffer) const
1245 InsetFig * tmp = new InsetFig(100, 100, buffer);
1247 if (lyxerr.debugging()) {
1248 lyxerr << "Clone Figure: buffer:["
1250 << "], cbuffer:[xx]" << endl;
1255 tmp->raw_wid = raw_wid;
1256 tmp->raw_hgh = raw_hgh;
1261 tmp->pflags = pflags;
1262 tmp->subfigure = subfigure;
1263 tmp->psubfigure = psubfigure;
1271 if (!fname.empty() && IsFileReadable(fname)
1272 && (flags & 3) && !lyxrc.ps_command.empty()
1274 // do not display if there is
1275 // "do not display" chosen (Matthias 260696)
1276 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1277 pswid, pshgh, raw_wid, raw_hgh,
1278 angle, flags & (3|8));
1279 } else tmp->figure->data = 0;
1280 tmp->subcaption = subcaption;
1281 tmp->changedfname = false;
1288 Inset::Code InsetFig::LyxCode() const
1290 return Inset::GRAPHICS_CODE;
1295 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1301 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1302 res = tostr(f) + "cm";
1305 res = tostr(f) + "in";
1307 case InsetFig::PER_PAGE:
1308 res = tostr(f/100) + "\\text" + suffix;
1310 case InsetFig::PER_COL:
1311 // Doesn't occur for htype...
1312 res = tostr(f/100) + "\\column" + suffix;
1319 void InsetFig::Regenerate() const
1322 string resizeW, resizeH;
1323 string rotate, recmd;
1325 if (fname.empty()) {
1326 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1327 cmd += _("empty figure path");
1332 string buf1 = OnlyPath(owner->fileName());
1333 string fname2 = MakeRelPath(fname, buf1);
1335 string gcmd = "\\includegraphics{" + fname2 + '}';
1336 resizeW = stringify(wtype, xwid, "width");
1337 resizeH = stringify(htype, xhgh, "height");
1339 if (!resizeW.empty() || !resizeH.empty()) {
1340 recmd = "\\resizebox*{";
1341 if (!resizeW.empty())
1346 if (!resizeH.empty())
1355 // \rotatebox{angle}{text}
1356 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1362 if (!rotate.empty()) cmdbuf += '}';
1363 if (!recmd.empty()) cmdbuf += '}';
1365 if (!subcaption.empty())
1366 cmdbuf = "\\subfigure[" + subcaption +
1367 "]{" + cmdbuf + "}";
1369 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1376 void InsetFig::TempRegenerate()
1379 string resizeW, resizeH;
1380 string rotate, recmd;
1382 char const * tfname = fl_get_input(form->EpsFile);
1383 string tsubcap = fl_get_input(form->Subcaption);
1384 float tangle = atof(fl_get_input(form->Angle));
1385 float txwid = atof(fl_get_input(form->Width));
1386 float txhgh = atof(fl_get_input(form->Height));
1388 if (!tfname || !*tfname) {
1389 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1390 cmd += _("empty figure path");
1395 string buf1 = OnlyPath(owner->fileName());
1396 string fname2 = MakeRelPath(tfname, buf1);
1397 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1398 string gcmd = "\\includegraphics{" + fname2 + '}';
1400 resizeW = stringify(twtype, txwid, "width");
1401 resizeH = stringify(thtype, txhgh, "height");
1403 // \resizebox*{h-length}{v-length}{text}
1404 if (!resizeW.empty() || !resizeH.empty()) {
1405 recmd = "\\resizebox*{";
1406 if (!resizeW.empty())
1411 if (!resizeH.empty())
1419 // \rotatebox{angle}{text}
1420 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1423 cmdbuf = recmd + rotate + gcmd;
1424 if (!rotate.empty()) cmdbuf += '}';
1425 if (!recmd.empty()) cmdbuf += '}';
1426 if (psubfigure && !tsubcap.empty()) {
1427 cmdbuf = string("\\subfigure{") + tsubcap
1428 + string("}{") + cmdbuf + "}";
1433 void InsetFig::Recompute()
1438 bool changed = changedfname;
1439 int newx, newy, nraw_x, nraw_y;
1441 if (changed) GetPSSizes();
1443 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1444 float cos_a = cos (angle / DEG2PI);
1445 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1446 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1448 string lfname = fname;
1449 if (GetExtension(fname).empty())
1452 /* now recompute wid and hgh, and if that is changed, set changed */
1453 /* this depends on chosen size of the picture and its bbox */
1454 // This will be redone in 0.13 ... (hen)
1455 if (!lfname.empty() && IsFileReadable(lfname)) {
1456 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1464 newx = int(28.346 * xwid);
1467 newx = int(72 * xwid);
1469 case PER_PAGE: /* % of page */
1470 newx = int(5.95 * xwid);
1472 case PER_COL: /* % of col */
1473 newx = int(2.975 * xwid);
1477 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1481 //lyxerr << "This should not happen!" << endl;
1484 newy = int(28.346 * xhgh);
1487 newy = int(72 * xhgh);
1489 case PER_PAGE: /* % of page */
1490 newy = int(8.42 * xhgh);
1493 // Doesn't occur; case exists to suppress
1494 // compiler warnings.
1497 if (htype && !wtype && frame_hgh)
1498 newx = newy*frame_wid/frame_hgh;
1507 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1512 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1514 // cannot be zero, actually, set it to some minimum, so its clickable
1515 if (newx < 5) newx = 5;
1516 if (newy < 5) newy = 5;
1518 if (newx != wid || newy != hgh ||
1519 nraw_x != raw_wid || nraw_y != raw_hgh ||
1520 flags != pflags || subfigure != psubfigure)
1528 subfigure = psubfigure;
1531 figdata * pf = figure->data;
1534 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1535 && !lyxrc.ps_command.empty()) {
1536 // do not display if there is "do not display"
1537 // chosen (Matthias 260696)
1538 figure->data = getfigdata(wid, hgh, lfname,
1539 psx, psy, pswid, pshgh,
1541 angle, flags & (3|8));
1542 } else figure->data = 0;
1544 // free the old data
1545 if (pf) freefigdata(pf);
1548 changedfname = false;
1552 void InsetFig::GetPSSizes()
1554 /* get %%BoundingBox: from postscript file */
1556 /* defaults to associated size
1557 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1564 if (fname.empty()) return;
1566 ifstream ifs(fname.c_str());
1568 if (!ifs) return; // file not found !!!!
1570 /* defaults to A4 page */
1576 char lastchar = 0; ifs.get(lastchar);
1578 char c = 0; ifs.get(c);
1580 lyxerr.debug() << "End of (E)PS file reached and"
1581 " no BoundingBox!" << endl;
1584 if (c == '%' && lastchar == '%') {
1586 if (p.empty()) break;
1587 lyxerr.debug() << "Token: `" << p << "'" << endl;
1588 if (p == "BoundingBox:") {
1589 float fpsx, fpsy, fpswid, fpshgh;
1590 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1593 pswid = int(fpswid);
1594 pshgh = int(fpshgh);
1596 if (lyxerr.debugging()) {
1597 lyxerr << "%%%%BoundingBox:"
1615 void InsetFig::CallbackFig(long arg)
1620 if (lyxerr.debugging()) {
1621 lyxerr << "Figure callback, arg " << arg << endl;
1627 case 12: /* width type */
1634 fl_deactivate_object(form->Width);
1639 fl_activate_object(form->Width);
1644 fl_activate_object(form->Width);
1649 fl_activate_object(form->Width);
1654 fl_activate_object(form->Width);
1657 lyxerr.debug() << "Unknown type!" << endl;
1664 case 22: /* height type */
1670 fl_deactivate_object(form->Height);
1675 fl_activate_object(form->Height);
1680 fl_activate_object(form->Height);
1685 fl_activate_object(form->Height);
1688 lyxerr.debug() << "Unknown type!" << endl;
1694 pflags = pflags & ~3; /* wysiwyg0 */
1697 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1700 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1703 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1706 pflags ^= 4; /* frame */
1709 pflags ^= 8; /* do translations */
1712 psubfigure = !psubfigure; /* This is a subfigure */
1715 regen = true; /* regenerate command */
1717 case 0: /* browse file */
1721 case 1: /* preview */
1722 p = fl_get_input(form->EpsFile);
1726 case 8: /* ok (apply and close) */
1727 if (!current_view->buffer()->isReadonly()) {
1730 xwid = atof(fl_get_input(form->Width));
1731 xhgh = atof(fl_get_input(form->Height));
1732 angle = atof(fl_get_input(form->Angle));
1733 p = fl_get_input(form->EpsFile);
1735 string buf1 = OnlyPath(owner->fileName());
1736 fname = MakeAbsPath(p, buf1);
1737 changedfname = true;
1739 if (!fname.empty()) {
1740 changedfname = true;
1744 subcaption = fl_get_input(form->Subcaption);
1748 /* now update inset */
1749 if (lyxerr.debugging()) {
1750 lyxerr << "Update: ["
1751 << wid << 'x' << hgh << ']' << endl;
1753 current_view->updateInset(this, true);
1755 fl_set_focus_object(form->Figure, form->OkBtn);
1756 fl_hide_form(form->Figure);
1757 #if FL_REVISION == 89
1758 // CHECK Reactivate this free_form calls
1760 fl_free_form(form->Figure);
1761 free(form); // Why free?
1767 // The user has already been informed about RO in ::Edit
1768 if (arg == 7) // if 'Apply'
1771 case 9: /* cancel = restore and close */
1772 fl_set_focus_object(form->Figure, form->OkBtn);
1773 fl_hide_form(form->Figure);
1774 #if FL_REVISION == 89
1775 // CHECK Reactivate this free_form calls
1776 // Jug, is this still a problem?
1778 fl_free_form(form->Figure);
1779 free(form); // Why free?
1785 if (regen) TempRegenerate();
1790 void DisableFigurePanel(FD_Figure * const form)
1792 fl_deactivate_object(form->EpsFile);
1793 fl_deactivate_object(form->Browse);
1794 fl_deactivate_object(form->Width);
1795 fl_deactivate_object(form->Height);
1796 fl_deactivate_object(form->Frame);
1797 fl_deactivate_object(form->Translations);
1798 fl_deactivate_object(form->Angle);
1799 fl_deactivate_object(form->HeightGrp);
1800 fl_deactivate_object(form->page2);
1801 fl_deactivate_object(form->Default2);
1802 fl_deactivate_object(form->cm2);
1803 fl_deactivate_object(form->in2);
1804 fl_deactivate_object(form->HeightLabel);
1805 fl_deactivate_object(form->WidthLabel);
1806 fl_deactivate_object(form->DisplayGrp);
1807 fl_deactivate_object(form->Wysiwyg3);
1808 fl_deactivate_object(form->Wysiwyg0);
1809 fl_deactivate_object(form->Wysiwyg2);
1810 fl_deactivate_object(form->Wysiwyg1);
1811 fl_deactivate_object(form->WidthGrp);
1812 fl_deactivate_object(form->Default1);
1813 fl_deactivate_object(form->cm1);
1814 fl_deactivate_object(form->in1);
1815 fl_deactivate_object(form->page1);
1816 fl_deactivate_object(form->column1);
1817 fl_deactivate_object(form->Subcaption);
1818 fl_deactivate_object(form->Subfigure);
1819 fl_deactivate_object (form->OkBtn);
1820 fl_deactivate_object (form->ApplyBtn);
1821 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1822 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1827 void EnableFigurePanel(FD_Figure * const form)
1829 fl_activate_object(form->EpsFile);
1830 fl_activate_object(form->Browse);
1831 fl_activate_object(form->Width);
1832 fl_activate_object(form->Height);
1833 fl_activate_object(form->Frame);
1834 fl_activate_object(form->Translations);
1835 fl_activate_object(form->Angle);
1836 fl_activate_object(form->HeightGrp);
1837 fl_activate_object(form->page2);
1838 fl_activate_object(form->Default2);
1839 fl_activate_object(form->cm2);
1840 fl_activate_object(form->in2);
1841 fl_activate_object(form->HeightLabel);
1842 fl_activate_object(form->WidthLabel);
1843 fl_activate_object(form->DisplayGrp);
1844 fl_activate_object(form->Wysiwyg3);
1845 fl_activate_object(form->Wysiwyg0);
1846 fl_activate_object(form->Wysiwyg2);
1847 fl_activate_object(form->Wysiwyg1);
1848 fl_activate_object(form->WidthGrp);
1849 fl_activate_object(form->Default1);
1850 fl_activate_object(form->cm1);
1851 fl_activate_object(form->in1);
1852 fl_activate_object(form->page1);
1853 fl_activate_object(form->column1);
1854 fl_activate_object(form->Subcaption);
1855 fl_activate_object(form->Subfigure);
1856 fl_activate_object (form->OkBtn);
1857 fl_activate_object (form->ApplyBtn);
1858 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1859 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1863 void InsetFig::RestoreForm()
1865 EnableFigurePanel(form);
1868 fl_set_button(form->Default1, (wtype == 0));
1869 fl_set_button(form->cm1, (wtype == 1));
1870 fl_set_button(form->in1, (wtype == 2));
1871 fl_set_button(form->page1, (wtype == 3));
1872 fl_set_button(form->column1, (wtype == 4));
1874 fl_deactivate_object(form->Width);
1876 fl_activate_object(form->Width);
1879 // enable and disable should be put here.
1881 fl_set_button(form->Default2, (htype == 0));
1882 fl_set_button(form->cm2, (htype == 1));
1883 fl_set_button(form->in2, (htype == 2));
1884 fl_set_button(form->page2, (htype == 3));
1885 // enable and disable should be put here.
1887 fl_deactivate_object(form->Height);
1889 fl_activate_object(form->Height);
1892 int piflags = flags & 3;
1893 fl_set_button(form->Wysiwyg0, (piflags == 0));
1894 fl_set_button(form->Wysiwyg1, (piflags == 1));
1895 fl_set_button(form->Wysiwyg2, (piflags == 2));
1896 fl_set_button(form->Wysiwyg3, (piflags == 3));
1897 fl_set_button(form->Frame, ((flags & 4) != 0));
1898 fl_set_button(form->Translations, ((flags & 8) != 0));
1899 fl_set_button(form->Subfigure, (subfigure != 0));
1901 psubfigure = subfigure;
1902 fl_set_input(form->Width, tostr(xwid).c_str());
1903 fl_set_input(form->Height, tostr(xhgh).c_str());
1904 fl_set_input(form->Angle, tostr(angle).c_str());
1905 if (!fname.empty()){
1906 string buf1 = OnlyPath(owner->fileName());
1907 string fname2 = MakeRelPath(fname, buf1);
1908 fl_set_input(form->EpsFile, fname2.c_str());
1910 else fl_set_input(form->EpsFile, "");
1911 fl_set_input(form->Subcaption, subcaption.c_str());
1912 if (current_view->buffer()->isReadonly())
1913 DisableFigurePanel(form);
1919 void InsetFig::Preview(string const & p)
1922 if (GetExtension(tfname).empty())
1924 string buf1 = OnlyPath(owner->fileName());
1925 string buf2 = MakeAbsPath(tfname, buf1);
1926 if (!formats.View(owner, buf2, "eps"))
1927 lyxerr << "Can't view " << buf2 << endl;
1930 void InsetFig::BrowseFile()
1932 static string current_figure_path;
1933 static int once = 0;
1936 if (lyxerr.debugging()) {
1937 lyxerr << "Filename: "
1938 << owner->fileName() << endl;
1940 string p = fl_get_input(form->EpsFile);
1942 string buf = MakeAbsPath(owner->fileName());
1943 string buf2 = OnlyPath(buf);
1945 buf = MakeAbsPath(p, buf2);
1946 buf = OnlyPath(buf);
1948 buf = OnlyPath(owner->fileName());
1951 // Does user clipart directory exist?
1952 string bufclip = AddName (user_lyxdir, "clipart");
1953 FileInfo fileInfo(bufclip);
1954 if (!(fileInfo.isOK() && fileInfo.isDir()))
1955 // No - bail out to system clipart directory
1956 bufclip = AddName (system_lyxdir, "clipart");
1959 fileDlg.SetButton(0, _("Clipart"), bufclip);
1960 fileDlg.SetButton(1, _("Document"), buf);
1964 ProhibitInput(current_view);
1966 p = fileDlg.Select(_("EPS Figure"),
1967 current_figure_path,
1970 p = fileDlg.Select(_("EPS Figure"), buf,
1973 AllowInput(current_view);
1975 if (p.empty()) return;
1977 buf = MakeRelPath(p, buf2);
1978 current_figure_path = OnlyPath(p);
1981 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1982 || contains(p, "%") || contains(p, " ")) {
1983 WriteAlert(_("Filename can't contain any "
1984 "of these characters:"),
1985 // xgettext:no-c-format
1986 _("space, '#', '~', '$' or '%'."));
1991 if (form) fl_set_input(form->EpsFile, buf.c_str());
1995 void GraphicsCB(FL_OBJECT * obj, long arg)
1997 /* obj->form contains the form */
1999 if (lyxerr.debugging()) {
2000 lyxerr << "GraphicsCB callback: " << arg << endl;
2003 /* find inset we were reacting to */
2004 for (figures_type::iterator it = figures.begin();
2005 it != figures.end(); ++it)
2006 if ((*it)->inset->form && (*it)->inset->form->Figure
2008 if (lyxerr.debugging()) {
2009 lyxerr << "Calling back figure "
2012 (*it)->inset->CallbackFig(arg);
2018 void HideFiguresPopups()
2020 for (figures_type::iterator it = figures.begin();
2021 it != figures.end(); ++it)
2022 if ((*it)->inset->form
2023 && (*it)->inset->form->Figure->visible) {
2024 if (lyxerr.debugging()) {
2025 lyxerr << "Hiding figure " << (*it) << endl;
2027 // hide and free the form
2028 (*it)->inset->CallbackFig(9);