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)
42 #include FORMS_H_LOCATION
51 #include "frontends/FileDialog.h"
52 #include "support/filetools.h"
53 #include "LyXView.h" // just because of form_main
55 #include "LaTeXFeatures.h"
58 #include "lyx_gui_misc.h" // CancelCloseBoxCB
59 #include "frontends/Alert.h"
60 #include "support/FileInfo.h"
61 #include "support/lyxlib.h"
62 #include "support/os.h"
65 #include "bufferview_funcs.h"
66 #include "ColorHandler.h"
67 #include "converter.h"
68 #include "frontends/Dialogs.h" // redrawGUI
69 #include "BufferView.h"
85 #ifndef CXX_GLOBAL_CSTD
94 extern BufferView * current_view;
95 extern FL_OBJECT * figinset_canvas;
97 extern char ** environ; // is this only redundtant on linux systems? Lgb.
99 // xforms doesn't define this (but it should be in <forms.h>).
101 FL_APPEVENT_CB fl_set_preemptive_callback(Window, FL_APPEVENT_CB, void *);
105 float const DEG2PI = 57.295779513;
107 struct queue_element {
108 float rx, ry; // resolution x and y
109 int ofsx, ofsy; // x and y translation
110 figdata * data; // we are doing it for this data
113 int const MAXGS = 3; /* maximum 3 gs's at a time */
115 typedef vector<Figref *> figures_type;
116 typedef vector<figdata *> bitmaps_type;
117 figures_type figures; // all figures
118 bitmaps_type bitmaps; // all bitmaps
120 queue<queue_element> gsqueue; // queue for ghostscripting
122 int gsrunning = 0; /* currently so many gs's are running */
123 bool bitmap_waiting = false; /* bitmaps are waiting finished */
125 bool gs_color; // do we allocate colors for gs?
126 bool color_visual; // is the visual color?
127 bool gs_xcolor = false; // allocated extended colors
128 unsigned long gs_pixels[128]; // allocated pixels
129 int gs_spc; // shades per color
130 int gs_allcolors; // number of all colors
132 list<int> pidwaitlist; // pid wait list
137 val.foreground = BlackPixel(fl_get_display(),
138 DefaultScreen(fl_get_display()));
141 val.graphics_exposures = false;
142 val.line_style = LineSolid;
144 return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0),
145 GCForeground | GCFunction | GCGraphicsExposures
146 | GCLineWidth | GCLineStyle , &val);
152 void addpidwait(int pid)
154 // adds pid to pid wait list
155 pidwaitlist.push_back(pid);
157 if (lyxerr.debugging()) {
158 lyxerr << "Pids to wait for: \n";
159 copy(pidwaitlist.begin(), pidwaitlist.end(),
160 std::ostream_iterator<int>(lyxerr, "\n"));
166 string make_tmp(int pid)
168 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
172 void kill_gs(int pid, int sig)
174 if (lyxerr.debugging())
175 lyxerr << "Killing gs " << pid << endl;
177 lyx::unlink(make_tmp(pid));
184 int GhostscriptMsg(XEvent * ev, void *)
186 // bin all events not of interest
187 if (ev->type != ClientMessage)
190 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
192 if (lyxerr.debugging()) {
193 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
194 << "] pm:[" << e->data.l[1] << "]" << endl;
197 // just kill gs, that way it will work for sure
198 // This loop looks like S**T so it probably is...
199 for (bitmaps_type::iterator it = bitmaps.begin();
200 it != bitmaps.end(); ++it)
201 if (static_cast<long>((*it)->bitmap) ==
202 static_cast<long>(e->data.l[1])) {
207 // first update p->bitmap, if necessary
208 if (p->bitmap != None
209 && p->flags > (1|8) && gs_color && p->wid) {
210 // query current colormap and re-render
211 // the pixmap with proper colors
212 XWindowAttributes wa;
213 register XImage * im;
216 int spc1 = gs_spc - 1;
217 int spc2 = gs_spc * gs_spc;
221 GC gc = local_gc_copy;
223 XGetWindowAttributes(fl_get_display(),
227 XFlush(fl_get_display());
228 if (lyxerr.debugging()) {
229 lyxerr << "Starting image translation "
232 << p->wid << "x" << p->hgh
234 << " " << XYPixmap << endl;
236 // now fork rendering process
238 if (forkstat == -1) {
240 << "Cannot fork, using slow "
241 "method for pixmap translation." << endl;
242 tmpdisp = fl_get_display();
243 } else if (forkstat > 0) { // parent
245 if (lyxerr.debugging()) {
246 lyxerr << "Spawned child "
249 addpidwait(forkstat);
252 tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
255 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
256 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
258 if (lyxerr.debugging()) {
259 lyxerr << "Got the image" << endl;
262 if (lyxerr.debugging()) {
263 lyxerr << "Error getting the image" << endl;
268 // query current colormap
269 XColor * cmap = new XColor[gs_allcolors];
270 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
271 XQueryColors(tmpdisp,
272 fl_state[fl_get_vclass()]
276 // now we process all the image
277 for (y = 0; y < p->hgh; ++y) {
278 for (int x = 0; x < wid; ++x) {
283 gs_pixels[((pc->red+6553)*
284 spc1/65535)*spc2+((pc->green+6553)*
285 spc1/65535)*gs_spc+((pc->blue+6553)*
290 // This must be correct.
292 if (lyxerr.debugging()) {
293 lyxerr << "Putting image back"
296 XPutImage(tmpdisp, p->bitmap,
298 0, 0, p->wid, p->hgh);
300 if (lyxerr.debugging()) {
301 lyxerr << "Done translation"
306 kill_gs(p->gspid, SIGHUP);
308 XCloseDisplay(tmpdisp);
312 kill_gs(p->gspid, SIGHUP);
322 void AllocColors(int num)
323 // allocate color cube numxnumxnum, if possible
325 if (lyxerr.debugging()) {
326 lyxerr << "Allocating color cube " << num
327 << 'x' << num << 'x' << num << endl;
331 lyxerr << "Error allocating color colormap." << endl;
335 if (num > 5) num = 5;
337 for (int i = 0; i < num * num * num; ++i) {
338 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
339 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
340 xcol.blue = short(65535 * (i % num) / (num - 1));
341 xcol.flags = DoRed | DoGreen | DoBlue;
342 if (!XAllocColor(fl_get_display(),
343 fl_state[fl_get_vclass()].colormap, &xcol)) {
344 if (i) XFreeColors(fl_get_display(),
345 fl_state[fl_get_vclass()].colormap,
347 if (lyxerr.debugging()) {
348 lyxerr << "Cannot allocate color cube "
351 AllocColors(num - 1);
354 gs_pixels[i] = xcol.pixel;
361 // allocate grayscale ramp
362 void AllocGrays(int num)
364 if (lyxerr.debugging()) {
365 lyxerr << "Allocating grayscale colormap "
370 lyxerr << "Error allocating grayscale colormap." << endl;
374 if (num > 128) num = 128;
376 for (int i = 0; i < num; ++i) {
377 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
378 xcol.flags = DoRed | DoGreen | DoBlue;
379 if (!XAllocColor(fl_get_display(),
380 fl_state[fl_get_vclass()].colormap, &xcol)) {
381 if (i) XFreeColors(fl_get_display(),
382 fl_state[fl_get_vclass()].colormap,
384 if (lyxerr.debugging()) {
385 lyxerr << "Cannot allocate grayscale "
391 gs_pixels[i] = xcol.pixel;
399 // if bitmaps and figures are not empty we will leak mem
403 // allocate color cube on pseudo-color display
407 /* we want to capture every event, in order to work around an
410 fl_set_preemptive_callback(fl_get_canvas_id(figinset_canvas), GhostscriptMsg, 0);
412 local_gc_copy = createGC();
414 Visual * vi = DefaultVisual(fl_get_display(),
415 DefaultScreen(fl_get_display()));
416 if (lyxerr.debugging()) {
417 printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n",
418 vi->visualid, vi->c_class,
419 vi->bits_per_rgb, vi->map_entries);
421 color_visual = ( (vi->c_class == StaticColor) ||
422 (vi->c_class == PseudoColor) ||
423 (vi->c_class == TrueColor) ||
424 (vi->c_class == DirectColor) );
425 if ((vi->c_class & 1) == 0) return;
426 // now allocate colors
427 if (vi->c_class == GrayScale) {
428 // allocate grayscale
429 AllocGrays(vi->map_entries/2);
431 // allocate normal color
433 while (i * i * i * 2 > vi->map_entries) --i;
436 gs_allcolors = vi->map_entries;
443 // if bitmaps and figures are not empty we will leak mem
447 lyxerr[Debug::INFO] << "Unregistering figures..." << endl;
451 void freefigdata(figdata * tmpdata)
454 if (tmpdata->ref) return;
456 if (tmpdata->gspid > 0) {
457 int pid = tmpdata->gspid;
458 // kill ghostscript and unlink it's files
460 kill_gs(pid, SIGKILL);
463 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
464 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
471 // This _have_ to be set before the fork!
472 unsigned long background_pixel =
473 lyxColorHandler->colorPixel(LColor::graphicsbg);
475 // run queued requests for ghostscript, if any
476 if (!gsrunning && gs_color && !gs_xcolor) {
477 // here alloc all colors, so that gs will use only
478 // those we allocated for it
483 while (gsrunning < MAXGS) {
484 //char tbuf[384]; //, tbuf2[80];
488 if (gsqueue.empty()) {
489 if (!gsrunning && gs_xcolor) {
490 // de-allocate rest of colors
496 queue_element * p = &gsqueue.front();
505 if (lyxerr.debugging()) {
506 lyxerr << "GS start error! Cannot fork."
509 p->data->broken = true;
510 p->data->reading = false;
513 if (pid == 0) { // child
516 Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
518 // create translation file
520 ofs.open(make_tmp(getpid()).c_str());
521 ofs << "gsave clippath pathbbox grestore\n"
523 << "/ury exch def /urx exch def /lly exch def "
525 << p->data->wid / 2.0 << " "
526 << p->data->hgh / 2.0 << " translate\n"
527 << p->data->angle << " rotate\n"
528 << -(p->data->raw_wid / 2.0) << " "
529 << -(p->data->raw_hgh / 2.0) << " translate\n"
530 << p->rx / 72.0 << " " << p->ry / 72.0
532 << -p->ofsx << " " << -p->ofsy << " translate\n"
534 ofs.close(); // Don't remove this.
536 // gs process - set ghostview environment first
538 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
539 << ' ' << p->data->bitmap;
540 // now set up ghostview property on a window
541 // #ifdef WITH_WARNINGS
542 // #warning BUG seems that the only bug here
543 // might be the hardcoded dpi.. Bummer!
546 t1 << "0 0 0 0 " << p->data->wid << ' '
547 << p->data->hgh << " 72 72 0 0 0 0";
549 if (lyxerr.debugging()) {
550 lyxerr << "Will set GHOSTVIEW property to ["
551 << t1.str() << "]" << endl;
553 // wait until property is deleted if executing multiple
555 XGrabServer(tempdisp);
557 // grab server to prevent other child
558 // interfering with setting GHOSTVIEW property
559 // The grabbing goes on for too long, is it
560 // really needed? (Lgb)
561 // I moved most of the grabs... (Lgb)
562 if (lyxerr.debugging()) {
563 lyxerr << "Grabbing the server"
566 prop = XListProperties(tempdisp,
568 figinset_canvas), &nprop);
572 for (i = 0; i < nprop; ++i) {
573 char * p = XGetAtomName(tempdisp,
575 if (compare(p, "GHOSTVIEW") == 0) {
577 // We free it when we leave so we don't leak.
583 XFree(reinterpret_cast<char *>(prop)); // jc:
585 // ok, property found, we must wait until
586 // ghostscript deletes it
587 if (lyxerr.debugging()) {
588 lyxerr << "Releasing the server\n["
590 << "] GHOSTVIEW property"
591 " found. Waiting." << endl;
593 XUngrabServer(tempdisp);
596 XGrabServer(tempdisp);
598 XChangeProperty(tempdisp,
599 fl_get_canvas_id(figinset_canvas),
600 XInternAtom(tempdisp, "GHOSTVIEW", false),
601 XInternAtom(tempdisp, "STRING", false),
603 reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
604 int(t1.str().size()));
605 XUngrabServer(tempdisp);
610 switch (p->data->flags & 3) {
611 case 0: t3 << 'H'; break; // Hidden
612 case 1: t3 << 'M'; break; // Mono
613 case 2: t3 << 'G'; break; // Gray
622 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
623 << ' ' << background_pixel;
625 XGrabServer(tempdisp);
626 XChangeProperty(tempdisp,
627 fl_get_canvas_id(figinset_canvas),
628 XInternAtom(tempdisp,
629 "GHOSTVIEW_COLORS", false),
630 XInternAtom(tempdisp, "STRING", false),
632 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
633 int(t3.str().size()));
634 XUngrabServer(tempdisp);
637 if (lyxerr.debugging()) {
638 lyxerr << "Releasing the server" << endl;
640 XCloseDisplay(tempdisp);
642 // set up environment
645 typedef char * char_p;
646 env = new char_p[ne + 2];
647 string tmp = t2.str().c_str();
648 env[0] = new char[tmp.size() + 1];
649 std::copy(tmp.begin(), tmp.end(), env[0]);
650 env[0][tmp.size()] = '\0';
651 memcpy(&env[1], environ,
652 sizeof(char*) * (ne + 1));
655 // now make gs command
657 // close(1); do NOT close. If GS writes out
658 // errors it would hang. (Matthias 290596)
660 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
661 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
663 // now chdir into dir with .eps file, to be on the safe
665 lyx::chdir(OnlyPath(p->data->fname));
666 // make temp file name
667 string tmpf = make_tmp(getpid());
668 if (lyxerr.debugging()) {
669 lyxerr << "starting gs " << tmpf << " "
671 << ", pid: " << getpid() << endl;
674 int err = ::execlp(lyxrc.ps_command.c_str(),
675 lyxrc.ps_command.c_str(),
677 "-dNOPAUSE", "-dQUIET",
679 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
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::INFO] << "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;
704 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
706 // recompute the stuff and put in the queue
710 p.rx = (float(data->raw_wid) * 72.0) / pswid;
711 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
717 // if possible, run the queue
722 figdata * getfigdata(int wid, int hgh, string const & fname,
723 int psx, int psy, int pswid, int pshgh,
724 int raw_wid, int raw_hgh, float angle, char flags)
726 /* first search for an exact match with fname and width/height */
728 if (fname.empty() || !IsFileReadable(fname))
731 for (bitmaps_type::iterator it = bitmaps.begin();
732 it != bitmaps.end(); ++it) {
733 if ((*it)->wid == wid && (*it)->hgh == hgh &&
734 (*it)->flags == flags && (*it)->fname == fname &&
735 (*it)->angle == angle) {
740 figdata * p = new figdata;
743 p->raw_wid = raw_wid;
744 p->raw_hgh = raw_hgh;
748 bitmaps.push_back(p);
749 XWindowAttributes wa;
750 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
751 figinset_canvas), &wa);
753 if (lyxerr.debugging()) {
754 lyxerr << "Create pixmap disp:" << fl_get_display()
755 << " scr:" << DefaultScreen(fl_get_display())
758 << " depth:" << wa.depth << endl;
766 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
767 figinset_canvas), wid, hgh, wa.depth);
769 // initialize reading of .eps file with correct sizes and stuff
770 addwait(psx, psy, pswid, pshgh, p);
781 void getbitmap(figdata * p)
787 void makeupdatelist(figdata * p)
789 for (figures_type::iterator it = figures.begin();
790 it != figures.end(); ++it)
791 if ((*it)->data == p) {
792 if (lyxerr.debugging()) {
793 lyxerr << "Updating inset "
797 // add inset figures[i]->inset into to_update list
798 current_view->pushIntoUpdateList((*it)->inset);
805 // this func is only "called" in spellchecker.C
806 void sigchldchecker(pid_t pid, int * status)
808 lyxerr[Debug::INFO] << "Got pid = " << pid << endl;
809 bool pid_handled = false;
810 for (bitmaps_type::iterator it = bitmaps.begin();
811 it != bitmaps.end(); ++it) {
812 if ((*it)->reading && pid == (*it)->gspid) {
813 lyxerr[Debug::INFO] << "Found pid in bitmaps" << endl;
814 // now read the file and remove it from disk
817 if ((*it)->gsdone) *status = 0;
819 lyxerr[Debug::INFO] << "GS [" << pid
820 << "] exit OK." << endl;
822 lyxerr << "GS [" << pid << "] error "
824 << WIFEXITED(*status)
825 << " " << WEXITSTATUS(*status)
826 << " S:" << WIFSIGNALED(*status)
827 << " " << WTERMSIG(*status) << endl;
830 bitmap_waiting = true;
833 // remove temporary files
834 lyx::unlink(make_tmp(p->gspid));
838 makeupdatelist((*it));
845 lyxerr[Debug::INFO] << "Checking pid in pidwait" << endl;
846 list<int>::iterator it = find(pidwaitlist.begin(),
847 pidwaitlist.end(), pid);
848 if (it != pidwaitlist.end()) {
849 lyxerr[Debug::INFO] << "Found pid in pidwait\n"
850 << "Caught child pid of recompute "
851 "routine" << pid << endl;
852 pidwaitlist.erase(it);
856 lyxerr[Debug::INFO] << "waitpid error" << endl;
859 lyxerr << "The process or process group specified by "
860 "pid does not exist or is not a child of "
861 "the calling process or can never be in the "
862 "states specified by options." << endl;
865 lyxerr << "waitpid() was interrupted due to the "
866 "receipt of a signal sent by the calling "
870 lyxerr << "An invalid value was specified for "
874 lyxerr << "Unknown error from waitpid" << endl;
877 } else if (pid == 0) {
878 lyxerr << "waitpid nohang" << endl;;
880 lyxerr[Debug::INFO] << "normal exit from childhandler" << endl;
889 bitmap_waiting = false;
890 for (bitmaps_type::iterator it = bitmaps.begin();
891 it != bitmaps.end(); ++it)
892 if ((*it)->gspid > 0 && !(*it)->reading)
897 void RegisterFigure(InsetFig * fi)
899 if (figures.empty()) InitFigures();
901 Figref * tmpfig = new Figref;
904 figures.push_back(tmpfig);
907 if (lyxerr.debugging() && current_view) {
908 lyxerr << "Register Figure: buffer:["
909 << current_view->buffer() << "]" << endl;
914 void UnregisterFigure(InsetFig * fi)
919 Figref * tmpfig = fi->figure;
921 if (tmpfig->data) freefigdata(tmpfig->data);
922 if (tmpfig->inset->form) {
923 if (tmpfig->inset->form->Figure->visible) {
924 fl_set_focus_object(tmpfig->inset->form->Figure,
925 tmpfig->inset->form->OkBtn);
926 fl_hide_form(tmpfig->inset->form->Figure);
928 #if FL_REVISION == 89
929 // CHECK Reactivate this free_form calls
931 fl_free_form(tmpfig->inset->form->Figure);
932 free(tmpfig->inset->form); // Why free?
933 tmpfig->inset->form = 0;
936 figures.erase(find(figures.begin(), figures.end(), tmpfig));
939 if (figures.empty()) DoneFigures();
945 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
955 psubfigure = subfigure = false;
956 xwid = xhgh = angle = 0;
958 raw_wid = raw_hgh = 0;
959 changedfname = false;
960 RegisterFigure(this);
961 r_ = Dialogs::redrawGUI.connect(SigC::slot(this, &InsetFig::redraw));
965 InsetFig::~InsetFig()
967 if (lyxerr.debugging()) {
968 lyxerr << "Figure destructor called" << endl;
970 UnregisterFigure(this);
975 void InsetFig::redraw()
977 if (form && form->Figure->visible)
978 fl_redraw_form(form->Figure);
982 int InsetFig::ascent(BufferView *, LyXFont const &) const
988 int InsetFig::descent(BufferView *, LyXFont const &) const
994 int InsetFig::width(BufferView *, LyXFont const &) const
1000 void InsetFig::draw(BufferView * bv, LyXFont const & f,
1001 int baseline, float & x, bool) const
1004 Painter & pain = bv->painter();
1006 if (bitmap_waiting) getbitmaps();
1008 // I wish that I didn't have to use this
1009 // but the figinset code is so complicated so
1010 // I don't want to fiddle with it now.
1012 if (figure && figure->data && figure->data->bitmap &&
1013 !figure->data->reading && !figure->data->broken) {
1015 pain.pixmap(int(x + 1), baseline - hgh,
1016 wid, hgh, figure->data->bitmap);
1019 pain.rectangle(int(x), baseline - hgh - 1,
1023 //char const * msg = 0;
1025 string lfname = fname;
1026 if (!fname.empty() && GetExtension(fname).empty())
1029 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1031 if (figure && figure->data) {
1032 if (figure->data->broken) msg = _("[render error]");
1033 else if (figure->data->reading) msg = _("[rendering ... ]");
1035 else if (fname.empty())
1036 msg = _("[no file]");
1037 else if (!IsFileReadable(lfname))
1038 msg = _("[bad file name]");
1039 else if ((flags & 3) == 0)
1040 msg = _("[not displayed]");
1041 else if (lyxrc.ps_command.empty())
1042 msg = _("[no ghostscript]");
1044 if (msg.empty()) msg = _("[unknown error]");
1046 font.setFamily(LyXFont::SANS_FAMILY);
1047 font.setSize(LyXFont::SIZE_FOOTNOTE);
1048 string const justname = OnlyFilename (fname);
1049 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1052 font.setSize(LyXFont::SIZE_TINY);
1053 pain.text(int(x + 8), baseline - 4, msg, font);
1055 x += width(bv, font); // ?
1059 void InsetFig::write(Buffer const *, ostream & os) const
1062 os << "Figure size " << wid << " " << hgh << "\n";
1063 if (!fname.empty()) {
1064 string buf1 = OnlyPath(owner->fileName());
1065 string fname2 = MakeRelPath(fname, buf1);
1066 os << "file " << fname2 << "\n";
1068 if (!subcaption.empty())
1069 os << "subcaption " << subcaption << "\n";
1070 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1071 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1072 if (angle != 0) os << "angle " << angle << "\n";
1073 os << "flags " << flags << "\n";
1074 if (subfigure) os << "subfigure\n";
1078 void InsetFig::read(Buffer const *, LyXLex & lex)
1081 bool finished = false;
1083 while (lex.isOK() && !finished) {
1086 string const token = lex.getString();
1087 lyxerr[Debug::INFO] << "Token: " << token << endl;
1091 else if (token == "\\end_inset") {
1093 } else if (token == "file") {
1095 buf = lex.getString();
1096 string const buf1(OnlyPath(owner->fileName()));
1097 fname = MakeAbsPath(buf, buf1);
1098 changedfname = true;
1100 } else if (token == "extra") {
1102 // kept for backwards compability. Delete in 0.13.x
1103 } else if (token == "subcaption") {
1105 subcaption = lex.getString();
1106 } else if (token == "label") {
1108 // kept for backwards compability. Delete in 0.13.x
1109 } else if (token == "angle") {
1111 angle = lex.getFloat();
1112 } else if (token == "size") {
1114 wid = lex.getInteger();
1116 hgh = lex.getInteger();
1117 } else if (token == "flags") {
1119 flags = pflags = lex.getInteger();
1120 } else if (token == "subfigure") {
1121 subfigure = psubfigure = true;
1122 } else if (token == "width") {
1125 typ = lex.getInteger();
1127 xwid = lex.getFloat();
1129 case DEF: wtype = DEF; break;
1130 case CM: wtype = CM; break;
1131 case IN: wtype = IN; break;
1132 case PER_PAGE: wtype = PER_PAGE; break;
1133 case PER_COL: wtype = PER_COL; break;
1135 lyxerr[Debug::INFO] << "Unknown type!" << endl;
1139 } else if (token == "height") {
1142 typ = lex.getInteger();
1144 xhgh = lex.getFloat();
1146 case DEF: htype = DEF; break;
1147 case CM: htype = CM; break;
1148 case IN: htype = IN; break;
1149 case PER_PAGE: htype = PER_PAGE; break;
1151 lyxerr[Debug::INFO] << "Unknown type!" << endl;
1162 int InsetFig::latex(Buffer const *, ostream & os,
1163 bool /* fragile*/, bool /* fs*/) const
1166 if (!cmd.empty()) os << cmd << " ";
1171 int InsetFig::ascii(Buffer const *, ostream &, int) const
1177 int InsetFig::linuxdoc(Buffer const *, ostream &) const
1183 int InsetFig::docbook(Buffer const *, ostream & os) const
1185 string const buf1 = OnlyPath(owner->fileName());
1186 string figurename = MakeRelPath(fname, buf1);
1188 if (suffixIs(figurename, ".eps"))
1189 figurename.erase(figurename.length() - 4);
1191 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1196 void InsetFig::validate(LaTeXFeatures & features) const
1198 features.require("graphics");
1200 features.require("subfigure");
1204 Inset::EDITABLE InsetFig::editable() const
1210 bool InsetFig::deletable() const
1216 string const InsetFig::editMessage() const
1218 return _("Opened figure");
1222 void InsetFig::edit(BufferView *, int, int, unsigned int)
1224 lyxerr[Debug::INFO] << "Editing InsetFig." << endl;
1228 form = create_form_Figure();
1229 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1230 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1231 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1232 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1235 if (form->Figure->visible) {
1236 fl_raise_form(form->Figure);
1238 fl_show_form(form->Figure,
1239 FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
1245 void InsetFig::edit(BufferView * bv, bool)
1251 Inset * InsetFig::clone(Buffer const & buffer, bool) const
1253 InsetFig * tmp = new InsetFig(100, 100, buffer);
1255 if (lyxerr.debugging()) {
1256 lyxerr << "Clone Figure: buffer:["
1258 << "], cbuffer:[xx]" << endl;
1263 tmp->raw_wid = raw_wid;
1264 tmp->raw_hgh = raw_hgh;
1269 tmp->pflags = pflags;
1270 tmp->subfigure = subfigure;
1271 tmp->psubfigure = psubfigure;
1279 string lfname = fname;
1280 if (!fname.empty() && GetExtension(fname).empty())
1282 if (!fname.empty() && IsFileReadable(lfname)
1283 && (flags & 3) && !lyxrc.ps_command.empty()
1285 // do not display if there is
1286 // "do not display" chosen (Matthias 260696)
1287 tmp->figure->data = getfigdata(wid, hgh, lfname, psx, psy,
1288 pswid, pshgh, raw_wid, raw_hgh,
1289 angle, flags & (3|8));
1290 } else tmp->figure->data = 0;
1291 tmp->subcaption = subcaption;
1292 tmp->changedfname = false;
1299 Inset::Code InsetFig::lyxCode() const
1301 return Inset::GRAPHICS_CODE;
1307 string const stringify(InsetFig::HWTYPE hw, float f, string suffix)
1313 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1314 res = tostr(f) + "cm";
1317 res = tostr(f) + "in";
1319 case InsetFig::PER_PAGE:
1320 res = tostr(f/100) + "\\text" + suffix;
1322 case InsetFig::PER_COL:
1323 // Doesn't occur for htype...
1324 res = tostr(f/100) + "\\column" + suffix;
1333 void InsetFig::regenerate() const
1341 if (fname.empty()) {
1342 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1343 cmd += _("empty figure path");
1348 string buf1 = OnlyPath(owner->fileName());
1349 string fname2 = MakeRelPath(fname, buf1);
1351 string gcmd = "\\includegraphics{" + fname2 + '}';
1352 resizeW = stringify(wtype, xwid, "width");
1353 resizeH = stringify(htype, xhgh, "height");
1355 if (!resizeW.empty() || !resizeH.empty()) {
1356 recmd = "\\resizebox*{";
1357 if (!resizeW.empty())
1362 if (!resizeH.empty())
1371 // \rotatebox{angle}{text}
1372 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1378 if (!rotate.empty()) cmdbuf += '}';
1379 if (!recmd.empty()) cmdbuf += '}';
1381 if (!subcaption.empty())
1382 cmdbuf = "\\subfigure[" + subcaption +
1383 "]{" + cmdbuf + "}";
1385 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1392 void InsetFig::tempRegenerate()
1400 char const * tfname = fl_get_input(form->EpsFile);
1401 string tsubcap = fl_get_input(form->Subcaption);
1402 float tangle = atof(fl_get_input(form->Angle));
1403 float txwid = atof(fl_get_input(form->Width));
1404 float txhgh = atof(fl_get_input(form->Height));
1406 if (!tfname || !*tfname) {
1407 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1408 cmd += _("empty figure path");
1413 string buf1 = OnlyPath(owner->fileName());
1414 string fname2 = MakeRelPath(tfname, buf1);
1415 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1416 string gcmd = "\\includegraphics{" + fname2 + '}';
1418 resizeW = stringify(twtype, txwid, "width");
1419 resizeH = stringify(thtype, txhgh, "height");
1421 // \resizebox*{h-length}{v-length}{text}
1422 if (!resizeW.empty() || !resizeH.empty()) {
1423 recmd = "\\resizebox*{";
1424 if (!resizeW.empty())
1429 if (!resizeH.empty())
1437 // \rotatebox{angle}{text}
1438 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1441 cmdbuf = recmd + rotate + gcmd;
1442 if (!rotate.empty()) cmdbuf += '}';
1443 if (!recmd.empty()) cmdbuf += '}';
1444 if (psubfigure && !tsubcap.empty()) {
1445 cmdbuf = string("\\subfigure{") + tsubcap
1446 + string("}{") + cmdbuf + "}";
1451 void InsetFig::recompute()
1456 bool changed = changedfname;
1457 int newx, newy, nraw_x, nraw_y;
1459 if (changed) getPSSizes();
1461 float sin_a = sin(angle / DEG2PI); /* rotation; H. Zeller 021296 */
1462 float cos_a = cos(angle / DEG2PI);
1463 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1464 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1466 string lfname = fname;
1467 if (GetExtension(fname).empty())
1470 /* now recompute wid and hgh, and if that is changed, set changed */
1471 /* this depends on chosen size of the picture and its bbox */
1472 // This will be redone in 0.13 ... (hen)
1473 if (!lfname.empty() && IsFileReadable(lfname)) {
1474 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1482 newx = int(28.346 * xwid);
1485 newx = int(72 * xwid);
1487 case PER_PAGE: /* % of page */
1488 newx = int(5.95 * xwid);
1490 case PER_COL: /* % of col */
1491 newx = int(2.975 * xwid);
1495 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1499 //lyxerr << "This should not happen!" << endl;
1502 newy = int(28.346 * xhgh);
1505 newy = int(72 * xhgh);
1507 case PER_PAGE: /* % of page */
1508 newy = int(8.42 * xhgh);
1511 // Doesn't occur; case exists to suppress
1512 // compiler warnings.
1515 if (htype && !wtype && frame_hgh)
1516 newx = newy*frame_wid/frame_hgh;
1525 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1530 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1532 // cannot be zero, actually, set it to some minimum, so its clickable
1533 if (newx < 5) newx = 5;
1534 if (newy < 5) newy = 5;
1536 if (newx != wid || newy != hgh ||
1537 nraw_x != raw_wid || nraw_y != raw_hgh ||
1538 flags != pflags || subfigure != psubfigure)
1546 subfigure = psubfigure;
1549 figdata * pf = figure->data;
1552 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1553 && !lyxrc.ps_command.empty()) {
1554 // do not display if there is "do not display"
1555 // chosen (Matthias 260696)
1556 figure->data = getfigdata(wid, hgh, lfname,
1557 psx, psy, pswid, pshgh,
1559 angle, flags & (3|8));
1560 } else figure->data = 0;
1562 // free the old data
1563 if (pf) freefigdata(pf);
1566 changedfname = false;
1570 void InsetFig::getPSSizes()
1572 /* get %%BoundingBox: from postscript file */
1574 /* defaults to associated size
1575 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1582 if (fname.empty()) return;
1584 string lfname = fname;
1585 if (GetExtension(fname).empty())
1587 ifstream ifs(lfname.c_str());
1589 if (!ifs) return; // file not found !!!!
1591 /* defaults to A4 page */
1597 char lastchar = 0; ifs.get(lastchar);
1599 char c = 0; ifs.get(c);
1601 lyxerr[Debug::INFO] << "End of (E)PS file reached and"
1602 " no BoundingBox!" << endl;
1605 if (c == '%' && lastchar == '%') {
1607 if (p.empty()) break;
1608 lyxerr[Debug::INFO] << "Token: `" << p << "'" << endl;
1609 if (p == "BoundingBox:") {
1610 float fpsx, fpsy, fpswid, fpshgh;
1611 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1614 pswid = int(fpswid);
1615 pshgh = int(fpshgh);
1617 if (lyxerr.debugging()) {
1618 lyxerr << "%%%%BoundingBox:"
1636 void InsetFig::callbackFig(long arg)
1641 if (lyxerr.debugging()) {
1642 lyxerr << "Figure callback, arg " << arg << endl;
1648 case 12: /* width type */
1655 fl_deactivate_object(form->Width);
1660 fl_activate_object(form->Width);
1665 fl_activate_object(form->Width);
1670 fl_activate_object(form->Width);
1675 fl_activate_object(form->Width);
1678 lyxerr[Debug::INFO] << "Unknown type!" << endl;
1685 case 22: /* height type */
1691 fl_deactivate_object(form->Height);
1696 fl_activate_object(form->Height);
1701 fl_activate_object(form->Height);
1706 fl_activate_object(form->Height);
1709 lyxerr[Debug::INFO] << "Unknown type!" << endl;
1715 pflags = pflags & ~3; /* wysiwyg0 */
1718 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1721 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1724 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1727 pflags ^= 4; /* frame */
1730 pflags ^= 8; /* do translations */
1733 psubfigure = !psubfigure; /* This is a subfigure */
1736 regen = true; /* regenerate command */
1738 case 0: /* browse file */
1742 case 1: /* preview */
1743 p = fl_get_input(form->EpsFile);
1747 case 8: /* ok (apply and close) */
1748 if (!current_view->buffer()->isReadonly()) {
1751 xwid = atof(fl_get_input(form->Width));
1752 xhgh = atof(fl_get_input(form->Height));
1753 angle = atof(fl_get_input(form->Angle));
1754 p = fl_get_input(form->EpsFile);
1756 string buf1 = OnlyPath(owner->fileName());
1757 fname = MakeAbsPath(p, buf1);
1758 changedfname = true;
1760 if (!fname.empty()) {
1761 changedfname = true;
1765 subcaption = fl_get_input(form->Subcaption);
1769 /* now update inset */
1770 if (lyxerr.debugging()) {
1771 lyxerr << "Update: ["
1772 << wid << 'x' << hgh << ']' << endl;
1774 current_view->updateInset(this, true);
1776 fl_set_focus_object(form->Figure, form->OkBtn);
1777 fl_hide_form(form->Figure);
1778 #if FL_REVISION == 89
1779 // CHECK Reactivate this free_form calls
1781 fl_free_form(form->Figure);
1782 free(form); // Why free?
1788 // The user has already been informed about RO in ::Edit
1789 if (arg == 7) // if 'Apply'
1792 case 9: /* cancel = restore and close */
1793 fl_set_focus_object(form->Figure, form->OkBtn);
1794 fl_hide_form(form->Figure);
1795 #if FL_REVISION == 89
1796 // CHECK Reactivate this free_form calls
1797 // Jug, is this still a problem?
1799 fl_free_form(form->Figure);
1800 free(form); // Why free?
1806 if (regen) tempRegenerate();
1811 void DisableFigurePanel(FD_Figure * const form)
1813 fl_deactivate_object(form->EpsFile);
1814 fl_deactivate_object(form->Browse);
1815 fl_deactivate_object(form->Width);
1816 fl_deactivate_object(form->Height);
1817 fl_deactivate_object(form->Frame);
1818 fl_deactivate_object(form->Translations);
1819 fl_deactivate_object(form->Angle);
1820 fl_deactivate_object(form->HeightGrp);
1821 fl_deactivate_object(form->page2);
1822 fl_deactivate_object(form->Default2);
1823 fl_deactivate_object(form->cm2);
1824 fl_deactivate_object(form->in2);
1825 fl_deactivate_object(form->HeightLabel);
1826 fl_deactivate_object(form->WidthLabel);
1827 fl_deactivate_object(form->DisplayGrp);
1828 fl_deactivate_object(form->Wysiwyg3);
1829 fl_deactivate_object(form->Wysiwyg0);
1830 fl_deactivate_object(form->Wysiwyg2);
1831 fl_deactivate_object(form->Wysiwyg1);
1832 fl_deactivate_object(form->WidthGrp);
1833 fl_deactivate_object(form->Default1);
1834 fl_deactivate_object(form->cm1);
1835 fl_deactivate_object(form->in1);
1836 fl_deactivate_object(form->page1);
1837 fl_deactivate_object(form->column1);
1838 fl_deactivate_object(form->Subcaption);
1839 fl_deactivate_object(form->Subfigure);
1840 fl_deactivate_object (form->OkBtn);
1841 fl_deactivate_object (form->ApplyBtn);
1842 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1843 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1848 void EnableFigurePanel(FD_Figure * const form)
1850 fl_activate_object(form->EpsFile);
1851 fl_activate_object(form->Browse);
1852 fl_activate_object(form->Width);
1853 fl_activate_object(form->Height);
1854 fl_activate_object(form->Frame);
1855 fl_activate_object(form->Translations);
1856 fl_activate_object(form->Angle);
1857 fl_activate_object(form->HeightGrp);
1858 fl_activate_object(form->page2);
1859 fl_activate_object(form->Default2);
1860 fl_activate_object(form->cm2);
1861 fl_activate_object(form->in2);
1862 fl_activate_object(form->HeightLabel);
1863 fl_activate_object(form->WidthLabel);
1864 fl_activate_object(form->DisplayGrp);
1865 fl_activate_object(form->Wysiwyg3);
1866 fl_activate_object(form->Wysiwyg0);
1867 fl_activate_object(form->Wysiwyg2);
1868 fl_activate_object(form->Wysiwyg1);
1869 fl_activate_object(form->WidthGrp);
1870 fl_activate_object(form->Default1);
1871 fl_activate_object(form->cm1);
1872 fl_activate_object(form->in1);
1873 fl_activate_object(form->page1);
1874 fl_activate_object(form->column1);
1875 fl_activate_object(form->Subcaption);
1876 fl_activate_object(form->Subfigure);
1877 fl_activate_object (form->OkBtn);
1878 fl_activate_object (form->ApplyBtn);
1879 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1880 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1884 void InsetFig::restoreForm()
1886 EnableFigurePanel(form);
1889 fl_set_button(form->Default1, (wtype == 0));
1890 fl_set_button(form->cm1, (wtype == 1));
1891 fl_set_button(form->in1, (wtype == 2));
1892 fl_set_button(form->page1, (wtype == 3));
1893 fl_set_button(form->column1, (wtype == 4));
1895 fl_deactivate_object(form->Width);
1897 fl_activate_object(form->Width);
1900 // enable and disable should be put here.
1902 fl_set_button(form->Default2, (htype == 0));
1903 fl_set_button(form->cm2, (htype == 1));
1904 fl_set_button(form->in2, (htype == 2));
1905 fl_set_button(form->page2, (htype == 3));
1906 // enable and disable should be put here.
1908 fl_deactivate_object(form->Height);
1910 fl_activate_object(form->Height);
1913 int piflags = flags & 3;
1914 fl_set_button(form->Wysiwyg0, (piflags == 0));
1915 fl_set_button(form->Wysiwyg1, (piflags == 1));
1916 fl_set_button(form->Wysiwyg2, (piflags == 2));
1917 fl_set_button(form->Wysiwyg3, (piflags == 3));
1918 fl_set_button(form->Frame, ((flags & 4) != 0));
1919 fl_set_button(form->Translations, ((flags & 8) != 0));
1920 fl_set_button(form->Subfigure, (subfigure != 0));
1922 psubfigure = subfigure;
1923 fl_set_input(form->Width, tostr(xwid).c_str());
1924 fl_set_input(form->Height, tostr(xhgh).c_str());
1925 fl_set_input(form->Angle, tostr(angle).c_str());
1926 if (!fname.empty()){
1927 string buf1 = OnlyPath(owner->fileName());
1928 string fname2 = MakeRelPath(fname, buf1);
1929 fl_set_input(form->EpsFile, fname2.c_str());
1931 else fl_set_input(form->EpsFile, "");
1932 fl_set_input(form->Subcaption, subcaption.c_str());
1933 if (current_view->buffer()->isReadonly())
1934 DisableFigurePanel(form);
1940 void InsetFig::preview(string const & p)
1943 if (GetExtension(tfname).empty())
1945 string buf1 = OnlyPath(owner->fileName());
1946 string buf2 = os::external_path(MakeAbsPath(tfname, buf1));
1947 if (!formats.view(owner, buf2, "eps"))
1948 lyxerr << "Can't view " << buf2 << endl;
1952 void InsetFig::browseFile()
1954 static string current_figure_path;
1957 if (lyxerr.debugging()) {
1958 lyxerr << "Filename: "
1959 << owner->fileName() << endl;
1961 string p = fl_get_input(form->EpsFile);
1963 string buf = MakeAbsPath(owner->fileName());
1964 string buf2 = OnlyPath(buf);
1966 buf = MakeAbsPath(p, buf2);
1967 buf = OnlyPath(buf);
1969 buf = OnlyPath(owner->fileName());
1972 // Does user clipart directory exist?
1973 string bufclip = AddName (user_lyxdir, "clipart");
1974 FileInfo fileInfo(bufclip);
1975 if (!(fileInfo.isOK() && fileInfo.isDir()))
1976 // No - bail out to system clipart directory
1977 bufclip = AddName (system_lyxdir, "clipart");
1980 FileDialog fileDlg(current_view->owner(), _("Select an EPS figure"),
1981 LFUN_SELECT_FILE_SYNC,
1982 make_pair(string(_("Clip art")), string(bufclip)),
1983 make_pair(string(_("Documents")), string(buf)));
1987 string const path = (once) ? current_figure_path : buf;
1989 FileDialog::Result result = fileDlg.Select(path, _("*ps| PostScript documents"));
1991 string const p = result.second;
1996 buf = MakeRelPath(p, buf2);
1997 current_figure_path = OnlyPath(p);
2000 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
2001 || contains(p, "%") || contains(p, " ")) {
2002 Alert::alert(_("Filename can't contain any "
2003 "of these characters:"),
2004 // xgettext:no-c-format
2005 _("space, '#', '~', '$' or '%'."));
2010 if (form) fl_set_input(form->EpsFile, buf.c_str());
2014 void GraphicsCB(FL_OBJECT * obj, long arg)
2016 /* obj->form contains the form */
2018 if (lyxerr.debugging()) {
2019 lyxerr << "GraphicsCB callback: " << arg << endl;
2022 /* find inset we were reacting to */
2023 for (figures_type::iterator it = figures.begin();
2024 it != figures.end(); ++it)
2025 if ((*it)->inset->form && (*it)->inset->form->Figure
2027 if (lyxerr.debugging()) {
2028 lyxerr << "Calling back figure "
2031 (*it)->inset->callbackFig(arg);
2037 void HideFiguresPopups()
2039 for (figures_type::iterator it = figures.begin();
2040 it != figures.end(); ++it)
2041 if ((*it)->inset->form
2042 && (*it)->inset->form->Figure->visible) {
2043 if (lyxerr.debugging()) {
2044 lyxerr << "Hiding figure " << (*it) << endl;
2046 // hide and free the form
2047 (*it)->inset->callbackFig(9);