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);
614 XChangeProperty(tempdisp,
615 fl_get_canvas_id(figinset_canvas),
616 XInternAtom(tempdisp, "GHOSTVIEW", false),
617 XInternAtom(tempdisp, "STRING", false),
620 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
623 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str())),
627 XUngrabServer(tempdisp);
634 ostrstream t3(tbuf3, sizeof(tbuf3));
636 switch (p->data->flags & 3) {
637 case 0: t3 << 'H'; break; // Hidden
638 case 1: t3 << 'M'; break; // Mono
639 case 2: t3 << 'G'; break; // Gray
648 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
649 << ' ' << background_pixel;
654 XGrabServer(tempdisp);
655 XChangeProperty(tempdisp,
656 fl_get_canvas_id(figinset_canvas),
657 XInternAtom(tempdisp,
658 "GHOSTVIEW_COLORS", false),
659 XInternAtom(tempdisp, "STRING", false),
662 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
665 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str())),
669 XUngrabServer(tempdisp);
672 if (lyxerr.debugging()) {
673 lyxerr << "Releasing the server" << endl;
675 XCloseDisplay(tempdisp);
677 // set up environment
680 typedef char * char_p;
681 env = new char_p[ne + 2];
683 string tmp = t2.str().c_str();
684 env[0] = new char[tmp.size() + 1];
685 std::copy(tmp.begin(), tmp.end(), env[0]);
686 env[0][tmp.size()] = '\0';
690 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
693 // now make gs command
695 // close(1); do NOT close. If GS writes out
696 // errors it would hang. (Matthias 290596)
698 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
699 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
701 // now chdir into dir with .eps file, to be on the safe
703 ::chdir(OnlyPath(p->data->fname).c_str());
704 // make temp file name
705 string tmpf = make_tmp(getpid());
706 if (lyxerr.debugging()) {
707 lyxerr << "starting gs " << tmpf << " "
709 << ", pid: " << getpid() << endl;
712 int err = ::execlp(lyxrc.ps_command.c_str(),
713 lyxrc.ps_command.c_str(),
715 "-dNOPAUSE", "-dQUIET",
717 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
718 p->data->fname.c_str(),
719 "showpage.ps", "quit.ps", "-", 0);
720 // if we are still there, an error occurred.
721 lyxerr << "Error executing ghostscript. "
722 << "Code: " << err << endl;
723 lyxerr.debug() << "Cmd: "
726 << tmpf.c_str() << ' '
727 << p->data->fname << endl;
730 // normal process (parent)
731 if (lyxerr.debugging()) {
732 lyxerr << "GS [" << pid << "] started" << endl;
735 p->data->gspid = pid;
743 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
745 // recompute the stuff and put in the queue
749 p.rx = (float(data->raw_wid) * 72.0) / pswid;
750 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
756 // if possible, run the queue
762 figdata * getfigdata(int wid, int hgh, string const & fname,
763 int psx, int psy, int pswid, int pshgh,
764 int raw_wid, int raw_hgh, float angle, char flags)
766 /* first search for an exact match with fname and width/height */
768 if (fname.empty()) return 0;
770 for (bitmaps_type::iterator it = bitmaps.begin();
771 it != bitmaps.end(); ++it) {
772 if ((*it)->wid == wid && (*it)->hgh == hgh &&
773 (*it)->flags == flags && (*it)->fname == fname &&
774 (*it)->angle == angle) {
779 figdata * p = new figdata;
782 p->raw_wid = raw_wid;
783 p->raw_hgh = raw_hgh;
787 bitmaps.push_back(p);
788 XWindowAttributes wa;
789 XGetWindowAttributes(fl_display, fl_get_canvas_id(
790 figinset_canvas), &wa);
792 if (lyxerr.debugging()) {
793 lyxerr << "Create pixmap disp:" << fl_display
794 << " scr:" << DefaultScreen(fl_display)
797 << " depth:" << wa.depth << endl;
805 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
806 figinset_canvas), wid, hgh, wa.depth);
808 // initialize reading of .eps file with correct sizes and stuff
809 addwait(psx, psy, pswid, pshgh, p);
821 void getbitmap(figdata * p)
828 void makeupdatelist(figdata * p)
830 for(figures_type::iterator it = figures.begin();
831 it != figures.end(); ++it)
832 if ((*it)->data == p) {
833 if (lyxerr.debugging()) {
834 lyxerr << "Updating inset "
838 // add inset figures[i]->inset into to_update list
839 current_view->pushIntoUpdateList((*it)->inset);
844 // this func is only "called" in spellchecker.C
845 void sigchldchecker(pid_t pid, int * status)
847 lyxerr.debug() << "Got pid = " << pid << endl;
848 bool pid_handled = false;
849 for (bitmaps_type::iterator it = bitmaps.begin();
850 it != bitmaps.end(); ++it) {
851 if ((*it)->reading && pid == (*it)->gspid) {
852 lyxerr.debug() << "Found pid in bitmaps" << endl;
853 // now read the file and remove it from disk
856 if ((*it)->gsdone) *status = 0;
858 lyxerr.debug() << "GS [" << pid
859 << "] exit OK." << endl;
861 lyxerr << "GS [" << pid << "] error "
863 << WIFEXITED(*status)
864 << " " << WEXITSTATUS(*status)
865 << " S:" << WIFSIGNALED(*status)
866 << " " << WTERMSIG(*status) << endl;
869 bitmap_waiting = true;
872 // remove temporary files
873 unlink(make_tmp(p->gspid).c_str());
877 makeupdatelist((*it));
884 lyxerr.debug() << "Checking pid in pidwait" << endl;
885 list<int>::iterator it = find(pidwaitlist.begin(),
886 pidwaitlist.end(), pid);
887 if (it != pidwaitlist.end()) {
888 lyxerr.debug() << "Found pid in pidwait\n"
889 << "Caught child pid of recompute "
890 "routine" << pid << endl;
891 pidwaitlist.erase(it);
895 lyxerr.debug() << "waitpid error" << endl;
898 lyxerr << "The process or process group specified by "
899 "pid does not exist or is not a child of "
900 "the calling process or can never be in the "
901 "states specified by options." << endl;
904 lyxerr << "waitpid() was interrupted due to the "
905 "receipt of a signal sent by the calling "
909 lyxerr << "An invalid value was specified for "
913 lyxerr << "Unknown error from waitpid" << endl;
916 } else if (pid == 0) {
917 lyxerr << "waitpid nohang" << endl;;
919 lyxerr.debug() << "normal exit from childhandler" << endl;
927 bitmap_waiting = false;
928 for (bitmaps_type::iterator it = bitmaps.begin();
929 it != bitmaps.end(); ++it)
930 if ((*it)->gspid > 0 && !(*it)->reading)
936 void RegisterFigure(InsetFig * fi)
938 if (figures.empty()) InitFigures();
940 Figref * tmpfig = new Figref;
943 figures.push_back(tmpfig);
946 if (lyxerr.debugging()) {
947 lyxerr << "Register Figure: buffer:["
948 << current_view->buffer() << "]" << endl;
954 void UnregisterFigure(InsetFig * fi)
956 Figref * tmpfig = fi->figure;
958 if (tmpfig->data) freefigdata(tmpfig->data);
959 if (tmpfig->inset->form) {
960 if (tmpfig->inset->form->Figure->visible) {
961 fl_set_focus_object(tmpfig->inset->form->Figure,
962 tmpfig->inset->form->OkBtn);
963 fl_hide_form(tmpfig->inset->form->Figure);
965 #if FL_REVISION == 89
966 #warning Reactivate this free_form calls
968 fl_free_form(tmpfig->inset->form->Figure);
969 free(tmpfig->inset->form); // Why free?
970 tmpfig->inset->form = 0;
973 figures.erase(find(figures.begin(), figures.end(), tmpfig));
976 if (figures.empty()) DoneFigures();
980 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
990 psubfigure = subfigure = false;
991 xwid = xhgh = angle = 0;
993 raw_wid = raw_hgh = 0;
994 changedfname = false;
995 RegisterFigure(this);
999 InsetFig::~InsetFig()
1001 if (lyxerr.debugging()) {
1002 lyxerr << "Figure destructor called" << endl;
1004 UnregisterFigure(this);
1008 int InsetFig::ascent(Painter &, LyXFont const &) const
1014 int InsetFig::descent(Painter &, LyXFont const &) const
1020 int InsetFig::width(Painter &, LyXFont const &) const
1026 void InsetFig::draw(Painter & pain, LyXFont const & f,
1027 int baseline, float & x) const
1031 if (bitmap_waiting) getbitmaps();
1033 // I wish that I didn't have to use this
1034 // but the figinset code is so complicated so
1035 // I don't want to fiddle with it now.
1037 if (figure && figure->data && figure->data->bitmap &&
1038 !figure->data->reading && !figure->data->broken) {
1040 pain.pixmap(int(x + 1), baseline - hgh,
1041 wid, hgh, figure->data->bitmap);
1044 pain.rectangle(int(x), baseline - hgh - 1,
1050 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1052 if (figure && figure->data) {
1053 if (figure->data->broken) msg = _("[render error]");
1054 else if (figure->data->reading) msg = _("[rendering ... ]");
1056 if (fname.empty()) msg = _("[no file]");
1057 else if ((flags & 3) == 0) msg = _("[not displayed]");
1058 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1060 if (!msg) msg = _("[unknown error]");
1062 font.setFamily(LyXFont::SANS_FAMILY);
1063 font.setSize(LyXFont::SIZE_FOOTNOTE);
1064 string justname = OnlyFilename (fname);
1065 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1068 font.setSize(LyXFont::SIZE_TINY);
1069 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1071 x += width(pain, font); // ?
1075 void InsetFig::Write(ostream & os) const
1078 os << "Figure size " << wid << " " << hgh << "\n";
1079 if (!fname.empty()) {
1080 string buf1 = OnlyPath(owner->fileName());
1081 string fname2 = MakeRelPath(fname, buf1);
1082 os << "file " << fname2 << "\n";
1084 if (!subcaption.empty())
1085 os << "subcaption " << subcaption << "\n";
1086 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1087 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1088 if (angle != 0) os << "angle " << angle << "\n";
1089 os << "flags " << flags << "\n";
1090 if (subfigure) os << "subfigure\n";
1094 void InsetFig::Read(LyXLex & lex)
1097 bool finished = false;
1099 while (lex.IsOK() && !finished) {
1102 string const token = lex.GetString();
1103 lyxerr.debug() << "Token: " << token << endl;
1107 else if (token == "\\end_inset") {
1109 } else if (token == "file") {
1111 buf = lex.GetString();
1112 string buf1 = OnlyPath(owner->fileName());
1113 fname = MakeAbsPath(buf, buf1);
1114 changedfname = true;
1116 } else if (token == "extra") {
1118 // kept for backwards compability. Delete in 0.13.x
1119 } else if (token == "subcaption") {
1121 subcaption = lex.GetString();
1122 } else if (token == "label") {
1124 // kept for backwards compability. Delete in 0.13.x
1125 } else if (token == "angle") {
1127 angle = lex.GetFloat();
1128 } else if (token == "size") {
1130 wid = lex.GetInteger();
1132 hgh = lex.GetInteger();
1133 } else if (token == "flags") {
1135 flags = pflags = lex.GetInteger();
1136 } else if (token == "subfigure") {
1137 subfigure = psubfigure = true;
1138 } else if (token == "width") {
1141 typ = lex.GetInteger();
1143 xwid = lex.GetFloat();
1145 case DEF: wtype = DEF; break;
1146 case CM: wtype = CM; break;
1147 case IN: wtype = IN; break;
1148 case PER_PAGE: wtype = PER_PAGE; break;
1149 case PER_COL: wtype = PER_COL; break;
1151 lyxerr.debug() << "Unknown type!" << endl;
1155 } else if (token == "height") {
1158 typ = lex.GetInteger();
1160 xhgh = lex.GetFloat();
1162 case DEF: htype = DEF; break;
1163 case CM: htype = CM; break;
1164 case IN: htype = IN; break;
1165 case PER_PAGE: htype = PER_PAGE; break;
1167 lyxerr.debug() << "Unknown type!" << endl;
1178 int InsetFig::Latex(ostream & os,
1179 bool /* fragile*/, bool /* fs*/) const
1182 if (!cmd.empty()) os << cmd << " ";
1187 int InsetFig::Ascii(ostream &) const
1193 int InsetFig::Linuxdoc(ostream &) const
1199 int InsetFig::DocBook(ostream & os) const
1201 string figurename = fname;
1203 if(suffixIs(figurename, ".eps"))
1204 figurename.erase(fname.length() - 4);
1206 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1211 void InsetFig::Validate(LaTeXFeatures & features) const
1213 features.graphics = true;
1214 if (subfigure) features.subfigure = true;
1218 Inset::EDITABLE InsetFig::Editable() const
1224 bool InsetFig::Deletable() const
1230 char const * InsetFig::EditMessage() const
1232 return _("Opened figure");
1236 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1238 lyxerr.debug() << "Editing InsetFig." << endl;
1241 // We should have RO-versions of the form instead.
1242 // The actual prevention of altering a readonly doc
1243 // is done in CallbackFig()
1244 if(bv->buffer()->isReadonly())
1245 WarnReadonly(bv->buffer()->fileName());
1248 form = create_form_Figure();
1249 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1250 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1251 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1252 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1255 if (form->Figure->visible) {
1256 fl_raise_form(form->Figure);
1258 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1259 FL_FULLBORDER, _("Figure"));
1264 Inset * InsetFig::Clone() const
1266 InsetFig * tmp = new InsetFig(100, 100, owner);
1268 if (lyxerr.debugging()) {
1269 lyxerr << "Clone Figure: buffer:["
1270 << current_view->buffer()
1271 << "], cbuffer:[xx]" << endl;
1276 tmp->raw_wid = raw_wid;
1277 tmp->raw_hgh = raw_hgh;
1282 tmp->pflags = pflags;
1283 tmp->subfigure = subfigure;
1284 tmp->psubfigure = psubfigure;
1292 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1294 // do not display if there is
1295 // "do not display" chosen (Matthias 260696)
1296 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1297 pswid, pshgh, raw_wid, raw_hgh,
1298 angle, flags & (3|8));
1299 } else tmp->figure->data = 0;
1300 tmp->subcaption = subcaption;
1301 tmp->changedfname = false;
1308 Inset::Code InsetFig::LyxCode() const
1310 return Inset::GRAPHICS_CODE;
1315 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1321 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1322 res = tostr(f) + "cm";
1325 res = tostr(f) + "in";
1327 case InsetFig::PER_PAGE:
1328 res = tostr(f/100) + "\\text" + suffix;
1330 case InsetFig::PER_COL:
1331 // Doesn't occur for htype...
1332 res = tostr(f/100) + "\\column" + suffix;
1339 void InsetFig::Regenerate() const
1342 string resizeW, resizeH;
1343 string rotate, recmd;
1345 if (fname.empty()) {
1346 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1347 cmd += _("empty figure path");
1352 string buf1 = OnlyPath(owner->fileName());
1353 string fname2 = MakeRelPath(fname, buf1);
1355 string gcmd = "\\includegraphics{" + fname2 + '}';
1356 resizeW = stringify(wtype, xwid, "width");
1357 resizeH = stringify(htype, xhgh, "height");
1359 if (!resizeW.empty() || !resizeH.empty()) {
1360 recmd = "\\resizebox*{";
1361 if (!resizeW.empty())
1366 if (!resizeH.empty())
1375 // \rotatebox{angle}{text}
1376 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1382 if (!rotate.empty()) cmdbuf += '}';
1383 if (!recmd.empty()) cmdbuf += '}';
1385 if (!subcaption.empty())
1386 cmdbuf = "\\subfigure[" + subcaption +
1387 "]{" + cmdbuf + "}";
1389 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1396 void InsetFig::TempRegenerate()
1399 string resizeW, resizeH;
1400 string rotate, recmd;
1402 char const * tfname = fl_get_input(form->EpsFile);
1403 string tsubcap = fl_get_input(form->Subcaption);
1404 float tangle = atof(fl_get_input(form->Angle));
1405 float txwid = atof(fl_get_input(form->Width));
1406 float txhgh = atof(fl_get_input(form->Height));
1408 if (!tfname || !*tfname) {
1409 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1410 cmd += _("empty figure path");
1415 string buf1 = OnlyPath(owner->fileName());
1416 string fname2 = MakeRelPath(tfname, buf1);
1417 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1418 string gcmd = "\\includegraphics{" + fname2 + '}';
1420 resizeW = stringify(twtype, txwid, "width");
1421 resizeH = stringify(thtype, txhgh, "height");
1423 // \resizebox*{h-length}{v-length}{text}
1424 if (!resizeW.empty() || !resizeH.empty()) {
1425 recmd = "\\resizebox*{";
1426 if (!resizeW.empty())
1431 if (!resizeH.empty())
1439 // \rotatebox{angle}{text}
1440 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1443 cmdbuf = recmd + rotate + gcmd;
1444 if (!rotate.empty()) cmdbuf += '}';
1445 if (!recmd.empty()) cmdbuf += '}';
1446 if (psubfigure && !tsubcap.empty()) {
1447 cmdbuf = string("\\subfigure{") + tsubcap
1448 + string("}{") + cmdbuf + "}";
1453 void InsetFig::Recompute()
1455 bool changed = changedfname;
1456 int newx, newy, nraw_x, nraw_y;
1458 if (changed) GetPSSizes();
1460 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1461 float cos_a = cos (angle / DEG2PI);
1462 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1463 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1465 /* now recompute wid and hgh, and if that is changed, set changed */
1466 /* this depends on chosen size of the picture and its bbox */
1467 // This will be redone in 0.13 ... (hen)
1468 if (!fname.empty()) {
1469 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1477 newx = int(28.346 * xwid);
1480 newx = int(72 * xwid);
1482 case PER_PAGE: /* % of page */
1483 newx = int(5.95 * xwid);
1485 case PER_COL: /* % of col */
1486 newx = int(2.975 * xwid);
1490 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1494 //lyxerr << "This should not happen!" << endl;
1497 newy = int(28.346 * xhgh);
1500 newy = int(72 * xhgh);
1502 case PER_PAGE: /* % of page */
1503 newy = int(8.42 * xhgh);
1506 // Doesn't occur; case exists to suppress
1507 // compiler warnings.
1510 if (htype && !wtype && frame_hgh)
1511 newx = newy*frame_wid/frame_hgh;
1520 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1525 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1527 // cannot be zero, actually, set it to some minimum, so its clickable
1528 if (newx < 5) newx = 5;
1529 if (newy < 5) newy = 5;
1531 if (newx != wid || newy != hgh ||
1532 nraw_x != raw_wid || nraw_y != raw_hgh ||
1533 flags != pflags || subfigure != psubfigure)
1541 subfigure = psubfigure;
1544 figdata * pf = figure->data;
1547 if (!fname.empty() && (flags & 3)
1548 && !lyxrc.ps_command.empty()) {
1549 // do not display if there is "do not display"
1550 // chosen (Matthias 260696)
1551 figure->data = getfigdata(wid, hgh, fname,
1552 psx, psy, pswid, pshgh,
1554 angle, flags & (3|8));
1555 } else figure->data = 0;
1557 // free the old data
1558 if (pf) freefigdata(pf);
1561 changedfname = false;
1565 void InsetFig::GetPSSizes()
1567 /* get %%BoundingBox: from postscript file */
1569 /* defaults to associated size
1570 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1577 if (fname.empty()) return;
1579 ifstream ifs(fname.c_str());
1581 if (!ifs) return; // file not found !!!!
1583 /* defaults to A4 page */
1589 char lastchar = 0; ifs.get(lastchar);
1591 char c = 0; ifs.get(c);
1593 lyxerr.debug() << "End of (E)PS file reached and"
1594 " no BoundingBox!" << endl;
1597 if (c == '%' && lastchar == '%') {
1599 if (p.empty()) break;
1600 lyxerr.debug() << "Token: `" << p << "'" << endl;
1601 if (p == "BoundingBox:") {
1602 float fpsx, fpsy, fpswid, fpshgh;
1603 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1606 pswid = int(fpswid);
1607 pshgh = int(fpshgh);
1609 if (lyxerr.debugging()) {
1610 lyxerr << "%%%%BoundingBox:"
1628 void InsetFig::CallbackFig(long arg)
1633 if (lyxerr.debugging()) {
1634 lyxerr << "Figure callback, arg " << arg << endl;
1640 case 12: /* width type */
1647 fl_deactivate_object(form->Width);
1652 fl_activate_object(form->Width);
1657 fl_activate_object(form->Width);
1662 fl_activate_object(form->Width);
1667 fl_activate_object(form->Width);
1670 lyxerr.debug() << "Unknown type!" << endl;
1677 case 22: /* height type */
1683 fl_deactivate_object(form->Height);
1688 fl_activate_object(form->Height);
1693 fl_activate_object(form->Height);
1698 fl_activate_object(form->Height);
1701 lyxerr.debug() << "Unknown type!" << endl;
1707 pflags = pflags & ~3; /* wysiwyg0 */
1710 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1713 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1716 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1719 pflags ^= 4; /* frame */
1722 pflags ^= 8; /* do translations */
1725 psubfigure = !psubfigure; /* This is a subfigure */
1728 regen = true; /* regenerate command */
1730 case 0: /* browse file */
1734 case 1: /* preview */
1735 p = fl_get_input(form->EpsFile);
1739 case 8: /* ok (apply and close) */
1740 if(!current_view->buffer()->isReadonly()) {
1743 xwid = atof(fl_get_input(form->Width));
1744 xhgh = atof(fl_get_input(form->Height));
1745 angle = atof(fl_get_input(form->Angle));
1746 p = fl_get_input(form->EpsFile);
1748 string buf1 = OnlyPath(owner->fileName());
1749 fname = MakeAbsPath(p, buf1);
1750 changedfname = true;
1752 if (!fname.empty()) {
1753 changedfname = true;
1757 subcaption = fl_get_input(form->Subcaption);
1761 /* now update inset */
1762 if (lyxerr.debugging()) {
1763 lyxerr << "Update: ["
1764 << wid << 'x' << hgh << ']' << endl;
1766 current_view->updateInset(this, true);
1768 fl_set_focus_object(form->Figure, form->OkBtn);
1769 fl_hide_form(form->Figure);
1770 #if FL_REVISION == 89
1771 #warning Reactivate this free_form calls
1773 fl_free_form(form->Figure);
1774 free(form); // Why free?
1780 // The user has already been informed about RO in ::Edit
1781 if(arg == 7) // if 'Apply'
1784 case 9: /* cancel = restore and close */
1785 fl_set_focus_object(form->Figure, form->OkBtn);
1786 fl_hide_form(form->Figure);
1787 #if FL_REVISION == 89
1788 #warning Reactivate this free_form calls
1789 #warning Jug, is this still a problem?
1791 fl_free_form(form->Figure);
1792 free(form); // Why free?
1798 if (regen) TempRegenerate();
1803 void DisableFigurePanel(FD_Figure * const form)
1805 fl_deactivate_object(form->EpsFile);
1806 fl_deactivate_object(form->Browse);
1807 fl_deactivate_object(form->Width);
1808 fl_deactivate_object(form->Height);
1809 fl_deactivate_object(form->Frame);
1810 fl_deactivate_object(form->Translations);
1811 fl_deactivate_object(form->Angle);
1812 fl_deactivate_object(form->HeightGrp);
1813 fl_deactivate_object(form->page2);
1814 fl_deactivate_object(form->Default2);
1815 fl_deactivate_object(form->cm2);
1816 fl_deactivate_object(form->in2);
1817 fl_deactivate_object(form->HeightLabel);
1818 fl_deactivate_object(form->WidthLabel);
1819 fl_deactivate_object(form->DisplayGrp);
1820 fl_deactivate_object(form->Wysiwyg3);
1821 fl_deactivate_object(form->Wysiwyg0);
1822 fl_deactivate_object(form->Wysiwyg2);
1823 fl_deactivate_object(form->Wysiwyg1);
1824 fl_deactivate_object(form->WidthGrp);
1825 fl_deactivate_object(form->Default1);
1826 fl_deactivate_object(form->cm1);
1827 fl_deactivate_object(form->in1);
1828 fl_deactivate_object(form->page1);
1829 fl_deactivate_object(form->column1);
1830 fl_deactivate_object(form->Subcaption);
1831 fl_deactivate_object(form->Subfigure);
1832 fl_deactivate_object (form->OkBtn);
1833 fl_deactivate_object (form->ApplyBtn);
1834 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1835 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1840 void EnableFigurePanel(FD_Figure * const form)
1842 fl_activate_object(form->EpsFile);
1843 fl_activate_object(form->Browse);
1844 fl_activate_object(form->Width);
1845 fl_activate_object(form->Height);
1846 fl_activate_object(form->Frame);
1847 fl_activate_object(form->Translations);
1848 fl_activate_object(form->Angle);
1849 fl_activate_object(form->HeightGrp);
1850 fl_activate_object(form->page2);
1851 fl_activate_object(form->Default2);
1852 fl_activate_object(form->cm2);
1853 fl_activate_object(form->in2);
1854 fl_activate_object(form->HeightLabel);
1855 fl_activate_object(form->WidthLabel);
1856 fl_activate_object(form->DisplayGrp);
1857 fl_activate_object(form->Wysiwyg3);
1858 fl_activate_object(form->Wysiwyg0);
1859 fl_activate_object(form->Wysiwyg2);
1860 fl_activate_object(form->Wysiwyg1);
1861 fl_activate_object(form->WidthGrp);
1862 fl_activate_object(form->Default1);
1863 fl_activate_object(form->cm1);
1864 fl_activate_object(form->in1);
1865 fl_activate_object(form->page1);
1866 fl_activate_object(form->column1);
1867 fl_activate_object(form->Subcaption);
1868 fl_activate_object(form->Subfigure);
1869 fl_activate_object (form->OkBtn);
1870 fl_activate_object (form->ApplyBtn);
1871 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1872 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1876 void InsetFig::RestoreForm()
1878 EnableFigurePanel(form);
1881 fl_set_button(form->Default1, (wtype == 0));
1882 fl_set_button(form->cm1, (wtype == 1));
1883 fl_set_button(form->in1, (wtype == 2));
1884 fl_set_button(form->page1, (wtype == 3));
1885 fl_set_button(form->column1, (wtype == 4));
1887 fl_deactivate_object(form->Width);
1889 fl_activate_object(form->Width);
1892 // enable and disable should be put here.
1894 fl_set_button(form->Default2, (htype == 0));
1895 fl_set_button(form->cm2, (htype == 1));
1896 fl_set_button(form->in2, (htype == 2));
1897 fl_set_button(form->page2, (htype == 3));
1898 // enable and disable should be put here.
1900 fl_deactivate_object(form->Height);
1902 fl_activate_object(form->Height);
1905 int pflags = flags & 3;
1906 fl_set_button(form->Wysiwyg0, (pflags == 0));
1907 fl_set_button(form->Wysiwyg1, (pflags == 1));
1908 fl_set_button(form->Wysiwyg2, (pflags == 2));
1909 fl_set_button(form->Wysiwyg3, (pflags == 3));
1910 fl_set_button(form->Frame, ((flags & 4) != 0));
1911 fl_set_button(form->Translations, ((flags & 8) != 0));
1912 fl_set_button(form->Subfigure, (subfigure != 0));
1914 psubfigure = subfigure;
1915 fl_set_input(form->Width, tostr(xwid).c_str());
1916 fl_set_input(form->Height, tostr(xhgh).c_str());
1917 fl_set_input(form->Angle, tostr(angle).c_str());
1918 if (!fname.empty()){
1919 string buf1 = OnlyPath(owner->fileName());
1920 string fname2 = MakeRelPath(fname, buf1);
1921 fl_set_input(form->EpsFile, fname2.c_str());
1923 else fl_set_input(form->EpsFile, "");
1924 fl_set_input(form->Subcaption, subcaption.c_str());
1925 if(current_view->buffer()->isReadonly())
1926 DisableFigurePanel(form);
1932 void InsetFig::Preview(char const * p)
1937 lyxerr << "Cannot fork process!" << endl;
1942 return; // parent process
1945 string buf1 = OnlyPath(owner->fileName());
1946 string buf2 = MakeAbsPath(p, buf1);
1948 lyxerr << "Error during rendering "
1949 << execlp(lyxrc.view_pspic_command.c_str(),
1950 lyxrc.view_pspic_command.c_str(),
1957 void InsetFig::BrowseFile()
1959 static string current_figure_path;
1960 static int once = 0;
1963 if (lyxerr.debugging()) {
1964 lyxerr << "Filename: "
1965 << owner->fileName() << endl;
1967 string p = fl_get_input(form->EpsFile);
1969 string buf = MakeAbsPath(owner->fileName());
1970 string buf2 = OnlyPath(buf);
1972 buf = MakeAbsPath(p, buf2);
1973 buf = OnlyPath(buf);
1975 buf = OnlyPath(owner->fileName().c_str());
1978 // Does user clipart directory exist?
1979 string bufclip = AddName (user_lyxdir, "clipart");
1980 FileInfo fileInfo(bufclip);
1981 if (!(fileInfo.isOK() && fileInfo.isDir()))
1982 // No - bail out to system clipart directory
1983 bufclip = AddName (system_lyxdir, "clipart");
1986 fileDlg.SetButton(0, _("Clipart"), bufclip);
1987 fileDlg.SetButton(1, _("Document"), buf);
1991 ProhibitInput(current_view);
1993 p = fileDlg.Select(_("EPS Figure"),
1994 current_figure_path,
1997 p = fileDlg.Select(_("EPS Figure"), buf,
2000 AllowInput(current_view);
2002 if (p.empty()) return;
2004 buf = MakeRelPath(p, buf2);
2005 current_figure_path = OnlyPath(p);
2008 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2009 || contains(p, "%") || contains(p, " ")) {
2010 WriteAlert(_("Filename can't contain any "
2011 "of these characters:"),
2012 // xgettext:no-c-format
2013 _("space, '#', '~', '$' or '%'."));
2018 if (form) fl_set_input(form->EpsFile, buf.c_str());
2022 void GraphicsCB(FL_OBJECT * obj, long arg)
2024 /* obj->form contains the form */
2026 if (lyxerr.debugging()) {
2027 lyxerr << "GraphicsCB callback: " << arg << endl;
2030 /* find inset we were reacting to */
2031 for (figures_type::iterator it = figures.begin();
2032 it != figures.end(); ++it)
2033 if ((*it)->inset->form && (*it)->inset->form->Figure
2035 if (lyxerr.debugging()) {
2036 lyxerr << "Calling back figure "
2039 (*it)->inset->CallbackFig(arg);
2045 void HideFiguresPopups()
2047 for (figures_type::iterator it = figures.begin();
2048 it != figures.end(); ++it)
2049 if ((*it)->inset->form
2050 && (*it)->inset->form->Figure->visible) {
2051 if (lyxerr.debugging()) {
2052 lyxerr << "Hiding figure " << (*it) << endl;
2054 // hide and free the form
2055 (*it)->inset->CallbackFig(9);