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"
76 using std::ostringstream;
79 extern BufferView * current_view;
80 extern FL_OBJECT * figinset_canvas;
82 extern char ** environ; // is this only redundtant on linux systems? Lgb.
84 static float const DEG2PI = 57.295779513;
86 struct queue_element {
87 float rx, ry; // resolution x and y
88 int ofsx, ofsy; // x and y translation
89 figdata * data; // we are doing it for this data
92 static int const MAXGS = 3; /* maximum 3 gs's at a time */
94 typedef vector<Figref *> figures_type;
95 typedef vector<figdata *> bitmaps_type;
96 static figures_type figures; // all figures
97 static bitmaps_type bitmaps; // all bitmaps
99 static queue<queue_element> gsqueue; // queue for ghostscripting
101 static int gsrunning = 0; /* currently so many gs's are running */
102 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
103 static char bittable[256]; /* bit reversion table */
105 static bool gs_color; // do we allocate colors for gs?
106 static bool color_visual; // is the visual color?
107 static bool gs_xcolor = false; // allocated extended colors
108 static unsigned long gs_pixels[128]; // allocated pixels
109 static int gs_num_pixels; // number of pixels allocated
110 static int gs_spc; // shades per color
111 static bool gs_gray; // is grayscale?
112 static int gs_allcolors; // number of all colors
114 static list<int> pidwaitlist; // pid wait list
120 val.foreground = BlackPixel(fl_display,
121 DefaultScreen(fl_display));
124 val.graphics_exposures = false;
125 val.line_style = LineSolid;
127 return XCreateGC(fl_display, RootWindow(fl_display, 0),
128 GCForeground | GCFunction | GCGraphicsExposures
129 | GCLineWidth | GCLineStyle , &val);
137 void addpidwait(int pid)
139 // adds pid to pid wait list
140 pidwaitlist.push_back(pid);
142 if (lyxerr.debugging()) {
143 lyxerr << "Pids to wait for: \n";
144 for (list<int>::const_iterator cit = pidwaitlist.begin();
145 cit != pidwaitlist.end(); ++cit) {
146 lyxerr << (*cit) << '\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 unlink(make_tmp(pid).c_str());
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;
201 int spc1 = gs_spc - 1;
202 int spc2 = gs_spc * gs_spc;
206 GC gc = local_gc_copy;
208 XGetWindowAttributes(fl_display,
213 if (lyxerr.debugging()) {
214 lyxerr << "Starting image translation "
217 << p->wid << "x" << p->hgh
219 << " " << XYPixmap << endl;
221 // now fork rendering process
223 if (forkstat == -1) {
225 << "Cannot fork, using slow "
226 "method for pixmap translation." << endl;
227 tmpdisp = fl_display;
228 } else if (forkstat > 0) { // parent
230 if (lyxerr.debugging()) {
231 lyxerr << "Spawned child "
234 addpidwait(forkstat);
237 tmpdisp = XOpenDisplay(XDisplayName(0));
240 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
241 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
243 if (lyxerr.debugging()) {
244 lyxerr << "Got the image" << endl;
247 if (lyxerr.debugging()) {
248 lyxerr << "Error getting the image" << endl;
253 // query current colormap
254 XColor * cmap = new XColor[gs_allcolors];
255 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
256 XQueryColors(tmpdisp,
257 fl_state[fl_get_vclass()]
262 // now we process all the image
263 for (y = 0; y < p->hgh; ++y) {
264 for (int x = 0; x < wid; ++x) {
269 gs_pixels[((pc->red+6553)*
270 spc1/65535)*spc2+((pc->green+6553)*
271 spc1/65535)*gs_spc+((pc->blue+6553)*
276 // This must be correct.
278 if (lyxerr.debugging()) {
279 lyxerr << "Putting image back"
282 XPutImage(tmpdisp, p->bitmap,
284 0, 0, p->wid, p->hgh);
286 if (lyxerr.debugging()) {
287 lyxerr << "Done translation"
292 kill_gs(p->gspid, SIGHUP);
294 XCloseDisplay(tmpdisp);
298 kill_gs(p->gspid, SIGHUP);
307 void AllocColors(int num)
308 // allocate color cube numxnumxnum, if possible
310 if (lyxerr.debugging()) {
311 lyxerr << "Allocating color cube " << num
312 << 'x' << num << 'x' << num << endl;
316 lyxerr << "Error allocating color colormap." << endl;
320 if (num > 5) num = 5;
322 for (int i = 0; i < num * num * num; ++i) {
323 xcol.red = 65535 * (i / (num * num)) / (num - 1);
324 xcol.green = 65535 * ((i / num) % num) / (num - 1);
325 xcol.blue = 65535 * (i % num) / (num - 1);
326 xcol.flags = DoRed | DoGreen | DoBlue;
327 if (!XAllocColor(fl_display,
328 fl_state[fl_get_vclass()].colormap, &xcol)) {
329 if (i) XFreeColors(fl_display,
330 fl_state[fl_get_vclass()].colormap,
332 if(lyxerr.debugging()) {
333 lyxerr << "Cannot allocate color cube "
336 AllocColors(num - 1);
339 gs_pixels[i] = xcol.pixel;
344 gs_num_pixels = num * num * num;
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 = 65535 * i / (num - 1);
366 xcol.flags = DoRed | DoGreen | DoBlue;
367 if (!XAllocColor(fl_display,
368 fl_state[fl_get_vclass()].colormap, &xcol)) {
369 if (i) XFreeColors(fl_display,
370 fl_state[fl_get_vclass()].colormap,
372 if (lyxerr.debugging()) {
373 lyxerr << "Cannot allocate grayscale "
379 gs_pixels[i] = xcol.pixel;
390 // if bitmaps and figures are not empty we will leak mem
395 for (unsigned int i = 0; i < 256; ++i) {
397 for (unsigned int j = 0; j < 8; ++j)
398 if (i & (1 << (7-j))) k |= 1 << j;
399 bittable[i] = char(~k);
402 // allocate color cube on pseudo-color display
406 fl_add_canvas_handler(figinset_canvas, ClientMessage,
408 current_view->owner()->getMainForm());
410 local_gc_copy = createGC();
412 Visual * vi = DefaultVisual(fl_display,
413 DefaultScreen(fl_display));
414 if (lyxerr.debugging()) {
415 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
416 vi->visualid, vi->c_class,
417 vi->bits_per_rgb, vi->map_entries);
419 color_visual = ( (vi->c_class == StaticColor) ||
420 (vi->c_class == PseudoColor) ||
421 (vi->c_class == TrueColor) ||
422 (vi->c_class == DirectColor) );
423 if ((vi->c_class & 1) == 0) return;
424 // now allocate colors
425 if (vi->c_class == GrayScale) {
426 // allocate grayscale
427 AllocGrays(vi->map_entries/2);
429 // allocate normal color
431 while (i * i * i * 2 > vi->map_entries) --i;
434 gs_allcolors = vi->map_entries;
442 // if bitmaps and figures are not empty we will leak mem
446 lyxerr.debug() << "Unregistering figures..." << endl;
448 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
454 void freefigdata(figdata * tmpdata)
457 if (tmpdata->ref) return;
459 if (tmpdata->gspid > 0) {
460 int pid = tmpdata->gspid;
461 // kill ghostscript and unlink it's files
463 kill_gs(pid, SIGKILL);
466 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
467 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
475 // This _have_ to be set before the fork!
476 unsigned long background_pixel =
477 lyxColorHandler->colorPixel(LColor::background);
479 // run queued requests for ghostscript, if any
480 if (!gsrunning && gs_color && !gs_xcolor) {
481 // here alloc all colors, so that gs will use only
482 // those we allocated for it
487 while (gsrunning < MAXGS) {
488 //char tbuf[384]; //, tbuf2[80];
492 if (gsqueue.empty()) {
493 if (!gsrunning && gs_xcolor) {
494 // de-allocate rest of colors
500 queue_element * p = &gsqueue.front();
509 if (lyxerr.debugging()) {
510 lyxerr << "GS start error! Cannot fork."
513 p->data->broken = true;
514 p->data->reading = false;
517 if (pid == 0) { // child
520 Display * tempdisp = XOpenDisplay(XDisplayName(0));
522 // create translation file
524 ofs.open(make_tmp(getpid()).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
545 ostrstream t2(tbuf2, sizeof(tbuf2));
547 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
548 << ' ' << p->data->bitmap;
552 // now set up ghostview property on a window
553 // #warning BUG seems that the only bug here
554 // might be the hardcoded dpi.. Bummer!
559 ostrstream t1(tbuf, sizeof(tbuf));
561 t1 << "0 0 0 0 " << p->data->wid << ' '
562 << p->data->hgh << " 72 72 0 0 0 0";
567 if (lyxerr.debugging()) {
568 lyxerr << "Will set GHOSTVIEW property to ["
569 << t1.str() << "]" << endl;
571 // wait until property is deleted if executing multiple
573 XGrabServer(tempdisp);
575 // grab server to prevent other child
576 // interfering with setting GHOSTVIEW property
577 // The grabbing goes on for too long, is it
578 // really needed? (Lgb)
579 // I moved most of the grabs... (Lgb)
580 if (lyxerr.debugging()) {
581 lyxerr << "Grabbing the server"
584 prop = XListProperties(tempdisp,
586 figinset_canvas), &nprop);
590 for (i = 0; i < nprop; ++i) {
591 char * p = XGetAtomName(tempdisp,
593 if (strcmp(p, "GHOSTVIEW") == 0) {
599 XFree(reinterpret_cast<char *>(prop)); // jc:
601 // ok, property found, we must wait until
602 // ghostscript deletes it
603 if (lyxerr.debugging()) {
604 lyxerr << "Releasing the server\n["
606 << "] GHOSTVIEW property"
607 " found. Waiting." << endl;
609 XUngrabServer(tempdisp);
612 XGrabServer(tempdisp);
615 XChangeProperty(tempdisp,
616 fl_get_canvas_id(figinset_canvas),
617 XInternAtom(tempdisp, "GHOSTVIEW", false),
618 XInternAtom(tempdisp, "STRING", false),
620 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
624 XChangeProperty(tempdisp,
625 fl_get_canvas_id(figinset_canvas),
626 XInternAtom(tempdisp, "GHOSTVIEW", false),
627 XInternAtom(tempdisp, "STRING", false),
629 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str())),
632 XUngrabServer(tempdisp);
639 ostrstream t3(tbuf, sizeof(tbuf));
641 switch (p->data->flags & 3) {
642 case 0: t3 << 'H'; break; // Hidden
643 case 1: t3 << 'M'; break; // Mono
644 case 2: t3 << 'G'; break; // Gray
653 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
654 << ' ' << background_pixel;
659 XGrabServer(tempdisp);
661 XChangeProperty(tempdisp,
662 fl_get_canvas_id(figinset_canvas),
663 XInternAtom(tempdisp,
664 "GHOSTVIEW_COLORS", false),
665 XInternAtom(tempdisp, "STRING", false),
667 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
670 XChangeProperty(tempdisp,
671 fl_get_canvas_id(figinset_canvas),
672 XInternAtom(tempdisp,
673 "GHOSTVIEW_COLORS", false),
674 XInternAtom(tempdisp, "STRING", false),
676 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str())),
679 XUngrabServer(tempdisp);
682 if (lyxerr.debugging()) {
683 lyxerr << "Releasing the server" << endl;
685 XCloseDisplay(tempdisp);
687 // set up environment
690 typedef char * char_p;
691 env = new char_p[ne + 2];
693 string tmp = t2.str().c_str();
694 env[0] = new char[tmp.size() + 1];
695 std::copy(tmp.begin(), tmp.end(), env[0]);
696 env[0][tmp.size()] = '\0';
700 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
703 // now make gs command
705 // close(1); do NOT close. If GS writes out
706 // errors it would hang. (Matthias 290596)
708 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
709 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
711 // now chdir into dir with .eps file, to be on the safe
713 ::chdir(OnlyPath(p->data->fname).c_str());
714 // make temp file name
715 string tmpf = make_tmp(getpid());
716 if (lyxerr.debugging()) {
717 lyxerr << "starting gs " << tmpf << " "
719 << ", pid: " << getpid() << endl;
722 int err = ::execlp(lyxrc.ps_command.c_str(),
723 lyxrc.ps_command.c_str(),
725 "-dNOPAUSE", "-dQUIET",
727 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
728 p->data->fname.c_str(),
729 "showpage.ps", "quit.ps", "-", 0);
730 // if we are still there, an error occurred.
731 lyxerr << "Error executing ghostscript. "
732 << "Code: " << err << endl;
733 lyxerr.debug() << "Cmd: "
736 << tmpf.c_str() << ' '
737 << p->data->fname << endl;
740 // normal process (parent)
741 if (lyxerr.debugging()) {
742 lyxerr << "GS [" << pid << "] started" << endl;
745 p->data->gspid = pid;
753 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
755 // recompute the stuff and put in the queue
759 p.rx = (float(data->raw_wid) * 72.0) / pswid;
760 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
766 // if possible, run the queue
772 figdata * getfigdata(int wid, int hgh, string const & fname,
773 int psx, int psy, int pswid, int pshgh,
774 int raw_wid, int raw_hgh, float angle, char flags)
776 /* first search for an exact match with fname and width/height */
778 if (fname.empty()) return 0;
780 for (bitmaps_type::iterator it = bitmaps.begin();
781 it != bitmaps.end(); ++it) {
782 if ((*it)->wid == wid && (*it)->hgh == hgh &&
783 (*it)->flags == flags && (*it)->fname == fname &&
784 (*it)->angle == angle) {
789 figdata * p = new figdata;
792 p->raw_wid = raw_wid;
793 p->raw_hgh = raw_hgh;
797 bitmaps.push_back(p);
798 XWindowAttributes wa;
799 XGetWindowAttributes(fl_display, fl_get_canvas_id(
800 figinset_canvas), &wa);
802 if (lyxerr.debugging()) {
803 lyxerr << "Create pixmap disp:" << fl_display
804 << " scr:" << DefaultScreen(fl_display)
807 << " depth:" << wa.depth << endl;
815 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
816 figinset_canvas), wid, hgh, wa.depth);
818 // initialize reading of .eps file with correct sizes and stuff
819 addwait(psx, psy, pswid, pshgh, p);
831 void getbitmap(figdata * p)
838 void makeupdatelist(figdata * p)
840 for(figures_type::iterator it = figures.begin();
841 it != figures.end(); ++it)
842 if ((*it)->data == p) {
843 if (lyxerr.debugging()) {
844 lyxerr << "Updating inset "
848 // add inset figures[i]->inset into to_update list
849 current_view->pushIntoUpdateList((*it)->inset);
854 // this func is only "called" in spellchecker.C
855 void sigchldchecker(pid_t pid, int * status)
857 lyxerr.debug() << "Got pid = " << pid << endl;
858 bool pid_handled = false;
859 for (bitmaps_type::iterator it = bitmaps.begin();
860 it != bitmaps.end(); ++it) {
861 if ((*it)->reading && pid == (*it)->gspid) {
862 lyxerr.debug() << "Found pid in bitmaps" << endl;
863 // now read the file and remove it from disk
866 if ((*it)->gsdone) *status = 0;
868 lyxerr.debug() << "GS [" << pid
869 << "] exit OK." << endl;
871 lyxerr << "GS [" << pid << "] error "
873 << WIFEXITED(*status)
874 << " " << WEXITSTATUS(*status)
875 << " S:" << WIFSIGNALED(*status)
876 << " " << WTERMSIG(*status) << endl;
879 bitmap_waiting = true;
882 // remove temporary files
883 unlink(make_tmp(p->gspid).c_str());
887 makeupdatelist((*it));
894 lyxerr.debug() << "Checking pid in pidwait" << endl;
895 list<int>::iterator it = find(pidwaitlist.begin(),
896 pidwaitlist.end(), pid);
897 if (it != pidwaitlist.end()) {
898 lyxerr.debug() << "Found pid in pidwait\n"
899 << "Caught child pid of recompute "
900 "routine" << pid << endl;
901 pidwaitlist.erase(it);
905 lyxerr.debug() << "waitpid error" << endl;
908 lyxerr << "The process or process group specified by "
909 "pid does not exist or is not a child of "
910 "the calling process or can never be in the "
911 "states specified by options." << endl;
914 lyxerr << "waitpid() was interrupted due to the "
915 "receipt of a signal sent by the calling "
919 lyxerr << "An invalid value was specified for "
923 lyxerr << "Unknown error from waitpid" << endl;
926 } else if (pid == 0) {
927 lyxerr << "waitpid nohang" << endl;;
929 lyxerr.debug() << "normal exit from childhandler" << endl;
937 bitmap_waiting = false;
938 for (bitmaps_type::iterator it = bitmaps.begin();
939 it != bitmaps.end(); ++it)
940 if ((*it)->gspid > 0 && !(*it)->reading)
946 void RegisterFigure(InsetFig * fi)
948 if (figures.empty()) InitFigures();
950 Figref * tmpfig = new Figref;
953 figures.push_back(tmpfig);
956 if (lyxerr.debugging()) {
957 lyxerr << "Register Figure: buffer:["
958 << current_view->buffer() << "]" << endl;
964 void UnregisterFigure(InsetFig * fi)
966 Figref * tmpfig = fi->figure;
968 if (tmpfig->data) freefigdata(tmpfig->data);
969 if (tmpfig->inset->form) {
970 if (tmpfig->inset->form->Figure->visible) {
971 fl_set_focus_object(tmpfig->inset->form->Figure,
972 tmpfig->inset->form->OkBtn);
973 fl_hide_form(tmpfig->inset->form->Figure);
975 #if FL_REVISION == 89
976 // CHECK Reactivate this free_form calls
978 fl_free_form(tmpfig->inset->form->Figure);
979 free(tmpfig->inset->form); // Why free?
980 tmpfig->inset->form = 0;
983 figures.erase(find(figures.begin(), figures.end(), tmpfig));
986 if (figures.empty()) DoneFigures();
990 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
1000 psubfigure = subfigure = false;
1001 xwid = xhgh = angle = 0;
1003 raw_wid = raw_hgh = 0;
1004 changedfname = false;
1005 RegisterFigure(this);
1009 InsetFig::~InsetFig()
1011 if (lyxerr.debugging()) {
1012 lyxerr << "Figure destructor called" << endl;
1014 UnregisterFigure(this);
1018 int InsetFig::ascent(Painter &, LyXFont const &) const
1024 int InsetFig::descent(Painter &, LyXFont const &) const
1030 int InsetFig::width(Painter &, LyXFont const &) const
1036 void InsetFig::draw(Painter & pain, LyXFont const & f,
1037 int baseline, float & x) const
1041 if (bitmap_waiting) getbitmaps();
1043 // I wish that I didn't have to use this
1044 // but the figinset code is so complicated so
1045 // I don't want to fiddle with it now.
1047 if (figure && figure->data && figure->data->bitmap &&
1048 !figure->data->reading && !figure->data->broken) {
1050 pain.pixmap(int(x + 1), baseline - hgh,
1051 wid, hgh, figure->data->bitmap);
1054 pain.rectangle(int(x), baseline - hgh - 1,
1060 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1062 if (figure && figure->data) {
1063 if (figure->data->broken) msg = _("[render error]");
1064 else if (figure->data->reading) msg = _("[rendering ... ]");
1066 if (fname.empty()) msg = _("[no file]");
1067 else if ((flags & 3) == 0) msg = _("[not displayed]");
1068 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1070 if (!msg) msg = _("[unknown error]");
1072 font.setFamily(LyXFont::SANS_FAMILY);
1073 font.setSize(LyXFont::SIZE_FOOTNOTE);
1074 string justname = OnlyFilename (fname);
1075 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1078 font.setSize(LyXFont::SIZE_TINY);
1079 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1081 x += width(pain, font); // ?
1085 void InsetFig::Write(ostream & os) const
1088 os << "Figure size " << wid << " " << hgh << "\n";
1089 if (!fname.empty()) {
1090 string buf1 = OnlyPath(owner->fileName());
1091 string fname2 = MakeRelPath(fname, buf1);
1092 os << "file " << fname2 << "\n";
1094 if (!subcaption.empty())
1095 os << "subcaption " << subcaption << "\n";
1096 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1097 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1098 if (angle != 0) os << "angle " << angle << "\n";
1099 os << "flags " << flags << "\n";
1100 if (subfigure) os << "subfigure\n";
1104 void InsetFig::Read(LyXLex & lex)
1107 bool finished = false;
1109 while (lex.IsOK() && !finished) {
1112 string const token = lex.GetString();
1113 lyxerr.debug() << "Token: " << token << endl;
1117 else if (token == "\\end_inset") {
1119 } else if (token == "file") {
1121 buf = lex.GetString();
1122 string buf1 = OnlyPath(owner->fileName());
1123 fname = MakeAbsPath(buf, buf1);
1124 changedfname = true;
1126 } else if (token == "extra") {
1128 // kept for backwards compability. Delete in 0.13.x
1129 } else if (token == "subcaption") {
1131 subcaption = lex.GetString();
1132 } else if (token == "label") {
1134 // kept for backwards compability. Delete in 0.13.x
1135 } else if (token == "angle") {
1137 angle = lex.GetFloat();
1138 } else if (token == "size") {
1140 wid = lex.GetInteger();
1142 hgh = lex.GetInteger();
1143 } else if (token == "flags") {
1145 flags = pflags = lex.GetInteger();
1146 } else if (token == "subfigure") {
1147 subfigure = psubfigure = true;
1148 } else if (token == "width") {
1151 typ = lex.GetInteger();
1153 xwid = lex.GetFloat();
1155 case DEF: wtype = DEF; break;
1156 case CM: wtype = CM; break;
1157 case IN: wtype = IN; break;
1158 case PER_PAGE: wtype = PER_PAGE; break;
1159 case PER_COL: wtype = PER_COL; break;
1161 lyxerr.debug() << "Unknown type!" << endl;
1165 } else if (token == "height") {
1168 typ = lex.GetInteger();
1170 xhgh = lex.GetFloat();
1172 case DEF: htype = DEF; break;
1173 case CM: htype = CM; break;
1174 case IN: htype = IN; break;
1175 case PER_PAGE: htype = PER_PAGE; break;
1177 lyxerr.debug() << "Unknown type!" << endl;
1188 int InsetFig::Latex(ostream & os,
1189 bool /* fragile*/, bool /* fs*/) const
1192 if (!cmd.empty()) os << cmd << " ";
1197 int InsetFig::Ascii(ostream &) const
1203 int InsetFig::Linuxdoc(ostream &) const
1209 int InsetFig::DocBook(ostream & os) const
1211 string figurename = fname;
1213 if(suffixIs(figurename, ".eps"))
1214 figurename.erase(fname.length() - 4);
1216 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1221 void InsetFig::Validate(LaTeXFeatures & features) const
1223 features.graphics = true;
1224 if (subfigure) features.subfigure = true;
1228 Inset::EDITABLE InsetFig::Editable() const
1234 bool InsetFig::Deletable() const
1240 char const * InsetFig::EditMessage() const
1242 return _("Opened figure");
1246 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1248 lyxerr.debug() << "Editing InsetFig." << endl;
1251 // We should have RO-versions of the form instead.
1252 // The actual prevention of altering a readonly doc
1253 // is done in CallbackFig()
1254 if(bv->buffer()->isReadonly())
1255 WarnReadonly(bv->buffer()->fileName());
1258 form = create_form_Figure();
1259 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1260 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1261 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1262 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1265 if (form->Figure->visible) {
1266 fl_raise_form(form->Figure);
1268 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1269 FL_FULLBORDER, _("Figure"));
1274 Inset * InsetFig::Clone() const
1276 InsetFig * tmp = new InsetFig(100, 100, owner);
1278 if (lyxerr.debugging()) {
1279 lyxerr << "Clone Figure: buffer:["
1280 << current_view->buffer()
1281 << "], cbuffer:[xx]" << endl;
1286 tmp->raw_wid = raw_wid;
1287 tmp->raw_hgh = raw_hgh;
1292 tmp->pflags = pflags;
1293 tmp->subfigure = subfigure;
1294 tmp->psubfigure = psubfigure;
1302 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1304 // do not display if there is
1305 // "do not display" chosen (Matthias 260696)
1306 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1307 pswid, pshgh, raw_wid, raw_hgh,
1308 angle, flags & (3|8));
1309 } else tmp->figure->data = 0;
1310 tmp->subcaption = subcaption;
1311 tmp->changedfname = false;
1318 Inset::Code InsetFig::LyxCode() const
1320 return Inset::GRAPHICS_CODE;
1325 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1331 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1332 res = tostr(f) + "cm";
1335 res = tostr(f) + "in";
1337 case InsetFig::PER_PAGE:
1338 res = tostr(f/100) + "\\text" + suffix;
1340 case InsetFig::PER_COL:
1341 // Doesn't occur for htype...
1342 res = tostr(f/100) + "\\column" + suffix;
1349 void InsetFig::Regenerate() const
1352 string resizeW, resizeH;
1353 string rotate, recmd;
1355 if (fname.empty()) {
1356 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1357 cmd += _("empty figure path");
1362 string buf1 = OnlyPath(owner->fileName());
1363 string fname2 = MakeRelPath(fname, buf1);
1365 string gcmd = "\\includegraphics{" + fname2 + '}';
1366 resizeW = stringify(wtype, xwid, "width");
1367 resizeH = stringify(htype, xhgh, "height");
1369 if (!resizeW.empty() || !resizeH.empty()) {
1370 recmd = "\\resizebox*{";
1371 if (!resizeW.empty())
1376 if (!resizeH.empty())
1385 // \rotatebox{angle}{text}
1386 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1392 if (!rotate.empty()) cmdbuf += '}';
1393 if (!recmd.empty()) cmdbuf += '}';
1395 if (!subcaption.empty())
1396 cmdbuf = "\\subfigure[" + subcaption +
1397 "]{" + cmdbuf + "}";
1399 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1406 void InsetFig::TempRegenerate()
1409 string resizeW, resizeH;
1410 string rotate, recmd;
1412 char const * tfname = fl_get_input(form->EpsFile);
1413 string tsubcap = fl_get_input(form->Subcaption);
1414 float tangle = atof(fl_get_input(form->Angle));
1415 float txwid = atof(fl_get_input(form->Width));
1416 float txhgh = atof(fl_get_input(form->Height));
1418 if (!tfname || !*tfname) {
1419 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1420 cmd += _("empty figure path");
1425 string buf1 = OnlyPath(owner->fileName());
1426 string fname2 = MakeRelPath(tfname, buf1);
1427 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1428 string gcmd = "\\includegraphics{" + fname2 + '}';
1430 resizeW = stringify(twtype, txwid, "width");
1431 resizeH = stringify(thtype, txhgh, "height");
1433 // \resizebox*{h-length}{v-length}{text}
1434 if (!resizeW.empty() || !resizeH.empty()) {
1435 recmd = "\\resizebox*{";
1436 if (!resizeW.empty())
1441 if (!resizeH.empty())
1449 // \rotatebox{angle}{text}
1450 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1453 cmdbuf = recmd + rotate + gcmd;
1454 if (!rotate.empty()) cmdbuf += '}';
1455 if (!recmd.empty()) cmdbuf += '}';
1456 if (psubfigure && !tsubcap.empty()) {
1457 cmdbuf = string("\\subfigure{") + tsubcap
1458 + string("}{") + cmdbuf + "}";
1463 void InsetFig::Recompute()
1465 bool changed = changedfname;
1466 int newx, newy, nraw_x, nraw_y;
1468 if (changed) GetPSSizes();
1470 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1471 float cos_a = cos (angle / DEG2PI);
1472 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1473 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1475 /* now recompute wid and hgh, and if that is changed, set changed */
1476 /* this depends on chosen size of the picture and its bbox */
1477 // This will be redone in 0.13 ... (hen)
1478 if (!fname.empty()) {
1479 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1487 newx = int(28.346 * xwid);
1490 newx = int(72 * xwid);
1492 case PER_PAGE: /* % of page */
1493 newx = int(5.95 * xwid);
1495 case PER_COL: /* % of col */
1496 newx = int(2.975 * xwid);
1500 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1504 //lyxerr << "This should not happen!" << endl;
1507 newy = int(28.346 * xhgh);
1510 newy = int(72 * xhgh);
1512 case PER_PAGE: /* % of page */
1513 newy = int(8.42 * xhgh);
1516 // Doesn't occur; case exists to suppress
1517 // compiler warnings.
1520 if (htype && !wtype && frame_hgh)
1521 newx = newy*frame_wid/frame_hgh;
1530 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1535 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1537 // cannot be zero, actually, set it to some minimum, so its clickable
1538 if (newx < 5) newx = 5;
1539 if (newy < 5) newy = 5;
1541 if (newx != wid || newy != hgh ||
1542 nraw_x != raw_wid || nraw_y != raw_hgh ||
1543 flags != pflags || subfigure != psubfigure)
1551 subfigure = psubfigure;
1554 figdata * pf = figure->data;
1557 if (!fname.empty() && (flags & 3)
1558 && !lyxrc.ps_command.empty()) {
1559 // do not display if there is "do not display"
1560 // chosen (Matthias 260696)
1561 figure->data = getfigdata(wid, hgh, fname,
1562 psx, psy, pswid, pshgh,
1564 angle, flags & (3|8));
1565 } else figure->data = 0;
1567 // free the old data
1568 if (pf) freefigdata(pf);
1571 changedfname = false;
1575 void InsetFig::GetPSSizes()
1577 /* get %%BoundingBox: from postscript file */
1579 /* defaults to associated size
1580 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1587 if (fname.empty()) return;
1589 ifstream ifs(fname.c_str());
1591 if (!ifs) return; // file not found !!!!
1593 /* defaults to A4 page */
1599 char lastchar = 0; ifs.get(lastchar);
1601 char c = 0; ifs.get(c);
1603 lyxerr.debug() << "End of (E)PS file reached and"
1604 " no BoundingBox!" << endl;
1607 if (c == '%' && lastchar == '%') {
1609 if (p.empty()) break;
1610 lyxerr.debug() << "Token: `" << p << "'" << endl;
1611 if (p == "BoundingBox:") {
1612 float fpsx, fpsy, fpswid, fpshgh;
1613 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1616 pswid = int(fpswid);
1617 pshgh = int(fpshgh);
1619 if (lyxerr.debugging()) {
1620 lyxerr << "%%%%BoundingBox:"
1638 void InsetFig::CallbackFig(long arg)
1643 if (lyxerr.debugging()) {
1644 lyxerr << "Figure callback, arg " << arg << endl;
1650 case 12: /* width type */
1657 fl_deactivate_object(form->Width);
1662 fl_activate_object(form->Width);
1667 fl_activate_object(form->Width);
1672 fl_activate_object(form->Width);
1677 fl_activate_object(form->Width);
1680 lyxerr.debug() << "Unknown type!" << endl;
1687 case 22: /* height type */
1693 fl_deactivate_object(form->Height);
1698 fl_activate_object(form->Height);
1703 fl_activate_object(form->Height);
1708 fl_activate_object(form->Height);
1711 lyxerr.debug() << "Unknown type!" << endl;
1717 pflags = pflags & ~3; /* wysiwyg0 */
1720 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1723 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1726 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1729 pflags ^= 4; /* frame */
1732 pflags ^= 8; /* do translations */
1735 psubfigure = !psubfigure; /* This is a subfigure */
1738 regen = true; /* regenerate command */
1740 case 0: /* browse file */
1744 case 1: /* preview */
1745 p = fl_get_input(form->EpsFile);
1749 case 8: /* ok (apply and close) */
1750 if(!current_view->buffer()->isReadonly()) {
1753 xwid = atof(fl_get_input(form->Width));
1754 xhgh = atof(fl_get_input(form->Height));
1755 angle = atof(fl_get_input(form->Angle));
1756 p = fl_get_input(form->EpsFile);
1758 string buf1 = OnlyPath(owner->fileName());
1759 fname = MakeAbsPath(p, buf1);
1760 changedfname = true;
1762 if (!fname.empty()) {
1763 changedfname = true;
1767 subcaption = fl_get_input(form->Subcaption);
1771 /* now update inset */
1772 if (lyxerr.debugging()) {
1773 lyxerr << "Update: ["
1774 << wid << 'x' << hgh << ']' << endl;
1776 current_view->updateInset(this, true);
1778 fl_set_focus_object(form->Figure, form->OkBtn);
1779 fl_hide_form(form->Figure);
1780 #if FL_REVISION == 89
1781 // CHECK Reactivate this free_form calls
1783 fl_free_form(form->Figure);
1784 free(form); // Why free?
1790 // The user has already been informed about RO in ::Edit
1791 if(arg == 7) // if 'Apply'
1794 case 9: /* cancel = restore and close */
1795 fl_set_focus_object(form->Figure, form->OkBtn);
1796 fl_hide_form(form->Figure);
1797 #if FL_REVISION == 89
1798 // CHECK Reactivate this free_form calls
1799 // Jug, is this still a problem?
1801 fl_free_form(form->Figure);
1802 free(form); // Why free?
1808 if (regen) TempRegenerate();
1813 void DisableFigurePanel(FD_Figure * const form)
1815 fl_deactivate_object(form->EpsFile);
1816 fl_deactivate_object(form->Browse);
1817 fl_deactivate_object(form->Width);
1818 fl_deactivate_object(form->Height);
1819 fl_deactivate_object(form->Frame);
1820 fl_deactivate_object(form->Translations);
1821 fl_deactivate_object(form->Angle);
1822 fl_deactivate_object(form->HeightGrp);
1823 fl_deactivate_object(form->page2);
1824 fl_deactivate_object(form->Default2);
1825 fl_deactivate_object(form->cm2);
1826 fl_deactivate_object(form->in2);
1827 fl_deactivate_object(form->HeightLabel);
1828 fl_deactivate_object(form->WidthLabel);
1829 fl_deactivate_object(form->DisplayGrp);
1830 fl_deactivate_object(form->Wysiwyg3);
1831 fl_deactivate_object(form->Wysiwyg0);
1832 fl_deactivate_object(form->Wysiwyg2);
1833 fl_deactivate_object(form->Wysiwyg1);
1834 fl_deactivate_object(form->WidthGrp);
1835 fl_deactivate_object(form->Default1);
1836 fl_deactivate_object(form->cm1);
1837 fl_deactivate_object(form->in1);
1838 fl_deactivate_object(form->page1);
1839 fl_deactivate_object(form->column1);
1840 fl_deactivate_object(form->Subcaption);
1841 fl_deactivate_object(form->Subfigure);
1842 fl_deactivate_object (form->OkBtn);
1843 fl_deactivate_object (form->ApplyBtn);
1844 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1845 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1850 void EnableFigurePanel(FD_Figure * const form)
1852 fl_activate_object(form->EpsFile);
1853 fl_activate_object(form->Browse);
1854 fl_activate_object(form->Width);
1855 fl_activate_object(form->Height);
1856 fl_activate_object(form->Frame);
1857 fl_activate_object(form->Translations);
1858 fl_activate_object(form->Angle);
1859 fl_activate_object(form->HeightGrp);
1860 fl_activate_object(form->page2);
1861 fl_activate_object(form->Default2);
1862 fl_activate_object(form->cm2);
1863 fl_activate_object(form->in2);
1864 fl_activate_object(form->HeightLabel);
1865 fl_activate_object(form->WidthLabel);
1866 fl_activate_object(form->DisplayGrp);
1867 fl_activate_object(form->Wysiwyg3);
1868 fl_activate_object(form->Wysiwyg0);
1869 fl_activate_object(form->Wysiwyg2);
1870 fl_activate_object(form->Wysiwyg1);
1871 fl_activate_object(form->WidthGrp);
1872 fl_activate_object(form->Default1);
1873 fl_activate_object(form->cm1);
1874 fl_activate_object(form->in1);
1875 fl_activate_object(form->page1);
1876 fl_activate_object(form->column1);
1877 fl_activate_object(form->Subcaption);
1878 fl_activate_object(form->Subfigure);
1879 fl_activate_object (form->OkBtn);
1880 fl_activate_object (form->ApplyBtn);
1881 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1882 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1886 void InsetFig::RestoreForm()
1888 EnableFigurePanel(form);
1891 fl_set_button(form->Default1, (wtype == 0));
1892 fl_set_button(form->cm1, (wtype == 1));
1893 fl_set_button(form->in1, (wtype == 2));
1894 fl_set_button(form->page1, (wtype == 3));
1895 fl_set_button(form->column1, (wtype == 4));
1897 fl_deactivate_object(form->Width);
1899 fl_activate_object(form->Width);
1902 // enable and disable should be put here.
1904 fl_set_button(form->Default2, (htype == 0));
1905 fl_set_button(form->cm2, (htype == 1));
1906 fl_set_button(form->in2, (htype == 2));
1907 fl_set_button(form->page2, (htype == 3));
1908 // enable and disable should be put here.
1910 fl_deactivate_object(form->Height);
1912 fl_activate_object(form->Height);
1915 int pflags = flags & 3;
1916 fl_set_button(form->Wysiwyg0, (pflags == 0));
1917 fl_set_button(form->Wysiwyg1, (pflags == 1));
1918 fl_set_button(form->Wysiwyg2, (pflags == 2));
1919 fl_set_button(form->Wysiwyg3, (pflags == 3));
1920 fl_set_button(form->Frame, ((flags & 4) != 0));
1921 fl_set_button(form->Translations, ((flags & 8) != 0));
1922 fl_set_button(form->Subfigure, (subfigure != 0));
1924 psubfigure = subfigure;
1925 fl_set_input(form->Width, tostr(xwid).c_str());
1926 fl_set_input(form->Height, tostr(xhgh).c_str());
1927 fl_set_input(form->Angle, tostr(angle).c_str());
1928 if (!fname.empty()){
1929 string buf1 = OnlyPath(owner->fileName());
1930 string fname2 = MakeRelPath(fname, buf1);
1931 fl_set_input(form->EpsFile, fname2.c_str());
1933 else fl_set_input(form->EpsFile, "");
1934 fl_set_input(form->Subcaption, subcaption.c_str());
1935 if(current_view->buffer()->isReadonly())
1936 DisableFigurePanel(form);
1942 void InsetFig::Preview(char const * p)
1947 lyxerr << "Cannot fork process!" << endl;
1952 return; // parent process
1955 string buf1 = OnlyPath(owner->fileName());
1956 string buf2 = MakeAbsPath(p, buf1);
1958 lyxerr << "Error during rendering "
1959 << execlp(lyxrc.view_pspic_command.c_str(),
1960 lyxrc.view_pspic_command.c_str(),
1967 void InsetFig::BrowseFile()
1969 static string current_figure_path;
1970 static int once = 0;
1973 if (lyxerr.debugging()) {
1974 lyxerr << "Filename: "
1975 << owner->fileName() << endl;
1977 string p = fl_get_input(form->EpsFile);
1979 string buf = MakeAbsPath(owner->fileName());
1980 string buf2 = OnlyPath(buf);
1982 buf = MakeAbsPath(p, buf2);
1983 buf = OnlyPath(buf);
1985 buf = OnlyPath(owner->fileName().c_str());
1988 // Does user clipart directory exist?
1989 string bufclip = AddName (user_lyxdir, "clipart");
1990 FileInfo fileInfo(bufclip);
1991 if (!(fileInfo.isOK() && fileInfo.isDir()))
1992 // No - bail out to system clipart directory
1993 bufclip = AddName (system_lyxdir, "clipart");
1996 fileDlg.SetButton(0, _("Clipart"), bufclip);
1997 fileDlg.SetButton(1, _("Document"), buf);
2001 ProhibitInput(current_view);
2003 p = fileDlg.Select(_("EPS Figure"),
2004 current_figure_path,
2007 p = fileDlg.Select(_("EPS Figure"), buf,
2010 AllowInput(current_view);
2012 if (p.empty()) return;
2014 buf = MakeRelPath(p, buf2);
2015 current_figure_path = OnlyPath(p);
2018 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2019 || contains(p, "%") || contains(p, " ")) {
2020 WriteAlert(_("Filename can't contain any "
2021 "of these characters:"),
2022 // xgettext:no-c-format
2023 _("space, '#', '~', '$' or '%'."));
2028 if (form) fl_set_input(form->EpsFile, buf.c_str());
2032 void GraphicsCB(FL_OBJECT * obj, long arg)
2034 /* obj->form contains the form */
2036 if (lyxerr.debugging()) {
2037 lyxerr << "GraphicsCB callback: " << arg << endl;
2040 /* find inset we were reacting to */
2041 for (figures_type::iterator it = figures.begin();
2042 it != figures.end(); ++it)
2043 if ((*it)->inset->form && (*it)->inset->form->Figure
2045 if (lyxerr.debugging()) {
2046 lyxerr << "Calling back figure "
2049 (*it)->inset->CallbackFig(arg);
2055 void HideFiguresPopups()
2057 for (figures_type::iterator it = figures.begin();
2058 it != figures.end(); ++it)
2059 if ((*it)->inset->form
2060 && (*it)->inset->form->Figure->visible) {
2061 if (lyxerr.debugging()) {
2062 lyxerr << "Hiding figure " << (*it) << endl;
2064 // hide and free the form
2065 (*it)->inset->CallbackFig(9);