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()->getMainForm());
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
543 ostrstream t2(tbuf2, sizeof(tbuf));
545 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
546 << ' ' << p->data->bitmap;
550 // now set up ghostview property on a window
551 // #warning BUG seems that the only bug here
552 // might be the hardcoded dpi.. Bummer!
557 ostrstream t1(tbuf, sizeof(tbuf));
559 t1 << "0 0 0 0 " << p->data->wid << ' '
560 << p->data->hgh << " 72 72 0 0 0 0";
565 if (lyxerr.debugging()) {
566 lyxerr << "Will set GHOSTVIEW property to ["
567 << t1.str() << "]" << endl;
569 // wait until property is deleted if executing multiple
571 XGrabServer(tempdisp);
573 // grab server to prevent other child
574 // interfering with setting GHOSTVIEW property
575 // The grabbing goes on for too long, is it
576 // really needed? (Lgb)
577 // I moved most of the grabs... (Lgb)
578 if (lyxerr.debugging()) {
579 lyxerr << "Grabbing the server"
582 prop = XListProperties(tempdisp,
584 figinset_canvas), &nprop);
588 for (i = 0; i < nprop; ++i) {
589 char * p = XGetAtomName(tempdisp,
591 if (strcmp(p, "GHOSTVIEW") == 0) {
597 XFree(reinterpret_cast<char *>(prop)); // jc:
599 // ok, property found, we must wait until
600 // ghostscript deletes it
601 if (lyxerr.debugging()) {
602 lyxerr << "Releasing the server\n["
604 << "] GHOSTVIEW property"
605 " found. Waiting." << endl;
607 XUngrabServer(tempdisp);
610 XGrabServer(tempdisp);
612 XChangeProperty(tempdisp,
613 fl_get_canvas_id(figinset_canvas),
614 XInternAtom(tempdisp, "GHOSTVIEW", false),
615 XInternAtom(tempdisp, "STRING", false),
617 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
619 XUngrabServer(tempdisp);
626 ostrstream t3(tbuf, sizeof(tbuf));
628 switch (p->data->flags & 3) {
629 case 0: t3 << 'H'; break; // Hidden
630 case 1: t3 << 'M'; break; // Mono
631 case 2: t3 << 'G'; break; // Gray
640 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
641 << ' ' << background_pixel;
646 XGrabServer(tempdisp);
647 XChangeProperty(tempdisp,
648 fl_get_canvas_id(figinset_canvas),
649 XInternAtom(tempdisp,
650 "GHOSTVIEW_COLORS", false),
651 XInternAtom(tempdisp, "STRING", false),
653 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
655 XUngrabServer(tempdisp);
658 if (lyxerr.debugging()) {
659 lyxerr << "Releasing the server" << endl;
661 XCloseDisplay(tempdisp);
663 // set up environment
666 typedef char * char_p;
667 env = new char_p[ne + 2];
669 string tmp = t2.str().c_str();
670 env[0] = new char[tmp.size() + 1];
671 std::copy(tmp.begin(), tmp.end(), env[0]);
672 env[0][tmp.size()] = '\0';
676 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
679 // now make gs command
681 // close(1); do NOT close. If GS writes out
682 // errors it would hang. (Matthias 290596)
684 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
685 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
687 // now chdir into dir with .eps file, to be on the safe
689 ::chdir(OnlyPath(p->data->fname).c_str());
690 // make temp file name
691 string tmpf = make_tmp(getpid());
692 if (lyxerr.debugging()) {
693 lyxerr << "starting gs " << tmpf << " "
695 << ", pid: " << getpid() << endl;
698 int err = ::execlp(lyxrc.ps_command.c_str(),
699 lyxrc.ps_command.c_str(),
701 "-dNOPAUSE", "-dQUIET",
703 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
704 p->data->fname.c_str(),
705 "showpage.ps", "quit.ps", "-", 0);
706 // if we are still there, an error occurred.
707 lyxerr << "Error executing ghostscript. "
708 << "Code: " << err << endl;
709 lyxerr.debug() << "Cmd: "
712 << tmpf.c_str() << ' '
713 << p->data->fname << endl;
716 // normal process (parent)
717 if (lyxerr.debugging()) {
718 lyxerr << "GS [" << pid << "] started" << endl;
721 p->data->gspid = pid;
729 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
731 // recompute the stuff and put in the queue
735 p.rx = (float(data->raw_wid) * 72.0) / pswid;
736 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
742 // if possible, run the queue
748 figdata * getfigdata(int wid, int hgh, string const & fname,
749 int psx, int psy, int pswid, int pshgh,
750 int raw_wid, int raw_hgh, float angle, char flags)
752 /* first search for an exact match with fname and width/height */
754 if (fname.empty()) return 0;
756 for (bitmaps_type::iterator it = bitmaps.begin();
757 it != bitmaps.end(); ++it) {
758 if ((*it)->wid == wid && (*it)->hgh == hgh &&
759 (*it)->flags == flags && (*it)->fname == fname &&
760 (*it)->angle == angle) {
765 figdata * p = new figdata;
768 p->raw_wid = raw_wid;
769 p->raw_hgh = raw_hgh;
773 bitmaps.push_back(p);
774 XWindowAttributes wa;
775 XGetWindowAttributes(fl_display, fl_get_canvas_id(
776 figinset_canvas), &wa);
778 if (lyxerr.debugging()) {
779 lyxerr << "Create pixmap disp:" << fl_display
780 << " scr:" << DefaultScreen(fl_display)
783 << " depth:" << wa.depth << endl;
791 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
792 figinset_canvas), wid, hgh, wa.depth);
794 // initialize reading of .eps file with correct sizes and stuff
795 addwait(psx, psy, pswid, pshgh, p);
807 void getbitmap(figdata * p)
814 void makeupdatelist(figdata * p)
816 for(figures_type::iterator it = figures.begin();
817 it != figures.end(); ++it)
818 if ((*it)->data == p) {
819 if (lyxerr.debugging()) {
820 lyxerr << "Updating inset "
824 // add inset figures[i]->inset into to_update list
825 current_view->pushIntoUpdateList((*it)->inset);
830 // this func is only "called" in spellchecker.C
831 void sigchldchecker(pid_t pid, int * status)
833 lyxerr.debug() << "Got pid = " << pid << endl;
834 bool pid_handled = false;
835 for (bitmaps_type::iterator it = bitmaps.begin();
836 it != bitmaps.end(); ++it) {
837 if ((*it)->reading && pid == (*it)->gspid) {
838 lyxerr.debug() << "Found pid in bitmaps" << endl;
839 // now read the file and remove it from disk
842 if ((*it)->gsdone) *status = 0;
844 lyxerr.debug() << "GS [" << pid
845 << "] exit OK." << endl;
847 lyxerr << "GS [" << pid << "] error "
849 << WIFEXITED(*status)
850 << " " << WEXITSTATUS(*status)
851 << " S:" << WIFSIGNALED(*status)
852 << " " << WTERMSIG(*status) << endl;
855 bitmap_waiting = true;
858 // remove temporary files
859 unlink(make_tmp(p->gspid).c_str());
863 makeupdatelist((*it));
870 lyxerr.debug() << "Checking pid in pidwait" << endl;
871 list<int>::iterator it = find(pidwaitlist.begin(),
872 pidwaitlist.end(), pid);
873 if (it != pidwaitlist.end()) {
874 lyxerr.debug() << "Found pid in pidwait\n"
875 << "Caught child pid of recompute "
876 "routine" << pid << endl;
877 pidwaitlist.erase(it);
881 lyxerr.debug() << "waitpid error" << endl;
884 lyxerr << "The process or process group specified by "
885 "pid does not exist or is not a child of "
886 "the calling process or can never be in the "
887 "states specified by options." << endl;
890 lyxerr << "waitpid() was interrupted due to the "
891 "receipt of a signal sent by the calling "
895 lyxerr << "An invalid value was specified for "
899 lyxerr << "Unknown error from waitpid" << endl;
902 } else if (pid == 0) {
903 lyxerr << "waitpid nohang" << endl;;
905 lyxerr.debug() << "normal exit from childhandler" << endl;
913 bitmap_waiting = false;
914 for (bitmaps_type::iterator it = bitmaps.begin();
915 it != bitmaps.end(); ++it)
916 if ((*it)->gspid > 0 && !(*it)->reading)
922 void RegisterFigure(InsetFig * fi)
924 if (figures.empty()) InitFigures();
926 Figref * tmpfig = new Figref;
929 figures.push_back(tmpfig);
932 if (lyxerr.debugging()) {
933 lyxerr << "Register Figure: buffer:["
934 << current_view->buffer() << "]" << endl;
940 void UnregisterFigure(InsetFig * fi)
942 Figref * tmpfig = fi->figure;
944 if (tmpfig->data) freefigdata(tmpfig->data);
945 if (tmpfig->inset->form) {
946 if (tmpfig->inset->form->Figure->visible) {
947 fl_set_focus_object(tmpfig->inset->form->Figure,
948 tmpfig->inset->form->OkBtn);
949 fl_hide_form(tmpfig->inset->form->Figure);
951 #if FL_REVISION == 89
952 #warning Reactivate this free_form calls
954 fl_free_form(tmpfig->inset->form->Figure);
955 free(tmpfig->inset->form); // Why free?
956 tmpfig->inset->form = 0;
959 figures.erase(find(figures.begin(), figures.end(), tmpfig));
962 if (figures.empty()) DoneFigures();
966 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
976 psubfigure = subfigure = false;
977 xwid = xhgh = angle = 0;
979 raw_wid = raw_hgh = 0;
980 changedfname = false;
981 RegisterFigure(this);
985 InsetFig::~InsetFig()
987 if (lyxerr.debugging()) {
988 lyxerr << "Figure destructor called" << endl;
990 UnregisterFigure(this);
994 int InsetFig::ascent(Painter &, LyXFont const &) const
1000 int InsetFig::descent(Painter &, LyXFont const &) const
1006 int InsetFig::width(Painter &, LyXFont const &) const
1012 void InsetFig::draw(Painter & pain, LyXFont const & f,
1013 int baseline, float & x) const
1017 if (bitmap_waiting) getbitmaps();
1019 // I wish that I didn't have to use this
1020 // but the figinset code is so complicated so
1021 // I don't want to fiddle with it now.
1023 if (figure && figure->data && figure->data->bitmap &&
1024 !figure->data->reading && !figure->data->broken) {
1026 pain.pixmap(int(x + 1), baseline - hgh,
1027 wid, hgh, figure->data->bitmap);
1030 pain.rectangle(int(x), baseline - hgh - 1,
1036 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1038 if (figure && figure->data) {
1039 if (figure->data->broken) msg = _("[render error]");
1040 else if (figure->data->reading) msg = _("[rendering ... ]");
1042 if (fname.empty()) msg = _("[no file]");
1043 else if ((flags & 3) == 0) msg = _("[not displayed]");
1044 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1046 if (!msg) msg = _("[unknown error]");
1048 font.setFamily(LyXFont::SANS_FAMILY);
1049 font.setSize(LyXFont::SIZE_FOOTNOTE);
1050 string justname = OnlyFilename (fname);
1051 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1054 font.setSize(LyXFont::SIZE_TINY);
1055 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1057 x += width(pain, font); // ?
1061 void InsetFig::Write(ostream & os) const
1064 os << "Figure size " << wid << " " << hgh << "\n";
1065 if (!fname.empty()) {
1066 string buf1 = OnlyPath(owner->fileName());
1067 string fname2 = MakeRelPath(fname, buf1);
1068 os << "file " << fname2 << "\n";
1070 if (!subcaption.empty())
1071 os << "subcaption " << subcaption << "\n";
1072 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1073 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1074 if (angle != 0) os << "angle " << angle << "\n";
1075 os << "flags " << flags << "\n";
1076 if (subfigure) os << "subfigure\n";
1080 void InsetFig::Read(LyXLex & lex)
1083 bool finished = false;
1085 while (lex.IsOK() && !finished) {
1088 string const token = lex.GetString();
1089 lyxerr.debug() << "Token: " << token << endl;
1093 else if (token == "\\end_inset") {
1095 } else if (token == "file") {
1097 buf = lex.GetString();
1098 string buf1 = OnlyPath(owner->fileName());
1099 fname = MakeAbsPath(buf, buf1);
1100 changedfname = true;
1102 } else if (token == "extra") {
1104 // kept for backwards compability. Delete in 0.13.x
1105 } else if (token == "subcaption") {
1107 subcaption = lex.GetString();
1108 } else if (token == "label") {
1110 // kept for backwards compability. Delete in 0.13.x
1111 } else if (token == "angle") {
1113 angle = lex.GetFloat();
1114 } else if (token == "size") {
1116 wid = lex.GetInteger();
1118 hgh = lex.GetInteger();
1119 } else if (token == "flags") {
1121 flags = pflags = lex.GetInteger();
1122 } else if (token == "subfigure") {
1123 subfigure = psubfigure = true;
1124 } else if (token == "width") {
1127 typ = lex.GetInteger();
1129 xwid = lex.GetFloat();
1131 case DEF: wtype = DEF; break;
1132 case CM: wtype = CM; break;
1133 case IN: wtype = IN; break;
1134 case PER_PAGE: wtype = PER_PAGE; break;
1135 case PER_COL: wtype = PER_COL; break;
1137 lyxerr.debug() << "Unknown type!" << endl;
1141 } else if (token == "height") {
1144 typ = lex.GetInteger();
1146 xhgh = lex.GetFloat();
1148 case DEF: htype = DEF; break;
1149 case CM: htype = CM; break;
1150 case IN: htype = IN; break;
1151 case PER_PAGE: htype = PER_PAGE; break;
1153 lyxerr.debug() << "Unknown type!" << endl;
1164 int InsetFig::Latex(ostream & os,
1165 bool /* fragile*/, bool /* fs*/) const
1168 if (!cmd.empty()) os << cmd << " ";
1173 int InsetFig::Ascii(ostream &) const
1179 int InsetFig::Linuxdoc(ostream &) const
1185 int InsetFig::DocBook(ostream & os) const
1187 string figurename = fname;
1189 if(suffixIs(figurename, ".eps"))
1190 figurename.erase(fname.length() - 4);
1192 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1197 void InsetFig::Validate(LaTeXFeatures & features) const
1199 features.graphics = true;
1200 if (subfigure) features.subfigure = true;
1204 Inset::EDITABLE InsetFig::Editable() const
1210 bool InsetFig::Deletable() const
1216 char const * InsetFig::EditMessage() const
1218 return _("Opened figure");
1222 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1224 lyxerr.debug() << "Editing InsetFig." << endl;
1227 // We should have RO-versions of the form instead.
1228 // The actual prevention of altering a readonly doc
1229 // is done in CallbackFig()
1230 if(bv->buffer()->isReadonly())
1231 WarnReadonly(bv->buffer()->fileName());
1234 form = create_form_Figure();
1235 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1236 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1237 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1238 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1241 if (form->Figure->visible) {
1242 fl_raise_form(form->Figure);
1244 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1245 FL_FULLBORDER, _("Figure"));
1250 Inset * InsetFig::Clone() const
1252 InsetFig * tmp = new InsetFig(100, 100, owner);
1254 if (lyxerr.debugging()) {
1255 lyxerr << "Clone Figure: buffer:["
1256 << current_view->buffer()
1257 << "], cbuffer:[xx]" << endl;
1262 tmp->raw_wid = raw_wid;
1263 tmp->raw_hgh = raw_hgh;
1268 tmp->pflags = pflags;
1269 tmp->subfigure = subfigure;
1270 tmp->psubfigure = psubfigure;
1278 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1280 // do not display if there is
1281 // "do not display" chosen (Matthias 260696)
1282 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1283 pswid, pshgh, raw_wid, raw_hgh,
1284 angle, flags & (3|8));
1285 } else tmp->figure->data = 0;
1286 tmp->subcaption = subcaption;
1287 tmp->changedfname = false;
1294 Inset::Code InsetFig::LyxCode() const
1296 return Inset::GRAPHICS_CODE;
1301 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1307 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1308 res = tostr(f) + "cm";
1311 res = tostr(f) + "in";
1313 case InsetFig::PER_PAGE:
1314 res = tostr(f/100) + "\\text" + suffix;
1316 case InsetFig::PER_COL:
1317 // Doesn't occur for htype...
1318 res = tostr(f/100) + "\\column" + suffix;
1325 void InsetFig::Regenerate() const
1328 string resizeW, resizeH;
1329 string rotate, recmd;
1331 if (fname.empty()) {
1332 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1333 cmd += _("empty figure path");
1338 string buf1 = OnlyPath(owner->fileName());
1339 string fname2 = MakeRelPath(fname, buf1);
1341 string gcmd = "\\includegraphics{" + fname2 + '}';
1342 resizeW = stringify(wtype, xwid, "width");
1343 resizeH = stringify(htype, xhgh, "height");
1345 if (!resizeW.empty() || !resizeH.empty()) {
1346 recmd = "\\resizebox*{";
1347 if (!resizeW.empty())
1352 if (!resizeH.empty())
1361 // \rotatebox{angle}{text}
1362 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1368 if (!rotate.empty()) cmdbuf += '}';
1369 if (!recmd.empty()) cmdbuf += '}';
1371 if (!subcaption.empty())
1372 cmdbuf = "\\subfigure[" + subcaption +
1373 "]{" + cmdbuf + "}";
1375 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1382 void InsetFig::TempRegenerate()
1385 string resizeW, resizeH;
1386 string rotate, recmd;
1388 char const * tfname = fl_get_input(form->EpsFile);
1389 string tsubcap = fl_get_input(form->Subcaption);
1390 float tangle = atof(fl_get_input(form->Angle));
1391 float txwid = atof(fl_get_input(form->Width));
1392 float txhgh = atof(fl_get_input(form->Height));
1394 if (!tfname || !*tfname) {
1395 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1396 cmd += _("empty figure path");
1401 string buf1 = OnlyPath(owner->fileName());
1402 string fname2 = MakeRelPath(tfname, buf1);
1403 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1404 string gcmd = "\\includegraphics{" + fname2 + '}';
1406 resizeW = stringify(twtype, txwid, "width");
1407 resizeH = stringify(thtype, txhgh, "height");
1409 // \resizebox*{h-length}{v-length}{text}
1410 if (!resizeW.empty() || !resizeH.empty()) {
1411 recmd = "\\resizebox*{";
1412 if (!resizeW.empty())
1417 if (!resizeH.empty())
1425 // \rotatebox{angle}{text}
1426 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1429 cmdbuf = recmd + rotate + gcmd;
1430 if (!rotate.empty()) cmdbuf += '}';
1431 if (!recmd.empty()) cmdbuf += '}';
1432 if (psubfigure && !tsubcap.empty()) {
1433 cmdbuf = string("\\subfigure{") + tsubcap
1434 + string("}{") + cmdbuf + "}";
1439 void InsetFig::Recompute()
1441 bool changed = changedfname;
1442 int newx, newy, nraw_x, nraw_y;
1444 if (changed) GetPSSizes();
1446 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1447 float cos_a = cos (angle / DEG2PI);
1448 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1449 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1451 /* now recompute wid and hgh, and if that is changed, set changed */
1452 /* this depends on chosen size of the picture and its bbox */
1453 // This will be redone in 0.13 ... (hen)
1454 if (!fname.empty()) {
1455 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1463 newx = int(28.346 * xwid);
1466 newx = int(72 * xwid);
1468 case PER_PAGE: /* % of page */
1469 newx = int(5.95 * xwid);
1471 case PER_COL: /* % of col */
1472 newx = int(2.975 * xwid);
1476 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1480 //lyxerr << "This should not happen!" << endl;
1483 newy = int(28.346 * xhgh);
1486 newy = int(72 * xhgh);
1488 case PER_PAGE: /* % of page */
1489 newy = int(8.42 * xhgh);
1492 // Doesn't occur; case exists to suppress
1493 // compiler warnings.
1496 if (htype && !wtype && frame_hgh)
1497 newx = newy*frame_wid/frame_hgh;
1506 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1511 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1513 // cannot be zero, actually, set it to some minimum, so its clickable
1514 if (newx < 5) newx = 5;
1515 if (newy < 5) newy = 5;
1517 if (newx != wid || newy != hgh ||
1518 nraw_x != raw_wid || nraw_y != raw_hgh ||
1519 flags != pflags || subfigure != psubfigure)
1527 subfigure = psubfigure;
1530 figdata * pf = figure->data;
1533 if (!fname.empty() && (flags & 3)
1534 && !lyxrc.ps_command.empty()) {
1535 // do not display if there is "do not display"
1536 // chosen (Matthias 260696)
1537 figure->data = getfigdata(wid, hgh, fname,
1538 psx, psy, pswid, pshgh,
1540 angle, flags & (3|8));
1541 } else figure->data = 0;
1543 // free the old data
1544 if (pf) freefigdata(pf);
1547 changedfname = false;
1551 void InsetFig::GetPSSizes()
1553 /* get %%BoundingBox: from postscript file */
1555 /* defaults to associated size
1556 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1563 if (fname.empty()) return;
1565 ifstream ifs(fname.c_str());
1567 if (!ifs) return; // file not found !!!!
1569 /* defaults to A4 page */
1575 char lastchar = 0; ifs.get(lastchar);
1577 char c = 0; ifs.get(c);
1579 lyxerr.debug() << "End of (E)PS file reached and"
1580 " no BoundingBox!" << endl;
1583 if (c == '%' && lastchar == '%') {
1585 if (p.empty()) break;
1586 lyxerr.debug() << "Token: `" << p << "'" << endl;
1587 if (p == "BoundingBox:") {
1588 float fpsx, fpsy, fpswid, fpshgh;
1589 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1592 pswid = int(fpswid);
1593 pshgh = int(fpshgh);
1595 if (lyxerr.debugging()) {
1596 lyxerr << "%%%%BoundingBox:"
1614 void InsetFig::CallbackFig(long arg)
1619 if (lyxerr.debugging()) {
1620 lyxerr << "Figure callback, arg " << arg << endl;
1626 case 12: /* width type */
1633 fl_deactivate_object(form->Width);
1638 fl_activate_object(form->Width);
1643 fl_activate_object(form->Width);
1648 fl_activate_object(form->Width);
1653 fl_activate_object(form->Width);
1656 lyxerr.debug() << "Unknown type!" << endl;
1663 case 22: /* height type */
1669 fl_deactivate_object(form->Height);
1674 fl_activate_object(form->Height);
1679 fl_activate_object(form->Height);
1684 fl_activate_object(form->Height);
1687 lyxerr.debug() << "Unknown type!" << endl;
1693 pflags = pflags & ~3; /* wysiwyg0 */
1696 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1699 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1702 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1705 pflags ^= 4; /* frame */
1708 pflags ^= 8; /* do translations */
1711 psubfigure = !psubfigure; /* This is a subfigure */
1714 regen = true; /* regenerate command */
1716 case 0: /* browse file */
1720 case 1: /* preview */
1721 p = fl_get_input(form->EpsFile);
1725 case 8: /* ok (apply and close) */
1726 if(!current_view->buffer()->isReadonly()) {
1729 xwid = atof(fl_get_input(form->Width));
1730 xhgh = atof(fl_get_input(form->Height));
1731 angle = atof(fl_get_input(form->Angle));
1732 p = fl_get_input(form->EpsFile);
1734 string buf1 = OnlyPath(owner->fileName());
1735 fname = MakeAbsPath(p, buf1);
1736 changedfname = true;
1738 if (!fname.empty()) {
1739 changedfname = true;
1743 subcaption = fl_get_input(form->Subcaption);
1747 /* now update inset */
1748 if (lyxerr.debugging()) {
1749 lyxerr << "Update: ["
1750 << wid << 'x' << hgh << ']' << endl;
1752 current_view->updateInset(this, true);
1754 fl_set_focus_object(form->Figure, form->OkBtn);
1755 fl_hide_form(form->Figure);
1756 #if FL_REVISION == 89
1757 #warning Reactivate this free_form calls
1759 fl_free_form(form->Figure);
1760 free(form); // Why free?
1766 // The user has already been informed about RO in ::Edit
1767 if(arg == 7) // if 'Apply'
1770 case 9: /* cancel = restore and close */
1771 fl_set_focus_object(form->Figure, form->OkBtn);
1772 fl_hide_form(form->Figure);
1773 #if FL_REVISION == 89
1774 #warning Reactivate this free_form calls
1775 #warning Jug, is this still a problem?
1777 fl_free_form(form->Figure);
1778 free(form); // Why free?
1784 if (regen) TempRegenerate();
1789 void DisableFigurePanel(FD_Figure * const form)
1791 fl_deactivate_object(form->EpsFile);
1792 fl_deactivate_object(form->Browse);
1793 fl_deactivate_object(form->Width);
1794 fl_deactivate_object(form->Height);
1795 fl_deactivate_object(form->Frame);
1796 fl_deactivate_object(form->Translations);
1797 fl_deactivate_object(form->Angle);
1798 fl_deactivate_object(form->HeightGrp);
1799 fl_deactivate_object(form->page2);
1800 fl_deactivate_object(form->Default2);
1801 fl_deactivate_object(form->cm2);
1802 fl_deactivate_object(form->in2);
1803 fl_deactivate_object(form->HeightLabel);
1804 fl_deactivate_object(form->WidthLabel);
1805 fl_deactivate_object(form->DisplayGrp);
1806 fl_deactivate_object(form->Wysiwyg3);
1807 fl_deactivate_object(form->Wysiwyg0);
1808 fl_deactivate_object(form->Wysiwyg2);
1809 fl_deactivate_object(form->Wysiwyg1);
1810 fl_deactivate_object(form->WidthGrp);
1811 fl_deactivate_object(form->Default1);
1812 fl_deactivate_object(form->cm1);
1813 fl_deactivate_object(form->in1);
1814 fl_deactivate_object(form->page1);
1815 fl_deactivate_object(form->column1);
1816 fl_deactivate_object(form->Subcaption);
1817 fl_deactivate_object(form->Subfigure);
1818 fl_deactivate_object (form->OkBtn);
1819 fl_deactivate_object (form->ApplyBtn);
1820 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1821 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1826 void EnableFigurePanel(FD_Figure * const form)
1828 fl_activate_object(form->EpsFile);
1829 fl_activate_object(form->Browse);
1830 fl_activate_object(form->Width);
1831 fl_activate_object(form->Height);
1832 fl_activate_object(form->Frame);
1833 fl_activate_object(form->Translations);
1834 fl_activate_object(form->Angle);
1835 fl_activate_object(form->HeightGrp);
1836 fl_activate_object(form->page2);
1837 fl_activate_object(form->Default2);
1838 fl_activate_object(form->cm2);
1839 fl_activate_object(form->in2);
1840 fl_activate_object(form->HeightLabel);
1841 fl_activate_object(form->WidthLabel);
1842 fl_activate_object(form->DisplayGrp);
1843 fl_activate_object(form->Wysiwyg3);
1844 fl_activate_object(form->Wysiwyg0);
1845 fl_activate_object(form->Wysiwyg2);
1846 fl_activate_object(form->Wysiwyg1);
1847 fl_activate_object(form->WidthGrp);
1848 fl_activate_object(form->Default1);
1849 fl_activate_object(form->cm1);
1850 fl_activate_object(form->in1);
1851 fl_activate_object(form->page1);
1852 fl_activate_object(form->column1);
1853 fl_activate_object(form->Subcaption);
1854 fl_activate_object(form->Subfigure);
1855 fl_activate_object (form->OkBtn);
1856 fl_activate_object (form->ApplyBtn);
1857 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1858 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1862 void InsetFig::RestoreForm()
1864 EnableFigurePanel(form);
1867 fl_set_button(form->Default1, (wtype == 0));
1868 fl_set_button(form->cm1, (wtype == 1));
1869 fl_set_button(form->in1, (wtype == 2));
1870 fl_set_button(form->page1, (wtype == 3));
1871 fl_set_button(form->column1, (wtype == 4));
1873 fl_deactivate_object(form->Width);
1875 fl_activate_object(form->Width);
1878 // enable and disable should be put here.
1880 fl_set_button(form->Default2, (htype == 0));
1881 fl_set_button(form->cm2, (htype == 1));
1882 fl_set_button(form->in2, (htype == 2));
1883 fl_set_button(form->page2, (htype == 3));
1884 // enable and disable should be put here.
1886 fl_deactivate_object(form->Height);
1888 fl_activate_object(form->Height);
1891 int pflags = flags & 3;
1892 fl_set_button(form->Wysiwyg0, (pflags == 0));
1893 fl_set_button(form->Wysiwyg1, (pflags == 1));
1894 fl_set_button(form->Wysiwyg2, (pflags == 2));
1895 fl_set_button(form->Wysiwyg3, (pflags == 3));
1896 fl_set_button(form->Frame, ((flags & 4) != 0));
1897 fl_set_button(form->Translations, ((flags & 8) != 0));
1898 fl_set_button(form->Subfigure, (subfigure != 0));
1900 psubfigure = subfigure;
1901 fl_set_input(form->Width, tostr(xwid).c_str());
1902 fl_set_input(form->Height, tostr(xhgh).c_str());
1903 fl_set_input(form->Angle, tostr(angle).c_str());
1904 if (!fname.empty()){
1905 string buf1 = OnlyPath(owner->fileName());
1906 string fname2 = MakeRelPath(fname, buf1);
1907 fl_set_input(form->EpsFile, fname2.c_str());
1909 else fl_set_input(form->EpsFile, "");
1910 fl_set_input(form->Subcaption, subcaption.c_str());
1911 if(current_view->buffer()->isReadonly())
1912 DisableFigurePanel(form);
1918 void InsetFig::Preview(char const * p)
1923 lyxerr << "Cannot fork process!" << endl;
1928 return; // parent process
1931 string buf1 = OnlyPath(owner->fileName());
1932 string buf2 = MakeAbsPath(p, buf1);
1934 lyxerr << "Error during rendering "
1935 << execlp(lyxrc.view_pspic_command.c_str(),
1936 lyxrc.view_pspic_command.c_str(),
1943 void InsetFig::BrowseFile()
1945 static string current_figure_path;
1946 static int once = 0;
1949 if (lyxerr.debugging()) {
1950 lyxerr << "Filename: "
1951 << owner->fileName() << endl;
1953 string p = fl_get_input(form->EpsFile);
1955 string buf = MakeAbsPath(owner->fileName());
1956 string buf2 = OnlyPath(buf);
1958 buf = MakeAbsPath(p, buf2);
1959 buf = OnlyPath(buf);
1961 buf = OnlyPath(owner->fileName().c_str());
1964 // Does user clipart directory exist?
1965 string bufclip = AddName (user_lyxdir, "clipart");
1966 FileInfo fileInfo(bufclip);
1967 if (!(fileInfo.isOK() && fileInfo.isDir()))
1968 // No - bail out to system clipart directory
1969 bufclip = AddName (system_lyxdir, "clipart");
1972 fileDlg.SetButton(0, _("Clipart"), bufclip);
1973 fileDlg.SetButton(1, _("Document"), buf);
1977 ProhibitInput(current_view);
1979 p = fileDlg.Select(_("EPS Figure"),
1980 current_figure_path,
1983 p = fileDlg.Select(_("EPS Figure"), buf,
1986 AllowInput(current_view);
1988 if (p.empty()) return;
1990 buf = MakeRelPath(p, buf2);
1991 current_figure_path = OnlyPath(p);
1994 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1995 || contains(p, "%") || contains(p, " ")) {
1996 WriteAlert(_("Filename can't contain any "
1997 "of these characters:"),
1998 // xgettext:no-c-format
1999 _("space, '#', '~', '$' or '%'."));
2004 if (form) fl_set_input(form->EpsFile, buf.c_str());
2008 void GraphicsCB(FL_OBJECT * obj, long arg)
2010 /* obj->form contains the form */
2012 if (lyxerr.debugging()) {
2013 lyxerr << "GraphicsCB callback: " << arg << endl;
2016 /* find inset we were reacting to */
2017 for (figures_type::iterator it = figures.begin();
2018 it != figures.end(); ++it)
2019 if ((*it)->inset->form && (*it)->inset->form->Figure
2021 if (lyxerr.debugging()) {
2022 lyxerr << "Calling back figure "
2025 (*it)->inset->CallbackFig(arg);
2031 void HideFiguresPopups()
2033 for (figures_type::iterator it = figures.begin();
2034 it != figures.end(); ++it)
2035 if ((*it)->inset->form
2036 && (*it)->inset->form->Figure->visible) {
2037 if (lyxerr.debugging()) {
2038 lyxerr << "Hiding figure " << (*it) << endl;
2040 // hide and free the form
2041 (*it)->inset->CallbackFig(9);