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));
171 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
174 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
176 if (lyxerr.debugging()) {
177 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
178 << "] pm:[" << e->data.l[1] << "]" << endl;
181 // just kill gs, that way it will work for sure
182 // This loop looks like S**T so it probably is...
183 for (bitmaps_type::iterator it = bitmaps.begin();
184 it != bitmaps.end(); ++it)
185 if (static_cast<long>((*it)->bitmap) ==
186 static_cast<long>(e->data.l[1])) {
191 // first update p->bitmap, if necessary
192 if (p->bitmap != None
193 && p->flags > (1|8) && gs_color && p->wid) {
194 // query current colormap and re-render
195 // the pixmap with proper colors
196 XWindowAttributes wa;
197 register XImage * im;
200 int spc1 = gs_spc - 1;
201 int spc2 = gs_spc * gs_spc;
205 GC gc = local_gc_copy;
207 XGetWindowAttributes(fl_get_display(),
211 XFlush(fl_get_display());
212 if (lyxerr.debugging()) {
213 lyxerr << "Starting image translation "
216 << p->wid << "x" << p->hgh
218 << " " << XYPixmap << endl;
220 // now fork rendering process
222 if (forkstat == -1) {
224 << "Cannot fork, using slow "
225 "method for pixmap translation." << endl;
226 tmpdisp = fl_get_display();
227 } else if (forkstat > 0) { // parent
229 if (lyxerr.debugging()) {
230 lyxerr << "Spawned child "
233 addpidwait(forkstat);
236 tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
239 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
240 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
242 if (lyxerr.debugging()) {
243 lyxerr << "Got the image" << endl;
246 if (lyxerr.debugging()) {
247 lyxerr << "Error getting the image" << endl;
252 // query current colormap
253 XColor * cmap = new XColor[gs_allcolors];
254 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
255 XQueryColors(tmpdisp,
256 fl_state[fl_get_vclass()]
260 // now we process all the image
261 for (y = 0; y < p->hgh; ++y) {
262 for (int x = 0; x < wid; ++x) {
267 gs_pixels[((pc->red+6553)*
268 spc1/65535)*spc2+((pc->green+6553)*
269 spc1/65535)*gs_spc+((pc->blue+6553)*
274 // This must be correct.
276 if (lyxerr.debugging()) {
277 lyxerr << "Putting image back"
280 XPutImage(tmpdisp, p->bitmap,
282 0, 0, p->wid, p->hgh);
284 if (lyxerr.debugging()) {
285 lyxerr << "Done translation"
290 kill_gs(p->gspid, SIGHUP);
292 XCloseDisplay(tmpdisp);
296 kill_gs(p->gspid, SIGHUP);
305 void AllocColors(int num)
306 // allocate color cube numxnumxnum, if possible
308 if (lyxerr.debugging()) {
309 lyxerr << "Allocating color cube " << num
310 << 'x' << num << 'x' << num << endl;
314 lyxerr << "Error allocating color colormap." << endl;
318 if (num > 5) num = 5;
320 for (int i = 0; i < num * num * num; ++i) {
321 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
322 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
323 xcol.blue = short(65535 * (i % num) / (num - 1));
324 xcol.flags = DoRed | DoGreen | DoBlue;
325 if (!XAllocColor(fl_get_display(),
326 fl_state[fl_get_vclass()].colormap, &xcol)) {
327 if (i) XFreeColors(fl_get_display(),
328 fl_state[fl_get_vclass()].colormap,
330 if (lyxerr.debugging()) {
331 lyxerr << "Cannot allocate color cube "
334 AllocColors(num - 1);
337 gs_pixels[i] = xcol.pixel;
344 // allocate grayscale ramp
346 void AllocGrays(int num)
348 if (lyxerr.debugging()) {
349 lyxerr << "Allocating grayscale colormap "
354 lyxerr << "Error allocating grayscale colormap." << endl;
358 if (num > 128) num = 128;
360 for (int i = 0; i < num; ++i) {
361 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
362 xcol.flags = DoRed | DoGreen | DoBlue;
363 if (!XAllocColor(fl_get_display(),
364 fl_state[fl_get_vclass()].colormap, &xcol)) {
365 if (i) XFreeColors(fl_get_display(),
366 fl_state[fl_get_vclass()].colormap,
368 if (lyxerr.debugging()) {
369 lyxerr << "Cannot allocate grayscale "
375 gs_pixels[i] = xcol.pixel;
384 // if bitmaps and figures are not empty we will leak mem
388 // allocate color cube on pseudo-color display
392 fl_add_canvas_handler(figinset_canvas, ClientMessage,
394 current_view->owner()->getForm());
396 local_gc_copy = createGC();
398 Visual * vi = DefaultVisual(fl_get_display(),
399 DefaultScreen(fl_get_display()));
400 if (lyxerr.debugging()) {
401 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
402 vi->visualid, vi->c_class,
403 vi->bits_per_rgb, vi->map_entries);
405 color_visual = ( (vi->c_class == StaticColor) ||
406 (vi->c_class == PseudoColor) ||
407 (vi->c_class == TrueColor) ||
408 (vi->c_class == DirectColor) );
409 if ((vi->c_class & 1) == 0) return;
410 // now allocate colors
411 if (vi->c_class == GrayScale) {
412 // allocate grayscale
413 AllocGrays(vi->map_entries/2);
415 // allocate normal color
417 while (i * i * i * 2 > vi->map_entries) --i;
420 gs_allcolors = vi->map_entries;
428 // if bitmaps and figures are not empty we will leak mem
432 lyxerr.debug() << "Unregistering figures..." << endl;
434 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
440 void freefigdata(figdata * tmpdata)
443 if (tmpdata->ref) return;
445 if (tmpdata->gspid > 0) {
446 int pid = tmpdata->gspid;
447 // kill ghostscript and unlink it's files
449 kill_gs(pid, SIGKILL);
452 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
453 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
461 // This _have_ to be set before the fork!
462 unsigned long background_pixel =
463 lyxColorHandler->colorPixel(LColor::background);
465 // run queued requests for ghostscript, if any
466 if (!gsrunning && gs_color && !gs_xcolor) {
467 // here alloc all colors, so that gs will use only
468 // those we allocated for it
473 while (gsrunning < MAXGS) {
474 //char tbuf[384]; //, tbuf2[80];
478 if (gsqueue.empty()) {
479 if (!gsrunning && gs_xcolor) {
480 // de-allocate rest of colors
486 queue_element * p = &gsqueue.front();
495 if (lyxerr.debugging()) {
496 lyxerr << "GS start error! Cannot fork."
499 p->data->broken = true;
500 p->data->reading = false;
503 if (pid == 0) { // child
506 Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
508 // create translation file
510 ofs.open(make_tmp(getpid()).c_str());
511 ofs << "gsave clippath pathbbox grestore\n"
513 << "/ury exch def /urx exch def /lly exch def "
515 << p->data->wid / 2.0 << " "
516 << p->data->hgh / 2.0 << " translate\n"
517 << p->data->angle << " rotate\n"
518 << -(p->data->raw_wid / 2.0) << " "
519 << -(p->data->raw_hgh / 2.0) << " translate\n"
520 << p->rx / 72.0 << " " << p->ry / 72.0
522 << -p->ofsx << " " << -p->ofsy << " translate\n"
524 ofs.close(); // Don't remove this.
526 // gs process - set ghostview environment first
528 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
529 << ' ' << p->data->bitmap;
530 // now set up ghostview property on a window
531 // #warning BUG seems that the only bug here
532 // might be the hardcoded dpi.. Bummer!
534 t1 << "0 0 0 0 " << p->data->wid << ' '
535 << p->data->hgh << " 72 72 0 0 0 0";
537 if (lyxerr.debugging()) {
538 lyxerr << "Will set GHOSTVIEW property to ["
539 << t1.str() << "]" << endl;
541 // wait until property is deleted if executing multiple
543 XGrabServer(tempdisp);
545 // grab server to prevent other child
546 // interfering with setting GHOSTVIEW property
547 // The grabbing goes on for too long, is it
548 // really needed? (Lgb)
549 // I moved most of the grabs... (Lgb)
550 if (lyxerr.debugging()) {
551 lyxerr << "Grabbing the server"
554 prop = XListProperties(tempdisp,
556 figinset_canvas), &nprop);
560 for (i = 0; i < nprop; ++i) {
561 char * p = XGetAtomName(tempdisp,
563 if (strcmp(p, "GHOSTVIEW") == 0) {
565 // We free it when we leave so we don't leak.
571 XFree(reinterpret_cast<char *>(prop)); // jc:
573 // ok, property found, we must wait until
574 // ghostscript deletes it
575 if (lyxerr.debugging()) {
576 lyxerr << "Releasing the server\n["
578 << "] GHOSTVIEW property"
579 " found. Waiting." << endl;
581 XUngrabServer(tempdisp);
584 XGrabServer(tempdisp);
586 XChangeProperty(tempdisp,
587 fl_get_canvas_id(figinset_canvas),
588 XInternAtom(tempdisp, "GHOSTVIEW", false),
589 XInternAtom(tempdisp, "STRING", false),
591 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
592 int(t1.str().size()));
593 XUngrabServer(tempdisp);
598 switch (p->data->flags & 3) {
599 case 0: t3 << 'H'; break; // Hidden
600 case 1: t3 << 'M'; break; // Mono
601 case 2: t3 << 'G'; break; // Gray
610 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
611 << ' ' << background_pixel;
613 XGrabServer(tempdisp);
614 XChangeProperty(tempdisp,
615 fl_get_canvas_id(figinset_canvas),
616 XInternAtom(tempdisp,
617 "GHOSTVIEW_COLORS", false),
618 XInternAtom(tempdisp, "STRING", false),
620 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
621 int(t3.str().size()));
622 XUngrabServer(tempdisp);
625 if (lyxerr.debugging()) {
626 lyxerr << "Releasing the server" << endl;
628 XCloseDisplay(tempdisp);
630 // set up environment
633 typedef char * char_p;
634 env = new char_p[ne + 2];
635 string tmp = t2.str().c_str();
636 env[0] = new char[tmp.size() + 1];
637 std::copy(tmp.begin(), tmp.end(), env[0]);
638 env[0][tmp.size()] = '\0';
639 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
642 // now make gs command
644 // close(1); do NOT close. If GS writes out
645 // errors it would hang. (Matthias 290596)
647 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
648 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
650 // now chdir into dir with .eps file, to be on the safe
652 lyx::chdir(OnlyPath(p->data->fname));
653 // make temp file name
654 string tmpf = make_tmp(getpid());
655 if (lyxerr.debugging()) {
656 lyxerr << "starting gs " << tmpf << " "
658 << ", pid: " << getpid() << endl;
661 int err = ::execlp(lyxrc.ps_command.c_str(),
662 lyxrc.ps_command.c_str(),
664 "-dNOPAUSE", "-dQUIET",
666 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
667 p->data->fname.c_str(),
668 "showpage.ps", "quit.ps", "-", 0);
669 // if we are still there, an error occurred.
670 lyxerr << "Error executing ghostscript. "
671 << "Code: " << err << endl;
672 lyxerr.debug() << "Cmd: "
676 << p->data->fname << endl;
679 // normal process (parent)
680 if (lyxerr.debugging()) {
681 lyxerr << "GS [" << pid << "] started" << endl;
684 p->data->gspid = pid;
692 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
694 // recompute the stuff and put in the queue
698 p.rx = (float(data->raw_wid) * 72.0) / pswid;
699 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
705 // if possible, run the queue
711 figdata * getfigdata(int wid, int hgh, string const & fname,
712 int psx, int psy, int pswid, int pshgh,
713 int raw_wid, int raw_hgh, float angle, char flags)
715 /* first search for an exact match with fname and width/height */
717 if (fname.empty() || !IsFileReadable(fname))
720 for (bitmaps_type::iterator it = bitmaps.begin();
721 it != bitmaps.end(); ++it) {
722 if ((*it)->wid == wid && (*it)->hgh == hgh &&
723 (*it)->flags == flags && (*it)->fname == fname &&
724 (*it)->angle == angle) {
729 figdata * p = new figdata;
732 p->raw_wid = raw_wid;
733 p->raw_hgh = raw_hgh;
737 bitmaps.push_back(p);
738 XWindowAttributes wa;
739 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
740 figinset_canvas), &wa);
742 if (lyxerr.debugging()) {
743 lyxerr << "Create pixmap disp:" << fl_get_display()
744 << " scr:" << DefaultScreen(fl_get_display())
747 << " depth:" << wa.depth << endl;
755 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
756 figinset_canvas), wid, hgh, wa.depth);
758 // initialize reading of .eps file with correct sizes and stuff
759 addwait(psx, psy, pswid, pshgh, p);
771 void getbitmap(figdata * p)
778 void makeupdatelist(figdata * p)
780 for (figures_type::iterator it = figures.begin();
781 it != figures.end(); ++it)
782 if ((*it)->data == p) {
783 if (lyxerr.debugging()) {
784 lyxerr << "Updating inset "
788 // add inset figures[i]->inset into to_update list
789 current_view->pushIntoUpdateList((*it)->inset);
794 // this func is only "called" in spellchecker.C
795 void sigchldchecker(pid_t pid, int * status)
797 lyxerr.debug() << "Got pid = " << pid << endl;
798 bool pid_handled = false;
799 for (bitmaps_type::iterator it = bitmaps.begin();
800 it != bitmaps.end(); ++it) {
801 if ((*it)->reading && pid == (*it)->gspid) {
802 lyxerr.debug() << "Found pid in bitmaps" << endl;
803 // now read the file and remove it from disk
806 if ((*it)->gsdone) *status = 0;
808 lyxerr.debug() << "GS [" << pid
809 << "] exit OK." << endl;
811 lyxerr << "GS [" << pid << "] error "
813 << WIFEXITED(*status)
814 << " " << WEXITSTATUS(*status)
815 << " S:" << WIFSIGNALED(*status)
816 << " " << WTERMSIG(*status) << endl;
819 bitmap_waiting = true;
822 // remove temporary files
823 lyx::unlink(make_tmp(p->gspid));
827 makeupdatelist((*it));
834 lyxerr.debug() << "Checking pid in pidwait" << endl;
835 list<int>::iterator it = find(pidwaitlist.begin(),
836 pidwaitlist.end(), pid);
837 if (it != pidwaitlist.end()) {
838 lyxerr.debug() << "Found pid in pidwait\n"
839 << "Caught child pid of recompute "
840 "routine" << pid << endl;
841 pidwaitlist.erase(it);
845 lyxerr.debug() << "waitpid error" << endl;
848 lyxerr << "The process or process group specified by "
849 "pid does not exist or is not a child of "
850 "the calling process or can never be in the "
851 "states specified by options." << endl;
854 lyxerr << "waitpid() was interrupted due to the "
855 "receipt of a signal sent by the calling "
859 lyxerr << "An invalid value was specified for "
863 lyxerr << "Unknown error from waitpid" << endl;
866 } else if (pid == 0) {
867 lyxerr << "waitpid nohang" << endl;;
869 lyxerr.debug() << "normal exit from childhandler" << endl;
877 bitmap_waiting = false;
878 for (bitmaps_type::iterator it = bitmaps.begin();
879 it != bitmaps.end(); ++it)
880 if ((*it)->gspid > 0 && !(*it)->reading)
886 void RegisterFigure(InsetFig * fi)
888 if (figures.empty()) InitFigures();
890 Figref * tmpfig = new Figref;
893 figures.push_back(tmpfig);
896 if (lyxerr.debugging()) {
897 lyxerr << "Register Figure: buffer:["
898 << current_view->buffer() << "]" << endl;
904 void UnregisterFigure(InsetFig * fi)
909 Figref * tmpfig = fi->figure;
911 if (tmpfig->data) freefigdata(tmpfig->data);
912 if (tmpfig->inset->form) {
913 if (tmpfig->inset->form->Figure->visible) {
914 fl_set_focus_object(tmpfig->inset->form->Figure,
915 tmpfig->inset->form->OkBtn);
916 fl_hide_form(tmpfig->inset->form->Figure);
918 #if FL_REVISION == 89
919 // CHECK Reactivate this free_form calls
921 fl_free_form(tmpfig->inset->form->Figure);
922 free(tmpfig->inset->form); // Why free?
923 tmpfig->inset->form = 0;
926 figures.erase(find(figures.begin(), figures.end(), tmpfig));
929 if (figures.empty()) DoneFigures();
933 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
943 psubfigure = subfigure = false;
944 xwid = xhgh = angle = 0;
946 raw_wid = raw_hgh = 0;
947 changedfname = false;
948 RegisterFigure(this);
949 r_ = Dialogs::redrawGUI.connect(slot(this, &InsetFig::redraw));
953 InsetFig::~InsetFig()
955 if (lyxerr.debugging()) {
956 lyxerr << "Figure destructor called" << endl;
958 UnregisterFigure(this);
963 void InsetFig::redraw()
965 if (form && form->Figure->visible)
966 fl_redraw_form(form->Figure);
970 int InsetFig::ascent(BufferView *, LyXFont const &) const
976 int InsetFig::descent(BufferView *, LyXFont const &) const
982 int InsetFig::width(BufferView *, LyXFont const &) const
988 void InsetFig::draw(BufferView * bv, LyXFont const & f,
989 int baseline, float & x, bool) const
992 Painter & pain = bv->painter();
994 if (bitmap_waiting) getbitmaps();
996 // I wish that I didn't have to use this
997 // but the figinset code is so complicated so
998 // I don't want to fiddle with it now.
1000 if (figure && figure->data && figure->data->bitmap &&
1001 !figure->data->reading && !figure->data->broken) {
1003 pain.pixmap(int(x + 1), baseline - hgh,
1004 wid, hgh, figure->data->bitmap);
1007 pain.rectangle(int(x), baseline - hgh - 1,
1011 char const * msg = 0;
1012 string lfname = fname;
1013 if (!fname.empty() && GetExtension(fname).empty())
1016 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1018 if (figure && figure->data) {
1019 if (figure->data->broken) msg = _("[render error]");
1020 else if (figure->data->reading) msg = _("[rendering ... ]");
1022 else if (fname.empty())
1023 msg = _("[no file]");
1024 else if (!IsFileReadable(lfname))
1025 msg = _("[bad file name]");
1026 else if ((flags & 3) == 0)
1027 msg = _("[not displayed]");
1028 else if (lyxrc.ps_command.empty())
1029 msg = _("[no ghostscript]");
1031 if (!msg) msg = _("[unknown error]");
1033 font.setFamily(LyXFont::SANS_FAMILY);
1034 font.setSize(LyXFont::SIZE_FOOTNOTE);
1035 string justname = OnlyFilename (fname);
1036 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1039 font.setSize(LyXFont::SIZE_TINY);
1040 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1042 x += width(bv, font); // ?
1046 void InsetFig::Write(Buffer const *, ostream & os) const
1049 os << "Figure size " << wid << " " << hgh << "\n";
1050 if (!fname.empty()) {
1051 string buf1 = OnlyPath(owner->fileName());
1052 string fname2 = MakeRelPath(fname, buf1);
1053 os << "file " << fname2 << "\n";
1055 if (!subcaption.empty())
1056 os << "subcaption " << subcaption << "\n";
1057 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1058 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1059 if (angle != 0) os << "angle " << angle << "\n";
1060 os << "flags " << flags << "\n";
1061 if (subfigure) os << "subfigure\n";
1065 void InsetFig::Read(Buffer const *, LyXLex & lex)
1068 bool finished = false;
1070 while (lex.IsOK() && !finished) {
1073 string const token = lex.GetString();
1074 lyxerr.debug() << "Token: " << token << endl;
1078 else if (token == "\\end_inset") {
1080 } else if (token == "file") {
1082 buf = lex.GetString();
1083 string buf1 = OnlyPath(owner->fileName());
1084 fname = MakeAbsPath(buf, buf1);
1085 changedfname = true;
1087 } else if (token == "extra") {
1089 // kept for backwards compability. Delete in 0.13.x
1090 } else if (token == "subcaption") {
1092 subcaption = lex.GetString();
1093 } else if (token == "label") {
1095 // kept for backwards compability. Delete in 0.13.x
1096 } else if (token == "angle") {
1098 angle = lex.GetFloat();
1099 } else if (token == "size") {
1101 wid = lex.GetInteger();
1103 hgh = lex.GetInteger();
1104 } else if (token == "flags") {
1106 flags = pflags = lex.GetInteger();
1107 } else if (token == "subfigure") {
1108 subfigure = psubfigure = true;
1109 } else if (token == "width") {
1112 typ = lex.GetInteger();
1114 xwid = lex.GetFloat();
1116 case DEF: wtype = DEF; break;
1117 case CM: wtype = CM; break;
1118 case IN: wtype = IN; break;
1119 case PER_PAGE: wtype = PER_PAGE; break;
1120 case PER_COL: wtype = PER_COL; break;
1122 lyxerr.debug() << "Unknown type!" << endl;
1126 } else if (token == "height") {
1129 typ = lex.GetInteger();
1131 xhgh = lex.GetFloat();
1133 case DEF: htype = DEF; break;
1134 case CM: htype = CM; break;
1135 case IN: htype = IN; break;
1136 case PER_PAGE: htype = PER_PAGE; break;
1138 lyxerr.debug() << "Unknown type!" << endl;
1149 int InsetFig::Latex(Buffer const *, ostream & os,
1150 bool /* fragile*/, bool /* fs*/) const
1153 if (!cmd.empty()) os << cmd << " ";
1158 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1164 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1170 int InsetFig::DocBook(Buffer const *, ostream & os) const
1172 string buf1 = OnlyPath(owner->fileName());
1173 string figurename = MakeRelPath(fname, buf1);
1175 if (suffixIs(figurename, ".eps"))
1176 figurename.erase(figurename.length() - 4);
1178 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1183 void InsetFig::Validate(LaTeXFeatures & features) const
1185 features.graphics = true;
1186 if (subfigure) features.subfigure = true;
1190 Inset::EDITABLE InsetFig::Editable() const
1196 bool InsetFig::Deletable() const
1202 string const InsetFig::EditMessage() const
1204 return _("Opened figure");
1208 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1210 lyxerr.debug() << "Editing InsetFig." << endl;
1213 // We should have RO-versions of the form instead.
1214 // The actual prevention of altering a readonly doc
1215 // is done in CallbackFig()
1216 if (bv->buffer()->isReadonly())
1217 WarnReadonly(bv->buffer()->fileName());
1220 form = create_form_Figure();
1221 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1222 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1223 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1224 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1227 if (form->Figure->visible) {
1228 fl_raise_form(form->Figure);
1230 fl_show_form(form->Figure,
1231 FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
1237 Inset * InsetFig::Clone(Buffer const & buffer) const
1239 InsetFig * tmp = new InsetFig(100, 100, buffer);
1241 if (lyxerr.debugging()) {
1242 lyxerr << "Clone Figure: buffer:["
1244 << "], cbuffer:[xx]" << endl;
1249 tmp->raw_wid = raw_wid;
1250 tmp->raw_hgh = raw_hgh;
1255 tmp->pflags = pflags;
1256 tmp->subfigure = subfigure;
1257 tmp->psubfigure = psubfigure;
1265 if (!fname.empty() && IsFileReadable(fname)
1266 && (flags & 3) && !lyxrc.ps_command.empty()
1268 // do not display if there is
1269 // "do not display" chosen (Matthias 260696)
1270 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1271 pswid, pshgh, raw_wid, raw_hgh,
1272 angle, flags & (3|8));
1273 } else tmp->figure->data = 0;
1274 tmp->subcaption = subcaption;
1275 tmp->changedfname = false;
1282 Inset::Code InsetFig::LyxCode() const
1284 return Inset::GRAPHICS_CODE;
1289 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1295 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1296 res = tostr(f) + "cm";
1299 res = tostr(f) + "in";
1301 case InsetFig::PER_PAGE:
1302 res = tostr(f/100) + "\\text" + suffix;
1304 case InsetFig::PER_COL:
1305 // Doesn't occur for htype...
1306 res = tostr(f/100) + "\\column" + suffix;
1313 void InsetFig::Regenerate() const
1316 string resizeW, resizeH;
1317 string rotate, recmd;
1319 if (fname.empty()) {
1320 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1321 cmd += _("empty figure path");
1326 string buf1 = OnlyPath(owner->fileName());
1327 string fname2 = MakeRelPath(fname, buf1);
1329 string gcmd = "\\includegraphics{" + fname2 + '}';
1330 resizeW = stringify(wtype, xwid, "width");
1331 resizeH = stringify(htype, xhgh, "height");
1333 if (!resizeW.empty() || !resizeH.empty()) {
1334 recmd = "\\resizebox*{";
1335 if (!resizeW.empty())
1340 if (!resizeH.empty())
1349 // \rotatebox{angle}{text}
1350 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1356 if (!rotate.empty()) cmdbuf += '}';
1357 if (!recmd.empty()) cmdbuf += '}';
1359 if (!subcaption.empty())
1360 cmdbuf = "\\subfigure[" + subcaption +
1361 "]{" + cmdbuf + "}";
1363 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1370 void InsetFig::TempRegenerate()
1373 string resizeW, resizeH;
1374 string rotate, recmd;
1376 char const * tfname = fl_get_input(form->EpsFile);
1377 string tsubcap = fl_get_input(form->Subcaption);
1378 float tangle = atof(fl_get_input(form->Angle));
1379 float txwid = atof(fl_get_input(form->Width));
1380 float txhgh = atof(fl_get_input(form->Height));
1382 if (!tfname || !*tfname) {
1383 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1384 cmd += _("empty figure path");
1389 string buf1 = OnlyPath(owner->fileName());
1390 string fname2 = MakeRelPath(tfname, buf1);
1391 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1392 string gcmd = "\\includegraphics{" + fname2 + '}';
1394 resizeW = stringify(twtype, txwid, "width");
1395 resizeH = stringify(thtype, txhgh, "height");
1397 // \resizebox*{h-length}{v-length}{text}
1398 if (!resizeW.empty() || !resizeH.empty()) {
1399 recmd = "\\resizebox*{";
1400 if (!resizeW.empty())
1405 if (!resizeH.empty())
1413 // \rotatebox{angle}{text}
1414 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1417 cmdbuf = recmd + rotate + gcmd;
1418 if (!rotate.empty()) cmdbuf += '}';
1419 if (!recmd.empty()) cmdbuf += '}';
1420 if (psubfigure && !tsubcap.empty()) {
1421 cmdbuf = string("\\subfigure{") + tsubcap
1422 + string("}{") + cmdbuf + "}";
1427 void InsetFig::Recompute()
1432 bool changed = changedfname;
1433 int newx, newy, nraw_x, nraw_y;
1435 if (changed) GetPSSizes();
1437 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1438 float cos_a = cos (angle / DEG2PI);
1439 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1440 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1442 string lfname = fname;
1443 if (GetExtension(fname).empty())
1446 /* now recompute wid and hgh, and if that is changed, set changed */
1447 /* this depends on chosen size of the picture and its bbox */
1448 // This will be redone in 0.13 ... (hen)
1449 if (!lfname.empty() && IsFileReadable(lfname)) {
1450 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1458 newx = int(28.346 * xwid);
1461 newx = int(72 * xwid);
1463 case PER_PAGE: /* % of page */
1464 newx = int(5.95 * xwid);
1466 case PER_COL: /* % of col */
1467 newx = int(2.975 * xwid);
1471 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1475 //lyxerr << "This should not happen!" << endl;
1478 newy = int(28.346 * xhgh);
1481 newy = int(72 * xhgh);
1483 case PER_PAGE: /* % of page */
1484 newy = int(8.42 * xhgh);
1487 // Doesn't occur; case exists to suppress
1488 // compiler warnings.
1491 if (htype && !wtype && frame_hgh)
1492 newx = newy*frame_wid/frame_hgh;
1501 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1506 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1508 // cannot be zero, actually, set it to some minimum, so its clickable
1509 if (newx < 5) newx = 5;
1510 if (newy < 5) newy = 5;
1512 if (newx != wid || newy != hgh ||
1513 nraw_x != raw_wid || nraw_y != raw_hgh ||
1514 flags != pflags || subfigure != psubfigure)
1522 subfigure = psubfigure;
1525 figdata * pf = figure->data;
1528 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1529 && !lyxrc.ps_command.empty()) {
1530 // do not display if there is "do not display"
1531 // chosen (Matthias 260696)
1532 figure->data = getfigdata(wid, hgh, lfname,
1533 psx, psy, pswid, pshgh,
1535 angle, flags & (3|8));
1536 } else figure->data = 0;
1538 // free the old data
1539 if (pf) freefigdata(pf);
1542 changedfname = false;
1546 void InsetFig::GetPSSizes()
1548 /* get %%BoundingBox: from postscript file */
1550 /* defaults to associated size
1551 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1558 if (fname.empty()) return;
1560 ifstream ifs(fname.c_str());
1562 if (!ifs) return; // file not found !!!!
1564 /* defaults to A4 page */
1570 char lastchar = 0; ifs.get(lastchar);
1572 char c = 0; ifs.get(c);
1574 lyxerr.debug() << "End of (E)PS file reached and"
1575 " no BoundingBox!" << endl;
1578 if (c == '%' && lastchar == '%') {
1580 if (p.empty()) break;
1581 lyxerr.debug() << "Token: `" << p << "'" << endl;
1582 if (p == "BoundingBox:") {
1583 float fpsx, fpsy, fpswid, fpshgh;
1584 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1587 pswid = int(fpswid);
1588 pshgh = int(fpshgh);
1590 if (lyxerr.debugging()) {
1591 lyxerr << "%%%%BoundingBox:"
1609 void InsetFig::CallbackFig(long arg)
1614 if (lyxerr.debugging()) {
1615 lyxerr << "Figure callback, arg " << arg << endl;
1621 case 12: /* width type */
1628 fl_deactivate_object(form->Width);
1633 fl_activate_object(form->Width);
1638 fl_activate_object(form->Width);
1643 fl_activate_object(form->Width);
1648 fl_activate_object(form->Width);
1651 lyxerr.debug() << "Unknown type!" << endl;
1658 case 22: /* height type */
1664 fl_deactivate_object(form->Height);
1669 fl_activate_object(form->Height);
1674 fl_activate_object(form->Height);
1679 fl_activate_object(form->Height);
1682 lyxerr.debug() << "Unknown type!" << endl;
1688 pflags = pflags & ~3; /* wysiwyg0 */
1691 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1694 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1697 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1700 pflags ^= 4; /* frame */
1703 pflags ^= 8; /* do translations */
1706 psubfigure = !psubfigure; /* This is a subfigure */
1709 regen = true; /* regenerate command */
1711 case 0: /* browse file */
1715 case 1: /* preview */
1716 p = fl_get_input(form->EpsFile);
1720 case 8: /* ok (apply and close) */
1721 if (!current_view->buffer()->isReadonly()) {
1724 xwid = atof(fl_get_input(form->Width));
1725 xhgh = atof(fl_get_input(form->Height));
1726 angle = atof(fl_get_input(form->Angle));
1727 p = fl_get_input(form->EpsFile);
1729 string buf1 = OnlyPath(owner->fileName());
1730 fname = MakeAbsPath(p, buf1);
1731 changedfname = true;
1733 if (!fname.empty()) {
1734 changedfname = true;
1738 subcaption = fl_get_input(form->Subcaption);
1742 /* now update inset */
1743 if (lyxerr.debugging()) {
1744 lyxerr << "Update: ["
1745 << wid << 'x' << hgh << ']' << endl;
1747 current_view->updateInset(this, true);
1749 fl_set_focus_object(form->Figure, form->OkBtn);
1750 fl_hide_form(form->Figure);
1751 #if FL_REVISION == 89
1752 // CHECK Reactivate this free_form calls
1754 fl_free_form(form->Figure);
1755 free(form); // Why free?
1761 // The user has already been informed about RO in ::Edit
1762 if (arg == 7) // if 'Apply'
1765 case 9: /* cancel = restore and close */
1766 fl_set_focus_object(form->Figure, form->OkBtn);
1767 fl_hide_form(form->Figure);
1768 #if FL_REVISION == 89
1769 // CHECK Reactivate this free_form calls
1770 // Jug, is this still a problem?
1772 fl_free_form(form->Figure);
1773 free(form); // Why free?
1779 if (regen) TempRegenerate();
1784 void DisableFigurePanel(FD_Figure * const form)
1786 fl_deactivate_object(form->EpsFile);
1787 fl_deactivate_object(form->Browse);
1788 fl_deactivate_object(form->Width);
1789 fl_deactivate_object(form->Height);
1790 fl_deactivate_object(form->Frame);
1791 fl_deactivate_object(form->Translations);
1792 fl_deactivate_object(form->Angle);
1793 fl_deactivate_object(form->HeightGrp);
1794 fl_deactivate_object(form->page2);
1795 fl_deactivate_object(form->Default2);
1796 fl_deactivate_object(form->cm2);
1797 fl_deactivate_object(form->in2);
1798 fl_deactivate_object(form->HeightLabel);
1799 fl_deactivate_object(form->WidthLabel);
1800 fl_deactivate_object(form->DisplayGrp);
1801 fl_deactivate_object(form->Wysiwyg3);
1802 fl_deactivate_object(form->Wysiwyg0);
1803 fl_deactivate_object(form->Wysiwyg2);
1804 fl_deactivate_object(form->Wysiwyg1);
1805 fl_deactivate_object(form->WidthGrp);
1806 fl_deactivate_object(form->Default1);
1807 fl_deactivate_object(form->cm1);
1808 fl_deactivate_object(form->in1);
1809 fl_deactivate_object(form->page1);
1810 fl_deactivate_object(form->column1);
1811 fl_deactivate_object(form->Subcaption);
1812 fl_deactivate_object(form->Subfigure);
1813 fl_deactivate_object (form->OkBtn);
1814 fl_deactivate_object (form->ApplyBtn);
1815 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1816 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1821 void EnableFigurePanel(FD_Figure * const form)
1823 fl_activate_object(form->EpsFile);
1824 fl_activate_object(form->Browse);
1825 fl_activate_object(form->Width);
1826 fl_activate_object(form->Height);
1827 fl_activate_object(form->Frame);
1828 fl_activate_object(form->Translations);
1829 fl_activate_object(form->Angle);
1830 fl_activate_object(form->HeightGrp);
1831 fl_activate_object(form->page2);
1832 fl_activate_object(form->Default2);
1833 fl_activate_object(form->cm2);
1834 fl_activate_object(form->in2);
1835 fl_activate_object(form->HeightLabel);
1836 fl_activate_object(form->WidthLabel);
1837 fl_activate_object(form->DisplayGrp);
1838 fl_activate_object(form->Wysiwyg3);
1839 fl_activate_object(form->Wysiwyg0);
1840 fl_activate_object(form->Wysiwyg2);
1841 fl_activate_object(form->Wysiwyg1);
1842 fl_activate_object(form->WidthGrp);
1843 fl_activate_object(form->Default1);
1844 fl_activate_object(form->cm1);
1845 fl_activate_object(form->in1);
1846 fl_activate_object(form->page1);
1847 fl_activate_object(form->column1);
1848 fl_activate_object(form->Subcaption);
1849 fl_activate_object(form->Subfigure);
1850 fl_activate_object (form->OkBtn);
1851 fl_activate_object (form->ApplyBtn);
1852 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1853 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1857 void InsetFig::RestoreForm()
1859 EnableFigurePanel(form);
1862 fl_set_button(form->Default1, (wtype == 0));
1863 fl_set_button(form->cm1, (wtype == 1));
1864 fl_set_button(form->in1, (wtype == 2));
1865 fl_set_button(form->page1, (wtype == 3));
1866 fl_set_button(form->column1, (wtype == 4));
1868 fl_deactivate_object(form->Width);
1870 fl_activate_object(form->Width);
1873 // enable and disable should be put here.
1875 fl_set_button(form->Default2, (htype == 0));
1876 fl_set_button(form->cm2, (htype == 1));
1877 fl_set_button(form->in2, (htype == 2));
1878 fl_set_button(form->page2, (htype == 3));
1879 // enable and disable should be put here.
1881 fl_deactivate_object(form->Height);
1883 fl_activate_object(form->Height);
1886 int piflags = flags & 3;
1887 fl_set_button(form->Wysiwyg0, (piflags == 0));
1888 fl_set_button(form->Wysiwyg1, (piflags == 1));
1889 fl_set_button(form->Wysiwyg2, (piflags == 2));
1890 fl_set_button(form->Wysiwyg3, (piflags == 3));
1891 fl_set_button(form->Frame, ((flags & 4) != 0));
1892 fl_set_button(form->Translations, ((flags & 8) != 0));
1893 fl_set_button(form->Subfigure, (subfigure != 0));
1895 psubfigure = subfigure;
1896 fl_set_input(form->Width, tostr(xwid).c_str());
1897 fl_set_input(form->Height, tostr(xhgh).c_str());
1898 fl_set_input(form->Angle, tostr(angle).c_str());
1899 if (!fname.empty()){
1900 string buf1 = OnlyPath(owner->fileName());
1901 string fname2 = MakeRelPath(fname, buf1);
1902 fl_set_input(form->EpsFile, fname2.c_str());
1904 else fl_set_input(form->EpsFile, "");
1905 fl_set_input(form->Subcaption, subcaption.c_str());
1906 if (current_view->buffer()->isReadonly())
1907 DisableFigurePanel(form);
1913 void InsetFig::Preview(string const & p)
1916 if (GetExtension(tfname).empty())
1918 string buf1 = OnlyPath(owner->fileName());
1919 string buf2 = MakeAbsPath(tfname, buf1);
1920 if (!formats.View(owner, buf2, "eps"))
1921 lyxerr << "Can't view " << buf2 << endl;
1924 void InsetFig::BrowseFile()
1926 static string current_figure_path;
1927 static int once = 0;
1930 if (lyxerr.debugging()) {
1931 lyxerr << "Filename: "
1932 << owner->fileName() << endl;
1934 string p = fl_get_input(form->EpsFile);
1936 string buf = MakeAbsPath(owner->fileName());
1937 string buf2 = OnlyPath(buf);
1939 buf = MakeAbsPath(p, buf2);
1940 buf = OnlyPath(buf);
1942 buf = OnlyPath(owner->fileName());
1945 // Does user clipart directory exist?
1946 string bufclip = AddName (user_lyxdir, "clipart");
1947 FileInfo fileInfo(bufclip);
1948 if (!(fileInfo.isOK() && fileInfo.isDir()))
1949 // No - bail out to system clipart directory
1950 bufclip = AddName (system_lyxdir, "clipart");
1953 fileDlg.SetButton(0, _("Clipart"), bufclip);
1954 fileDlg.SetButton(1, _("Document"), buf);
1958 ProhibitInput(current_view);
1960 p = fileDlg.Select(_("EPS Figure"),
1961 current_figure_path,
1964 p = fileDlg.Select(_("EPS Figure"), buf,
1967 AllowInput(current_view);
1969 if (p.empty()) return;
1971 buf = MakeRelPath(p, buf2);
1972 current_figure_path = OnlyPath(p);
1975 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1976 || contains(p, "%") || contains(p, " ")) {
1977 WriteAlert(_("Filename can't contain any "
1978 "of these characters:"),
1979 // xgettext:no-c-format
1980 _("space, '#', '~', '$' or '%'."));
1985 if (form) fl_set_input(form->EpsFile, buf.c_str());
1989 void GraphicsCB(FL_OBJECT * obj, long arg)
1991 /* obj->form contains the form */
1993 if (lyxerr.debugging()) {
1994 lyxerr << "GraphicsCB callback: " << arg << endl;
1997 /* find inset we were reacting to */
1998 for (figures_type::iterator it = figures.begin();
1999 it != figures.end(); ++it)
2000 if ((*it)->inset->form && (*it)->inset->form->Figure
2002 if (lyxerr.debugging()) {
2003 lyxerr << "Calling back figure "
2006 (*it)->inset->CallbackFig(arg);
2012 void HideFiguresPopups()
2014 for (figures_type::iterator it = figures.begin();
2015 it != figures.end(); ++it)
2016 if ((*it)->inset->form
2017 && (*it)->inset->form->Figure->visible) {
2018 if (lyxerr.debugging()) {
2019 lyxerr << "Hiding figure " << (*it) << endl;
2021 // hide and free the form
2022 (*it)->inset->CallbackFig(9);