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)
35 #include FORMS_H_LOCATION
50 #include "support/filetools.h"
51 #include "LyXView.h" // just because of form_main
53 #include "LaTeXFeatures.h"
56 #include "lyx_gui_misc.h" // CancelCloseBoxCB
57 #include "support/FileInfo.h"
58 #include "support/lyxlib.h"
62 #include "bufferview_funcs.h"
75 extern BufferView * current_view;
76 extern FL_OBJECT * figinset_canvas;
78 extern char ** environ; // is this only redundtant on linux systems? Lgb.
80 static float const DEG2PI = 57.295779513;
82 struct queue_element {
83 float rx, ry; // resolution x and y
84 int ofsx, ofsy; // x and y translation
85 figdata * data; // we are doing it for this data
88 static int const MAXGS = 3; /* maximum 3 gs's at a time */
90 typedef vector<Figref *> figures_type;
91 typedef vector<figdata *> bitmaps_type;
92 static figures_type figures; // all figures
93 static bitmaps_type bitmaps; // all bitmaps
95 static queue<queue_element> gsqueue; // queue for ghostscripting
97 static int gsrunning = 0; /* currently so many gs's are running */
98 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
99 static char bittable[256]; /* bit reversion table */
101 static bool gs_color; // do we allocate colors for gs?
102 static bool color_visual; // is the visual color?
103 static bool gs_xcolor = false; // allocated extended colors
104 static unsigned long gs_pixels[128]; // allocated pixels
105 static int gs_num_pixels; // number of pixels allocated
106 static int gs_spc; // shades per color
107 static bool gs_gray; // is grayscale?
108 static int gs_allcolors; // number of all colors
110 static list<int> pidwaitlist; // pid wait list
117 val.foreground = BlackPixel(fl_display,
118 DefaultScreen(fl_display));
121 val.graphics_exposures = false;
122 val.line_style = LineSolid;
124 return XCreateGC(fl_display, RootWindow(fl_display, 0),
125 GCForeground | GCFunction | GCGraphicsExposures
126 | GCLineWidth | GCLineStyle , &val);
134 void addpidwait(int pid)
136 // adds pid to pid wait list
137 pidwaitlist.push_back(pid);
139 if (lyxerr.debugging()) {
140 lyxerr << "Pids to wait for: \n";
141 for (list<int>::const_iterator cit = pidwaitlist.begin();
142 cit != pidwaitlist.end(); ++cit) {
143 lyxerr << (*cit) << '\n';
151 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
156 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
158 if(lyxerr.debugging()) {
159 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
160 << "] pm:[" << e->data.l[1] << "]" << endl;
163 // just kill gs, that way it will work for sure
164 // This loop looks like S**T so it probably is...
165 //for (bitmaps_type::size_type i = 0; i < bitmaps.size(); ++i)
166 for (bitmaps_type::iterator it = bitmaps.begin();
167 it != bitmaps.end(); ++it)
168 if (static_cast<long>((*it)->bitmap) ==
169 static_cast<long>(e->data.l[1])) {
174 // first update p->bitmap, if necessary
175 if (p->bitmap != None
176 && p->flags > (1|8) && gs_color && p->wid) {
177 // query current colormap and re-render
178 // the pixmap with proper colors
179 XWindowAttributes wa;
180 register XImage * im;
184 int spc1 = gs_spc - 1;
185 int spc2 = gs_spc * gs_spc;
189 GC gc = local_gc_copy;
191 XGetWindowAttributes(fl_display,
196 if (lyxerr.debugging()) {
197 lyxerr << "Starting image translation "
200 << p->wid << "x" << p->hgh
202 << " " << XYPixmap << endl;
204 // now fork rendering process
206 if (forkstat == -1) {
208 << "Cannot fork, using slow "
209 "method for pixmap translation." << endl;
210 tmpdisp = fl_display;
211 } else if (forkstat > 0) { // parent
213 if (lyxerr.debugging()) {
214 lyxerr << "Spawned child "
217 addpidwait(forkstat);
220 tmpdisp = XOpenDisplay(XDisplayName(0));
223 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
224 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
226 if (lyxerr.debugging()) {
227 lyxerr << "Got the image" << endl;
230 if (lyxerr.debugging()) {
231 lyxerr << "Error getting the image" << endl;
236 // query current colormap
237 XColor * cmap = new XColor[gs_allcolors];
238 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
239 XQueryColors(tmpdisp,
240 fl_state[fl_get_vclass()]
245 // now we process all the image
246 for (y = 0; y < p->hgh; ++y) {
247 for (int x = 0; x < wid; ++x) {
252 gs_pixels[((pc->red+6553)*
253 spc1/65535)*spc2+((pc->green+6553)*
254 spc1/65535)*gs_spc+((pc->blue+6553)*
259 // This must be correct.
261 if (lyxerr.debugging()) {
262 lyxerr << "Putting image back"
265 XPutImage(tmpdisp, p->bitmap,
267 0, 0, p->wid, p->hgh);
269 if (lyxerr.debugging()) {
270 lyxerr << "Done translation"
275 if (lyxerr.debugging()) {
276 lyxerr << "Killing gs "
279 lyx::kill(p->gspid, SIGHUP);
281 sprintf(tmp, "%s/~lyxgs%d.ps",
282 system_tempdir.c_str(),
286 XCloseDisplay(tmpdisp);
290 if (lyxerr.debugging()) {
291 lyxerr << "Killing gs "
294 lyx::kill(p->gspid, SIGHUP);
296 sprintf(tmp, "%s/~lyxgs%d.ps",
297 system_tempdir.c_str(),
308 void AllocColors(int num)
309 // allocate color cube numxnumxnum, if possible
311 if (lyxerr.debugging()) {
312 lyxerr << "Allocating color cube " << num
313 << 'x' << num << 'x' << num << endl;
317 lyxerr << "Error allocating color colormap." << endl;
321 if (num > 5) num = 5;
323 for (int i = 0; i < num * num * num; ++i) {
324 xcol.red = 65535 * (i / (num * num)) / (num - 1);
325 xcol.green = 65535 * ((i / num) % num) / (num - 1);
326 xcol.blue = 65535 * (i % num) / (num - 1);
327 xcol.flags = DoRed | DoGreen | DoBlue;
328 if (!XAllocColor(fl_display,
329 fl_state[fl_get_vclass()].colormap, &xcol)) {
330 if (i) XFreeColors(fl_display,
331 fl_state[fl_get_vclass()].colormap,
333 if(lyxerr.debugging()) {
334 lyxerr << "Cannot allocate color cube "
337 AllocColors(num - 1);
340 gs_pixels[i] = xcol.pixel;
345 gs_num_pixels = num * num * num;
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 = 65535 * i / (num - 1);
367 xcol.flags = DoRed | DoGreen | DoBlue;
368 if (!XAllocColor(fl_display,
369 fl_state[fl_get_vclass()].colormap, &xcol)) {
370 if (i) XFreeColors(fl_display,
371 fl_state[fl_get_vclass()].colormap,
373 if (lyxerr.debugging()) {
374 lyxerr << "Cannot allocate grayscale "
380 gs_pixels[i] = xcol.pixel;
391 // if bitmaps and figures are not empty we will leak mem
396 for (unsigned int i = 0; i < 256; ++i) {
398 for (unsigned int j = 0; j < 8; ++j)
399 if (i & (1 << (7-j))) k |= 1 << j;
400 bittable[i] = char(~k);
403 // allocate color cube on pseudo-color display
407 fl_add_canvas_handler(figinset_canvas, ClientMessage,
408 GhostscriptMsg, current_view->owner()->getMainForm());
410 local_gc_copy = createGC();
412 Visual * vi = DefaultVisual(fl_display, DefaultScreen(fl_display));
413 if (lyxerr.debugging()) {
414 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
415 vi->visualid, vi->c_class,
416 vi->bits_per_rgb, vi->map_entries);
418 color_visual = ( (vi->c_class == StaticColor) ||
419 (vi->c_class == PseudoColor) ||
420 (vi->c_class == TrueColor) ||
421 (vi->c_class == DirectColor) );
422 if ((vi->c_class & 1) == 0) return;
423 // now allocate colors
424 if (vi->c_class == GrayScale) {
425 // allocate grayscale
426 AllocGrays(vi->map_entries/2);
428 // allocate normal color
430 while (i * i * i * 2 > vi->map_entries) --i;
433 gs_allcolors = vi->map_entries;
441 // if bitmaps and figures are not empty we will leak mem
445 lyxerr.debug() << "Unregistering figures..." << endl;
447 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
453 void freefigdata(figdata * tmpdata)
456 if (tmpdata->ref) return;
458 if (tmpdata->gspid > 0) {
459 int pid = tmpdata->gspid;
461 // kill ghostscript and unlink it's files
463 lyx::kill(pid, SIGKILL);
464 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
468 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
469 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
477 // run queued requests for ghostscript, if any
478 if (!gsrunning && gs_color && !gs_xcolor) {
479 // here alloc all colors, so that gs will use only
480 // those we allocated for it
485 while (gsrunning < MAXGS) {
486 char tbuf[384], tbuf2[80];
490 if (gsqueue.empty()) {
491 if (!gsrunning && gs_xcolor) {
492 // de-allocate rest of colors
498 queue_element * p = &gsqueue.front();
507 if (lyxerr.debugging()) {
508 lyxerr << "GS start error! Cannot fork."
511 p->data->broken = true;
512 p->data->reading = false;
515 if (pid == 0) { // child
516 char ** env, rbuf[80], gbuf[40];
518 Display * tempdisp = XOpenDisplay(XDisplayName(0));
520 // create translation file
521 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
525 ofs << "gsave clippath pathbbox grestore\n"
527 << "/ury exch def /urx exch def /lly exch def "
529 << p->data->wid / 2.0 << " "
530 << p->data->hgh / 2.0 << " translate\n"
531 << p->data->angle << " rotate\n"
532 << -(p->data->raw_wid / 2.0) << " "
533 << -(p->data->raw_hgh / 2.0) << " translate\n"
534 << p->rx / 72.0 << " " << p->ry / 72.0
536 << -p->ofsx << " " << -p->ofsy << " translate\n"
538 ofs.close(); // Don't remove this.
540 // gs process - set ghostview environment first
541 sprintf(tbuf2, "GHOSTVIEW=%ld %ld", fl_get_canvas_id(
542 figinset_canvas), p->data->bitmap);
544 // now set up ghostview property on a window
545 sprintf(tbuf, "0 0 0 0 %d %d 72 72 0 0 0 0",
546 p->data->wid, p->data->hgh);
547 // #warning BUG seems that the only bug here
548 // might be the hardcoded dpi.. Bummer!
550 if (lyxerr.debugging()) {
551 lyxerr << "Will set GHOSTVIEW property to ["
552 << tbuf << "]" << endl;
554 // wait until property is deleted if executing multiple
557 // grab server to prevent other child
558 // interfering with setting GHOSTVIEW property
559 if (lyxerr.debugging()) {
560 lyxerr << "Grabbing the server"
563 XGrabServer(tempdisp);
564 prop = XListProperties(tempdisp,
566 figinset_canvas), &nprop);
570 for (i = 0; i < nprop; ++i) {
571 char * p = XGetAtomName(tempdisp,
573 if (strcmp(p, "GHOSTVIEW") == 0) {
579 XFree(reinterpret_cast<char *>(prop)); // jc:
581 // release the server
582 XUngrabServer(tempdisp);
584 // ok, property found, we must wait until
585 // ghostscript deletes it
586 if (lyxerr.debugging()) {
587 lyxerr << "Releasing the server\n["
589 << "] GHOSTVIEW property"
590 " found. Waiting." << endl;
596 XChangeProperty(tempdisp,
597 fl_get_canvas_id(figinset_canvas),
598 XInternAtom(tempdisp, "GHOSTVIEW", false),
599 XInternAtom(tempdisp, "STRING", false),
601 reinterpret_cast<unsigned char*>(tbuf),
604 switch (p->data->flags & 3) {
605 case 0: tbuf[0] = 'H'; break; // Hidden
606 case 1: tbuf[0] = 'M'; break; // Mono
607 case 2: tbuf[0] = 'G'; break; // Gray
610 tbuf[0] = 'C'; // Color
612 tbuf[0] = 'G'; // Gray
616 sprintf(tbuf+1, " %ld %ld", BlackPixelOfScreen(
617 DefaultScreenOfDisplay(fl_display)),
618 fl_get_pixel(FL_WHITE));
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*>(tbuf),
628 XUngrabServer(tempdisp);
630 if (lyxerr.debugging()) {
631 lyxerr << "Releasing the server" << endl;
633 XCloseDisplay(tempdisp);
635 // set up environment
636 while (environ[ne]) ++ne;
637 typedef char * char_p;
638 env = new char_p[ne + 2];
640 memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
643 // now make gs command
645 // close(1); do NOT close. If GS writes out
646 // errors it would hang. (Matthias 290596)
647 sprintf(rbuf, "-r%gx%g", p->rx, p->ry);
648 sprintf(gbuf, "-g%dx%d", p->data->wid, p->data->hgh);
649 // now chdir into dir with .eps file, to be on the safe
651 chdir(OnlyPath(p->data->fname).c_str());
652 // make temp file name
653 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
655 if (lyxerr.debugging()) {
656 lyxerr << "starting gs " << tbuf << " "
658 << ", pid: " << getpid() << endl;
661 int err = execlp(lyxrc.ps_command.c_str(),
662 lyxrc.ps_command.c_str(),
664 "-dNOPAUSE", "-dQUIET",
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()) return 0;
719 for (bitmaps_type::iterator it = bitmaps.begin();
720 it != bitmaps.end(); ++it) {
721 if ((*it)->wid == wid && (*it)->hgh == hgh &&
722 (*it)->flags == flags && (*it)->fname == fname &&
723 (*it)->angle == angle) {
728 figdata * p = new figdata;
731 p->raw_wid = raw_wid;
732 p->raw_hgh = raw_hgh;
736 bitmaps.push_back(p);
737 XWindowAttributes wa;
738 XGetWindowAttributes(fl_display, fl_get_canvas_id(
739 figinset_canvas), &wa);
741 if (lyxerr.debugging()) {
742 lyxerr << "Create pixmap disp:" << fl_display
743 << " scr:" << DefaultScreen(fl_display)
746 << " depth:" << wa.depth << endl;
754 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
755 figinset_canvas), wid, hgh, wa.depth);
757 // initialize reading of .eps file with correct sizes and stuff
758 addwait(psx, psy, pswid, pshgh, p);
770 void getbitmap(figdata * p)
777 void makeupdatelist(figdata * p)
779 for(figures_type::iterator it = figures.begin();
780 it != figures.end(); ++it)
781 if ((*it)->data == p) {
782 if (lyxerr.debugging()) {
783 lyxerr << "Updating inset "
787 // add inset figures[i]->inset into to_update list
788 current_view->pushIntoUpdateList((*it)->inset);
793 // this func is only "called" in spellchecker.C
794 void sigchldchecker(pid_t pid, int * status)
796 lyxerr.debug() << "Got pid = " << pid << endl;
797 bool pid_handled = false;
798 for (bitmaps_type::iterator it = bitmaps.begin();
799 it != bitmaps.end(); ++it) {
800 if ((*it)->reading && pid == (*it)->gspid) {
801 lyxerr.debug() << "Found pid in bitmaps" << endl;
802 // now read the file and remove it from disk
805 if ((*it)->gsdone) *status = 0;
807 lyxerr.debug() << "GS [" << pid
808 << "] exit OK." << endl;
810 lyxerr << "GS [" << pid << "] error "
812 << WIFEXITED(*status)
813 << " " << WEXITSTATUS(*status)
814 << " S:" << WIFSIGNALED(*status)
815 << " " << WTERMSIG(*status) << endl;
818 bitmap_waiting = true;
821 // remove temporary files
823 sprintf(tmp, "%s/~lyxgs%d.ps",
824 system_tempdir.c_str(),
830 makeupdatelist((*it));
837 lyxerr.debug() << "Checking pid in pidwait" << endl;
838 list<int>::iterator it = find(pidwaitlist.begin(),
839 pidwaitlist.end(), pid);
840 if (it != pidwaitlist.end()) {
841 lyxerr.debug() << "Found pid in pidwait\n"
842 << "Caught child pid of recompute "
843 "routine" << pid << endl;
844 pidwaitlist.erase(it);
848 lyxerr.debug() << "waitpid error" << endl;
851 lyxerr << "The process or process group specified by "
852 "pid does not exist or is not a child of "
853 "the calling process or can never be in the "
854 "states specified by options." << endl;
857 lyxerr << "waitpid() was interrupted due to the "
858 "receipt of a signal sent by the calling "
862 lyxerr << "An invalid value was specified for "
866 lyxerr << "Unknown error from waitpid" << endl;
869 } else if (pid == 0) {
870 lyxerr << "waitpid nohang" << endl;;
872 lyxerr.debug() << "normal exit from childhandler" << endl;
880 bitmap_waiting = false;
881 for (bitmaps_type::iterator it = bitmaps.begin();
882 it != bitmaps.end(); ++it)
883 if ((*it)->gspid > 0 && !(*it)->reading)
889 void RegisterFigure(InsetFig * fi)
891 if (figures.empty()) InitFigures();
893 Figref * tmpfig = new Figref;
896 figures.push_back(tmpfig);
899 if (lyxerr.debugging()) {
900 lyxerr << "Register Figure: buffer:["
901 << current_view->buffer() << "]" << endl;
907 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 #warning 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();
934 string NextToken(istream & is)
942 } while (!is.eof() && !isspace(c));
943 token.erase(token.length() - 1); // remove the isspace
949 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
959 psubfigure = subfigure = false;
960 xwid = xhgh = angle = 0;
962 raw_wid = raw_hgh = 0;
963 changedfname = false;
964 RegisterFigure(this);
968 InsetFig::~InsetFig()
970 if (lyxerr.debugging()) {
971 lyxerr << "Figure destructor called" << endl;
973 UnregisterFigure(this);
977 int InsetFig::ascent(Painter &, LyXFont const &) const
983 int InsetFig::descent(Painter &, LyXFont const &) const
989 int InsetFig::width(Painter &, LyXFont const &) const
995 void InsetFig::draw(Painter & pain, LyXFont const & f,
996 int baseline, float & x) const
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,
1019 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1021 if (figure && figure->data) {
1022 if (figure->data->broken) msg = _("[render error]");
1023 else if (figure->data->reading) msg = _("[rendering ... ]");
1025 if (fname.empty()) msg = _("[no file]");
1026 else if ((flags & 3) == 0) msg = _("[not displayed]");
1027 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1029 if (!msg) msg = _("[unknown error]");
1031 font.setFamily(LyXFont::SANS_FAMILY);
1032 font.setSize(LyXFont::SIZE_FOOTNOTE);
1033 string justname = OnlyFilename (fname);
1034 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1037 font.setSize(LyXFont::SIZE_TINY);
1038 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1040 x += width(pain, font); // ?
1044 void InsetFig::Write(ostream & os) const
1047 os << "Figure size " << wid << " " << hgh << "\n";
1048 if (!fname.empty()) {
1049 string buf1 = OnlyPath(owner->fileName());
1050 string fname2 = MakeRelPath(fname, buf1);
1051 os << "file " << fname2 << "\n";
1053 if (!subcaption.empty())
1054 os << "subcaption " << subcaption << "\n";
1055 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1056 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1057 if (angle != 0) os << "angle " << angle << "\n";
1058 os << "flags " << flags << "\n";
1059 if (subfigure) os << "subfigure\n";
1063 void InsetFig::Read(LyXLex & lex)
1066 bool finished = false;
1068 while (lex.IsOK() && !finished) {
1071 string const token = lex.GetString();
1072 lyxerr.debug() << "Token: " << token << endl;
1076 else if (token == "\\end_inset") {
1078 } else if (token == "file") {
1080 buf = lex.GetString();
1081 string buf1 = OnlyPath(owner->fileName());
1082 fname = MakeAbsPath(buf, buf1);
1083 changedfname = true;
1085 } else if (token == "extra") {
1087 // kept for backwards compability. Delete in 0.13.x
1088 } else if (token == "subcaption") {
1090 subcaption = lex.GetString();
1091 } else if (token == "label") {
1093 // kept for backwards compability. Delete in 0.13.x
1094 } else if (token == "angle") {
1096 angle = lex.GetFloat();
1097 } else if (token == "size") {
1099 wid = lex.GetInteger();
1101 hgh = lex.GetInteger();
1102 } else if (token == "flags") {
1104 flags = pflags = lex.GetInteger();
1105 } else if (token == "subfigure") {
1106 subfigure = psubfigure = true;
1107 } else if (token == "width") {
1110 typ = lex.GetInteger();
1112 xwid = lex.GetFloat();
1114 case DEF: wtype = DEF; break;
1115 case CM: wtype = CM; break;
1116 case IN: wtype = IN; break;
1117 case PER_PAGE: wtype = PER_PAGE; break;
1118 case PER_COL: wtype = PER_COL; break;
1120 lyxerr.debug() << "Unknown type!" << endl;
1124 } else if (token == "height") {
1127 typ = lex.GetInteger();
1129 xhgh = lex.GetFloat();
1131 case DEF: htype = DEF; break;
1132 case CM: htype = CM; break;
1133 case IN: htype = IN; break;
1134 case PER_PAGE: htype = PER_PAGE; break;
1136 lyxerr.debug() << "Unknown type!" << endl;
1147 int InsetFig::Latex(ostream & os,
1148 signed char /* fragile*/, bool /* fs*/) const
1151 if (!cmd.empty()) os << cmd << " ";
1156 int InsetFig::Linuxdoc(ostream &) const
1162 int InsetFig::DocBook(ostream & os) const
1164 string figurename = fname;
1166 if(suffixIs(figurename, ".eps"))
1167 figurename.erase(fname.length() - 5);
1169 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1174 void InsetFig::Validate(LaTeXFeatures & features) const
1176 features.graphics = true;
1177 if (subfigure) features.subfigure = true;
1181 Inset::EDITABLE InsetFig::Editable() const
1187 bool InsetFig::Deletable() const
1193 char const * InsetFig::EditMessage() const
1195 return _("Opened figure");
1199 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1201 lyxerr.debug() << "Editing InsetFig." << endl;
1204 // We should have RO-versions of the form instead.
1205 // The actual prevention of altering a readonly doc
1206 // is done in CallbackFig()
1207 if(bv->buffer()->isReadonly())
1208 WarnReadonly(bv->buffer()->fileName());
1211 form = create_form_Figure();
1212 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1213 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1214 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1215 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1218 if (form->Figure->visible) {
1219 fl_raise_form(form->Figure);
1221 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1222 FL_FULLBORDER, _("Figure"));
1227 Inset * InsetFig::Clone() const
1229 InsetFig * tmp = new InsetFig(100, 100, owner);
1231 if (lyxerr.debugging()) {
1232 lyxerr << "Clone Figure: buffer:["
1233 << current_view->buffer()
1234 << "], cbuffer:[xx]" << endl;
1239 tmp->raw_wid = raw_wid;
1240 tmp->raw_hgh = raw_hgh;
1245 tmp->pflags = pflags;
1246 tmp->subfigure = subfigure;
1247 tmp->psubfigure = psubfigure;
1255 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1257 // do not display if there is
1258 // "do not display" chosen (Matthias 260696)
1259 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1260 pswid, pshgh, raw_wid, raw_hgh,
1261 angle, flags & (3|8));
1262 } else tmp->figure->data = 0;
1263 tmp->subcaption = subcaption;
1264 tmp->changedfname = false;
1271 Inset::Code InsetFig::LyxCode() const
1273 return Inset::GRAPHICS_CODE;
1277 void InsetFig::Regenerate() const
1280 string resizeW, resizeH;
1281 string rotate, recmd;
1283 if (fname.empty()) {
1284 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1285 cmd += _("empty figure path");
1290 string buf1 = OnlyPath(owner->fileName());
1291 string fname2 = MakeRelPath(fname, buf1);
1293 string gcmd = "\\includegraphics{" + fname2 + '}';
1298 case CM:{// \resizebox*{h-length}{v-length}{text}
1300 sprintf(buf, "%g", xwid); // should find better
1307 sprintf(buf, "%g", xwid);
1314 sprintf(buf, "%g", xwid/100);
1316 resizeW += "\\textwidth";
1321 sprintf(buf, "%g", xwid/100);
1323 resizeW += "\\columnwidth";
1333 sprintf(buf, "%g", xhgh);
1340 sprintf(buf, "%g", xhgh);
1347 sprintf(buf, "%g", xhgh/100);
1349 resizeH += "\\textheight";
1353 // Doesn't occur; case exists to suppress compiler warnings.
1358 if (!resizeW.empty() || !resizeH.empty()) {
1359 recmd = "\\resizebox*{";
1360 if (!resizeW.empty())
1365 if (!resizeH.empty())
1375 sprintf(buf, "%g", angle);
1376 // \rotatebox{angle}{text}
1377 rotate = "\\rotatebox{";
1385 if (!rotate.empty()) cmdbuf += '}';
1386 if (!recmd.empty()) cmdbuf += '}';
1388 if (!subcaption.empty())
1389 cmdbuf = "\\subfigure[" + subcaption +
1390 "]{" + cmdbuf + "}";
1392 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1399 void InsetFig::TempRegenerate()
1402 string resizeW, resizeH;
1403 string rotate, recmd;
1405 char const * tfname = fl_get_input(form->EpsFile);
1406 string tsubcap = fl_get_input(form->Subcaption);
1407 float tangle = atof(fl_get_input(form->Angle));
1408 float txwid = atof(fl_get_input(form->Width));
1409 float txhgh = atof(fl_get_input(form->Height));
1411 if (!tfname || !*tfname) {
1412 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1413 cmd += _("empty figure path");
1418 string buf1 = OnlyPath(owner->fileName());
1419 string fname2 = MakeRelPath(tfname, buf1);
1420 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1421 string gcmd = "\\includegraphics{" + fname2 + '}';
1426 case CM: {// \resizebox*{h-length}{v-length}{text}
1428 sprintf(buf, "%g", txwid); // should find better
1435 sprintf(buf, "%g", txwid);
1442 sprintf(buf, "%g", txwid/100);
1444 resizeW += "\\textwidth";
1449 sprintf(buf, "%g", txwid/100);
1451 resizeW += "\\columnwidth";
1461 sprintf(buf, "%g", txhgh);
1468 sprintf(buf, "%g", txhgh);
1475 sprintf(buf, "%g", txhgh/100);
1477 resizeH += "\\textheight";
1481 // Doesn't occur; case exists to suppress compiler warnings.
1486 // \resizebox*{h-length}{v-length}{text}
1487 if (!resizeW.empty() || !resizeH.empty()) {
1488 recmd = "\\resizebox*{";
1489 if (!resizeW.empty())
1494 if (!resizeH.empty())
1503 sprintf(buf, "%g", tangle);
1504 // \rotatebox{angle}{text}
1505 rotate = "\\rotatebox{";
1513 if (!rotate.empty()) cmdbuf += '}';
1514 if (!recmd.empty()) cmdbuf += '}';
1515 if (psubfigure && !tsubcap.empty()) {
1516 cmdbuf = string("\\subfigure{") + tsubcap
1517 + string("}{") + cmdbuf + "}";
1522 void InsetFig::Recompute()
1524 bool changed = changedfname;
1525 int newx, newy, nraw_x, nraw_y;
1527 if (changed) GetPSSizes();
1529 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1530 float cos_a = cos (angle / DEG2PI);
1531 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1532 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1534 /* now recompute wid and hgh, and if that is changed, set changed */
1535 /* this depends on chosen size of the picture and its bbox */
1536 // This will be redone in 0.13 ... (hen)
1537 if (!fname.empty()) {
1538 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1546 newx = int(28.346 * xwid);
1549 newx = int(72 * xwid);
1551 case PER_PAGE: /* % of page */
1552 newx = int(5.95 * xwid);
1554 case PER_COL: /* % of col */
1555 newx = int(2.975 * xwid);
1559 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1563 //lyxerr << "This should not happen!" << endl;
1566 newy = int(28.346 * xhgh);
1569 newy = int(72 * xhgh);
1571 case PER_PAGE: /* % of page */
1572 newy = int(8.42 * xhgh);
1575 // Doesn't occur; case exists to suppress
1576 // compiler warnings.
1579 if (htype && !wtype && frame_hgh)
1580 newx = newy*frame_wid/frame_hgh;
1589 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1594 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1596 // cannot be zero, actually, set it to some minimum, so its clickable
1597 if (newx < 5) newx = 5;
1598 if (newy < 5) newy = 5;
1600 if (newx != wid || newy != hgh ||
1601 nraw_x != raw_wid || nraw_y != raw_hgh ||
1602 flags != pflags || subfigure != psubfigure)
1610 subfigure = psubfigure;
1613 figdata * pf = figure->data;
1616 if (!fname.empty() && (flags & 3)
1617 && !lyxrc.ps_command.empty()) {
1618 // do not display if there is "do not display"
1619 // chosen (Matthias 260696)
1620 figure->data = getfigdata(wid, hgh, fname,
1621 psx, psy, pswid, pshgh,
1623 angle, flags & (3|8));
1624 } else figure->data = 0;
1626 // free the old data
1627 if (pf) freefigdata(pf);
1630 changedfname = false;
1634 void InsetFig::GetPSSizes()
1636 /* get %%BoundingBox: from postscript file */
1638 /* defaults to associated size
1639 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1646 if (fname.empty()) return;
1648 ifstream ifs(fname.c_str());
1650 if (!ifs) return; // file not found !!!!
1652 /* defaults to A4 page */
1658 char lastchar = 0; ifs.get(lastchar);
1660 char c = 0; ifs.get(c);
1662 lyxerr.debug() << "End of (E)PS file reached and"
1663 " no BoundingBox!" << endl;
1666 if (c == '%' && lastchar == '%') {
1668 if (p.empty()) break;
1669 // we should not use this, with it we cannot
1670 // discover bounding box and end of file.
1671 //if (strcmp(p, "EndComments") == 0) break;
1672 lyxerr.debug() << "Token: `" << p << "'" << endl;
1673 if (p == "BoundingBox:") {
1674 float fpsx, fpsy, fpswid, fpshgh;
1675 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1678 pswid = int(fpswid);
1679 pshgh = int(fpshgh);
1681 if (lyxerr.debugging()) {
1682 lyxerr << "%%%%BoundingBox:"
1700 void InsetFig::CallbackFig(long arg)
1705 if (lyxerr.debugging()) {
1706 lyxerr << "Figure callback, arg " << arg << endl;
1712 case 12: /* width type */
1719 fl_deactivate_object(form->Width);
1724 fl_activate_object(form->Width);
1729 fl_activate_object(form->Width);
1734 fl_activate_object(form->Width);
1739 fl_activate_object(form->Width);
1742 lyxerr.debug() << "Unknown type!" << endl;
1749 case 22: /* height type */
1755 fl_deactivate_object(form->Height);
1760 fl_activate_object(form->Height);
1765 fl_activate_object(form->Height);
1770 fl_activate_object(form->Height);
1773 lyxerr.debug() << "Unknown type!" << endl;
1779 pflags = pflags & ~3; /* wysiwyg0 */
1782 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1785 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1788 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1791 pflags ^= 4; /* frame */
1794 pflags ^= 8; /* do translations */
1797 psubfigure = !psubfigure; /* This is a subfigure */
1800 regen = true; /* regenerate command */
1802 case 0: /* browse file */
1806 case 1: /* preview */
1807 p = fl_get_input(form->EpsFile);
1811 case 8: /* ok (apply and close) */
1812 if(!current_view->buffer()->isReadonly()) {
1815 xwid = atof(fl_get_input(form->Width));
1816 xhgh = atof(fl_get_input(form->Height));
1817 angle = atof(fl_get_input(form->Angle));
1818 p = fl_get_input(form->EpsFile);
1820 string buf1 = OnlyPath(owner->fileName());
1821 fname = MakeAbsPath(p, buf1);
1822 changedfname = true;
1824 if (!fname.empty()) {
1825 changedfname = true;
1829 subcaption = fl_get_input(form->Subcaption);
1833 /* now update inset */
1834 if (lyxerr.debugging()) {
1835 lyxerr << "Update: ["
1836 << wid << 'x' << hgh << ']' << endl;
1838 current_view->updateInset(this, true);
1840 fl_set_focus_object(form->Figure, form->OkBtn);
1841 fl_hide_form(form->Figure);
1842 #if FL_REVISION == 89
1843 #warning Reactivate this free_form calls
1845 fl_free_form(form->Figure);
1846 free(form); // Why free?
1852 // The user has already been informed about RO in ::Edit
1853 if(arg == 7) // if 'Apply'
1856 case 9: /* cancel = restore and close */
1857 fl_set_focus_object(form->Figure, form->OkBtn);
1858 fl_hide_form(form->Figure);
1859 #if FL_REVISION == 89
1860 #warning Reactivate this free_form calls
1861 #warning Jug, is this still a problem?
1863 fl_free_form(form->Figure);
1864 free(form); // Why free?
1870 if (regen) TempRegenerate();
1875 void DisableFigurePanel(FD_Figure * const form)
1877 fl_deactivate_object(form->EpsFile);
1878 fl_deactivate_object(form->Browse);
1879 fl_deactivate_object(form->Width);
1880 fl_deactivate_object(form->Height);
1881 fl_deactivate_object(form->Frame);
1882 fl_deactivate_object(form->Translations);
1883 fl_deactivate_object(form->Angle);
1884 fl_deactivate_object(form->HeightGrp);
1885 fl_deactivate_object(form->page2);
1886 fl_deactivate_object(form->Default2);
1887 fl_deactivate_object(form->cm2);
1888 fl_deactivate_object(form->in2);
1889 fl_deactivate_object(form->HeightLabel);
1890 fl_deactivate_object(form->WidthLabel);
1891 fl_deactivate_object(form->DisplayGrp);
1892 fl_deactivate_object(form->Wysiwyg3);
1893 fl_deactivate_object(form->Wysiwyg0);
1894 fl_deactivate_object(form->Wysiwyg2);
1895 fl_deactivate_object(form->Wysiwyg1);
1896 fl_deactivate_object(form->WidthGrp);
1897 fl_deactivate_object(form->Default1);
1898 fl_deactivate_object(form->cm1);
1899 fl_deactivate_object(form->in1);
1900 fl_deactivate_object(form->page1);
1901 fl_deactivate_object(form->column1);
1902 fl_deactivate_object(form->Subcaption);
1903 fl_deactivate_object(form->Subfigure);
1904 fl_deactivate_object (form->OkBtn);
1905 fl_deactivate_object (form->ApplyBtn);
1906 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1907 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1912 void EnableFigurePanel(FD_Figure * const form)
1914 fl_activate_object(form->EpsFile);
1915 fl_activate_object(form->Browse);
1916 fl_activate_object(form->Width);
1917 fl_activate_object(form->Height);
1918 fl_activate_object(form->Frame);
1919 fl_activate_object(form->Translations);
1920 fl_activate_object(form->Angle);
1921 fl_activate_object(form->HeightGrp);
1922 fl_activate_object(form->page2);
1923 fl_activate_object(form->Default2);
1924 fl_activate_object(form->cm2);
1925 fl_activate_object(form->in2);
1926 fl_activate_object(form->HeightLabel);
1927 fl_activate_object(form->WidthLabel);
1928 fl_activate_object(form->DisplayGrp);
1929 fl_activate_object(form->Wysiwyg3);
1930 fl_activate_object(form->Wysiwyg0);
1931 fl_activate_object(form->Wysiwyg2);
1932 fl_activate_object(form->Wysiwyg1);
1933 fl_activate_object(form->WidthGrp);
1934 fl_activate_object(form->Default1);
1935 fl_activate_object(form->cm1);
1936 fl_activate_object(form->in1);
1937 fl_activate_object(form->page1);
1938 fl_activate_object(form->column1);
1939 fl_activate_object(form->Subcaption);
1940 fl_activate_object(form->Subfigure);
1941 fl_activate_object (form->OkBtn);
1942 fl_activate_object (form->ApplyBtn);
1943 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1944 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1948 void InsetFig::RestoreForm()
1952 EnableFigurePanel(form);
1955 fl_set_button(form->Default1, (wtype == 0));
1956 fl_set_button(form->cm1, (wtype == 1));
1957 fl_set_button(form->in1, (wtype == 2));
1958 fl_set_button(form->page1, (wtype == 3));
1959 fl_set_button(form->column1, (wtype == 4));
1961 fl_deactivate_object(form->Width);
1963 fl_activate_object(form->Width);
1966 // enable and disable should be put here.
1968 fl_set_button(form->Default2, (htype == 0));
1969 fl_set_button(form->cm2, (htype == 1));
1970 fl_set_button(form->in2, (htype == 2));
1971 fl_set_button(form->page2, (htype == 3));
1972 // enable and disable should be put here.
1974 fl_deactivate_object(form->Height);
1976 fl_activate_object(form->Height);
1979 int pflags = flags & 3;
1980 fl_set_button(form->Wysiwyg0, (pflags == 0));
1981 fl_set_button(form->Wysiwyg1, (pflags == 1));
1982 fl_set_button(form->Wysiwyg2, (pflags == 2));
1983 fl_set_button(form->Wysiwyg3, (pflags == 3));
1984 fl_set_button(form->Frame, ((flags & 4) != 0));
1985 fl_set_button(form->Translations, ((flags & 8) != 0));
1986 fl_set_button(form->Subfigure, (subfigure != 0));
1988 psubfigure = subfigure;
1989 sprintf(buf, "%g", xwid);
1990 fl_set_input(form->Width, buf);
1991 sprintf(buf, "%g", xhgh);
1992 fl_set_input(form->Height, buf);
1993 sprintf(buf, "%g", angle);
1994 fl_set_input(form->Angle, buf);
1995 if (!fname.empty()){
1996 string buf1 = OnlyPath(owner->fileName());
1997 string fname2 = MakeRelPath(fname, buf1);
1998 fl_set_input(form->EpsFile, fname2.c_str());
2000 else fl_set_input(form->EpsFile, "");
2001 fl_set_input(form->Subcaption, subcaption.c_str());
2002 if(current_view->buffer()->isReadonly())
2003 DisableFigurePanel(form);
2009 void InsetFig::Preview(char const * p)
2014 lyxerr << "Cannot fork process!" << endl;
2019 return; // parent process
2022 string buf1 = OnlyPath(owner->fileName());
2023 string buf2 = MakeAbsPath(p, buf1);
2025 lyxerr << "Error during rendering "
2026 << execlp(lyxrc.view_pspic_command.c_str(),
2027 lyxrc.view_pspic_command.c_str(),
2034 void InsetFig::BrowseFile()
2036 static string current_figure_path;
2037 static int once = 0;
2040 if (lyxerr.debugging()) {
2041 lyxerr << "Filename: "
2042 << owner->fileName() << endl;
2044 string p = fl_get_input(form->EpsFile);
2046 string buf = MakeAbsPath(owner->fileName());
2047 string buf2 = OnlyPath(buf);
2049 buf = MakeAbsPath(p, buf2);
2050 buf = OnlyPath(buf);
2052 buf = OnlyPath(owner->fileName().c_str());
2055 // Does user clipart directory exist?
2056 string bufclip = AddName (user_lyxdir, "clipart");
2057 FileInfo fileInfo(bufclip);
2058 if (!(fileInfo.isOK() && fileInfo.isDir()))
2059 // No - bail out to system clipart directory
2060 bufclip = AddName (system_lyxdir, "clipart");
2063 fileDlg.SetButton(0, _("Clipart"), bufclip);
2064 fileDlg.SetButton(1, _("Document"), buf);
2068 ProhibitInput(current_view);
2070 p = fileDlg.Select(_("EPS Figure"),
2071 current_figure_path,
2074 p = fileDlg.Select(_("EPS Figure"), buf,
2077 AllowInput(current_view);
2079 if (p.empty()) return;
2081 buf = MakeRelPath(p, buf2);
2082 current_figure_path = OnlyPath(p);
2085 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2086 || contains(p, "%") || contains(p, " "))
2088 WriteAlert(_("Filename can't contain any "
2089 "of these characters:"),
2090 // xgettext:no-c-format
2091 _("space, '#', '~', '$' or '%'."));
2096 if (form) fl_set_input(form->EpsFile, buf.c_str());
2100 void GraphicsCB(FL_OBJECT * obj, long arg)
2102 /* obj->form contains the form */
2104 if (lyxerr.debugging()) {
2105 lyxerr << "GraphicsCB callback: " << arg << endl;
2108 /* find inset we were reacting to */
2109 for (figures_type::iterator it = figures.begin();
2110 it != figures.end(); ++it)
2111 if ((*it)->inset->form && (*it)->inset->form->Figure
2113 if (lyxerr.debugging()) {
2114 lyxerr << "Calling back figure "
2117 (*it)->inset->CallbackFig(arg);
2123 void HideFiguresPopups()
2125 for (figures_type::iterator it = figures.begin();
2126 it != figures.end(); ++it)
2127 if ((*it)->inset->form
2128 && (*it)->inset->form->Figure->visible) {
2129 if (lyxerr.debugging()) {
2130 lyxerr << "Hiding figure " << (*it) << endl;
2132 // hide and free the form
2133 (*it)->inset->CallbackFig(9);