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)
42 #include FORMS_H_LOCATION
51 #include "frontends/FileDialog.h"
52 #include "support/filetools.h"
53 #include "LyXView.h" // just because of form_main
55 #include "LaTeXFeatures.h"
58 #include "lyx_gui_misc.h" // CancelCloseBoxCB
59 #include "support/FileInfo.h"
60 #include "support/lyxlib.h"
63 #include "bufferview_funcs.h"
64 #include "ColorHandler.h"
65 #include "converter.h"
66 #include "frontends/Dialogs.h" // redrawGUI
78 using std::ostringstream;
83 extern BufferView * current_view;
84 extern FL_OBJECT * figinset_canvas;
86 extern char ** environ; // is this only redundtant on linux systems? Lgb.
88 static float const DEG2PI = 57.295779513;
90 struct queue_element {
91 float rx, ry; // resolution x and y
92 int ofsx, ofsy; // x and y translation
93 figdata * data; // we are doing it for this data
96 static int const MAXGS = 3; /* maximum 3 gs's at a time */
98 typedef vector<Figref *> figures_type;
99 typedef vector<figdata *> bitmaps_type;
100 static figures_type figures; // all figures
101 static bitmaps_type bitmaps; // all bitmaps
103 static queue<queue_element> gsqueue; // queue for ghostscripting
105 static int gsrunning = 0; /* currently so many gs's are running */
106 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
108 static bool gs_color; // do we allocate colors for gs?
109 static bool color_visual; // is the visual color?
110 static bool gs_xcolor = false; // allocated extended colors
111 static unsigned long gs_pixels[128]; // allocated pixels
112 static int gs_spc; // shades per color
113 static int gs_allcolors; // number of all colors
115 static list<int> pidwaitlist; // pid wait list
121 val.foreground = BlackPixel(fl_get_display(),
122 DefaultScreen(fl_get_display()));
125 val.graphics_exposures = false;
126 val.line_style = LineSolid;
128 return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0),
129 GCForeground | GCFunction | GCGraphicsExposures
130 | GCLineWidth | GCLineStyle , &val);
138 void addpidwait(int pid)
140 // adds pid to pid wait list
141 pidwaitlist.push_back(pid);
143 if (lyxerr.debugging()) {
144 lyxerr << "Pids to wait for: \n";
145 copy(pidwaitlist.begin(), pidwaitlist.end(),
146 std::ostream_iterator<int>(lyxerr, "\n"));
153 string make_tmp(int pid)
155 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
160 void kill_gs(int pid, int sig)
162 if (lyxerr.debugging())
163 lyxerr << "Killing gs " << pid << endl;
165 lyx::unlink(make_tmp(pid));
171 int GhostscriptMsg(XEvent * ev, void *)
173 // bin all events not of interest
174 if (ev->type != ClientMessage)
177 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
179 if (lyxerr.debugging()) {
180 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
181 << "] pm:[" << e->data.l[1] << "]" << endl;
184 // just kill gs, that way it will work for sure
185 // This loop looks like S**T so it probably is...
186 for (bitmaps_type::iterator it = bitmaps.begin();
187 it != bitmaps.end(); ++it)
188 if (static_cast<long>((*it)->bitmap) ==
189 static_cast<long>(e->data.l[1])) {
194 // first update p->bitmap, if necessary
195 if (p->bitmap != None
196 && p->flags > (1|8) && gs_color && p->wid) {
197 // query current colormap and re-render
198 // the pixmap with proper colors
199 XWindowAttributes wa;
200 register XImage * im;
203 int spc1 = gs_spc - 1;
204 int spc2 = gs_spc * gs_spc;
208 GC gc = local_gc_copy;
210 XGetWindowAttributes(fl_get_display(),
214 XFlush(fl_get_display());
215 if (lyxerr.debugging()) {
216 lyxerr << "Starting image translation "
219 << p->wid << "x" << p->hgh
221 << " " << XYPixmap << endl;
223 // now fork rendering process
225 if (forkstat == -1) {
227 << "Cannot fork, using slow "
228 "method for pixmap translation." << endl;
229 tmpdisp = fl_get_display();
230 } else if (forkstat > 0) { // parent
232 if (lyxerr.debugging()) {
233 lyxerr << "Spawned child "
236 addpidwait(forkstat);
239 tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
242 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
243 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
245 if (lyxerr.debugging()) {
246 lyxerr << "Got the image" << endl;
249 if (lyxerr.debugging()) {
250 lyxerr << "Error getting the image" << endl;
255 // query current colormap
256 XColor * cmap = new XColor[gs_allcolors];
257 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
258 XQueryColors(tmpdisp,
259 fl_state[fl_get_vclass()]
263 // now we process all the image
264 for (y = 0; y < p->hgh; ++y) {
265 for (int x = 0; x < wid; ++x) {
270 gs_pixels[((pc->red+6553)*
271 spc1/65535)*spc2+((pc->green+6553)*
272 spc1/65535)*gs_spc+((pc->blue+6553)*
277 // This must be correct.
279 if (lyxerr.debugging()) {
280 lyxerr << "Putting image back"
283 XPutImage(tmpdisp, p->bitmap,
285 0, 0, p->wid, p->hgh);
287 if (lyxerr.debugging()) {
288 lyxerr << "Done translation"
293 kill_gs(p->gspid, SIGHUP);
295 XCloseDisplay(tmpdisp);
299 kill_gs(p->gspid, SIGHUP);
309 void AllocColors(int num)
310 // allocate color cube numxnumxnum, if possible
312 if (lyxerr.debugging()) {
313 lyxerr << "Allocating color cube " << num
314 << 'x' << num << 'x' << num << endl;
318 lyxerr << "Error allocating color colormap." << endl;
322 if (num > 5) num = 5;
324 for (int i = 0; i < num * num * num; ++i) {
325 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
326 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
327 xcol.blue = short(65535 * (i % num) / (num - 1));
328 xcol.flags = DoRed | DoGreen | DoBlue;
329 if (!XAllocColor(fl_get_display(),
330 fl_state[fl_get_vclass()].colormap, &xcol)) {
331 if (i) XFreeColors(fl_get_display(),
332 fl_state[fl_get_vclass()].colormap,
334 if (lyxerr.debugging()) {
335 lyxerr << "Cannot allocate color cube "
338 AllocColors(num - 1);
341 gs_pixels[i] = xcol.pixel;
348 // allocate grayscale ramp
350 void AllocGrays(int num)
352 if (lyxerr.debugging()) {
353 lyxerr << "Allocating grayscale colormap "
358 lyxerr << "Error allocating grayscale colormap." << endl;
362 if (num > 128) num = 128;
364 for (int i = 0; i < num; ++i) {
365 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
366 xcol.flags = DoRed | DoGreen | DoBlue;
367 if (!XAllocColor(fl_get_display(),
368 fl_state[fl_get_vclass()].colormap, &xcol)) {
369 if (i) XFreeColors(fl_get_display(),
370 fl_state[fl_get_vclass()].colormap,
372 if (lyxerr.debugging()) {
373 lyxerr << "Cannot allocate grayscale "
379 gs_pixels[i] = xcol.pixel;
385 // xforms doesn't define this
386 extern "C" FL_APPEVENT_CB fl_set_preemptive_callback(Window, FL_APPEVENT_CB, void *);
391 // if bitmaps and figures are not empty we will leak mem
395 // allocate color cube on pseudo-color display
399 /* we want to capture every event, in order to work around an
402 fl_set_preemptive_callback(fl_get_canvas_id(figinset_canvas), GhostscriptMsg, 0);
404 local_gc_copy = createGC();
406 Visual * vi = DefaultVisual(fl_get_display(),
407 DefaultScreen(fl_get_display()));
408 if (lyxerr.debugging()) {
409 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
410 vi->visualid, vi->c_class,
411 vi->bits_per_rgb, vi->map_entries);
413 color_visual = ( (vi->c_class == StaticColor) ||
414 (vi->c_class == PseudoColor) ||
415 (vi->c_class == TrueColor) ||
416 (vi->c_class == DirectColor) );
417 if ((vi->c_class & 1) == 0) return;
418 // now allocate colors
419 if (vi->c_class == GrayScale) {
420 // allocate grayscale
421 AllocGrays(vi->map_entries/2);
423 // allocate normal color
425 while (i * i * i * 2 > vi->map_entries) --i;
428 gs_allcolors = vi->map_entries;
436 // if bitmaps and figures are not empty we will leak mem
440 lyxerr.debug() << "Unregistering figures..." << endl;
445 void freefigdata(figdata * tmpdata)
448 if (tmpdata->ref) return;
450 if (tmpdata->gspid > 0) {
451 int pid = tmpdata->gspid;
452 // kill ghostscript and unlink it's files
454 kill_gs(pid, SIGKILL);
457 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
458 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
466 // This _have_ to be set before the fork!
467 unsigned long background_pixel =
468 lyxColorHandler->colorPixel(LColor::background);
470 // run queued requests for ghostscript, if any
471 if (!gsrunning && gs_color && !gs_xcolor) {
472 // here alloc all colors, so that gs will use only
473 // those we allocated for it
478 while (gsrunning < MAXGS) {
479 //char tbuf[384]; //, tbuf2[80];
483 if (gsqueue.empty()) {
484 if (!gsrunning && gs_xcolor) {
485 // de-allocate rest of colors
491 queue_element * p = &gsqueue.front();
500 if (lyxerr.debugging()) {
501 lyxerr << "GS start error! Cannot fork."
504 p->data->broken = true;
505 p->data->reading = false;
508 if (pid == 0) { // child
511 Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
513 // create translation file
515 ofs.open(make_tmp(getpid()).c_str());
516 ofs << "gsave clippath pathbbox grestore\n"
518 << "/ury exch def /urx exch def /lly exch def "
520 << p->data->wid / 2.0 << " "
521 << p->data->hgh / 2.0 << " translate\n"
522 << p->data->angle << " rotate\n"
523 << -(p->data->raw_wid / 2.0) << " "
524 << -(p->data->raw_hgh / 2.0) << " translate\n"
525 << p->rx / 72.0 << " " << p->ry / 72.0
527 << -p->ofsx << " " << -p->ofsy << " translate\n"
529 ofs.close(); // Don't remove this.
531 // gs process - set ghostview environment first
533 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
534 << ' ' << p->data->bitmap;
535 // now set up ghostview property on a window
536 // #warning BUG seems that the only bug here
537 // might be the hardcoded dpi.. Bummer!
539 t1 << "0 0 0 0 " << p->data->wid << ' '
540 << p->data->hgh << " 72 72 0 0 0 0";
542 if (lyxerr.debugging()) {
543 lyxerr << "Will set GHOSTVIEW property to ["
544 << t1.str() << "]" << endl;
546 // wait until property is deleted if executing multiple
548 XGrabServer(tempdisp);
550 // grab server to prevent other child
551 // interfering with setting GHOSTVIEW property
552 // The grabbing goes on for too long, is it
553 // really needed? (Lgb)
554 // I moved most of the grabs... (Lgb)
555 if (lyxerr.debugging()) {
556 lyxerr << "Grabbing the server"
559 prop = XListProperties(tempdisp,
561 figinset_canvas), &nprop);
565 for (i = 0; i < nprop; ++i) {
566 char * p = XGetAtomName(tempdisp,
568 if (compare(p, "GHOSTVIEW") == 0) {
570 // We free it when we leave so we don't leak.
576 XFree(reinterpret_cast<char *>(prop)); // jc:
578 // ok, property found, we must wait until
579 // ghostscript deletes it
580 if (lyxerr.debugging()) {
581 lyxerr << "Releasing the server\n["
583 << "] GHOSTVIEW property"
584 " found. Waiting." << endl;
586 XUngrabServer(tempdisp);
589 XGrabServer(tempdisp);
591 XChangeProperty(tempdisp,
592 fl_get_canvas_id(figinset_canvas),
593 XInternAtom(tempdisp, "GHOSTVIEW", false),
594 XInternAtom(tempdisp, "STRING", false),
596 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
597 int(t1.str().size()));
598 XUngrabServer(tempdisp);
603 switch (p->data->flags & 3) {
604 case 0: t3 << 'H'; break; // Hidden
605 case 1: t3 << 'M'; break; // Mono
606 case 2: t3 << 'G'; break; // Gray
615 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
616 << ' ' << background_pixel;
618 XGrabServer(tempdisp);
619 XChangeProperty(tempdisp,
620 fl_get_canvas_id(figinset_canvas),
621 XInternAtom(tempdisp,
622 "GHOSTVIEW_COLORS", false),
623 XInternAtom(tempdisp, "STRING", false),
625 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
626 int(t3.str().size()));
627 XUngrabServer(tempdisp);
630 if (lyxerr.debugging()) {
631 lyxerr << "Releasing the server" << endl;
633 XCloseDisplay(tempdisp);
635 // set up environment
638 typedef char * char_p;
639 env = new char_p[ne + 2];
640 string tmp = t2.str().c_str();
641 env[0] = new char[tmp.size() + 1];
642 std::copy(tmp.begin(), tmp.end(), env[0]);
643 env[0][tmp.size()] = '\0';
644 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
647 // now make gs command
649 // close(1); do NOT close. If GS writes out
650 // errors it would hang. (Matthias 290596)
652 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
653 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
655 // now chdir into dir with .eps file, to be on the safe
657 lyx::chdir(OnlyPath(p->data->fname));
658 // make temp file name
659 string tmpf = make_tmp(getpid());
660 if (lyxerr.debugging()) {
661 lyxerr << "starting gs " << tmpf << " "
663 << ", pid: " << getpid() << endl;
666 int err = ::execlp(lyxrc.ps_command.c_str(),
667 lyxrc.ps_command.c_str(),
669 "-dNOPAUSE", "-dQUIET",
671 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
672 p->data->fname.c_str(),
673 "showpage.ps", "quit.ps", "-", 0);
674 // if we are still there, an error occurred.
675 lyxerr << "Error executing ghostscript. "
676 << "Code: " << err << endl;
677 lyxerr.debug() << "Cmd: "
681 << p->data->fname << endl;
684 // normal process (parent)
685 if (lyxerr.debugging()) {
686 lyxerr << "GS [" << pid << "] started" << endl;
689 p->data->gspid = pid;
697 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
699 // recompute the stuff and put in the queue
703 p.rx = (float(data->raw_wid) * 72.0) / pswid;
704 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
710 // if possible, run the queue
716 figdata * getfigdata(int wid, int hgh, string const & fname,
717 int psx, int psy, int pswid, int pshgh,
718 int raw_wid, int raw_hgh, float angle, char flags)
720 /* first search for an exact match with fname and width/height */
722 if (fname.empty() || !IsFileReadable(fname))
725 for (bitmaps_type::iterator it = bitmaps.begin();
726 it != bitmaps.end(); ++it) {
727 if ((*it)->wid == wid && (*it)->hgh == hgh &&
728 (*it)->flags == flags && (*it)->fname == fname &&
729 (*it)->angle == angle) {
734 figdata * p = new figdata;
737 p->raw_wid = raw_wid;
738 p->raw_hgh = raw_hgh;
742 bitmaps.push_back(p);
743 XWindowAttributes wa;
744 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
745 figinset_canvas), &wa);
747 if (lyxerr.debugging()) {
748 lyxerr << "Create pixmap disp:" << fl_get_display()
749 << " scr:" << DefaultScreen(fl_get_display())
752 << " depth:" << wa.depth << endl;
760 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
761 figinset_canvas), wid, hgh, wa.depth);
763 // initialize reading of .eps file with correct sizes and stuff
764 addwait(psx, psy, pswid, pshgh, p);
776 void getbitmap(figdata * p)
783 void makeupdatelist(figdata * p)
785 for (figures_type::iterator it = figures.begin();
786 it != figures.end(); ++it)
787 if ((*it)->data == p) {
788 if (lyxerr.debugging()) {
789 lyxerr << "Updating inset "
793 // add inset figures[i]->inset into to_update list
794 current_view->pushIntoUpdateList((*it)->inset);
799 // this func is only "called" in spellchecker.C
800 void sigchldchecker(pid_t pid, int * status)
802 lyxerr.debug() << "Got pid = " << pid << endl;
803 bool pid_handled = false;
804 for (bitmaps_type::iterator it = bitmaps.begin();
805 it != bitmaps.end(); ++it) {
806 if ((*it)->reading && pid == (*it)->gspid) {
807 lyxerr.debug() << "Found pid in bitmaps" << endl;
808 // now read the file and remove it from disk
811 if ((*it)->gsdone) *status = 0;
813 lyxerr.debug() << "GS [" << pid
814 << "] exit OK." << endl;
816 lyxerr << "GS [" << pid << "] error "
818 << WIFEXITED(*status)
819 << " " << WEXITSTATUS(*status)
820 << " S:" << WIFSIGNALED(*status)
821 << " " << WTERMSIG(*status) << endl;
824 bitmap_waiting = true;
827 // remove temporary files
828 lyx::unlink(make_tmp(p->gspid));
832 makeupdatelist((*it));
839 lyxerr.debug() << "Checking pid in pidwait" << endl;
840 list<int>::iterator it = find(pidwaitlist.begin(),
841 pidwaitlist.end(), pid);
842 if (it != pidwaitlist.end()) {
843 lyxerr.debug() << "Found pid in pidwait\n"
844 << "Caught child pid of recompute "
845 "routine" << pid << endl;
846 pidwaitlist.erase(it);
850 lyxerr.debug() << "waitpid error" << endl;
853 lyxerr << "The process or process group specified by "
854 "pid does not exist or is not a child of "
855 "the calling process or can never be in the "
856 "states specified by options." << endl;
859 lyxerr << "waitpid() was interrupted due to the "
860 "receipt of a signal sent by the calling "
864 lyxerr << "An invalid value was specified for "
868 lyxerr << "Unknown error from waitpid" << endl;
871 } else if (pid == 0) {
872 lyxerr << "waitpid nohang" << endl;;
874 lyxerr.debug() << "normal exit from childhandler" << endl;
882 bitmap_waiting = false;
883 for (bitmaps_type::iterator it = bitmaps.begin();
884 it != bitmaps.end(); ++it)
885 if ((*it)->gspid > 0 && !(*it)->reading)
891 void RegisterFigure(InsetFig * fi)
893 if (figures.empty()) InitFigures();
895 Figref * tmpfig = new Figref;
898 figures.push_back(tmpfig);
901 if (lyxerr.debugging()) {
902 lyxerr << "Register Figure: buffer:["
903 << current_view->buffer() << "]" << endl;
909 void UnregisterFigure(InsetFig * fi)
914 Figref * tmpfig = fi->figure;
916 if (tmpfig->data) freefigdata(tmpfig->data);
917 if (tmpfig->inset->form) {
918 if (tmpfig->inset->form->Figure->visible) {
919 fl_set_focus_object(tmpfig->inset->form->Figure,
920 tmpfig->inset->form->OkBtn);
921 fl_hide_form(tmpfig->inset->form->Figure);
923 #if FL_REVISION == 89
924 // CHECK Reactivate this free_form calls
926 fl_free_form(tmpfig->inset->form->Figure);
927 free(tmpfig->inset->form); // Why free?
928 tmpfig->inset->form = 0;
931 figures.erase(find(figures.begin(), figures.end(), tmpfig));
934 if (figures.empty()) DoneFigures();
938 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
948 psubfigure = subfigure = false;
949 xwid = xhgh = angle = 0;
951 raw_wid = raw_hgh = 0;
952 changedfname = false;
953 RegisterFigure(this);
954 r_ = Dialogs::redrawGUI.connect(SigC::slot(this, &InsetFig::redraw));
958 InsetFig::~InsetFig()
960 if (lyxerr.debugging()) {
961 lyxerr << "Figure destructor called" << endl;
963 UnregisterFigure(this);
968 void InsetFig::redraw()
970 if (form && form->Figure->visible)
971 fl_redraw_form(form->Figure);
975 int InsetFig::ascent(BufferView *, LyXFont const &) const
981 int InsetFig::descent(BufferView *, LyXFont const &) const
987 int InsetFig::width(BufferView *, LyXFont const &) const
993 void InsetFig::draw(BufferView * bv, LyXFont const & f,
994 int baseline, float & x, bool) const
997 Painter & pain = bv->painter();
999 if (bitmap_waiting) getbitmaps();
1001 // I wish that I didn't have to use this
1002 // but the figinset code is so complicated so
1003 // I don't want to fiddle with it now.
1005 if (figure && figure->data && figure->data->bitmap &&
1006 !figure->data->reading && !figure->data->broken) {
1008 pain.pixmap(int(x + 1), baseline - hgh,
1009 wid, hgh, figure->data->bitmap);
1012 pain.rectangle(int(x), baseline - hgh - 1,
1016 char const * msg = 0;
1017 string lfname = fname;
1018 if (!fname.empty() && GetExtension(fname).empty())
1021 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1023 if (figure && figure->data) {
1024 if (figure->data->broken) msg = _("[render error]");
1025 else if (figure->data->reading) msg = _("[rendering ... ]");
1027 else if (fname.empty())
1028 msg = _("[no file]");
1029 else if (!IsFileReadable(lfname))
1030 msg = _("[bad file name]");
1031 else if ((flags & 3) == 0)
1032 msg = _("[not displayed]");
1033 else if (lyxrc.ps_command.empty())
1034 msg = _("[no ghostscript]");
1036 if (!msg) msg = _("[unknown error]");
1038 font.setFamily(LyXFont::SANS_FAMILY);
1039 font.setSize(LyXFont::SIZE_FOOTNOTE);
1040 string justname = OnlyFilename (fname);
1041 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1044 font.setSize(LyXFont::SIZE_TINY);
1045 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1047 x += width(bv, font); // ?
1051 void InsetFig::Write(Buffer const *, ostream & os) const
1054 os << "Figure size " << wid << " " << hgh << "\n";
1055 if (!fname.empty()) {
1056 string buf1 = OnlyPath(owner->fileName());
1057 string fname2 = MakeRelPath(fname, buf1);
1058 os << "file " << fname2 << "\n";
1060 if (!subcaption.empty())
1061 os << "subcaption " << subcaption << "\n";
1062 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1063 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1064 if (angle != 0) os << "angle " << angle << "\n";
1065 os << "flags " << flags << "\n";
1066 if (subfigure) os << "subfigure\n";
1070 void InsetFig::Read(Buffer const *, LyXLex & lex)
1073 bool finished = false;
1075 while (lex.IsOK() && !finished) {
1078 string const token = lex.GetString();
1079 lyxerr.debug() << "Token: " << token << endl;
1083 else if (token == "\\end_inset") {
1085 } else if (token == "file") {
1087 buf = lex.GetString();
1088 string buf1 = OnlyPath(owner->fileName());
1089 fname = MakeAbsPath(buf, buf1);
1090 changedfname = true;
1092 } else if (token == "extra") {
1094 // kept for backwards compability. Delete in 0.13.x
1095 } else if (token == "subcaption") {
1097 subcaption = lex.GetString();
1098 } else if (token == "label") {
1100 // kept for backwards compability. Delete in 0.13.x
1101 } else if (token == "angle") {
1103 angle = lex.GetFloat();
1104 } else if (token == "size") {
1106 wid = lex.GetInteger();
1108 hgh = lex.GetInteger();
1109 } else if (token == "flags") {
1111 flags = pflags = lex.GetInteger();
1112 } else if (token == "subfigure") {
1113 subfigure = psubfigure = true;
1114 } else if (token == "width") {
1117 typ = lex.GetInteger();
1119 xwid = lex.GetFloat();
1121 case DEF: wtype = DEF; break;
1122 case CM: wtype = CM; break;
1123 case IN: wtype = IN; break;
1124 case PER_PAGE: wtype = PER_PAGE; break;
1125 case PER_COL: wtype = PER_COL; break;
1127 lyxerr.debug() << "Unknown type!" << endl;
1131 } else if (token == "height") {
1134 typ = lex.GetInteger();
1136 xhgh = lex.GetFloat();
1138 case DEF: htype = DEF; break;
1139 case CM: htype = CM; break;
1140 case IN: htype = IN; break;
1141 case PER_PAGE: htype = PER_PAGE; break;
1143 lyxerr.debug() << "Unknown type!" << endl;
1154 int InsetFig::Latex(Buffer const *, ostream & os,
1155 bool /* fragile*/, bool /* fs*/) const
1158 if (!cmd.empty()) os << cmd << " ";
1163 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1169 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1175 int InsetFig::DocBook(Buffer const *, ostream & os) const
1177 string buf1 = OnlyPath(owner->fileName());
1178 string figurename = MakeRelPath(fname, buf1);
1180 if (suffixIs(figurename, ".eps"))
1181 figurename.erase(figurename.length() - 4);
1183 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1188 void InsetFig::Validate(LaTeXFeatures & features) const
1190 features.graphics = true;
1191 if (subfigure) features.subfigure = true;
1195 Inset::EDITABLE InsetFig::Editable() const
1201 bool InsetFig::Deletable() const
1207 string const InsetFig::EditMessage() const
1209 return _("Opened figure");
1213 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1215 lyxerr.debug() << "Editing InsetFig." << endl;
1218 // We should have RO-versions of the form instead.
1219 // The actual prevention of altering a readonly doc
1220 // is done in CallbackFig()
1221 if (bv->buffer()->isReadonly())
1222 WarnReadonly(bv->buffer()->fileName());
1225 form = create_form_Figure();
1226 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1227 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1228 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1229 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1232 if (form->Figure->visible) {
1233 fl_raise_form(form->Figure);
1235 fl_show_form(form->Figure,
1236 FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
1242 Inset * InsetFig::Clone(Buffer const & buffer) const
1244 InsetFig * tmp = new InsetFig(100, 100, buffer);
1246 if (lyxerr.debugging()) {
1247 lyxerr << "Clone Figure: buffer:["
1249 << "], cbuffer:[xx]" << endl;
1254 tmp->raw_wid = raw_wid;
1255 tmp->raw_hgh = raw_hgh;
1260 tmp->pflags = pflags;
1261 tmp->subfigure = subfigure;
1262 tmp->psubfigure = psubfigure;
1270 if (!fname.empty() && IsFileReadable(fname)
1271 && (flags & 3) && !lyxrc.ps_command.empty()
1273 // do not display if there is
1274 // "do not display" chosen (Matthias 260696)
1275 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1276 pswid, pshgh, raw_wid, raw_hgh,
1277 angle, flags & (3|8));
1278 } else tmp->figure->data = 0;
1279 tmp->subcaption = subcaption;
1280 tmp->changedfname = false;
1287 Inset::Code InsetFig::LyxCode() const
1289 return Inset::GRAPHICS_CODE;
1294 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1300 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1301 res = tostr(f) + "cm";
1304 res = tostr(f) + "in";
1306 case InsetFig::PER_PAGE:
1307 res = tostr(f/100) + "\\text" + suffix;
1309 case InsetFig::PER_COL:
1310 // Doesn't occur for htype...
1311 res = tostr(f/100) + "\\column" + suffix;
1318 void InsetFig::Regenerate() const
1321 string resizeW, resizeH;
1322 string rotate, recmd;
1324 if (fname.empty()) {
1325 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1326 cmd += _("empty figure path");
1331 string buf1 = OnlyPath(owner->fileName());
1332 string fname2 = MakeRelPath(fname, buf1);
1334 string gcmd = "\\includegraphics{" + fname2 + '}';
1335 resizeW = stringify(wtype, xwid, "width");
1336 resizeH = stringify(htype, xhgh, "height");
1338 if (!resizeW.empty() || !resizeH.empty()) {
1339 recmd = "\\resizebox*{";
1340 if (!resizeW.empty())
1345 if (!resizeH.empty())
1354 // \rotatebox{angle}{text}
1355 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1361 if (!rotate.empty()) cmdbuf += '}';
1362 if (!recmd.empty()) cmdbuf += '}';
1364 if (!subcaption.empty())
1365 cmdbuf = "\\subfigure[" + subcaption +
1366 "]{" + cmdbuf + "}";
1368 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1375 void InsetFig::TempRegenerate()
1378 string resizeW, resizeH;
1379 string rotate, recmd;
1381 char const * tfname = fl_get_input(form->EpsFile);
1382 string tsubcap = fl_get_input(form->Subcaption);
1383 float tangle = atof(fl_get_input(form->Angle));
1384 float txwid = atof(fl_get_input(form->Width));
1385 float txhgh = atof(fl_get_input(form->Height));
1387 if (!tfname || !*tfname) {
1388 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1389 cmd += _("empty figure path");
1394 string buf1 = OnlyPath(owner->fileName());
1395 string fname2 = MakeRelPath(tfname, buf1);
1396 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1397 string gcmd = "\\includegraphics{" + fname2 + '}';
1399 resizeW = stringify(twtype, txwid, "width");
1400 resizeH = stringify(thtype, txhgh, "height");
1402 // \resizebox*{h-length}{v-length}{text}
1403 if (!resizeW.empty() || !resizeH.empty()) {
1404 recmd = "\\resizebox*{";
1405 if (!resizeW.empty())
1410 if (!resizeH.empty())
1418 // \rotatebox{angle}{text}
1419 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1422 cmdbuf = recmd + rotate + gcmd;
1423 if (!rotate.empty()) cmdbuf += '}';
1424 if (!recmd.empty()) cmdbuf += '}';
1425 if (psubfigure && !tsubcap.empty()) {
1426 cmdbuf = string("\\subfigure{") + tsubcap
1427 + string("}{") + cmdbuf + "}";
1432 void InsetFig::Recompute()
1437 bool changed = changedfname;
1438 int newx, newy, nraw_x, nraw_y;
1440 if (changed) GetPSSizes();
1442 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1443 float cos_a = cos (angle / DEG2PI);
1444 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1445 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1447 string lfname = fname;
1448 if (GetExtension(fname).empty())
1451 /* now recompute wid and hgh, and if that is changed, set changed */
1452 /* this depends on chosen size of the picture and its bbox */
1453 // This will be redone in 0.13 ... (hen)
1454 if (!lfname.empty() && IsFileReadable(lfname)) {
1455 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1463 newx = int(28.346 * xwid);
1466 newx = int(72 * xwid);
1468 case PER_PAGE: /* % of page */
1469 newx = int(5.95 * xwid);
1471 case PER_COL: /* % of col */
1472 newx = int(2.975 * xwid);
1476 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1480 //lyxerr << "This should not happen!" << endl;
1483 newy = int(28.346 * xhgh);
1486 newy = int(72 * xhgh);
1488 case PER_PAGE: /* % of page */
1489 newy = int(8.42 * xhgh);
1492 // Doesn't occur; case exists to suppress
1493 // compiler warnings.
1496 if (htype && !wtype && frame_hgh)
1497 newx = newy*frame_wid/frame_hgh;
1506 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1511 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1513 // cannot be zero, actually, set it to some minimum, so its clickable
1514 if (newx < 5) newx = 5;
1515 if (newy < 5) newy = 5;
1517 if (newx != wid || newy != hgh ||
1518 nraw_x != raw_wid || nraw_y != raw_hgh ||
1519 flags != pflags || subfigure != psubfigure)
1527 subfigure = psubfigure;
1530 figdata * pf = figure->data;
1533 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1534 && !lyxrc.ps_command.empty()) {
1535 // do not display if there is "do not display"
1536 // chosen (Matthias 260696)
1537 figure->data = getfigdata(wid, hgh, lfname,
1538 psx, psy, pswid, pshgh,
1540 angle, flags & (3|8));
1541 } else figure->data = 0;
1543 // free the old data
1544 if (pf) freefigdata(pf);
1547 changedfname = false;
1551 void InsetFig::GetPSSizes()
1553 /* get %%BoundingBox: from postscript file */
1555 /* defaults to associated size
1556 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1563 if (fname.empty()) return;
1565 ifstream ifs(fname.c_str());
1567 if (!ifs) return; // file not found !!!!
1569 /* defaults to A4 page */
1575 char lastchar = 0; ifs.get(lastchar);
1577 char c = 0; ifs.get(c);
1579 lyxerr.debug() << "End of (E)PS file reached and"
1580 " no BoundingBox!" << endl;
1583 if (c == '%' && lastchar == '%') {
1585 if (p.empty()) break;
1586 lyxerr.debug() << "Token: `" << p << "'" << endl;
1587 if (p == "BoundingBox:") {
1588 float fpsx, fpsy, fpswid, fpshgh;
1589 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1592 pswid = int(fpswid);
1593 pshgh = int(fpshgh);
1595 if (lyxerr.debugging()) {
1596 lyxerr << "%%%%BoundingBox:"
1614 void InsetFig::CallbackFig(long arg)
1619 if (lyxerr.debugging()) {
1620 lyxerr << "Figure callback, arg " << arg << endl;
1626 case 12: /* width type */
1633 fl_deactivate_object(form->Width);
1638 fl_activate_object(form->Width);
1643 fl_activate_object(form->Width);
1648 fl_activate_object(form->Width);
1653 fl_activate_object(form->Width);
1656 lyxerr.debug() << "Unknown type!" << endl;
1663 case 22: /* height type */
1669 fl_deactivate_object(form->Height);
1674 fl_activate_object(form->Height);
1679 fl_activate_object(form->Height);
1684 fl_activate_object(form->Height);
1687 lyxerr.debug() << "Unknown type!" << endl;
1693 pflags = pflags & ~3; /* wysiwyg0 */
1696 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1699 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1702 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1705 pflags ^= 4; /* frame */
1708 pflags ^= 8; /* do translations */
1711 psubfigure = !psubfigure; /* This is a subfigure */
1714 regen = true; /* regenerate command */
1716 case 0: /* browse file */
1720 case 1: /* preview */
1721 p = fl_get_input(form->EpsFile);
1725 case 8: /* ok (apply and close) */
1726 if (!current_view->buffer()->isReadonly()) {
1729 xwid = atof(fl_get_input(form->Width));
1730 xhgh = atof(fl_get_input(form->Height));
1731 angle = atof(fl_get_input(form->Angle));
1732 p = fl_get_input(form->EpsFile);
1734 string buf1 = OnlyPath(owner->fileName());
1735 fname = MakeAbsPath(p, buf1);
1736 changedfname = true;
1738 if (!fname.empty()) {
1739 changedfname = true;
1743 subcaption = fl_get_input(form->Subcaption);
1747 /* now update inset */
1748 if (lyxerr.debugging()) {
1749 lyxerr << "Update: ["
1750 << wid << 'x' << hgh << ']' << endl;
1752 current_view->updateInset(this, true);
1754 fl_set_focus_object(form->Figure, form->OkBtn);
1755 fl_hide_form(form->Figure);
1756 #if FL_REVISION == 89
1757 // CHECK Reactivate this free_form calls
1759 fl_free_form(form->Figure);
1760 free(form); // Why free?
1766 // The user has already been informed about RO in ::Edit
1767 if (arg == 7) // if 'Apply'
1770 case 9: /* cancel = restore and close */
1771 fl_set_focus_object(form->Figure, form->OkBtn);
1772 fl_hide_form(form->Figure);
1773 #if FL_REVISION == 89
1774 // CHECK Reactivate this free_form calls
1775 // Jug, is this still a problem?
1777 fl_free_form(form->Figure);
1778 free(form); // Why free?
1784 if (regen) TempRegenerate();
1789 void DisableFigurePanel(FD_Figure * const form)
1791 fl_deactivate_object(form->EpsFile);
1792 fl_deactivate_object(form->Browse);
1793 fl_deactivate_object(form->Width);
1794 fl_deactivate_object(form->Height);
1795 fl_deactivate_object(form->Frame);
1796 fl_deactivate_object(form->Translations);
1797 fl_deactivate_object(form->Angle);
1798 fl_deactivate_object(form->HeightGrp);
1799 fl_deactivate_object(form->page2);
1800 fl_deactivate_object(form->Default2);
1801 fl_deactivate_object(form->cm2);
1802 fl_deactivate_object(form->in2);
1803 fl_deactivate_object(form->HeightLabel);
1804 fl_deactivate_object(form->WidthLabel);
1805 fl_deactivate_object(form->DisplayGrp);
1806 fl_deactivate_object(form->Wysiwyg3);
1807 fl_deactivate_object(form->Wysiwyg0);
1808 fl_deactivate_object(form->Wysiwyg2);
1809 fl_deactivate_object(form->Wysiwyg1);
1810 fl_deactivate_object(form->WidthGrp);
1811 fl_deactivate_object(form->Default1);
1812 fl_deactivate_object(form->cm1);
1813 fl_deactivate_object(form->in1);
1814 fl_deactivate_object(form->page1);
1815 fl_deactivate_object(form->column1);
1816 fl_deactivate_object(form->Subcaption);
1817 fl_deactivate_object(form->Subfigure);
1818 fl_deactivate_object (form->OkBtn);
1819 fl_deactivate_object (form->ApplyBtn);
1820 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1821 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1826 void EnableFigurePanel(FD_Figure * const form)
1828 fl_activate_object(form->EpsFile);
1829 fl_activate_object(form->Browse);
1830 fl_activate_object(form->Width);
1831 fl_activate_object(form->Height);
1832 fl_activate_object(form->Frame);
1833 fl_activate_object(form->Translations);
1834 fl_activate_object(form->Angle);
1835 fl_activate_object(form->HeightGrp);
1836 fl_activate_object(form->page2);
1837 fl_activate_object(form->Default2);
1838 fl_activate_object(form->cm2);
1839 fl_activate_object(form->in2);
1840 fl_activate_object(form->HeightLabel);
1841 fl_activate_object(form->WidthLabel);
1842 fl_activate_object(form->DisplayGrp);
1843 fl_activate_object(form->Wysiwyg3);
1844 fl_activate_object(form->Wysiwyg0);
1845 fl_activate_object(form->Wysiwyg2);
1846 fl_activate_object(form->Wysiwyg1);
1847 fl_activate_object(form->WidthGrp);
1848 fl_activate_object(form->Default1);
1849 fl_activate_object(form->cm1);
1850 fl_activate_object(form->in1);
1851 fl_activate_object(form->page1);
1852 fl_activate_object(form->column1);
1853 fl_activate_object(form->Subcaption);
1854 fl_activate_object(form->Subfigure);
1855 fl_activate_object (form->OkBtn);
1856 fl_activate_object (form->ApplyBtn);
1857 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1858 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1862 void InsetFig::RestoreForm()
1864 EnableFigurePanel(form);
1867 fl_set_button(form->Default1, (wtype == 0));
1868 fl_set_button(form->cm1, (wtype == 1));
1869 fl_set_button(form->in1, (wtype == 2));
1870 fl_set_button(form->page1, (wtype == 3));
1871 fl_set_button(form->column1, (wtype == 4));
1873 fl_deactivate_object(form->Width);
1875 fl_activate_object(form->Width);
1878 // enable and disable should be put here.
1880 fl_set_button(form->Default2, (htype == 0));
1881 fl_set_button(form->cm2, (htype == 1));
1882 fl_set_button(form->in2, (htype == 2));
1883 fl_set_button(form->page2, (htype == 3));
1884 // enable and disable should be put here.
1886 fl_deactivate_object(form->Height);
1888 fl_activate_object(form->Height);
1891 int piflags = flags & 3;
1892 fl_set_button(form->Wysiwyg0, (piflags == 0));
1893 fl_set_button(form->Wysiwyg1, (piflags == 1));
1894 fl_set_button(form->Wysiwyg2, (piflags == 2));
1895 fl_set_button(form->Wysiwyg3, (piflags == 3));
1896 fl_set_button(form->Frame, ((flags & 4) != 0));
1897 fl_set_button(form->Translations, ((flags & 8) != 0));
1898 fl_set_button(form->Subfigure, (subfigure != 0));
1900 psubfigure = subfigure;
1901 fl_set_input(form->Width, tostr(xwid).c_str());
1902 fl_set_input(form->Height, tostr(xhgh).c_str());
1903 fl_set_input(form->Angle, tostr(angle).c_str());
1904 if (!fname.empty()){
1905 string buf1 = OnlyPath(owner->fileName());
1906 string fname2 = MakeRelPath(fname, buf1);
1907 fl_set_input(form->EpsFile, fname2.c_str());
1909 else fl_set_input(form->EpsFile, "");
1910 fl_set_input(form->Subcaption, subcaption.c_str());
1911 if (current_view->buffer()->isReadonly())
1912 DisableFigurePanel(form);
1918 void InsetFig::Preview(string const & p)
1921 if (GetExtension(tfname).empty())
1923 string buf1 = OnlyPath(owner->fileName());
1924 string buf2 = MakeAbsPath(tfname, buf1);
1925 if (!formats.View(owner, buf2, "eps"))
1926 lyxerr << "Can't view " << buf2 << endl;
1929 void InsetFig::BrowseFile()
1931 static string current_figure_path;
1932 static int once = 0;
1934 if (lyxerr.debugging()) {
1935 lyxerr << "Filename: "
1936 << owner->fileName() << endl;
1938 string p = fl_get_input(form->EpsFile);
1940 string buf = MakeAbsPath(owner->fileName());
1941 string buf2 = OnlyPath(buf);
1943 buf = MakeAbsPath(p, buf2);
1944 buf = OnlyPath(buf);
1946 buf = OnlyPath(owner->fileName());
1949 // Does user clipart directory exist?
1950 string bufclip = AddName (user_lyxdir, "clipart");
1951 FileInfo fileInfo(bufclip);
1952 if (!(fileInfo.isOK() && fileInfo.isDir()))
1953 // No - bail out to system clipart directory
1954 bufclip = AddName (system_lyxdir, "clipart");
1957 FileDialog fileDlg(current_view->owner(), _("Select an EPS figure"),
1958 LFUN_SELECT_FILE_SYNC,
1959 make_pair(string(_("Clip art")), string(bufclip)),
1960 make_pair(string(_("Documents")), string(buf)));
1964 string const path = (once) ? current_figure_path : buf;
1966 FileDialog::Result result = fileDlg.Select(path, _("*ps| PostScript documents"));
1968 string const p = result.second;
1973 buf = MakeRelPath(p, buf2);
1974 current_figure_path = OnlyPath(p);
1977 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1978 || contains(p, "%") || contains(p, " ")) {
1979 WriteAlert(_("Filename can't contain any "
1980 "of these characters:"),
1981 // xgettext:no-c-format
1982 _("space, '#', '~', '$' or '%'."));
1987 if (form) fl_set_input(form->EpsFile, buf.c_str());
1991 void GraphicsCB(FL_OBJECT * obj, long arg)
1993 /* obj->form contains the form */
1995 if (lyxerr.debugging()) {
1996 lyxerr << "GraphicsCB callback: " << arg << endl;
1999 /* find inset we were reacting to */
2000 for (figures_type::iterator it = figures.begin();
2001 it != figures.end(); ++it)
2002 if ((*it)->inset->form && (*it)->inset->form->Figure
2004 if (lyxerr.debugging()) {
2005 lyxerr << "Calling back figure "
2008 (*it)->inset->CallbackFig(arg);
2014 void HideFiguresPopups()
2016 for (figures_type::iterator it = figures.begin();
2017 it != figures.end(); ++it)
2018 if ((*it)->inset->form
2019 && (*it)->inset->form->Figure->visible) {
2020 if (lyxerr.debugging()) {
2021 lyxerr << "Hiding figure " << (*it) << endl;
2023 // hide and free the form
2024 (*it)->inset->CallbackFig(9);