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"
75 using std::ostringstream;
77 extern BufferView * current_view;
78 extern FL_OBJECT * figinset_canvas;
80 extern char ** environ; // is this only redundtant on linux systems? Lgb.
82 static float const DEG2PI = 57.295779513;
84 struct queue_element {
85 float rx, ry; // resolution x and y
86 int ofsx, ofsy; // x and y translation
87 figdata * data; // we are doing it for this data
90 static int const MAXGS = 3; /* maximum 3 gs's at a time */
92 typedef vector<Figref *> figures_type;
93 typedef vector<figdata *> bitmaps_type;
94 static figures_type figures; // all figures
95 static bitmaps_type bitmaps; // all bitmaps
97 static queue<queue_element> gsqueue; // queue for ghostscripting
99 static int gsrunning = 0; /* currently so many gs's are running */
100 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
101 static char bittable[256]; /* bit reversion table */
103 static bool gs_color; // do we allocate colors for gs?
104 static bool color_visual; // is the visual color?
105 static bool gs_xcolor = false; // allocated extended colors
106 static unsigned long gs_pixels[128]; // allocated pixels
107 static int gs_num_pixels; // number of pixels allocated
108 static int gs_spc; // shades per color
109 static bool gs_gray; // is grayscale?
110 static int gs_allcolors; // number of all colors
112 static list<int> pidwaitlist; // pid wait list
118 val.foreground = BlackPixel(fl_display,
119 DefaultScreen(fl_display));
122 val.graphics_exposures = false;
123 val.line_style = LineSolid;
125 return XCreateGC(fl_display, RootWindow(fl_display, 0),
126 GCForeground | GCFunction | GCGraphicsExposures
127 | GCLineWidth | GCLineStyle , &val);
135 void addpidwait(int pid)
137 // adds pid to pid wait list
138 pidwaitlist.push_back(pid);
140 if (lyxerr.debugging()) {
141 lyxerr << "Pids to wait for: \n";
142 for (list<int>::const_iterator cit = pidwaitlist.begin();
143 cit != pidwaitlist.end(); ++cit) {
144 lyxerr << (*cit) << '\n';
152 string make_tmp(int pid)
154 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
159 void kill_gs(int pid, int sig)
161 if (lyxerr.debugging())
162 lyxerr << "Killing gs " << pid << endl;
164 unlink(make_tmp(pid).c_str());
169 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
172 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
174 if(lyxerr.debugging()) {
175 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
176 << "] pm:[" << e->data.l[1] << "]" << endl;
179 // just kill gs, that way it will work for sure
180 // This loop looks like S**T so it probably is...
181 for (bitmaps_type::iterator it = bitmaps.begin();
182 it != bitmaps.end(); ++it)
183 if (static_cast<long>((*it)->bitmap) ==
184 static_cast<long>(e->data.l[1])) {
189 // first update p->bitmap, if necessary
190 if (p->bitmap != None
191 && p->flags > (1|8) && gs_color && p->wid) {
192 // query current colormap and re-render
193 // the pixmap with proper colors
194 XWindowAttributes wa;
195 register XImage * im;
199 int spc1 = gs_spc - 1;
200 int spc2 = gs_spc * gs_spc;
204 GC gc = local_gc_copy;
206 XGetWindowAttributes(fl_display,
211 if (lyxerr.debugging()) {
212 lyxerr << "Starting image translation "
215 << p->wid << "x" << p->hgh
217 << " " << XYPixmap << endl;
219 // now fork rendering process
221 if (forkstat == -1) {
223 << "Cannot fork, using slow "
224 "method for pixmap translation." << endl;
225 tmpdisp = fl_display;
226 } else if (forkstat > 0) { // parent
228 if (lyxerr.debugging()) {
229 lyxerr << "Spawned child "
232 addpidwait(forkstat);
235 tmpdisp = XOpenDisplay(XDisplayName(0));
238 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
239 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
241 if (lyxerr.debugging()) {
242 lyxerr << "Got the image" << endl;
245 if (lyxerr.debugging()) {
246 lyxerr << "Error getting the image" << endl;
251 // query current colormap
252 XColor * cmap = new XColor[gs_allcolors];
253 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
254 XQueryColors(tmpdisp,
255 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 = 65535 * (i / (num * num)) / (num - 1);
322 xcol.green = 65535 * ((i / num) % num) / (num - 1);
323 xcol.blue = 65535 * (i % num) / (num - 1);
324 xcol.flags = DoRed | DoGreen | DoBlue;
325 if (!XAllocColor(fl_display,
326 fl_state[fl_get_vclass()].colormap, &xcol)) {
327 if (i) XFreeColors(fl_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;
342 gs_num_pixels = num * num * num;
346 // allocate grayscale ramp
348 void AllocGrays(int num)
350 if (lyxerr.debugging()) {
351 lyxerr << "Allocating grayscale colormap "
356 lyxerr << "Error allocating grayscale colormap." << endl;
360 if (num > 128) num = 128;
362 for (int i = 0; i < num; ++i) {
363 xcol.red = xcol.green = xcol.blue = 65535 * i / (num - 1);
364 xcol.flags = DoRed | DoGreen | DoBlue;
365 if (!XAllocColor(fl_display,
366 fl_state[fl_get_vclass()].colormap, &xcol)) {
367 if (i) XFreeColors(fl_display,
368 fl_state[fl_get_vclass()].colormap,
370 if (lyxerr.debugging()) {
371 lyxerr << "Cannot allocate grayscale "
377 gs_pixels[i] = xcol.pixel;
388 // if bitmaps and figures are not empty we will leak mem
393 for (unsigned int i = 0; i < 256; ++i) {
395 for (unsigned int j = 0; j < 8; ++j)
396 if (i & (1 << (7-j))) k |= 1 << j;
397 bittable[i] = char(~k);
400 // allocate color cube on pseudo-color display
404 fl_add_canvas_handler(figinset_canvas, ClientMessage,
406 current_view->owner()->getForm());
408 local_gc_copy = createGC();
410 Visual * vi = DefaultVisual(fl_display,
411 DefaultScreen(fl_display));
412 if (lyxerr.debugging()) {
413 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
414 vi->visualid, vi->c_class,
415 vi->bits_per_rgb, vi->map_entries);
417 color_visual = ( (vi->c_class == StaticColor) ||
418 (vi->c_class == PseudoColor) ||
419 (vi->c_class == TrueColor) ||
420 (vi->c_class == DirectColor) );
421 if ((vi->c_class & 1) == 0) return;
422 // now allocate colors
423 if (vi->c_class == GrayScale) {
424 // allocate grayscale
425 AllocGrays(vi->map_entries/2);
427 // allocate normal color
429 while (i * i * i * 2 > vi->map_entries) --i;
432 gs_allcolors = vi->map_entries;
440 // if bitmaps and figures are not empty we will leak mem
444 lyxerr.debug() << "Unregistering figures..." << endl;
446 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
452 void freefigdata(figdata * tmpdata)
455 if (tmpdata->ref) return;
457 if (tmpdata->gspid > 0) {
458 int pid = tmpdata->gspid;
459 // kill ghostscript and unlink it's files
461 kill_gs(pid, SIGKILL);
464 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
465 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
473 // This _have_ to be set before the fork!
474 unsigned long background_pixel =
475 lyxColorHandler->colorPixel(LColor::background);
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
518 Display * tempdisp = XOpenDisplay(XDisplayName(0));
520 // create translation file
522 ofs.open(make_tmp(getpid()).c_str());
523 ofs << "gsave clippath pathbbox grestore\n"
525 << "/ury exch def /urx exch def /lly exch def "
527 << p->data->wid / 2.0 << " "
528 << p->data->hgh / 2.0 << " translate\n"
529 << p->data->angle << " rotate\n"
530 << -(p->data->raw_wid / 2.0) << " "
531 << -(p->data->raw_hgh / 2.0) << " translate\n"
532 << p->rx / 72.0 << " " << p->ry / 72.0
534 << -p->ofsx << " " << -p->ofsy << " translate\n"
536 ofs.close(); // Don't remove this.
538 // gs process - set ghostview environment first
540 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
541 << ' ' << p->data->bitmap;
542 // now set up ghostview property on a window
543 // #warning BUG seems that the only bug here
544 // might be the hardcoded dpi.. Bummer!
546 t1 << "0 0 0 0 " << p->data->wid << ' '
547 << p->data->hgh << " 72 72 0 0 0 0";
549 if (lyxerr.debugging()) {
550 lyxerr << "Will set GHOSTVIEW property to ["
551 << t1.str() << "]" << endl;
553 // wait until property is deleted if executing multiple
555 XGrabServer(tempdisp);
557 // grab server to prevent other child
558 // interfering with setting GHOSTVIEW property
559 // The grabbing goes on for too long, is it
560 // really needed? (Lgb)
561 // I moved most of the grabs... (Lgb)
562 if (lyxerr.debugging()) {
563 lyxerr << "Grabbing the server"
566 prop = XListProperties(tempdisp,
568 figinset_canvas), &nprop);
572 for (i = 0; i < nprop; ++i) {
573 char * p = XGetAtomName(tempdisp,
575 if (strcmp(p, "GHOSTVIEW") == 0) {
577 // We free it when we leave so we don't leak.
583 XFree(reinterpret_cast<char *>(prop)); // jc:
585 // ok, property found, we must wait until
586 // ghostscript deletes it
587 if (lyxerr.debugging()) {
588 lyxerr << "Releasing the server\n["
590 << "] GHOSTVIEW property"
591 " found. Waiting." << endl;
593 XUngrabServer(tempdisp);
596 XGrabServer(tempdisp);
598 XChangeProperty(tempdisp,
599 fl_get_canvas_id(figinset_canvas),
600 XInternAtom(tempdisp, "GHOSTVIEW", false),
601 XInternAtom(tempdisp, "STRING", false),
603 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
605 XUngrabServer(tempdisp);
610 switch (p->data->flags & 3) {
611 case 0: t3 << 'H'; break; // Hidden
612 case 1: t3 << 'M'; break; // Mono
613 case 2: t3 << 'G'; break; // Gray
622 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
623 << ' ' << background_pixel;
625 XGrabServer(tempdisp);
626 XChangeProperty(tempdisp,
627 fl_get_canvas_id(figinset_canvas),
628 XInternAtom(tempdisp,
629 "GHOSTVIEW_COLORS", false),
630 XInternAtom(tempdisp, "STRING", false),
632 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
634 XUngrabServer(tempdisp);
637 if (lyxerr.debugging()) {
638 lyxerr << "Releasing the server" << endl;
640 XCloseDisplay(tempdisp);
642 // set up environment
645 typedef char * char_p;
646 env = new char_p[ne + 2];
647 string tmp = t2.str().c_str();
648 env[0] = new char[tmp.size() + 1];
649 std::copy(tmp.begin(), tmp.end(), env[0]);
650 env[0][tmp.size()] = '\0';
651 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
654 // now make gs command
656 // close(1); do NOT close. If GS writes out
657 // errors it would hang. (Matthias 290596)
659 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
660 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
662 // now chdir into dir with .eps file, to be on the safe
664 ::chdir(OnlyPath(p->data->fname).c_str());
665 // make temp file name
666 string tmpf = make_tmp(getpid());
667 if (lyxerr.debugging()) {
668 lyxerr << "starting gs " << tmpf << " "
670 << ", pid: " << getpid() << endl;
673 int err = ::execlp(lyxrc.ps_command.c_str(),
674 lyxrc.ps_command.c_str(),
676 "-dNOPAUSE", "-dQUIET",
678 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
679 p->data->fname.c_str(),
680 "showpage.ps", "quit.ps", "-", 0);
681 // if we are still there, an error occurred.
682 lyxerr << "Error executing ghostscript. "
683 << "Code: " << err << endl;
684 lyxerr.debug() << "Cmd: "
687 << tmpf.c_str() << ' '
688 << p->data->fname << endl;
691 // normal process (parent)
692 if (lyxerr.debugging()) {
693 lyxerr << "GS [" << pid << "] started" << endl;
696 p->data->gspid = pid;
704 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
706 // recompute the stuff and put in the queue
710 p.rx = (float(data->raw_wid) * 72.0) / pswid;
711 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
717 // if possible, run the queue
723 figdata * getfigdata(int wid, int hgh, string const & fname,
724 int psx, int psy, int pswid, int pshgh,
725 int raw_wid, int raw_hgh, float angle, char flags)
727 /* first search for an exact match with fname and width/height */
729 if (fname.empty() || !IsFileReadable(fname))
732 for (bitmaps_type::iterator it = bitmaps.begin();
733 it != bitmaps.end(); ++it) {
734 if ((*it)->wid == wid && (*it)->hgh == hgh &&
735 (*it)->flags == flags && (*it)->fname == fname &&
736 (*it)->angle == angle) {
741 figdata * p = new figdata;
744 p->raw_wid = raw_wid;
745 p->raw_hgh = raw_hgh;
749 bitmaps.push_back(p);
750 XWindowAttributes wa;
751 XGetWindowAttributes(fl_display, fl_get_canvas_id(
752 figinset_canvas), &wa);
754 if (lyxerr.debugging()) {
755 lyxerr << "Create pixmap disp:" << fl_display
756 << " scr:" << DefaultScreen(fl_display)
759 << " depth:" << wa.depth << endl;
767 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
768 figinset_canvas), wid, hgh, wa.depth);
770 // initialize reading of .eps file with correct sizes and stuff
771 addwait(psx, psy, pswid, pshgh, p);
783 void getbitmap(figdata * p)
790 void makeupdatelist(figdata * p)
792 for(figures_type::iterator it = figures.begin();
793 it != figures.end(); ++it)
794 if ((*it)->data == p) {
795 if (lyxerr.debugging()) {
796 lyxerr << "Updating inset "
800 // add inset figures[i]->inset into to_update list
801 current_view->pushIntoUpdateList((*it)->inset);
806 // this func is only "called" in spellchecker.C
807 void sigchldchecker(pid_t pid, int * status)
809 lyxerr.debug() << "Got pid = " << pid << endl;
810 bool pid_handled = false;
811 for (bitmaps_type::iterator it = bitmaps.begin();
812 it != bitmaps.end(); ++it) {
813 if ((*it)->reading && pid == (*it)->gspid) {
814 lyxerr.debug() << "Found pid in bitmaps" << endl;
815 // now read the file and remove it from disk
818 if ((*it)->gsdone) *status = 0;
820 lyxerr.debug() << "GS [" << pid
821 << "] exit OK." << endl;
823 lyxerr << "GS [" << pid << "] error "
825 << WIFEXITED(*status)
826 << " " << WEXITSTATUS(*status)
827 << " S:" << WIFSIGNALED(*status)
828 << " " << WTERMSIG(*status) << endl;
831 bitmap_waiting = true;
834 // remove temporary files
835 unlink(make_tmp(p->gspid).c_str());
839 makeupdatelist((*it));
846 lyxerr.debug() << "Checking pid in pidwait" << endl;
847 list<int>::iterator it = find(pidwaitlist.begin(),
848 pidwaitlist.end(), pid);
849 if (it != pidwaitlist.end()) {
850 lyxerr.debug() << "Found pid in pidwait\n"
851 << "Caught child pid of recompute "
852 "routine" << pid << endl;
853 pidwaitlist.erase(it);
857 lyxerr.debug() << "waitpid error" << endl;
860 lyxerr << "The process or process group specified by "
861 "pid does not exist or is not a child of "
862 "the calling process or can never be in the "
863 "states specified by options." << endl;
866 lyxerr << "waitpid() was interrupted due to the "
867 "receipt of a signal sent by the calling "
871 lyxerr << "An invalid value was specified for "
875 lyxerr << "Unknown error from waitpid" << endl;
878 } else if (pid == 0) {
879 lyxerr << "waitpid nohang" << endl;;
881 lyxerr.debug() << "normal exit from childhandler" << endl;
889 bitmap_waiting = false;
890 for (bitmaps_type::iterator it = bitmaps.begin();
891 it != bitmaps.end(); ++it)
892 if ((*it)->gspid > 0 && !(*it)->reading)
898 void RegisterFigure(InsetFig * fi)
900 if (figures.empty()) InitFigures();
902 Figref * tmpfig = new Figref;
905 figures.push_back(tmpfig);
908 if (lyxerr.debugging()) {
909 lyxerr << "Register Figure: buffer:["
910 << current_view->buffer() << "]" << endl;
916 void UnregisterFigure(InsetFig * fi)
918 Figref * tmpfig = fi->figure;
920 if (tmpfig->data) freefigdata(tmpfig->data);
921 if (tmpfig->inset->form) {
922 if (tmpfig->inset->form->Figure->visible) {
923 fl_set_focus_object(tmpfig->inset->form->Figure,
924 tmpfig->inset->form->OkBtn);
925 fl_hide_form(tmpfig->inset->form->Figure);
927 #if FL_REVISION == 89
928 // CHECK Reactivate this free_form calls
930 fl_free_form(tmpfig->inset->form->Figure);
931 free(tmpfig->inset->form); // Why free?
932 tmpfig->inset->form = 0;
935 figures.erase(find(figures.begin(), figures.end(), tmpfig));
938 if (figures.empty()) DoneFigures();
942 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
952 psubfigure = subfigure = false;
953 xwid = xhgh = angle = 0;
955 raw_wid = raw_hgh = 0;
956 changedfname = false;
957 RegisterFigure(this);
961 InsetFig::~InsetFig()
963 if (lyxerr.debugging()) {
964 lyxerr << "Figure destructor called" << endl;
966 UnregisterFigure(this);
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,
1012 string lfname = fname;
1013 if (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 &) 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(fname.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, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1231 FL_FULLBORDER, _("Figure"));
1236 Inset * InsetFig::Clone() const
1238 InsetFig * tmp = new InsetFig(100, 100, owner);
1240 if (lyxerr.debugging()) {
1241 lyxerr << "Clone Figure: buffer:["
1242 << current_view->buffer()
1243 << "], cbuffer:[xx]" << endl;
1248 tmp->raw_wid = raw_wid;
1249 tmp->raw_hgh = raw_hgh;
1254 tmp->pflags = pflags;
1255 tmp->subfigure = subfigure;
1256 tmp->psubfigure = psubfigure;
1264 if (!fname.empty() && IsFileReadable(fname)
1265 && (flags & 3) && !lyxrc.ps_command.empty()
1267 // do not display if there is
1268 // "do not display" chosen (Matthias 260696)
1269 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1270 pswid, pshgh, raw_wid, raw_hgh,
1271 angle, flags & (3|8));
1272 } else tmp->figure->data = 0;
1273 tmp->subcaption = subcaption;
1274 tmp->changedfname = false;
1281 Inset::Code InsetFig::LyxCode() const
1283 return Inset::GRAPHICS_CODE;
1288 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1294 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1295 res = tostr(f) + "cm";
1298 res = tostr(f) + "in";
1300 case InsetFig::PER_PAGE:
1301 res = tostr(f/100) + "\\text" + suffix;
1303 case InsetFig::PER_COL:
1304 // Doesn't occur for htype...
1305 res = tostr(f/100) + "\\column" + suffix;
1312 void InsetFig::Regenerate() const
1315 string resizeW, resizeH;
1316 string rotate, recmd;
1318 if (fname.empty()) {
1319 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1320 cmd += _("empty figure path");
1325 string buf1 = OnlyPath(owner->fileName());
1326 string fname2 = MakeRelPath(fname, buf1);
1328 string gcmd = "\\includegraphics{" + fname2 + '}';
1329 resizeW = stringify(wtype, xwid, "width");
1330 resizeH = stringify(htype, xhgh, "height");
1332 if (!resizeW.empty() || !resizeH.empty()) {
1333 recmd = "\\resizebox*{";
1334 if (!resizeW.empty())
1339 if (!resizeH.empty())
1348 // \rotatebox{angle}{text}
1349 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1355 if (!rotate.empty()) cmdbuf += '}';
1356 if (!recmd.empty()) cmdbuf += '}';
1358 if (!subcaption.empty())
1359 cmdbuf = "\\subfigure[" + subcaption +
1360 "]{" + cmdbuf + "}";
1362 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1369 void InsetFig::TempRegenerate()
1372 string resizeW, resizeH;
1373 string rotate, recmd;
1375 char const * tfname = fl_get_input(form->EpsFile);
1376 string tsubcap = fl_get_input(form->Subcaption);
1377 float tangle = atof(fl_get_input(form->Angle));
1378 float txwid = atof(fl_get_input(form->Width));
1379 float txhgh = atof(fl_get_input(form->Height));
1381 if (!tfname || !*tfname) {
1382 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1383 cmd += _("empty figure path");
1388 string buf1 = OnlyPath(owner->fileName());
1389 string fname2 = MakeRelPath(tfname, buf1);
1390 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1391 string gcmd = "\\includegraphics{" + fname2 + '}';
1393 resizeW = stringify(twtype, txwid, "width");
1394 resizeH = stringify(thtype, txhgh, "height");
1396 // \resizebox*{h-length}{v-length}{text}
1397 if (!resizeW.empty() || !resizeH.empty()) {
1398 recmd = "\\resizebox*{";
1399 if (!resizeW.empty())
1404 if (!resizeH.empty())
1412 // \rotatebox{angle}{text}
1413 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1416 cmdbuf = recmd + rotate + gcmd;
1417 if (!rotate.empty()) cmdbuf += '}';
1418 if (!recmd.empty()) cmdbuf += '}';
1419 if (psubfigure && !tsubcap.empty()) {
1420 cmdbuf = string("\\subfigure{") + tsubcap
1421 + string("}{") + cmdbuf + "}";
1426 void InsetFig::Recompute()
1428 bool changed = changedfname;
1429 int newx, newy, nraw_x, nraw_y;
1431 if (changed) GetPSSizes();
1433 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1434 float cos_a = cos (angle / DEG2PI);
1435 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1436 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1438 string lfname = fname;
1439 if (GetExtension(fname).empty())
1442 /* now recompute wid and hgh, and if that is changed, set changed */
1443 /* this depends on chosen size of the picture and its bbox */
1444 // This will be redone in 0.13 ... (hen)
1445 if (!lfname.empty() && IsFileReadable(lfname)) {
1446 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1454 newx = int(28.346 * xwid);
1457 newx = int(72 * xwid);
1459 case PER_PAGE: /* % of page */
1460 newx = int(5.95 * xwid);
1462 case PER_COL: /* % of col */
1463 newx = int(2.975 * xwid);
1467 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1471 //lyxerr << "This should not happen!" << endl;
1474 newy = int(28.346 * xhgh);
1477 newy = int(72 * xhgh);
1479 case PER_PAGE: /* % of page */
1480 newy = int(8.42 * xhgh);
1483 // Doesn't occur; case exists to suppress
1484 // compiler warnings.
1487 if (htype && !wtype && frame_hgh)
1488 newx = newy*frame_wid/frame_hgh;
1497 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1502 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1504 // cannot be zero, actually, set it to some minimum, so its clickable
1505 if (newx < 5) newx = 5;
1506 if (newy < 5) newy = 5;
1508 if (newx != wid || newy != hgh ||
1509 nraw_x != raw_wid || nraw_y != raw_hgh ||
1510 flags != pflags || subfigure != psubfigure)
1518 subfigure = psubfigure;
1521 figdata * pf = figure->data;
1524 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1525 && !lyxrc.ps_command.empty()) {
1526 // do not display if there is "do not display"
1527 // chosen (Matthias 260696)
1528 figure->data = getfigdata(wid, hgh, lfname,
1529 psx, psy, pswid, pshgh,
1531 angle, flags & (3|8));
1532 } else figure->data = 0;
1534 // free the old data
1535 if (pf) freefigdata(pf);
1538 changedfname = false;
1542 void InsetFig::GetPSSizes()
1544 /* get %%BoundingBox: from postscript file */
1546 /* defaults to associated size
1547 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1554 if (fname.empty()) return;
1556 ifstream ifs(fname.c_str());
1558 if (!ifs) return; // file not found !!!!
1560 /* defaults to A4 page */
1566 char lastchar = 0; ifs.get(lastchar);
1568 char c = 0; ifs.get(c);
1570 lyxerr.debug() << "End of (E)PS file reached and"
1571 " no BoundingBox!" << endl;
1574 if (c == '%' && lastchar == '%') {
1576 if (p.empty()) break;
1577 lyxerr.debug() << "Token: `" << p << "'" << endl;
1578 if (p == "BoundingBox:") {
1579 float fpsx, fpsy, fpswid, fpshgh;
1580 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1583 pswid = int(fpswid);
1584 pshgh = int(fpshgh);
1586 if (lyxerr.debugging()) {
1587 lyxerr << "%%%%BoundingBox:"
1605 void InsetFig::CallbackFig(long arg)
1610 if (lyxerr.debugging()) {
1611 lyxerr << "Figure callback, arg " << arg << endl;
1617 case 12: /* width type */
1624 fl_deactivate_object(form->Width);
1629 fl_activate_object(form->Width);
1634 fl_activate_object(form->Width);
1639 fl_activate_object(form->Width);
1644 fl_activate_object(form->Width);
1647 lyxerr.debug() << "Unknown type!" << endl;
1654 case 22: /* height type */
1660 fl_deactivate_object(form->Height);
1665 fl_activate_object(form->Height);
1670 fl_activate_object(form->Height);
1675 fl_activate_object(form->Height);
1678 lyxerr.debug() << "Unknown type!" << endl;
1684 pflags = pflags & ~3; /* wysiwyg0 */
1687 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1690 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1693 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1696 pflags ^= 4; /* frame */
1699 pflags ^= 8; /* do translations */
1702 psubfigure = !psubfigure; /* This is a subfigure */
1705 regen = true; /* regenerate command */
1707 case 0: /* browse file */
1711 case 1: /* preview */
1712 p = fl_get_input(form->EpsFile);
1716 case 8: /* ok (apply and close) */
1717 if(!current_view->buffer()->isReadonly()) {
1720 xwid = atof(fl_get_input(form->Width));
1721 xhgh = atof(fl_get_input(form->Height));
1722 angle = atof(fl_get_input(form->Angle));
1723 p = fl_get_input(form->EpsFile);
1725 string buf1 = OnlyPath(owner->fileName());
1726 fname = MakeAbsPath(p, buf1);
1727 changedfname = true;
1729 if (!fname.empty()) {
1730 changedfname = true;
1734 subcaption = fl_get_input(form->Subcaption);
1738 /* now update inset */
1739 if (lyxerr.debugging()) {
1740 lyxerr << "Update: ["
1741 << wid << 'x' << hgh << ']' << endl;
1743 current_view->updateInset(this, true);
1745 fl_set_focus_object(form->Figure, form->OkBtn);
1746 fl_hide_form(form->Figure);
1747 #if FL_REVISION == 89
1748 // CHECK Reactivate this free_form calls
1750 fl_free_form(form->Figure);
1751 free(form); // Why free?
1757 // The user has already been informed about RO in ::Edit
1758 if(arg == 7) // if 'Apply'
1761 case 9: /* cancel = restore and close */
1762 fl_set_focus_object(form->Figure, form->OkBtn);
1763 fl_hide_form(form->Figure);
1764 #if FL_REVISION == 89
1765 // CHECK Reactivate this free_form calls
1766 // Jug, is this still a problem?
1768 fl_free_form(form->Figure);
1769 free(form); // Why free?
1775 if (regen) TempRegenerate();
1780 void DisableFigurePanel(FD_Figure * const form)
1782 fl_deactivate_object(form->EpsFile);
1783 fl_deactivate_object(form->Browse);
1784 fl_deactivate_object(form->Width);
1785 fl_deactivate_object(form->Height);
1786 fl_deactivate_object(form->Frame);
1787 fl_deactivate_object(form->Translations);
1788 fl_deactivate_object(form->Angle);
1789 fl_deactivate_object(form->HeightGrp);
1790 fl_deactivate_object(form->page2);
1791 fl_deactivate_object(form->Default2);
1792 fl_deactivate_object(form->cm2);
1793 fl_deactivate_object(form->in2);
1794 fl_deactivate_object(form->HeightLabel);
1795 fl_deactivate_object(form->WidthLabel);
1796 fl_deactivate_object(form->DisplayGrp);
1797 fl_deactivate_object(form->Wysiwyg3);
1798 fl_deactivate_object(form->Wysiwyg0);
1799 fl_deactivate_object(form->Wysiwyg2);
1800 fl_deactivate_object(form->Wysiwyg1);
1801 fl_deactivate_object(form->WidthGrp);
1802 fl_deactivate_object(form->Default1);
1803 fl_deactivate_object(form->cm1);
1804 fl_deactivate_object(form->in1);
1805 fl_deactivate_object(form->page1);
1806 fl_deactivate_object(form->column1);
1807 fl_deactivate_object(form->Subcaption);
1808 fl_deactivate_object(form->Subfigure);
1809 fl_deactivate_object (form->OkBtn);
1810 fl_deactivate_object (form->ApplyBtn);
1811 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1812 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1817 void EnableFigurePanel(FD_Figure * const form)
1819 fl_activate_object(form->EpsFile);
1820 fl_activate_object(form->Browse);
1821 fl_activate_object(form->Width);
1822 fl_activate_object(form->Height);
1823 fl_activate_object(form->Frame);
1824 fl_activate_object(form->Translations);
1825 fl_activate_object(form->Angle);
1826 fl_activate_object(form->HeightGrp);
1827 fl_activate_object(form->page2);
1828 fl_activate_object(form->Default2);
1829 fl_activate_object(form->cm2);
1830 fl_activate_object(form->in2);
1831 fl_activate_object(form->HeightLabel);
1832 fl_activate_object(form->WidthLabel);
1833 fl_activate_object(form->DisplayGrp);
1834 fl_activate_object(form->Wysiwyg3);
1835 fl_activate_object(form->Wysiwyg0);
1836 fl_activate_object(form->Wysiwyg2);
1837 fl_activate_object(form->Wysiwyg1);
1838 fl_activate_object(form->WidthGrp);
1839 fl_activate_object(form->Default1);
1840 fl_activate_object(form->cm1);
1841 fl_activate_object(form->in1);
1842 fl_activate_object(form->page1);
1843 fl_activate_object(form->column1);
1844 fl_activate_object(form->Subcaption);
1845 fl_activate_object(form->Subfigure);
1846 fl_activate_object (form->OkBtn);
1847 fl_activate_object (form->ApplyBtn);
1848 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1849 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1853 void InsetFig::RestoreForm()
1855 EnableFigurePanel(form);
1858 fl_set_button(form->Default1, (wtype == 0));
1859 fl_set_button(form->cm1, (wtype == 1));
1860 fl_set_button(form->in1, (wtype == 2));
1861 fl_set_button(form->page1, (wtype == 3));
1862 fl_set_button(form->column1, (wtype == 4));
1864 fl_deactivate_object(form->Width);
1866 fl_activate_object(form->Width);
1869 // enable and disable should be put here.
1871 fl_set_button(form->Default2, (htype == 0));
1872 fl_set_button(form->cm2, (htype == 1));
1873 fl_set_button(form->in2, (htype == 2));
1874 fl_set_button(form->page2, (htype == 3));
1875 // enable and disable should be put here.
1877 fl_deactivate_object(form->Height);
1879 fl_activate_object(form->Height);
1882 int piflags = flags & 3;
1883 fl_set_button(form->Wysiwyg0, (piflags == 0));
1884 fl_set_button(form->Wysiwyg1, (piflags == 1));
1885 fl_set_button(form->Wysiwyg2, (piflags == 2));
1886 fl_set_button(form->Wysiwyg3, (piflags == 3));
1887 fl_set_button(form->Frame, ((flags & 4) != 0));
1888 fl_set_button(form->Translations, ((flags & 8) != 0));
1889 fl_set_button(form->Subfigure, (subfigure != 0));
1891 psubfigure = subfigure;
1892 fl_set_input(form->Width, tostr(xwid).c_str());
1893 fl_set_input(form->Height, tostr(xhgh).c_str());
1894 fl_set_input(form->Angle, tostr(angle).c_str());
1895 if (!fname.empty()){
1896 string buf1 = OnlyPath(owner->fileName());
1897 string fname2 = MakeRelPath(fname, buf1);
1898 fl_set_input(form->EpsFile, fname2.c_str());
1900 else fl_set_input(form->EpsFile, "");
1901 fl_set_input(form->Subcaption, subcaption.c_str());
1902 if(current_view->buffer()->isReadonly())
1903 DisableFigurePanel(form);
1909 void InsetFig::Preview(string const & p)
1914 lyxerr << "Cannot fork process!" << endl;
1919 return; // parent process
1923 if (GetExtension(tfname).empty())
1925 string buf1 = OnlyPath(owner->fileName());
1926 string buf2 = MakeAbsPath(tfname, buf1);
1928 lyxerr << "Error during rendering "
1929 << execlp(lyxrc.view_pspic_command.c_str(),
1930 lyxrc.view_pspic_command.c_str(),
1937 void InsetFig::BrowseFile()
1939 static string current_figure_path;
1940 static int once = 0;
1943 if (lyxerr.debugging()) {
1944 lyxerr << "Filename: "
1945 << owner->fileName() << endl;
1947 string p = fl_get_input(form->EpsFile);
1949 string buf = MakeAbsPath(owner->fileName());
1950 string buf2 = OnlyPath(buf);
1952 buf = MakeAbsPath(p, buf2);
1953 buf = OnlyPath(buf);
1955 buf = OnlyPath(owner->fileName().c_str());
1958 // Does user clipart directory exist?
1959 string bufclip = AddName (user_lyxdir, "clipart");
1960 FileInfo fileInfo(bufclip);
1961 if (!(fileInfo.isOK() && fileInfo.isDir()))
1962 // No - bail out to system clipart directory
1963 bufclip = AddName (system_lyxdir, "clipart");
1966 fileDlg.SetButton(0, _("Clipart"), bufclip);
1967 fileDlg.SetButton(1, _("Document"), buf);
1971 ProhibitInput(current_view);
1973 p = fileDlg.Select(_("EPS Figure"),
1974 current_figure_path,
1977 p = fileDlg.Select(_("EPS Figure"), buf,
1980 AllowInput(current_view);
1982 if (p.empty()) return;
1984 buf = MakeRelPath(p, buf2);
1985 current_figure_path = OnlyPath(p);
1988 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1989 || contains(p, "%") || contains(p, " ")) {
1990 WriteAlert(_("Filename can't contain any "
1991 "of these characters:"),
1992 // xgettext:no-c-format
1993 _("space, '#', '~', '$' or '%'."));
1998 if (form) fl_set_input(form->EpsFile, buf.c_str());
2002 void GraphicsCB(FL_OBJECT * obj, long arg)
2004 /* obj->form contains the form */
2006 if (lyxerr.debugging()) {
2007 lyxerr << "GraphicsCB callback: " << arg << endl;
2010 /* find inset we were reacting to */
2011 for (figures_type::iterator it = figures.begin();
2012 it != figures.end(); ++it)
2013 if ((*it)->inset->form && (*it)->inset->form->Figure
2015 if (lyxerr.debugging()) {
2016 lyxerr << "Calling back figure "
2019 (*it)->inset->CallbackFig(arg);
2025 void HideFiguresPopups()
2027 for (figures_type::iterator it = figures.begin();
2028 it != figures.end(); ++it)
2029 if ((*it)->inset->form
2030 && (*it)->inset->form->Figure->visible) {
2031 if (lyxerr.debugging()) {
2032 lyxerr << "Hiding figure " << (*it) << endl;
2034 // hide and free the form
2035 (*it)->inset->CallbackFig(9);