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"
62 #include "bufferview_funcs.h"
63 #include "ColorHandler.h"
76 extern BufferView * current_view;
77 extern FL_OBJECT * figinset_canvas;
79 extern char ** environ; // is this only redundtant on linux systems? Lgb.
81 static float const DEG2PI = 57.295779513;
83 struct queue_element {
84 float rx, ry; // resolution x and y
85 int ofsx, ofsy; // x and y translation
86 figdata * data; // we are doing it for this data
89 static int const MAXGS = 3; /* maximum 3 gs's at a time */
91 typedef vector<Figref *> figures_type;
92 typedef vector<figdata *> bitmaps_type;
93 static figures_type figures; // all figures
94 static bitmaps_type bitmaps; // all bitmaps
96 static queue<queue_element> gsqueue; // queue for ghostscripting
98 static int gsrunning = 0; /* currently so many gs's are running */
99 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
100 static char bittable[256]; /* bit reversion table */
102 static bool gs_color; // do we allocate colors for gs?
103 static bool color_visual; // is the visual color?
104 static bool gs_xcolor = false; // allocated extended colors
105 static unsigned long gs_pixels[128]; // allocated pixels
106 static int gs_num_pixels; // number of pixels allocated
107 static int gs_spc; // shades per color
108 static bool gs_gray; // is grayscale?
109 static int gs_allcolors; // number of all colors
111 static list<int> pidwaitlist; // pid wait list
117 val.foreground = BlackPixel(fl_display,
118 DefaultScreen(fl_display));
121 val.graphics_exposures = false;
122 val.line_style = LineSolid;
124 return XCreateGC(fl_display, RootWindow(fl_display, 0),
125 GCForeground | GCFunction | GCGraphicsExposures
126 | GCLineWidth | GCLineStyle , &val);
134 void addpidwait(int pid)
136 // adds pid to pid wait list
137 pidwaitlist.push_back(pid);
139 if (lyxerr.debugging()) {
140 lyxerr << "Pids to wait for: \n";
141 for (list<int>::const_iterator cit = pidwaitlist.begin();
142 cit != pidwaitlist.end(); ++cit) {
143 lyxerr << (*cit) << '\n';
151 int GhostscriptMsg(FL_OBJECT *, Window, int, int,
156 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
158 if(lyxerr.debugging()) {
159 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
160 << "] pm:[" << e->data.l[1] << "]" << endl;
163 // just kill gs, that way it will work for sure
164 // This loop looks like S**T so it probably is...
165 //for (bitmaps_type::size_type i = 0; i < bitmaps.size(); ++i)
166 for (bitmaps_type::iterator it = bitmaps.begin();
167 it != bitmaps.end(); ++it)
168 if (static_cast<long>((*it)->bitmap) ==
169 static_cast<long>(e->data.l[1])) {
174 // first update p->bitmap, if necessary
175 if (p->bitmap != None
176 && p->flags > (1|8) && gs_color && p->wid) {
177 // query current colormap and re-render
178 // the pixmap with proper colors
179 XWindowAttributes wa;
180 register XImage * im;
184 int spc1 = gs_spc - 1;
185 int spc2 = gs_spc * gs_spc;
189 GC gc = local_gc_copy;
191 XGetWindowAttributes(fl_display,
196 if (lyxerr.debugging()) {
197 lyxerr << "Starting image translation "
200 << p->wid << "x" << p->hgh
202 << " " << XYPixmap << endl;
204 // now fork rendering process
206 if (forkstat == -1) {
208 << "Cannot fork, using slow "
209 "method for pixmap translation." << endl;
210 tmpdisp = fl_display;
211 } else if (forkstat > 0) { // parent
213 if (lyxerr.debugging()) {
214 lyxerr << "Spawned child "
217 addpidwait(forkstat);
220 tmpdisp = XOpenDisplay(XDisplayName(0));
223 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
224 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
226 if (lyxerr.debugging()) {
227 lyxerr << "Got the image" << endl;
230 if (lyxerr.debugging()) {
231 lyxerr << "Error getting the image" << endl;
236 // query current colormap
237 XColor * cmap = new XColor[gs_allcolors];
238 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
239 XQueryColors(tmpdisp,
240 fl_state[fl_get_vclass()]
245 // now we process all the image
246 for (y = 0; y < p->hgh; ++y) {
247 for (int x = 0; x < wid; ++x) {
252 gs_pixels[((pc->red+6553)*
253 spc1/65535)*spc2+((pc->green+6553)*
254 spc1/65535)*gs_spc+((pc->blue+6553)*
259 // This must be correct.
261 if (lyxerr.debugging()) {
262 lyxerr << "Putting image back"
265 XPutImage(tmpdisp, p->bitmap,
267 0, 0, p->wid, p->hgh);
269 if (lyxerr.debugging()) {
270 lyxerr << "Done translation"
275 if (lyxerr.debugging()) {
276 lyxerr << "Killing gs "
279 lyx::kill(p->gspid, SIGHUP);
281 sprintf(tmp, "%s/~lyxgs%d.ps",
282 system_tempdir.c_str(),
286 XCloseDisplay(tmpdisp);
290 if (lyxerr.debugging()) {
291 lyxerr << "Killing gs "
294 lyx::kill(p->gspid, SIGHUP);
296 sprintf(tmp, "%s/~lyxgs%d.ps",
297 system_tempdir.c_str(),
308 void AllocColors(int num)
309 // allocate color cube numxnumxnum, if possible
311 if (lyxerr.debugging()) {
312 lyxerr << "Allocating color cube " << num
313 << 'x' << num << 'x' << num << endl;
317 lyxerr << "Error allocating color colormap." << endl;
321 if (num > 5) num = 5;
323 for (int i = 0; i < num * num * num; ++i) {
324 xcol.red = 65535 * (i / (num * num)) / (num - 1);
325 xcol.green = 65535 * ((i / num) % num) / (num - 1);
326 xcol.blue = 65535 * (i % num) / (num - 1);
327 xcol.flags = DoRed | DoGreen | DoBlue;
328 if (!XAllocColor(fl_display,
329 fl_state[fl_get_vclass()].colormap, &xcol)) {
330 if (i) XFreeColors(fl_display,
331 fl_state[fl_get_vclass()].colormap,
333 if(lyxerr.debugging()) {
334 lyxerr << "Cannot allocate color cube "
337 AllocColors(num - 1);
340 gs_pixels[i] = xcol.pixel;
345 gs_num_pixels = num * num * num;
349 // allocate grayscale ramp
351 void AllocGrays(int num)
353 if (lyxerr.debugging()) {
354 lyxerr << "Allocating grayscale colormap "
359 lyxerr << "Error allocating grayscale colormap." << endl;
363 if (num > 128) num = 128;
365 for (int i = 0; i < num; ++i) {
366 xcol.red = xcol.green = xcol.blue = 65535 * i / (num - 1);
367 xcol.flags = DoRed | DoGreen | DoBlue;
368 if (!XAllocColor(fl_display,
369 fl_state[fl_get_vclass()].colormap, &xcol)) {
370 if (i) XFreeColors(fl_display,
371 fl_state[fl_get_vclass()].colormap,
373 if (lyxerr.debugging()) {
374 lyxerr << "Cannot allocate grayscale "
380 gs_pixels[i] = xcol.pixel;
391 // if bitmaps and figures are not empty we will leak mem
396 for (unsigned int i = 0; i < 256; ++i) {
398 for (unsigned int j = 0; j < 8; ++j)
399 if (i & (1 << (7-j))) k |= 1 << j;
400 bittable[i] = char(~k);
403 // allocate color cube on pseudo-color display
407 fl_add_canvas_handler(figinset_canvas, ClientMessage,
408 GhostscriptMsg, current_view->owner()->getMainForm());
410 local_gc_copy = createGC();
412 Visual * vi = DefaultVisual(fl_display, DefaultScreen(fl_display));
413 if (lyxerr.debugging()) {
414 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
415 vi->visualid, vi->c_class,
416 vi->bits_per_rgb, vi->map_entries);
418 color_visual = ( (vi->c_class == StaticColor) ||
419 (vi->c_class == PseudoColor) ||
420 (vi->c_class == TrueColor) ||
421 (vi->c_class == DirectColor) );
422 if ((vi->c_class & 1) == 0) return;
423 // now allocate colors
424 if (vi->c_class == GrayScale) {
425 // allocate grayscale
426 AllocGrays(vi->map_entries/2);
428 // allocate normal color
430 while (i * i * i * 2 > vi->map_entries) --i;
433 gs_allcolors = vi->map_entries;
441 // if bitmaps and figures are not empty we will leak mem
445 lyxerr.debug() << "Unregistering figures..." << endl;
447 fl_remove_canvas_handler(figinset_canvas, ClientMessage,
453 void freefigdata(figdata * tmpdata)
456 if (tmpdata->ref) return;
458 if (tmpdata->gspid > 0) {
459 int pid = tmpdata->gspid;
461 // kill ghostscript and unlink it's files
463 lyx::kill(pid, SIGKILL);
464 sprintf(buf, "%s/~lyxgs%d.ps", system_tempdir.c_str(), pid);
468 if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
469 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
477 // This _have_ to be set before the fork!
478 unsigned long background_pixel =
479 lyxColorHandler->colorPixel(LColor::background);
481 // run queued requests for ghostscript, if any
482 if (!gsrunning && gs_color && !gs_xcolor) {
483 // here alloc all colors, so that gs will use only
484 // those we allocated for it
489 while (gsrunning < MAXGS) {
490 char tbuf[384], tbuf2[80];
494 if (gsqueue.empty()) {
495 if (!gsrunning && gs_xcolor) {
496 // de-allocate rest of colors
502 queue_element * p = &gsqueue.front();
511 if (lyxerr.debugging()) {
512 lyxerr << "GS start error! Cannot fork."
515 p->data->broken = true;
516 p->data->reading = false;
519 if (pid == 0) { // child
520 char ** env, rbuf[80], gbuf[40];
522 Display * tempdisp = XOpenDisplay(XDisplayName(0));
524 // create translation file
525 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
529 ofs << "gsave clippath pathbbox grestore\n"
531 << "/ury exch def /urx exch def /lly exch def "
533 << p->data->wid / 2.0 << " "
534 << p->data->hgh / 2.0 << " translate\n"
535 << p->data->angle << " rotate\n"
536 << -(p->data->raw_wid / 2.0) << " "
537 << -(p->data->raw_hgh / 2.0) << " translate\n"
538 << p->rx / 72.0 << " " << p->ry / 72.0
540 << -p->ofsx << " " << -p->ofsy << " translate\n"
542 ofs.close(); // Don't remove this.
544 // gs process - set ghostview environment first
545 sprintf(tbuf2, "GHOSTVIEW=%ld %ld", fl_get_canvas_id(
546 figinset_canvas), p->data->bitmap);
548 // now set up ghostview property on a window
549 sprintf(tbuf, "0 0 0 0 %d %d 72 72 0 0 0 0",
550 p->data->wid, p->data->hgh);
551 // #warning BUG seems that the only bug here
552 // might be the hardcoded dpi.. Bummer!
554 if (lyxerr.debugging()) {
555 lyxerr << "Will set GHOSTVIEW property to ["
556 << tbuf << "]" << endl;
558 // wait until property is deleted if executing multiple
560 XGrabServer(tempdisp);
562 // grab server to prevent other child
563 // interfering with setting GHOSTVIEW property
564 // The grabbing goes on for too long, is it
565 // really needed? (Lgb)
566 // I moved most of the grabs... (Lgb)
567 if (lyxerr.debugging()) {
568 lyxerr << "Grabbing the server"
571 prop = XListProperties(tempdisp,
573 figinset_canvas), &nprop);
577 for (i = 0; i < nprop; ++i) {
578 char * p = XGetAtomName(tempdisp,
580 if (strcmp(p, "GHOSTVIEW") == 0) {
586 XFree(reinterpret_cast<char *>(prop)); // jc:
588 // release the server
589 //XUngrabServer(tempdisp);
591 // ok, property found, we must wait until
592 // ghostscript deletes it
593 if (lyxerr.debugging()) {
594 lyxerr << "Releasing the server\n["
596 << "] GHOSTVIEW property"
597 " found. Waiting." << endl;
599 XUngrabServer(tempdisp);
602 XGrabServer(tempdisp);
604 XChangeProperty(tempdisp,
605 fl_get_canvas_id(figinset_canvas),
606 XInternAtom(tempdisp, "GHOSTVIEW", false),
607 XInternAtom(tempdisp, "STRING", false),
609 reinterpret_cast<unsigned char*>(tbuf),
611 XUngrabServer(tempdisp);
614 switch (p->data->flags & 3) {
615 case 0: tbuf[0] = 'H'; break; // Hidden
616 case 1: tbuf[0] = 'M'; break; // Mono
617 case 2: tbuf[0] = 'G'; break; // Gray
620 tbuf[0] = 'C'; // Color
622 tbuf[0] = 'G'; // Gray
626 sprintf(tbuf + 1, " %ld %ld",
628 DefaultScreenOfDisplay(tempdisp)),
631 XGrabServer(tempdisp);
632 XChangeProperty(tempdisp,
633 fl_get_canvas_id(figinset_canvas),
634 XInternAtom(tempdisp,
635 "GHOSTVIEW_COLORS", false),
636 XInternAtom(tempdisp, "STRING", false),
638 reinterpret_cast<unsigned char*>(tbuf),
640 XUngrabServer(tempdisp);
643 if (lyxerr.debugging()) {
644 lyxerr << "Releasing the server" << endl;
646 XCloseDisplay(tempdisp);
648 // set up environment
649 while (environ[ne]) ++ne;
650 typedef char * char_p;
651 env = new char_p[ne + 2];
653 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
656 // now make gs command
658 // close(1); do NOT close. If GS writes out
659 // errors it would hang. (Matthias 290596)
660 sprintf(rbuf, "-r%gx%g", p->rx, p->ry);
661 sprintf(gbuf, "-g%dx%d", p->data->wid, p->data->hgh);
662 // now chdir into dir with .eps file, to be on the safe
664 ::chdir(OnlyPath(p->data->fname).c_str());
665 // make temp file name
666 sprintf(tbuf, "%s/~lyxgs%d.ps", system_tempdir.c_str(),
668 if (lyxerr.debugging()) {
669 lyxerr << "starting gs " << tbuf << " "
671 << ", pid: " << getpid() << endl;
674 int err = ::execlp(lyxrc.ps_command.c_str(),
675 lyxrc.ps_command.c_str(),
677 "-dNOPAUSE", "-dQUIET",
680 p->data->fname.c_str(),
681 "showpage.ps", "quit.ps", "-", 0);
682 // if we are still there, an error occurred.
683 lyxerr << "Error executing ghostscript. "
684 << "Code: " << err << endl;
685 lyxerr.debug() << "Cmd: "
689 << p->data->fname << endl;
692 // normal process (parent)
693 if (lyxerr.debugging()) {
694 lyxerr << "GS [" << pid << "] started" << endl;
697 p->data->gspid = pid;
705 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
707 // recompute the stuff and put in the queue
711 p.rx = (float(data->raw_wid) * 72.0) / pswid;
712 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
718 // if possible, run the queue
724 figdata * getfigdata(int wid, int hgh, string const & fname,
725 int psx, int psy, int pswid, int pshgh,
726 int raw_wid, int raw_hgh, float angle, char flags)
728 /* first search for an exact match with fname and width/height */
730 if (fname.empty()) return 0;
732 for (bitmaps_type::iterator it = bitmaps.begin();
733 it != bitmaps.end(); ++it) {
734 if ((*it)->wid == wid && (*it)->hgh == hgh &&
735 (*it)->flags == flags && (*it)->fname == fname &&
736 (*it)->angle == angle) {
741 figdata * p = new figdata;
744 p->raw_wid = raw_wid;
745 p->raw_hgh = raw_hgh;
749 bitmaps.push_back(p);
750 XWindowAttributes wa;
751 XGetWindowAttributes(fl_display, fl_get_canvas_id(
752 figinset_canvas), &wa);
754 if (lyxerr.debugging()) {
755 lyxerr << "Create pixmap disp:" << fl_display
756 << " scr:" << DefaultScreen(fl_display)
759 << " depth:" << wa.depth << endl;
767 p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
768 figinset_canvas), wid, hgh, wa.depth);
770 // initialize reading of .eps file with correct sizes and stuff
771 addwait(psx, psy, pswid, pshgh, p);
783 void getbitmap(figdata * p)
790 void makeupdatelist(figdata * p)
792 for(figures_type::iterator it = figures.begin();
793 it != figures.end(); ++it)
794 if ((*it)->data == p) {
795 if (lyxerr.debugging()) {
796 lyxerr << "Updating inset "
800 // add inset figures[i]->inset into to_update list
801 current_view->pushIntoUpdateList((*it)->inset);
806 // this func is only "called" in spellchecker.C
807 void sigchldchecker(pid_t pid, int * status)
809 lyxerr.debug() << "Got pid = " << pid << endl;
810 bool pid_handled = false;
811 for (bitmaps_type::iterator it = bitmaps.begin();
812 it != bitmaps.end(); ++it) {
813 if ((*it)->reading && pid == (*it)->gspid) {
814 lyxerr.debug() << "Found pid in bitmaps" << endl;
815 // now read the file and remove it from disk
818 if ((*it)->gsdone) *status = 0;
820 lyxerr.debug() << "GS [" << pid
821 << "] exit OK." << endl;
823 lyxerr << "GS [" << pid << "] error "
825 << WIFEXITED(*status)
826 << " " << WEXITSTATUS(*status)
827 << " S:" << WIFSIGNALED(*status)
828 << " " << WTERMSIG(*status) << endl;
831 bitmap_waiting = true;
834 // remove temporary files
836 sprintf(tmp, "%s/~lyxgs%d.ps",
837 system_tempdir.c_str(),
843 makeupdatelist((*it));
850 lyxerr.debug() << "Checking pid in pidwait" << endl;
851 list<int>::iterator it = find(pidwaitlist.begin(),
852 pidwaitlist.end(), pid);
853 if (it != pidwaitlist.end()) {
854 lyxerr.debug() << "Found pid in pidwait\n"
855 << "Caught child pid of recompute "
856 "routine" << pid << endl;
857 pidwaitlist.erase(it);
861 lyxerr.debug() << "waitpid error" << endl;
864 lyxerr << "The process or process group specified by "
865 "pid does not exist or is not a child of "
866 "the calling process or can never be in the "
867 "states specified by options." << endl;
870 lyxerr << "waitpid() was interrupted due to the "
871 "receipt of a signal sent by the calling "
875 lyxerr << "An invalid value was specified for "
879 lyxerr << "Unknown error from waitpid" << endl;
882 } else if (pid == 0) {
883 lyxerr << "waitpid nohang" << endl;;
885 lyxerr.debug() << "normal exit from childhandler" << endl;
893 bitmap_waiting = false;
894 for (bitmaps_type::iterator it = bitmaps.begin();
895 it != bitmaps.end(); ++it)
896 if ((*it)->gspid > 0 && !(*it)->reading)
902 void RegisterFigure(InsetFig * fi)
904 if (figures.empty()) InitFigures();
906 Figref * tmpfig = new Figref;
909 figures.push_back(tmpfig);
912 if (lyxerr.debugging()) {
913 lyxerr << "Register Figure: buffer:["
914 << current_view->buffer() << "]" << endl;
920 void UnregisterFigure(InsetFig * fi)
922 Figref * tmpfig = fi->figure;
924 if (tmpfig->data) freefigdata(tmpfig->data);
925 if (tmpfig->inset->form) {
926 if (tmpfig->inset->form->Figure->visible) {
927 fl_set_focus_object(tmpfig->inset->form->Figure,
928 tmpfig->inset->form->OkBtn);
929 fl_hide_form(tmpfig->inset->form->Figure);
931 #if FL_REVISION == 89
932 #warning Reactivate this free_form calls
934 fl_free_form(tmpfig->inset->form->Figure);
935 free(tmpfig->inset->form); // Why free?
936 tmpfig->inset->form = 0;
939 figures.erase(find(figures.begin(), figures.end(), tmpfig));
942 if (figures.empty()) DoneFigures();
946 InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
956 psubfigure = subfigure = false;
957 xwid = xhgh = angle = 0;
959 raw_wid = raw_hgh = 0;
960 changedfname = false;
961 RegisterFigure(this);
965 InsetFig::~InsetFig()
967 if (lyxerr.debugging()) {
968 lyxerr << "Figure destructor called" << endl;
970 UnregisterFigure(this);
974 int InsetFig::ascent(Painter &, LyXFont const &) const
980 int InsetFig::descent(Painter &, LyXFont const &) const
986 int InsetFig::width(Painter &, LyXFont const &) const
992 void InsetFig::draw(Painter & pain, LyXFont const & f,
993 int baseline, float & x) const
997 if (bitmap_waiting) getbitmaps();
999 // I wish that I didn't have to use this
1000 // but the figinset code is so complicated so
1001 // I don't want to fiddle with it now.
1003 if (figure && figure->data && figure->data->bitmap &&
1004 !figure->data->reading && !figure->data->broken) {
1006 pain.pixmap(int(x + 1), baseline - hgh,
1007 wid, hgh, figure->data->bitmap);
1010 pain.rectangle(int(x), baseline - hgh - 1,
1016 pain.rectangle(x, baseline - hgh - 1, wid + 1, hgh + 1);
1018 if (figure && figure->data) {
1019 if (figure->data->broken) msg = _("[render error]");
1020 else if (figure->data->reading) msg = _("[rendering ... ]");
1022 if (fname.empty()) msg = _("[no file]");
1023 else if ((flags & 3) == 0) msg = _("[not displayed]");
1024 else if (lyxrc.ps_command.empty()) msg = _("[no ghostscript]");
1026 if (!msg) msg = _("[unknown error]");
1028 font.setFamily(LyXFont::SANS_FAMILY);
1029 font.setSize(LyXFont::SIZE_FOOTNOTE);
1030 string justname = OnlyFilename (fname);
1031 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1034 font.setSize(LyXFont::SIZE_TINY);
1035 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1037 x += width(pain, font); // ?
1041 void InsetFig::Write(ostream & os) const
1044 os << "Figure size " << wid << " " << hgh << "\n";
1045 if (!fname.empty()) {
1046 string buf1 = OnlyPath(owner->fileName());
1047 string fname2 = MakeRelPath(fname, buf1);
1048 os << "file " << fname2 << "\n";
1050 if (!subcaption.empty())
1051 os << "subcaption " << subcaption << "\n";
1052 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1053 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1054 if (angle != 0) os << "angle " << angle << "\n";
1055 os << "flags " << flags << "\n";
1056 if (subfigure) os << "subfigure\n";
1060 void InsetFig::Read(LyXLex & lex)
1063 bool finished = false;
1065 while (lex.IsOK() && !finished) {
1068 string const token = lex.GetString();
1069 lyxerr.debug() << "Token: " << token << endl;
1073 else if (token == "\\end_inset") {
1075 } else if (token == "file") {
1077 buf = lex.GetString();
1078 string buf1 = OnlyPath(owner->fileName());
1079 fname = MakeAbsPath(buf, buf1);
1080 changedfname = true;
1082 } else if (token == "extra") {
1084 // kept for backwards compability. Delete in 0.13.x
1085 } else if (token == "subcaption") {
1087 subcaption = lex.GetString();
1088 } else if (token == "label") {
1090 // kept for backwards compability. Delete in 0.13.x
1091 } else if (token == "angle") {
1093 angle = lex.GetFloat();
1094 } else if (token == "size") {
1096 wid = lex.GetInteger();
1098 hgh = lex.GetInteger();
1099 } else if (token == "flags") {
1101 flags = pflags = lex.GetInteger();
1102 } else if (token == "subfigure") {
1103 subfigure = psubfigure = true;
1104 } else if (token == "width") {
1107 typ = lex.GetInteger();
1109 xwid = lex.GetFloat();
1111 case DEF: wtype = DEF; break;
1112 case CM: wtype = CM; break;
1113 case IN: wtype = IN; break;
1114 case PER_PAGE: wtype = PER_PAGE; break;
1115 case PER_COL: wtype = PER_COL; break;
1117 lyxerr.debug() << "Unknown type!" << endl;
1121 } else if (token == "height") {
1124 typ = lex.GetInteger();
1126 xhgh = lex.GetFloat();
1128 case DEF: htype = DEF; break;
1129 case CM: htype = CM; break;
1130 case IN: htype = IN; break;
1131 case PER_PAGE: htype = PER_PAGE; break;
1133 lyxerr.debug() << "Unknown type!" << endl;
1144 int InsetFig::Latex(ostream & os,
1145 bool /* fragile*/, bool /* fs*/) const
1148 if (!cmd.empty()) os << cmd << " ";
1153 int InsetFig::Linuxdoc(ostream &) const
1159 int InsetFig::DocBook(ostream & os) const
1161 string figurename = fname;
1163 if(suffixIs(figurename, ".eps"))
1164 figurename.erase(fname.length() - 4);
1166 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1171 void InsetFig::Validate(LaTeXFeatures & features) const
1173 features.graphics = true;
1174 if (subfigure) features.subfigure = true;
1178 Inset::EDITABLE InsetFig::Editable() const
1184 bool InsetFig::Deletable() const
1190 char const * InsetFig::EditMessage() const
1192 return _("Opened figure");
1196 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1198 lyxerr.debug() << "Editing InsetFig." << endl;
1201 // We should have RO-versions of the form instead.
1202 // The actual prevention of altering a readonly doc
1203 // is done in CallbackFig()
1204 if(bv->buffer()->isReadonly())
1205 WarnReadonly(bv->buffer()->fileName());
1208 form = create_form_Figure();
1209 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1210 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1211 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1212 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1215 if (form->Figure->visible) {
1216 fl_raise_form(form->Figure);
1218 fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
1219 FL_FULLBORDER, _("Figure"));
1224 Inset * InsetFig::Clone() const
1226 InsetFig * tmp = new InsetFig(100, 100, owner);
1228 if (lyxerr.debugging()) {
1229 lyxerr << "Clone Figure: buffer:["
1230 << current_view->buffer()
1231 << "], cbuffer:[xx]" << endl;
1236 tmp->raw_wid = raw_wid;
1237 tmp->raw_hgh = raw_hgh;
1242 tmp->pflags = pflags;
1243 tmp->subfigure = subfigure;
1244 tmp->psubfigure = psubfigure;
1252 if (!fname.empty() && (flags & 3) && !lyxrc.ps_command.empty()
1254 // do not display if there is
1255 // "do not display" chosen (Matthias 260696)
1256 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1257 pswid, pshgh, raw_wid, raw_hgh,
1258 angle, flags & (3|8));
1259 } else tmp->figure->data = 0;
1260 tmp->subcaption = subcaption;
1261 tmp->changedfname = false;
1268 Inset::Code InsetFig::LyxCode() const
1270 return Inset::GRAPHICS_CODE;
1274 void InsetFig::Regenerate() const
1277 string resizeW, resizeH;
1278 string rotate, recmd;
1280 if (fname.empty()) {
1281 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1282 cmd += _("empty figure path");
1287 string buf1 = OnlyPath(owner->fileName());
1288 string fname2 = MakeRelPath(fname, buf1);
1290 string gcmd = "\\includegraphics{" + fname2 + '}';
1295 case CM:{// \resizebox*{h-length}{v-length}{text}
1297 sprintf(buf, "%g", xwid); // should find better
1304 sprintf(buf, "%g", xwid);
1311 sprintf(buf, "%g", xwid/100);
1313 resizeW += "\\textwidth";
1318 sprintf(buf, "%g", xwid/100);
1320 resizeW += "\\columnwidth";
1330 sprintf(buf, "%g", xhgh);
1337 sprintf(buf, "%g", xhgh);
1344 sprintf(buf, "%g", xhgh/100);
1346 resizeH += "\\textheight";
1350 // Doesn't occur; case exists to suppress compiler warnings.
1355 if (!resizeW.empty() || !resizeH.empty()) {
1356 recmd = "\\resizebox*{";
1357 if (!resizeW.empty())
1362 if (!resizeH.empty())
1372 sprintf(buf, "%g", angle);
1373 // \rotatebox{angle}{text}
1374 rotate = "\\rotatebox{";
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 + '}';
1423 case CM: {// \resizebox*{h-length}{v-length}{text}
1425 sprintf(buf, "%g", txwid); // should find better
1432 sprintf(buf, "%g", txwid);
1439 sprintf(buf, "%g", txwid/100);
1441 resizeW += "\\textwidth";
1446 sprintf(buf, "%g", txwid/100);
1448 resizeW += "\\columnwidth";
1458 sprintf(buf, "%g", txhgh);
1465 sprintf(buf, "%g", txhgh);
1472 sprintf(buf, "%g", txhgh/100);
1474 resizeH += "\\textheight";
1478 // Doesn't occur; case exists to suppress compiler warnings.
1483 // \resizebox*{h-length}{v-length}{text}
1484 if (!resizeW.empty() || !resizeH.empty()) {
1485 recmd = "\\resizebox*{";
1486 if (!resizeW.empty())
1491 if (!resizeH.empty())
1500 sprintf(buf, "%g", tangle);
1501 // \rotatebox{angle}{text}
1502 rotate = "\\rotatebox{";
1510 if (!rotate.empty()) cmdbuf += '}';
1511 if (!recmd.empty()) cmdbuf += '}';
1512 if (psubfigure && !tsubcap.empty()) {
1513 cmdbuf = string("\\subfigure{") + tsubcap
1514 + string("}{") + cmdbuf + "}";
1519 void InsetFig::Recompute()
1521 bool changed = changedfname;
1522 int newx, newy, nraw_x, nraw_y;
1524 if (changed) GetPSSizes();
1526 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1527 float cos_a = cos (angle / DEG2PI);
1528 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1529 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1531 /* now recompute wid and hgh, and if that is changed, set changed */
1532 /* this depends on chosen size of the picture and its bbox */
1533 // This will be redone in 0.13 ... (hen)
1534 if (!fname.empty()) {
1535 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1543 newx = int(28.346 * xwid);
1546 newx = int(72 * xwid);
1548 case PER_PAGE: /* % of page */
1549 newx = int(5.95 * xwid);
1551 case PER_COL: /* % of col */
1552 newx = int(2.975 * xwid);
1556 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1560 //lyxerr << "This should not happen!" << endl;
1563 newy = int(28.346 * xhgh);
1566 newy = int(72 * xhgh);
1568 case PER_PAGE: /* % of page */
1569 newy = int(8.42 * xhgh);
1572 // Doesn't occur; case exists to suppress
1573 // compiler warnings.
1576 if (htype && !wtype && frame_hgh)
1577 newx = newy*frame_wid/frame_hgh;
1586 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1591 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1593 // cannot be zero, actually, set it to some minimum, so its clickable
1594 if (newx < 5) newx = 5;
1595 if (newy < 5) newy = 5;
1597 if (newx != wid || newy != hgh ||
1598 nraw_x != raw_wid || nraw_y != raw_hgh ||
1599 flags != pflags || subfigure != psubfigure)
1607 subfigure = psubfigure;
1610 figdata * pf = figure->data;
1613 if (!fname.empty() && (flags & 3)
1614 && !lyxrc.ps_command.empty()) {
1615 // do not display if there is "do not display"
1616 // chosen (Matthias 260696)
1617 figure->data = getfigdata(wid, hgh, fname,
1618 psx, psy, pswid, pshgh,
1620 angle, flags & (3|8));
1621 } else figure->data = 0;
1623 // free the old data
1624 if (pf) freefigdata(pf);
1627 changedfname = false;
1631 void InsetFig::GetPSSizes()
1633 /* get %%BoundingBox: from postscript file */
1635 /* defaults to associated size
1636 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1643 if (fname.empty()) return;
1645 ifstream ifs(fname.c_str());
1647 if (!ifs) return; // file not found !!!!
1649 /* defaults to A4 page */
1655 char lastchar = 0; ifs.get(lastchar);
1657 char c = 0; ifs.get(c);
1659 lyxerr.debug() << "End of (E)PS file reached and"
1660 " no BoundingBox!" << endl;
1663 if (c == '%' && lastchar == '%') {
1665 if (p.empty()) break;
1666 // we should not use this, with it we cannot
1667 // discover bounding box and end of file.
1668 //if (strcmp(p, "EndComments") == 0) break;
1669 lyxerr.debug() << "Token: `" << p << "'" << endl;
1670 if (p == "BoundingBox:") {
1671 float fpsx, fpsy, fpswid, fpshgh;
1672 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1675 pswid = int(fpswid);
1676 pshgh = int(fpshgh);
1678 if (lyxerr.debugging()) {
1679 lyxerr << "%%%%BoundingBox:"
1697 void InsetFig::CallbackFig(long arg)
1702 if (lyxerr.debugging()) {
1703 lyxerr << "Figure callback, arg " << arg << endl;
1709 case 12: /* width type */
1716 fl_deactivate_object(form->Width);
1721 fl_activate_object(form->Width);
1726 fl_activate_object(form->Width);
1731 fl_activate_object(form->Width);
1736 fl_activate_object(form->Width);
1739 lyxerr.debug() << "Unknown type!" << endl;
1746 case 22: /* height type */
1752 fl_deactivate_object(form->Height);
1757 fl_activate_object(form->Height);
1762 fl_activate_object(form->Height);
1767 fl_activate_object(form->Height);
1770 lyxerr.debug() << "Unknown type!" << endl;
1776 pflags = pflags & ~3; /* wysiwyg0 */
1779 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1782 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1785 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1788 pflags ^= 4; /* frame */
1791 pflags ^= 8; /* do translations */
1794 psubfigure = !psubfigure; /* This is a subfigure */
1797 regen = true; /* regenerate command */
1799 case 0: /* browse file */
1803 case 1: /* preview */
1804 p = fl_get_input(form->EpsFile);
1808 case 8: /* ok (apply and close) */
1809 if(!current_view->buffer()->isReadonly()) {
1812 xwid = atof(fl_get_input(form->Width));
1813 xhgh = atof(fl_get_input(form->Height));
1814 angle = atof(fl_get_input(form->Angle));
1815 p = fl_get_input(form->EpsFile);
1817 string buf1 = OnlyPath(owner->fileName());
1818 fname = MakeAbsPath(p, buf1);
1819 changedfname = true;
1821 if (!fname.empty()) {
1822 changedfname = true;
1826 subcaption = fl_get_input(form->Subcaption);
1830 /* now update inset */
1831 if (lyxerr.debugging()) {
1832 lyxerr << "Update: ["
1833 << wid << 'x' << hgh << ']' << endl;
1835 current_view->updateInset(this, true);
1837 fl_set_focus_object(form->Figure, form->OkBtn);
1838 fl_hide_form(form->Figure);
1839 #if FL_REVISION == 89
1840 #warning Reactivate this free_form calls
1842 fl_free_form(form->Figure);
1843 free(form); // Why free?
1849 // The user has already been informed about RO in ::Edit
1850 if(arg == 7) // if 'Apply'
1853 case 9: /* cancel = restore and close */
1854 fl_set_focus_object(form->Figure, form->OkBtn);
1855 fl_hide_form(form->Figure);
1856 #if FL_REVISION == 89
1857 #warning Reactivate this free_form calls
1858 #warning Jug, is this still a problem?
1860 fl_free_form(form->Figure);
1861 free(form); // Why free?
1867 if (regen) TempRegenerate();
1872 void DisableFigurePanel(FD_Figure * const form)
1874 fl_deactivate_object(form->EpsFile);
1875 fl_deactivate_object(form->Browse);
1876 fl_deactivate_object(form->Width);
1877 fl_deactivate_object(form->Height);
1878 fl_deactivate_object(form->Frame);
1879 fl_deactivate_object(form->Translations);
1880 fl_deactivate_object(form->Angle);
1881 fl_deactivate_object(form->HeightGrp);
1882 fl_deactivate_object(form->page2);
1883 fl_deactivate_object(form->Default2);
1884 fl_deactivate_object(form->cm2);
1885 fl_deactivate_object(form->in2);
1886 fl_deactivate_object(form->HeightLabel);
1887 fl_deactivate_object(form->WidthLabel);
1888 fl_deactivate_object(form->DisplayGrp);
1889 fl_deactivate_object(form->Wysiwyg3);
1890 fl_deactivate_object(form->Wysiwyg0);
1891 fl_deactivate_object(form->Wysiwyg2);
1892 fl_deactivate_object(form->Wysiwyg1);
1893 fl_deactivate_object(form->WidthGrp);
1894 fl_deactivate_object(form->Default1);
1895 fl_deactivate_object(form->cm1);
1896 fl_deactivate_object(form->in1);
1897 fl_deactivate_object(form->page1);
1898 fl_deactivate_object(form->column1);
1899 fl_deactivate_object(form->Subcaption);
1900 fl_deactivate_object(form->Subfigure);
1901 fl_deactivate_object (form->OkBtn);
1902 fl_deactivate_object (form->ApplyBtn);
1903 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1904 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1909 void EnableFigurePanel(FD_Figure * const form)
1911 fl_activate_object(form->EpsFile);
1912 fl_activate_object(form->Browse);
1913 fl_activate_object(form->Width);
1914 fl_activate_object(form->Height);
1915 fl_activate_object(form->Frame);
1916 fl_activate_object(form->Translations);
1917 fl_activate_object(form->Angle);
1918 fl_activate_object(form->HeightGrp);
1919 fl_activate_object(form->page2);
1920 fl_activate_object(form->Default2);
1921 fl_activate_object(form->cm2);
1922 fl_activate_object(form->in2);
1923 fl_activate_object(form->HeightLabel);
1924 fl_activate_object(form->WidthLabel);
1925 fl_activate_object(form->DisplayGrp);
1926 fl_activate_object(form->Wysiwyg3);
1927 fl_activate_object(form->Wysiwyg0);
1928 fl_activate_object(form->Wysiwyg2);
1929 fl_activate_object(form->Wysiwyg1);
1930 fl_activate_object(form->WidthGrp);
1931 fl_activate_object(form->Default1);
1932 fl_activate_object(form->cm1);
1933 fl_activate_object(form->in1);
1934 fl_activate_object(form->page1);
1935 fl_activate_object(form->column1);
1936 fl_activate_object(form->Subcaption);
1937 fl_activate_object(form->Subfigure);
1938 fl_activate_object (form->OkBtn);
1939 fl_activate_object (form->ApplyBtn);
1940 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1941 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1945 void InsetFig::RestoreForm()
1949 EnableFigurePanel(form);
1952 fl_set_button(form->Default1, (wtype == 0));
1953 fl_set_button(form->cm1, (wtype == 1));
1954 fl_set_button(form->in1, (wtype == 2));
1955 fl_set_button(form->page1, (wtype == 3));
1956 fl_set_button(form->column1, (wtype == 4));
1958 fl_deactivate_object(form->Width);
1960 fl_activate_object(form->Width);
1963 // enable and disable should be put here.
1965 fl_set_button(form->Default2, (htype == 0));
1966 fl_set_button(form->cm2, (htype == 1));
1967 fl_set_button(form->in2, (htype == 2));
1968 fl_set_button(form->page2, (htype == 3));
1969 // enable and disable should be put here.
1971 fl_deactivate_object(form->Height);
1973 fl_activate_object(form->Height);
1976 int pflags = flags & 3;
1977 fl_set_button(form->Wysiwyg0, (pflags == 0));
1978 fl_set_button(form->Wysiwyg1, (pflags == 1));
1979 fl_set_button(form->Wysiwyg2, (pflags == 2));
1980 fl_set_button(form->Wysiwyg3, (pflags == 3));
1981 fl_set_button(form->Frame, ((flags & 4) != 0));
1982 fl_set_button(form->Translations, ((flags & 8) != 0));
1983 fl_set_button(form->Subfigure, (subfigure != 0));
1985 psubfigure = subfigure;
1986 sprintf(buf, "%g", xwid);
1987 fl_set_input(form->Width, buf);
1988 sprintf(buf, "%g", xhgh);
1989 fl_set_input(form->Height, buf);
1990 sprintf(buf, "%g", angle);
1991 fl_set_input(form->Angle, buf);
1992 if (!fname.empty()){
1993 string buf1 = OnlyPath(owner->fileName());
1994 string fname2 = MakeRelPath(fname, buf1);
1995 fl_set_input(form->EpsFile, fname2.c_str());
1997 else fl_set_input(form->EpsFile, "");
1998 fl_set_input(form->Subcaption, subcaption.c_str());
1999 if(current_view->buffer()->isReadonly())
2000 DisableFigurePanel(form);
2006 void InsetFig::Preview(char const * p)
2011 lyxerr << "Cannot fork process!" << endl;
2016 return; // parent process
2019 string buf1 = OnlyPath(owner->fileName());
2020 string buf2 = MakeAbsPath(p, buf1);
2022 lyxerr << "Error during rendering "
2023 << execlp(lyxrc.view_pspic_command.c_str(),
2024 lyxrc.view_pspic_command.c_str(),
2031 void InsetFig::BrowseFile()
2033 static string current_figure_path;
2034 static int once = 0;
2037 if (lyxerr.debugging()) {
2038 lyxerr << "Filename: "
2039 << owner->fileName() << endl;
2041 string p = fl_get_input(form->EpsFile);
2043 string buf = MakeAbsPath(owner->fileName());
2044 string buf2 = OnlyPath(buf);
2046 buf = MakeAbsPath(p, buf2);
2047 buf = OnlyPath(buf);
2049 buf = OnlyPath(owner->fileName().c_str());
2052 // Does user clipart directory exist?
2053 string bufclip = AddName (user_lyxdir, "clipart");
2054 FileInfo fileInfo(bufclip);
2055 if (!(fileInfo.isOK() && fileInfo.isDir()))
2056 // No - bail out to system clipart directory
2057 bufclip = AddName (system_lyxdir, "clipart");
2060 fileDlg.SetButton(0, _("Clipart"), bufclip);
2061 fileDlg.SetButton(1, _("Document"), buf);
2065 ProhibitInput(current_view);
2067 p = fileDlg.Select(_("EPS Figure"),
2068 current_figure_path,
2071 p = fileDlg.Select(_("EPS Figure"), buf,
2074 AllowInput(current_view);
2076 if (p.empty()) return;
2078 buf = MakeRelPath(p, buf2);
2079 current_figure_path = OnlyPath(p);
2082 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2083 || contains(p, "%") || contains(p, " "))
2085 WriteAlert(_("Filename can't contain any "
2086 "of these characters:"),
2087 // xgettext:no-c-format
2088 _("space, '#', '~', '$' or '%'."));
2093 if (form) fl_set_input(form->EpsFile, buf.c_str());
2097 void GraphicsCB(FL_OBJECT * obj, long arg)
2099 /* obj->form contains the form */
2101 if (lyxerr.debugging()) {
2102 lyxerr << "GraphicsCB callback: " << arg << endl;
2105 /* find inset we were reacting to */
2106 for (figures_type::iterator it = figures.begin();
2107 it != figures.end(); ++it)
2108 if ((*it)->inset->form && (*it)->inset->form->Figure
2110 if (lyxerr.debugging()) {
2111 lyxerr << "Calling back figure "
2114 (*it)->inset->CallbackFig(arg);
2120 void HideFiguresPopups()
2122 for (figures_type::iterator it = figures.begin();
2123 it != figures.end(); ++it)
2124 if ((*it)->inset->form
2125 && (*it)->inset->form->Figure->visible) {
2126 if (lyxerr.debugging()) {
2127 lyxerr << "Hiding figure " << (*it) << endl;
2129 // hide and free the form
2130 (*it)->inset->CallbackFig(9);