2 * figinset.C - part of LyX project
5 /* Rework of path-handling (Matthias 04.07.1996 )
6 * ------------------------------------------------
7 * figinsets keep an absolute path to the eps-file.
8 * For the user alway a relative path appears
9 * (in lyx-file, latex-file and edit-popup).
10 * To calculate this relative path the path to the
11 * document where the figinset is in is needed.
12 * This is done by a reference to the buffer, called
13 * figinset::cbuffer. To be up to date the cbuffer
14 * is sometimes set to the current buffer
15 * bufferlist.current(), when it can be assumed that
16 * this operation happens in the current buffer.
17 * This is true for InsetFig::Edit(...),
18 * InsetFig::InsetFig(...), InsetFig::Read(...),
19 * InsetFig::Write and InsetFig::Latex(...).
20 * Therefore the bufferlist has to make sure that
21 * during these operations bufferlist.current()
22 * returns the buffer where the figinsets are in.
23 * This made few changes in buffer.C necessary.
25 * The above is not totally valid anymore. (Lgb)
35 #include FORMS_H_LOCATION
50 #include "support/filetools.h"
51 #include "LyXView.h" // just because of form_main
53 #include "LaTeXFeatures.h"
56 #include "lyx_gui_misc.h" // CancelCloseBoxCB
57 #include "support/FileInfo.h"
58 #include "support/lyxlib.h"
74 extern BufferView * current_view;
75 extern FL_OBJECT * figinset_canvas;
77 extern char ** environ; // is this only redundtant on linux systems? Lgb.
79 static float const DEG2PI = 57.295779513;
81 struct queue_element {
82 float rx, ry; // resolution x and y
83 int ofsx, ofsy; // x and y translation
84 figdata * data; // we are doing it for this data
87 static int const MAXGS = 3; /* maximum 3 gs's at a time */
89 typedef vector<Figref *> figures_type;
90 typedef vector<figdata *> bitmaps_type;
91 static figures_type figures; // all figures
92 static bitmaps_type bitmaps; // all bitmaps
94 static queue<queue_element> gsqueue; // queue for ghostscripting
96 static int gsrunning = 0; /* currently so many gs's are running */
97 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
98 static char bittable[256]; /* bit reversion table */
100 static bool gs_color; // do we allocate colors for gs?
101 static bool color_visual; // is the visual color?
102 static bool gs_xcolor = false; // allocated extended colors
103 static unsigned long gs_pixels[128]; // allocated pixels
104 static int gs_num_pixels; // number of pixels allocated
105 static int gs_spc; // shades per color
106 static bool gs_gray; // is grayscale?
107 static int gs_allcolors; // number of all colors
109 static list<int> pidwaitlist; // pid wait list
116 val.foreground = BlackPixel(fl_display,
117 DefaultScreen(fl_display));
120 val.graphics_exposures = false;
121 val.line_style = LineSolid;
123 return XCreateGC(fl_display, RootWindow(fl_display, 0),
124 GCForeground | GCFunction | GCGraphicsExposures
125 | GCLineWidth | GCLineStyle , &val);
133 void addpidwait(int pid)
135 // adds pid to pid wait list
136 pidwaitlist.push_back(pid);
138 if (lyxerr.debugging()) {
139 lyxerr << "Pids to wait for: \n";
140 for (list<int>::const_iterator cit = pidwaitlist.begin();
141 cit != pidwaitlist.end(); ++cit) {
142 lyxerr << (*cit) << '\n';
150 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
155 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
157 if(lyxerr.debugging()) {
158 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
159 << "] pm:[" << e->data.l[1] << "]" << endl;
162 // just kill gs, that way it will work for sure
163 // This loop looks like S**T so it probably is...
164 //for (bitmaps_type::size_type i = 0; i < bitmaps.size(); ++i)
165 for (bitmaps_type::iterator it = bitmaps.begin();
166 it != bitmaps.end(); ++it)
167 if (static_cast<long>((*it)->bitmap) ==
168 static_cast<long>(e->data.l[1])) {
173 // first update p->bitmap, if necessary
174 if (p->bitmap != None
175 && p->flags > (1|8) && gs_color && p->wid) {
176 // query current colormap and re-render
177 // the pixmap with proper colors
178 XWindowAttributes wa;
179 register XImage * im;
183 int spc1 = gs_spc - 1;
184 int spc2 = gs_spc * gs_spc;
188 GC gc = local_gc_copy;
190 XGetWindowAttributes(fl_display,
195 if (lyxerr.debugging()) {
196 lyxerr << "Starting image translation "
199 << p->wid << "x" << p->hgh
201 << " " << XYPixmap << endl;
203 // now fork rendering process
205 if (forkstat == -1) {
207 << "Cannot fork, using slow "
208 "method for pixmap translation." << endl;
209 tmpdisp = fl_display;
210 } else if (forkstat > 0) { // parent
212 if (lyxerr.debugging()) {
213 lyxerr << "Spawned child "
216 addpidwait(forkstat);
219 tmpdisp = XOpenDisplay(XDisplayName(0));
222 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
223 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
225 if (lyxerr.debugging()) {
226 lyxerr << "Got the image" << endl;
229 if (lyxerr.debugging()) {
230 lyxerr << "Error getting the image" << endl;
235 // query current colormap
236 XColor * cmap = new XColor[gs_allcolors];
237 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
238 XQueryColors(tmpdisp,
239 fl_state[fl_get_vclass()]
244 // now we process all the image
245 for (y = 0; y < p->hgh; ++y) {
246 for (int x = 0; x < wid; ++x) {
251 gs_pixels[((pc->red+6553)*
252 spc1/65535)*spc2+((pc->green+6553)*
253 spc1/65535)*gs_spc+((pc->blue+6553)*
258 // This must be correct.
260 if (lyxerr.debugging()) {
261 lyxerr << "Putting image back"
264 XPutImage(tmpdisp, p->bitmap,
266 0, 0, p->wid, p->hgh);
268 if (lyxerr.debugging()) {
269 lyxerr << "Done translation"
274 if (lyxerr.debugging()) {
275 lyxerr << "Killing gs "
278 lyx::kill(p->gspid, SIGHUP);
280 sprintf(tmp, "%s/~lyxgs%d.ps",
281 system_tempdir.c_str(),
285 XCloseDisplay(tmpdisp);
289 if (lyxerr.debugging()) {
290 lyxerr << "Killing gs "
293 lyx::kill(p->gspid, SIGHUP);
295 sprintf(tmp, "%s/~lyxgs%d.ps",
296 system_tempdir.c_str(),
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,
407 GhostscriptMsg, current_view->owner()->getMainForm());
409 local_gc_copy = createGC();
411 Visual * vi = DefaultVisual(fl_display, 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;
460 // kill ghostscript and unlink it's files
462 lyx::kill(pid, SIGKILL);
463 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
467 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
468 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
476 // run queued requests for ghostscript, if any
477 if (!gsrunning && gs_color && !gs_xcolor) {
478 // here alloc all colors, so that gs will use only
479 // those we allocated for it
484 while (gsrunning < MAXGS) {
485 char tbuf[384], tbuf2[80];
489 if (gsqueue.empty()) {
490 if (!gsrunning && gs_xcolor) {
491 // de-allocate rest of colors
497 queue_element * p = &gsqueue.front();
506 if (lyxerr.debugging()) {
507 lyxerr << "GS start error! Cannot fork."
510 p->data->broken = true;
511 p->data->reading = false;
514 if (pid == 0) { // child
515 char ** env, rbuf[80], gbuf[40];
517 Display * tempdisp = XOpenDisplay(XDisplayName(0));
519 // create translation file
520 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
524 ofs << "gsave clippath pathbbox grestore\n"
526 << "/ury exch def /urx exch def /lly exch def "
528 << p->data->wid / 2.0 << " "
529 << p->data->hgh / 2.0 << " translate\n"
530 << p->data->angle << " rotate\n"
531 << -(p->data->raw_wid / 2.0) << " "
532 << -(p->data->raw_hgh / 2.0) << " translate\n"
533 << p->rx / 72.0 << " " << p->ry / 72.0
535 << -p->ofsx << " " << -p->ofsy << " translate\n"
537 ofs.close(); // Don't remove this.
539 // gs process - set ghostview environment first
540 sprintf(tbuf2, "GHOSTVIEW=%ld %ld", fl_get_canvas_id(
541 figinset_canvas), p->data->bitmap);
543 // now set up ghostview property on a window
544 sprintf(tbuf, "0 0 0 0 %d %d 72 72 0 0 0 0",
545 p->data->wid, p->data->hgh);
546 // #warning BUG seems that the only bug here
547 // might be the hardcoded dpi.. Bummer!
549 if (lyxerr.debugging()) {
550 lyxerr << "Will set GHOSTVIEW property to ["
551 << tbuf << "]" << endl;
553 // wait until property is deleted if executing multiple
556 // grab server to prevent other child
557 // interfering with setting GHOSTVIEW property
558 if (lyxerr.debugging()) {
559 lyxerr << "Grabbing the server"
562 XGrabServer(tempdisp);
563 prop = XListProperties(tempdisp,
565 figinset_canvas), &nprop);
569 for (i = 0; i < nprop; ++i) {
570 char * p = XGetAtomName(tempdisp,
572 if (strcmp(p, "GHOSTVIEW") == 0) {
578 XFree(reinterpret_cast<char *>(prop)); // jc:
580 // release the server
581 XUngrabServer(tempdisp);
583 // ok, property found, we must wait until
584 // ghostscript deletes it
585 if (lyxerr.debugging()) {
586 lyxerr << "Releasing the server\n["
588 << "] GHOSTVIEW property"
589 " found. Waiting." << endl;
595 XChangeProperty(tempdisp,
596 fl_get_canvas_id(figinset_canvas),
597 XInternAtom(tempdisp, "GHOSTVIEW", false),
598 XInternAtom(tempdisp, "STRING", false),
600 reinterpret_cast<unsigned char*>(tbuf),
603 switch (p->data->flags & 3) {
604 case 0: tbuf[0] = 'H'; break; // Hidden
605 case 1: tbuf[0] = 'M'; break; // Mono
606 case 2: tbuf[0] = 'G'; break; // Gray
609 tbuf[0] = 'C'; // Color
611 tbuf[0] = 'G'; // Gray
615 sprintf(tbuf+1, " %ld %ld", BlackPixelOfScreen(
616 DefaultScreenOfDisplay(fl_display)),
617 fl_get_pixel(FL_WHITE));
619 XChangeProperty(tempdisp,
620 fl_get_canvas_id(figinset_canvas),
621 XInternAtom(tempdisp,
622 "GHOSTVIEW_COLORS", false),
623 XInternAtom(tempdisp, "STRING", false),
625 reinterpret_cast<unsigned char*>(tbuf),
627 XUngrabServer(tempdisp);
629 if (lyxerr.debugging()) {
630 lyxerr << "Releasing the server" << endl;
632 XCloseDisplay(tempdisp);
634 // set up environment
635 while (environ[ne]) ++ne;
636 typedef char * char_p;
637 env = new char_p[ne + 2];
639 memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
642 // now make gs command
644 // close(1); do NOT close. If GS writes out
645 // errors it would hang. (Matthias 290596)
646 sprintf(rbuf, "-r%gx%g", p->rx, p->ry);
647 sprintf(gbuf, "-g%dx%d", p->data->wid, p->data->hgh);
648 // now chdir into dir with .eps file, to be on the safe
650 chdir(OnlyPath(p->data->fname).c_str());
651 // make temp file name
652 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
654 if (lyxerr.debugging()) {
655 lyxerr << "starting gs " << tbuf << " "
657 << ", pid: " << getpid() << endl;
660 int err = execlp(lyxrc.ps_command.c_str(),
661 lyxrc.ps_command.c_str(),
663 "-dNOPAUSE", "-dQUIET",
666 p->data->fname.c_str(),
667 "showpage.ps", "quit.ps", "-", 0);
668 // if we are still there, an error occurred.
669 lyxerr << "Error executing ghostscript. "
670 << "Code: " << err << endl;
671 lyxerr.debug() << "Cmd: "
675 << p->data->fname << endl;
678 // normal process (parent)
679 if (lyxerr.debugging()) {
680 lyxerr << "GS [" << pid << "] started" << endl;
683 p->data->gspid = pid;
691 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
693 // recompute the stuff and put in the queue
697 p.rx = (float(data->raw_wid) * 72.0) / pswid;
698 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
704 // if possible, run the queue
710 figdata * getfigdata(int wid, int hgh, string const & fname,
711 int psx, int psy, int pswid, int pshgh,
712 int raw_wid, int raw_hgh, float angle, char flags)
714 /* first search for an exact match with fname and width/height */
716 if (fname.empty()) return 0;
718 for (bitmaps_type::iterator it = bitmaps.begin();
719 it != bitmaps.end(); ++it) {
720 if ((*it)->wid == wid && (*it)->hgh == hgh &&
721 (*it)->flags == flags && (*it)->fname == fname &&
722 (*it)->angle == angle) {
727 figdata * p = new figdata;
730 p->raw_wid = raw_wid;
731 p->raw_hgh = raw_hgh;
735 bitmaps.push_back(p);
736 XWindowAttributes wa;
737 XGetWindowAttributes(fl_display, fl_get_canvas_id(
738 figinset_canvas), &wa);
740 if (lyxerr.debugging()) {
741 lyxerr << "Create pixmap disp:" << fl_display
742 << " scr:" << DefaultScreen(fl_display)
745 << " depth:" << wa.depth << endl;
753 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
754 figinset_canvas), wid, hgh, wa.depth);
756 // initialize reading of .eps file with correct sizes and stuff
757 addwait(psx, psy, pswid, pshgh, p);
769 void getbitmap(figdata * p)
776 void makeupdatelist(figdata * p)
778 for(figures_type::iterator it = figures.begin();
779 it != figures.end(); ++it)
780 if ((*it)->data == p) {
781 if (lyxerr.debugging()) {
782 lyxerr << "Updating inset "
786 // add inset figures[i]->inset into to_update list
787 current_view->pushIntoUpdateList((*it)->inset);
792 // this func is only "called" in spellchecker.C
793 void sigchldchecker(pid_t pid, int * status)
795 lyxerr.debug() << "Got pid = " << pid << endl;
796 bool pid_handled = false;
797 for (bitmaps_type::iterator it = bitmaps.begin();
798 it != bitmaps.end(); ++it) {
799 if ((*it)->reading && pid == (*it)->gspid) {
800 lyxerr.debug() << "Found pid in bitmaps" << endl;
801 // now read the file and remove it from disk
804 if ((*it)->gsdone) *status = 0;
806 lyxerr.debug() << "GS [" << pid
807 << "] exit OK." << endl;
809 lyxerr << "GS [" << pid << "] error "
811 << WIFEXITED(*status)
812 << " " << WEXITSTATUS(*status)
813 << " S:" << WIFSIGNALED(*status)
814 << " " << WTERMSIG(*status) << endl;
817 bitmap_waiting = true;
820 // remove temporary files
822 sprintf(tmp, "%s/~lyxgs%d.ps",
823 system_tempdir.c_str(),
829 makeupdatelist((*it));
836 lyxerr.debug() << "Checking pid in pidwait" << endl;
837 list<int>::iterator it = find(pidwaitlist.begin(),
838 pidwaitlist.end(), pid);
839 if (it != pidwaitlist.end()) {
840 lyxerr.debug() << "Found pid in pidwait\n"
841 << "Caught child pid of recompute "
842 "routine" << pid << endl;
843 pidwaitlist.erase(it);
847 lyxerr.debug() << "waitpid error" << endl;
850 lyxerr << "The process or process group specified by "
851 "pid does not exist or is not a child of "
852 "the calling process or can never be in the "
853 "states specified by options." << endl;
856 lyxerr << "waitpid() was interrupted due to the "
857 "receipt of a signal sent by the calling "
861 lyxerr << "An invalid value was specified for "
865 lyxerr << "Unknown error from waitpid" << endl;
868 } else if (pid == 0) {
869 lyxerr << "waitpid nohang" << endl;;
871 lyxerr.debug() << "normal exit from childhandler" << endl;
879 bitmap_waiting = false;
880 for (bitmaps_type::iterator it = bitmaps.begin();
881 it != bitmaps.end(); ++it)
882 if ((*it)->gspid > 0 && !(*it)->reading)
888 void RegisterFigure(InsetFig * fi)
890 if (figures.empty()) InitFigures();
892 Figref * tmpfig = new Figref;
895 figures.push_back(tmpfig);
898 if (lyxerr.debugging()) {
899 lyxerr << "Register Figure: buffer:["
900 << current_view->buffer() << "]" << endl;
906 void UnregisterFigure(InsetFig * fi)
908 Figref * tmpfig = fi->figure;
910 if (tmpfig->data) freefigdata(tmpfig->data);
911 if (tmpfig->inset->form) {
912 if (tmpfig->inset->form->Figure->visible) {
913 fl_set_focus_object(tmpfig->inset->form->Figure,
914 tmpfig->inset->form->OkBtn);
915 fl_hide_form(tmpfig->inset->form->Figure);
917 #if FL_REVISION == 89
918 #warning Reactivate this free_form calls
920 fl_free_form(tmpfig->inset->form->Figure);
921 free(tmpfig->inset->form); // Why free?
922 tmpfig->inset->form = 0;
925 figures.erase(find(figures.begin(), figures.end(), tmpfig));
928 if (figures.empty()) DoneFigures();
933 string NextToken(istream & is)
941 } while (!is.eof() && !isspace(c));
942 token.erase(token.length() - 1); // remove the isspace
948 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
958 psubfigure = subfigure = false;
959 xwid = xhgh = angle = 0;
961 raw_wid = raw_hgh = 0;
962 changedfname = false;
963 RegisterFigure(this);
967 InsetFig::~InsetFig()
969 if (lyxerr.debugging()) {
970 lyxerr << "Figure destructor called" << endl;
972 UnregisterFigure(this);
976 int InsetFig::ascent(Painter &, LyXFont const &) const
982 int InsetFig::descent(Painter &, LyXFont const &) const
988 int InsetFig::width(Painter &, LyXFont const &) const
994 void InsetFig::draw(Painter & pain, LyXFont const & f,
995 int baseline, float & x) const
999 if (bitmap_waiting) getbitmaps();
1001 // I wish that I didn't have to use this
1002 // but the figinset code is so complicated so
1003 // I don't want to fiddle with it now.
1005 if (figure && figure->data && figure->data->bitmap &&
1006 !figure->data->reading && !figure->data->broken) {
1008 pain.pixmap(int(x + 1), baseline - hgh,
1009 wid, hgh, figure->data->bitmap);
1012 pain.rectangle(int(x), baseline - hgh - 1,
1018 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1020 if (figure && figure->data) {
1021 if (figure->data->broken) msg = _("[render error]");
1022 else if (figure->data->reading) msg = _("[rendering ... ]");
1024 if (fname.empty()) msg = _("[no file]");
1025 else if ((flags & 3) == 0) msg = _("[not displayed]");
1026 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1028 if (!msg) msg = _("[unknown error]");
1030 font.setFamily(LyXFont::SANS_FAMILY);
1031 font.setSize(LyXFont::SIZE_FOOTNOTE);
1032 string justname = OnlyFilename (fname);
1033 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1036 font.setSize(LyXFont::SIZE_TINY);
1037 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1039 x += width(pain, font); // ?
1043 void InsetFig::Write(ostream & os) const
1046 os << "Figure size " << wid << " " << hgh << "\n";
1047 if (!fname.empty()) {
1048 string buf1 = OnlyPath(owner->fileName());
1049 string fname2 = MakeRelPath(fname, buf1);
1050 os << "file " << fname2 << "\n";
1052 if (!subcaption.empty())
1053 os << "subcaption " << subcaption << "\n";
1054 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1055 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1056 if (angle != 0) os << "angle " << angle << "\n";
1057 os << "flags " << flags << "\n";
1058 if (subfigure) os << "subfigure\n";
1062 void InsetFig::Read(LyXLex & lex)
1065 bool finished = false;
1067 while (lex.IsOK() && !finished) {
1070 string const token = lex.GetString();
1071 lyxerr.debug() << "Token: " << token << endl;
1075 else if (token == "\\end_inset") {
1077 } else if (token == "file") {
1079 buf = lex.GetString();
1080 string buf1 = OnlyPath(owner->fileName());
1081 fname = MakeAbsPath(buf, buf1);
1082 changedfname = true;
1084 } else if (token == "extra") {
1086 // kept for backwards compability. Delete in 0.13.x
1087 } else if (token == "subcaption") {
1089 subcaption = lex.GetString();
1090 } else if (token == "label") {
1092 // kept for backwards compability. Delete in 0.13.x
1093 } else if (token == "angle") {
1095 angle = lex.GetFloat();
1096 } else if (token == "size") {
1098 wid = lex.GetInteger();
1100 hgh = lex.GetInteger();
1101 } else if (token == "flags") {
1103 flags = pflags = lex.GetInteger();
1104 } else if (token == "subfigure") {
1105 subfigure = psubfigure = true;
1106 } else if (token == "width") {
1109 typ = lex.GetInteger();
1111 xwid = lex.GetFloat();
1113 case DEF: wtype = DEF; break;
1114 case CM: wtype = CM; break;
1115 case IN: wtype = IN; break;
1116 case PER_PAGE: wtype = PER_PAGE; break;
1117 case PER_COL: wtype = PER_COL; break;
1119 lyxerr.debug() << "Unknown type!" << endl;
1123 } else if (token == "height") {
1126 typ = lex.GetInteger();
1128 xhgh = lex.GetFloat();
1130 case DEF: htype = DEF; break;
1131 case CM: htype = CM; break;
1132 case IN: htype = IN; break;
1133 case PER_PAGE: htype = PER_PAGE; break;
1135 lyxerr.debug() << "Unknown type!" << endl;
1146 int InsetFig::Latex(ostream & os,
1147 signed char /* fragile*/, bool /* fs*/) const
1150 if (!cmd.empty()) os << cmd << " ";
1155 int InsetFig::Linuxdoc(ostream &) const
1161 int InsetFig::DocBook(ostream & os) const
1163 string figurename = fname;
1165 if(suffixIs(figurename, ".eps"))
1166 figurename.erase(fname.length() - 5);
1168 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1173 void InsetFig::Validate(LaTeXFeatures & features) const
1175 features.graphics = true;
1176 if (subfigure) features.subfigure = true;
1180 Inset::EDITABLE InsetFig::Editable() const
1186 bool InsetFig::Deletable() const
1192 char const * InsetFig::EditMessage() const
1194 return _("Opened figure");
1198 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1200 lyxerr.debug() << "Editing InsetFig." << endl;
1203 // We should have RO-versions of the form instead.
1204 // The actual prevention of altering a readonly doc
1205 // is done in CallbackFig()
1206 if(bv->buffer()->isReadonly())
1207 WarnReadonly(bv->buffer()->fileName());
1210 form = create_form_Figure();
1211 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1212 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1213 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1214 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1217 if (form->Figure->visible) {
1218 fl_raise_form(form->Figure);
1220 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1221 FL_FULLBORDER, _("Figure"));
1226 Inset * InsetFig::Clone() const
1228 InsetFig * tmp = new InsetFig(100, 100, owner);
1230 if (lyxerr.debugging()) {
1231 lyxerr << "Clone Figure: buffer:["
1232 << current_view->buffer()
1233 << "], cbuffer:[xx]" << endl;
1238 tmp->raw_wid = raw_wid;
1239 tmp->raw_hgh = raw_hgh;
1244 tmp->pflags = pflags;
1245 tmp->subfigure = subfigure;
1246 tmp->psubfigure = psubfigure;
1254 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1256 // do not display if there is
1257 // "do not display" chosen (Matthias 260696)
1258 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1259 pswid, pshgh, raw_wid, raw_hgh,
1260 angle, flags & (3|8));
1261 } else tmp->figure->data = 0;
1262 tmp->subcaption = subcaption;
1263 tmp->changedfname = false;
1270 Inset::Code InsetFig::LyxCode() const
1272 return Inset::GRAPHICS_CODE;
1276 void InsetFig::Regenerate() const
1279 string resizeW, resizeH;
1280 string rotate, recmd;
1282 if (fname.empty()) {
1283 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1284 cmd += _("empty figure path");
1289 string buf1 = OnlyPath(owner->fileName());
1290 string fname2 = MakeRelPath(fname, buf1);
1292 string gcmd = "\\includegraphics{" + fname2 + '}';
1297 case CM:{// \resizebox*{h-length}{v-length}{text}
1299 sprintf(buf, "%g", xwid); // should find better
1306 sprintf(buf, "%g", xwid);
1313 sprintf(buf, "%g", xwid/100);
1315 resizeW += "\\textwidth";
1320 sprintf(buf, "%g", xwid/100);
1322 resizeW += "\\columnwidth";
1332 sprintf(buf, "%g", xhgh);
1339 sprintf(buf, "%g", xhgh);
1346 sprintf(buf, "%g", xhgh/100);
1348 resizeH += "\\textheight";
1352 // Doesn't occur; case exists to suppress compiler warnings.
1357 if (!resizeW.empty() || !resizeH.empty()) {
1358 recmd = "\\resizebox*{";
1359 if (!resizeW.empty())
1364 if (!resizeH.empty())
1374 sprintf(buf, "%g", angle);
1375 // \rotatebox{angle}{text}
1376 rotate = "\\rotatebox{";
1384 if (!rotate.empty()) cmdbuf += '}';
1385 if (!recmd.empty()) cmdbuf += '}';
1387 if (!subcaption.empty())
1388 cmdbuf = "\\subfigure[" + subcaption +
1389 "]{" + cmdbuf + "}";
1391 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1398 void InsetFig::TempRegenerate()
1401 string resizeW, resizeH;
1402 string rotate, recmd;
1404 char const * tfname = fl_get_input(form->EpsFile);
1405 string tsubcap = fl_get_input(form->Subcaption);
1406 float tangle = atof(fl_get_input(form->Angle));
1407 float txwid = atof(fl_get_input(form->Width));
1408 float txhgh = atof(fl_get_input(form->Height));
1410 if (!tfname || !*tfname) {
1411 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1412 cmd += _("empty figure path");
1417 string buf1 = OnlyPath(owner->fileName());
1418 string fname2 = MakeRelPath(tfname, buf1);
1419 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1420 string gcmd = "\\includegraphics{" + fname2 + '}';
1425 case CM: {// \resizebox*{h-length}{v-length}{text}
1427 sprintf(buf, "%g", txwid); // should find better
1434 sprintf(buf, "%g", txwid);
1441 sprintf(buf, "%g", txwid/100);
1443 resizeW += "\\textwidth";
1448 sprintf(buf, "%g", txwid/100);
1450 resizeW += "\\columnwidth";
1460 sprintf(buf, "%g", txhgh);
1467 sprintf(buf, "%g", txhgh);
1474 sprintf(buf, "%g", txhgh/100);
1476 resizeH += "\\textheight";
1480 // Doesn't occur; case exists to suppress compiler warnings.
1485 // \resizebox*{h-length}{v-length}{text}
1486 if (!resizeW.empty() || !resizeH.empty()) {
1487 recmd = "\\resizebox*{";
1488 if (!resizeW.empty())
1493 if (!resizeH.empty())
1502 sprintf(buf, "%g", tangle);
1503 // \rotatebox{angle}{text}
1504 rotate = "\\rotatebox{";
1512 if (!rotate.empty()) cmdbuf += '}';
1513 if (!recmd.empty()) cmdbuf += '}';
1514 if (psubfigure && !tsubcap.empty()) {
1515 cmdbuf = string("\\subfigure{") + tsubcap
1516 + string("}{") + cmdbuf + "}";
1521 void InsetFig::Recompute()
1523 bool changed = changedfname;
1524 int newx, newy, nraw_x, nraw_y;
1526 if (changed) GetPSSizes();
1528 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1529 float cos_a = cos (angle / DEG2PI);
1530 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1531 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1533 /* now recompute wid and hgh, and if that is changed, set changed */
1534 /* this depends on chosen size of the picture and its bbox */
1535 // This will be redone in 0.13 ... (hen)
1536 if (!fname.empty()) {
1537 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1545 newx = int(28.346 * xwid);
1548 newx = int(72 * xwid);
1550 case PER_PAGE: /* % of page */
1551 newx = int(5.95 * xwid);
1553 case PER_COL: /* % of col */
1554 newx = int(2.975 * xwid);
1558 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1562 //lyxerr << "This should not happen!" << endl;
1565 newy = int(28.346 * xhgh);
1568 newy = int(72 * xhgh);
1570 case PER_PAGE: /* % of page */
1571 newy = int(8.42 * xhgh);
1574 // Doesn't occur; case exists to suppress
1575 // compiler warnings.
1578 if (htype && !wtype && frame_hgh)
1579 newx = newy*frame_wid/frame_hgh;
1588 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1593 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1595 // cannot be zero, actually, set it to some minimum, so its clickable
1596 if (newx < 5) newx = 5;
1597 if (newy < 5) newy = 5;
1599 if (newx != wid || newy != hgh ||
1600 nraw_x != raw_wid || nraw_y != raw_hgh ||
1601 flags != pflags || subfigure != psubfigure)
1609 subfigure = psubfigure;
1612 figdata * pf = figure->data;
1615 if (!fname.empty() && (flags & 3)
1616 && !lyxrc.ps_command.empty()) {
1617 // do not display if there is "do not display"
1618 // chosen (Matthias 260696)
1619 figure->data = getfigdata(wid, hgh, fname,
1620 psx, psy, pswid, pshgh,
1622 angle, flags & (3|8));
1623 } else figure->data = 0;
1625 // free the old data
1626 if (pf) freefigdata(pf);
1629 changedfname = false;
1633 void InsetFig::GetPSSizes()
1635 /* get %%BoundingBox: from postscript file */
1637 /* defaults to associated size
1638 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1645 if (fname.empty()) return;
1647 ifstream ifs(fname.c_str());
1649 if (!ifs) return; // file not found !!!!
1651 /* defaults to A4 page */
1657 char lastchar = 0; ifs.get(lastchar);
1659 char c = 0; ifs.get(c);
1661 lyxerr.debug() << "End of (E)PS file reached and"
1662 " no BoundingBox!" << endl;
1665 if (c == '%' && lastchar == '%') {
1667 if (p.empty()) break;
1668 // we should not use this, with it we cannot
1669 // discover bounding box and end of file.
1670 //if (strcmp(p, "EndComments") == 0) break;
1671 lyxerr.debug() << "Token: `" << p << "'" << endl;
1672 if (p == "BoundingBox:") {
1673 float fpsx, fpsy, fpswid, fpshgh;
1674 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1677 pswid = int(fpswid);
1678 pshgh = int(fpshgh);
1680 if (lyxerr.debugging()) {
1681 lyxerr << "%%%%BoundingBox:"
1699 void InsetFig::CallbackFig(long arg)
1704 if (lyxerr.debugging()) {
1705 lyxerr << "Figure callback, arg " << arg << endl;
1711 case 12: /* width type */
1718 fl_deactivate_object(form->Width);
1723 fl_activate_object(form->Width);
1728 fl_activate_object(form->Width);
1733 fl_activate_object(form->Width);
1738 fl_activate_object(form->Width);
1741 lyxerr.debug() << "Unknown type!" << endl;
1748 case 22: /* height type */
1754 fl_deactivate_object(form->Height);
1759 fl_activate_object(form->Height);
1764 fl_activate_object(form->Height);
1769 fl_activate_object(form->Height);
1772 lyxerr.debug() << "Unknown type!" << endl;
1778 pflags = pflags & ~3; /* wysiwyg0 */
1781 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1784 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1787 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1790 pflags ^= 4; /* frame */
1793 pflags ^= 8; /* do translations */
1796 psubfigure = !psubfigure; /* This is a subfigure */
1799 regen = true; /* regenerate command */
1801 case 0: /* browse file */
1805 case 1: /* preview */
1806 p = fl_get_input(form->EpsFile);
1810 case 8: /* ok (apply and close) */
1811 if(!current_view->buffer()->isReadonly()) {
1814 xwid = atof(fl_get_input(form->Width));
1815 xhgh = atof(fl_get_input(form->Height));
1816 angle = atof(fl_get_input(form->Angle));
1817 p = fl_get_input(form->EpsFile);
1819 string buf1 = OnlyPath(owner->fileName());
1820 fname = MakeAbsPath(p, buf1);
1821 changedfname = true;
1823 if (!fname.empty()) {
1824 changedfname = true;
1828 subcaption = fl_get_input(form->Subcaption);
1832 /* now update inset */
1833 if (lyxerr.debugging()) {
1834 lyxerr << "Update: ["
1835 << wid << 'x' << hgh << ']' << endl;
1837 current_view->updateInset(this, true);
1839 fl_set_focus_object(form->Figure, form->OkBtn);
1840 fl_hide_form(form->Figure);
1841 #if FL_REVISION == 89
1842 #warning Reactivate this free_form calls
1844 fl_free_form(form->Figure);
1845 free(form); // Why free?
1851 // The user has already been informed about RO in ::Edit
1852 if(arg == 7) // if 'Apply'
1855 case 9: /* cancel = restore and close */
1856 fl_set_focus_object(form->Figure, form->OkBtn);
1857 fl_hide_form(form->Figure);
1858 #if FL_REVISION == 89
1859 #warning Reactivate this free_form calls
1860 #warning Jug, is this still a problem?
1862 fl_free_form(form->Figure);
1863 free(form); // Why free?
1869 if (regen) TempRegenerate();
1874 void DisableFigurePanel(FD_Figure * const form)
1876 fl_deactivate_object(form->EpsFile);
1877 fl_deactivate_object(form->Browse);
1878 fl_deactivate_object(form->Width);
1879 fl_deactivate_object(form->Height);
1880 fl_deactivate_object(form->Frame);
1881 fl_deactivate_object(form->Translations);
1882 fl_deactivate_object(form->Angle);
1883 fl_deactivate_object(form->HeightGrp);
1884 fl_deactivate_object(form->page2);
1885 fl_deactivate_object(form->Default2);
1886 fl_deactivate_object(form->cm2);
1887 fl_deactivate_object(form->in2);
1888 fl_deactivate_object(form->HeightLabel);
1889 fl_deactivate_object(form->WidthLabel);
1890 fl_deactivate_object(form->DisplayGrp);
1891 fl_deactivate_object(form->Wysiwyg3);
1892 fl_deactivate_object(form->Wysiwyg0);
1893 fl_deactivate_object(form->Wysiwyg2);
1894 fl_deactivate_object(form->Wysiwyg1);
1895 fl_deactivate_object(form->WidthGrp);
1896 fl_deactivate_object(form->Default1);
1897 fl_deactivate_object(form->cm1);
1898 fl_deactivate_object(form->in1);
1899 fl_deactivate_object(form->page1);
1900 fl_deactivate_object(form->column1);
1901 fl_deactivate_object(form->Subcaption);
1902 fl_deactivate_object(form->Subfigure);
1903 fl_deactivate_object (form->OkBtn);
1904 fl_deactivate_object (form->ApplyBtn);
1905 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1906 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1911 void EnableFigurePanel(FD_Figure * const form)
1913 fl_activate_object(form->EpsFile);
1914 fl_activate_object(form->Browse);
1915 fl_activate_object(form->Width);
1916 fl_activate_object(form->Height);
1917 fl_activate_object(form->Frame);
1918 fl_activate_object(form->Translations);
1919 fl_activate_object(form->Angle);
1920 fl_activate_object(form->HeightGrp);
1921 fl_activate_object(form->page2);
1922 fl_activate_object(form->Default2);
1923 fl_activate_object(form->cm2);
1924 fl_activate_object(form->in2);
1925 fl_activate_object(form->HeightLabel);
1926 fl_activate_object(form->WidthLabel);
1927 fl_activate_object(form->DisplayGrp);
1928 fl_activate_object(form->Wysiwyg3);
1929 fl_activate_object(form->Wysiwyg0);
1930 fl_activate_object(form->Wysiwyg2);
1931 fl_activate_object(form->Wysiwyg1);
1932 fl_activate_object(form->WidthGrp);
1933 fl_activate_object(form->Default1);
1934 fl_activate_object(form->cm1);
1935 fl_activate_object(form->in1);
1936 fl_activate_object(form->page1);
1937 fl_activate_object(form->column1);
1938 fl_activate_object(form->Subcaption);
1939 fl_activate_object(form->Subfigure);
1940 fl_activate_object (form->OkBtn);
1941 fl_activate_object (form->ApplyBtn);
1942 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1943 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1947 void InsetFig::RestoreForm()
1951 EnableFigurePanel(form);
1954 fl_set_button(form->Default1, (wtype == 0));
1955 fl_set_button(form->cm1, (wtype == 1));
1956 fl_set_button(form->in1, (wtype == 2));
1957 fl_set_button(form->page1, (wtype == 3));
1958 fl_set_button(form->column1, (wtype == 4));
1960 fl_deactivate_object(form->Width);
1962 fl_activate_object(form->Width);
1965 // enable and disable should be put here.
1967 fl_set_button(form->Default2, (htype == 0));
1968 fl_set_button(form->cm2, (htype == 1));
1969 fl_set_button(form->in2, (htype == 2));
1970 fl_set_button(form->page2, (htype == 3));
1971 // enable and disable should be put here.
1973 fl_deactivate_object(form->Height);
1975 fl_activate_object(form->Height);
1978 int pflags = flags & 3;
1979 fl_set_button(form->Wysiwyg0, (pflags == 0));
1980 fl_set_button(form->Wysiwyg1, (pflags == 1));
1981 fl_set_button(form->Wysiwyg2, (pflags == 2));
1982 fl_set_button(form->Wysiwyg3, (pflags == 3));
1983 fl_set_button(form->Frame, ((flags & 4) != 0));
1984 fl_set_button(form->Translations, ((flags & 8) != 0));
1985 fl_set_button(form->Subfigure, (subfigure != 0));
1987 psubfigure = subfigure;
1988 sprintf(buf, "%g", xwid);
1989 fl_set_input(form->Width, buf);
1990 sprintf(buf, "%g", xhgh);
1991 fl_set_input(form->Height, buf);
1992 sprintf(buf, "%g", angle);
1993 fl_set_input(form->Angle, buf);
1994 if (!fname.empty()){
1995 string buf1 = OnlyPath(owner->fileName());
1996 string fname2 = MakeRelPath(fname, buf1);
1997 fl_set_input(form->EpsFile, fname2.c_str());
1999 else fl_set_input(form->EpsFile, "");
2000 fl_set_input(form->Subcaption, subcaption.c_str());
2001 if(current_view->buffer()->isReadonly())
2002 DisableFigurePanel(form);
2008 void InsetFig::Preview(char const * p)
2013 lyxerr << "Cannot fork process!" << endl;
2018 return; // parent process
2021 string buf1 = OnlyPath(owner->fileName());
2022 string buf2 = MakeAbsPath(p, buf1);
2024 lyxerr << "Error during rendering "
2025 << execlp(lyxrc.view_pspic_command.c_str(),
2026 lyxrc.view_pspic_command.c_str(),
2033 void InsetFig::BrowseFile()
2035 static string current_figure_path;
2036 static int once = 0;
2039 if (lyxerr.debugging()) {
2040 lyxerr << "Filename: "
2041 << owner->fileName() << endl;
2043 string p = fl_get_input(form->EpsFile);
2045 string buf = MakeAbsPath(owner->fileName());
2046 string buf2 = OnlyPath(buf);
2048 buf = MakeAbsPath(p, buf2);
2049 buf = OnlyPath(buf);
2051 buf = OnlyPath(owner->fileName().c_str());
2054 // Does user clipart directory exist?
2055 string bufclip = AddName (user_lyxdir, "clipart");
2056 FileInfo fileInfo(bufclip);
2057 if (!(fileInfo.isOK() && fileInfo.isDir()))
2058 // No - bail out to system clipart directory
2059 bufclip = AddName (system_lyxdir, "clipart");
2062 fileDlg.SetButton(0, _("Clipart"), bufclip);
2063 fileDlg.SetButton(1, _("Document"), buf);
2067 ProhibitInput(current_view);
2069 p = fileDlg.Select(_("EPS Figure"),
2070 current_figure_path,
2073 p = fileDlg.Select(_("EPS Figure"), buf,
2076 AllowInput(current_view);
2078 if (p.empty()) return;
2080 buf = MakeRelPath(p, buf2);
2081 current_figure_path = OnlyPath(p);
2084 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2085 || contains(p, "%") || contains(p, " "))
2087 WriteAlert(_("Filename can't contain any "
2088 "of these characters:"),
2089 // xgettext:no-c-format
2090 _("space, '#', '~', '$' or '%'."));
2095 if (form) fl_set_input(form->EpsFile, buf.c_str());
2099 void GraphicsCB(FL_OBJECT * obj, long arg)
2101 /* obj->form contains the form */
2103 if (lyxerr.debugging()) {
2104 lyxerr << "GraphicsCB callback: " << arg << endl;
2107 /* find inset we were reacting to */
2108 for (figures_type::iterator it = figures.begin();
2109 it != figures.end(); ++it)
2110 if ((*it)->inset->form && (*it)->inset->form->Figure
2112 if (lyxerr.debugging()) {
2113 lyxerr << "Calling back figure "
2116 (*it)->inset->CallbackFig(arg);
2122 void HideFiguresPopups()
2124 for (figures_type::iterator it = figures.begin();
2125 it != figures.end(); ++it)
2126 if ((*it)->inset->form
2127 && (*it)->inset->form->Figure->visible) {
2128 if (lyxerr.debugging()) {
2129 lyxerr << "Hiding figure " << (*it) << endl;
2131 // hide and free the form
2132 (*it)->inset->CallbackFig(9);