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 "support/FileInfo.h"
60 #include "support/lyxlib.h"
63 #include "bufferview_funcs.h"
64 #include "ColorHandler.h"
65 #include "converter.h"
66 #include "frontends/Dialogs.h" // redrawGUI
68 #ifdef SIGC_CXX_NAMESPACES
82 using std::ostringstream;
87 extern BufferView * current_view;
88 extern FL_OBJECT * figinset_canvas;
90 extern char ** environ; // is this only redundtant on linux systems? Lgb.
92 static float const DEG2PI = 57.295779513;
94 struct queue_element {
95 float rx, ry; // resolution x and y
96 int ofsx, ofsy; // x and y translation
97 figdata * data; // we are doing it for this data
100 static int const MAXGS = 3; /* maximum 3 gs's at a time */
102 typedef vector<Figref *> figures_type;
103 typedef vector<figdata *> bitmaps_type;
104 static figures_type figures; // all figures
105 static bitmaps_type bitmaps; // all bitmaps
107 static queue<queue_element> gsqueue; // queue for ghostscripting
109 static int gsrunning = 0; /* currently so many gs's are running */
110 static bool bitmap_waiting = false; /* bitmaps are waiting finished */
112 static bool gs_color; // do we allocate colors for gs?
113 static bool color_visual; // is the visual color?
114 static bool gs_xcolor = false; // allocated extended colors
115 static unsigned long gs_pixels[128]; // allocated pixels
116 static int gs_spc; // shades per color
117 static int gs_allcolors; // number of all colors
119 static list<int> pidwaitlist; // pid wait list
125 val.foreground = BlackPixel(fl_get_display(),
126 DefaultScreen(fl_get_display()));
129 val.graphics_exposures = false;
130 val.line_style = LineSolid;
132 return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0),
133 GCForeground | GCFunction | GCGraphicsExposures
134 | GCLineWidth | GCLineStyle , &val);
142 void addpidwait(int pid)
144 // adds pid to pid wait list
145 pidwaitlist.push_back(pid);
147 if (lyxerr.debugging()) {
148 lyxerr << "Pids to wait for: \n";
149 copy(pidwaitlist.begin(), pidwaitlist.end(),
150 std::ostream_iterator<int>(lyxerr, "\n"));
157 string make_tmp(int pid)
159 return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
164 void kill_gs(int pid, int sig)
166 if (lyxerr.debugging())
167 lyxerr << "Killing gs " << pid << endl;
169 lyx::unlink(make_tmp(pid));
175 int GhostscriptMsg(XEvent * ev, void *)
177 // bin all events not of interest
178 if (ev->type != ClientMessage)
181 XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
183 if (lyxerr.debugging()) {
184 lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
185 << "] pm:[" << e->data.l[1] << "]" << endl;
188 // just kill gs, that way it will work for sure
189 // This loop looks like S**T so it probably is...
190 for (bitmaps_type::iterator it = bitmaps.begin();
191 it != bitmaps.end(); ++it)
192 if (static_cast<long>((*it)->bitmap) ==
193 static_cast<long>(e->data.l[1])) {
198 // first update p->bitmap, if necessary
199 if (p->bitmap != None
200 && p->flags > (1|8) && gs_color && p->wid) {
201 // query current colormap and re-render
202 // the pixmap with proper colors
203 XWindowAttributes wa;
204 register XImage * im;
207 int spc1 = gs_spc - 1;
208 int spc2 = gs_spc * gs_spc;
212 GC gc = local_gc_copy;
214 XGetWindowAttributes(fl_get_display(),
218 XFlush(fl_get_display());
219 if (lyxerr.debugging()) {
220 lyxerr << "Starting image translation "
223 << p->wid << "x" << p->hgh
225 << " " << XYPixmap << endl;
227 // now fork rendering process
229 if (forkstat == -1) {
231 << "Cannot fork, using slow "
232 "method for pixmap translation." << endl;
233 tmpdisp = fl_get_display();
234 } else if (forkstat > 0) { // parent
236 if (lyxerr.debugging()) {
237 lyxerr << "Spawned child "
240 addpidwait(forkstat);
243 tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
246 im = XGetImage(tmpdisp, p->bitmap, 0, 0,
247 p->wid, p->hgh, (1<<wa.depth)-1, XYPixmap);
249 if (lyxerr.debugging()) {
250 lyxerr << "Got the image" << endl;
253 if (lyxerr.debugging()) {
254 lyxerr << "Error getting the image" << endl;
259 // query current colormap
260 XColor * cmap = new XColor[gs_allcolors];
261 for (i = 0; i < gs_allcolors; ++i) cmap[i].pixel = i;
262 XQueryColors(tmpdisp,
263 fl_state[fl_get_vclass()]
267 // now we process all the image
268 for (y = 0; y < p->hgh; ++y) {
269 for (int x = 0; x < wid; ++x) {
274 gs_pixels[((pc->red+6553)*
275 spc1/65535)*spc2+((pc->green+6553)*
276 spc1/65535)*gs_spc+((pc->blue+6553)*
281 // This must be correct.
283 if (lyxerr.debugging()) {
284 lyxerr << "Putting image back"
287 XPutImage(tmpdisp, p->bitmap,
289 0, 0, p->wid, p->hgh);
291 if (lyxerr.debugging()) {
292 lyxerr << "Done translation"
297 kill_gs(p->gspid, SIGHUP);
299 XCloseDisplay(tmpdisp);
303 kill_gs(p->gspid, SIGHUP);
313 void AllocColors(int num)
314 // allocate color cube numxnumxnum, if possible
316 if (lyxerr.debugging()) {
317 lyxerr << "Allocating color cube " << num
318 << 'x' << num << 'x' << num << endl;
322 lyxerr << "Error allocating color colormap." << endl;
326 if (num > 5) num = 5;
328 for (int i = 0; i < num * num * num; ++i) {
329 xcol.red = short(65535 * (i / (num * num)) / (num - 1));
330 xcol.green = short(65535 * ((i / num) % num) / (num - 1));
331 xcol.blue = short(65535 * (i % num) / (num - 1));
332 xcol.flags = DoRed | DoGreen | DoBlue;
333 if (!XAllocColor(fl_get_display(),
334 fl_state[fl_get_vclass()].colormap, &xcol)) {
335 if (i) XFreeColors(fl_get_display(),
336 fl_state[fl_get_vclass()].colormap,
338 if (lyxerr.debugging()) {
339 lyxerr << "Cannot allocate color cube "
342 AllocColors(num - 1);
345 gs_pixels[i] = xcol.pixel;
352 // allocate grayscale ramp
354 void AllocGrays(int num)
356 if (lyxerr.debugging()) {
357 lyxerr << "Allocating grayscale colormap "
362 lyxerr << "Error allocating grayscale colormap." << endl;
366 if (num > 128) num = 128;
368 for (int i = 0; i < num; ++i) {
369 xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
370 xcol.flags = DoRed | DoGreen | DoBlue;
371 if (!XAllocColor(fl_get_display(),
372 fl_state[fl_get_vclass()].colormap, &xcol)) {
373 if (i) XFreeColors(fl_get_display(),
374 fl_state[fl_get_vclass()].colormap,
376 if (lyxerr.debugging()) {
377 lyxerr << "Cannot allocate grayscale "
383 gs_pixels[i] = xcol.pixel;
389 // xforms doesn't define this
390 extern "C" FL_APPEVENT_CB fl_set_preemptive_callback(Window, FL_APPEVENT_CB, void *);
395 // if bitmaps and figures are not empty we will leak mem
399 // allocate color cube on pseudo-color display
403 /* we want to capture every event, in order to work around an
406 fl_set_preemptive_callback(fl_get_canvas_id(figinset_canvas), GhostscriptMsg, 0);
408 local_gc_copy = createGC();
410 Visual * vi = DefaultVisual(fl_get_display(),
411 DefaultScreen(fl_get_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;
449 void freefigdata(figdata * tmpdata)
452 if (tmpdata->ref) return;
454 if (tmpdata->gspid > 0) {
455 int pid = tmpdata->gspid;
456 // kill ghostscript and unlink it's files
458 kill_gs(pid, SIGKILL);
461 if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
462 bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
470 // This _have_ to be set before the fork!
471 unsigned long background_pixel =
472 lyxColorHandler->colorPixel(LColor::background);
474 // run queued requests for ghostscript, if any
475 if (!gsrunning && gs_color && !gs_xcolor) {
476 // here alloc all colors, so that gs will use only
477 // those we allocated for it
482 while (gsrunning < MAXGS) {
483 //char tbuf[384]; //, tbuf2[80];
487 if (gsqueue.empty()) {
488 if (!gsrunning && gs_xcolor) {
489 // de-allocate rest of colors
495 queue_element * p = &gsqueue.front();
504 if (lyxerr.debugging()) {
505 lyxerr << "GS start error! Cannot fork."
508 p->data->broken = true;
509 p->data->reading = false;
512 if (pid == 0) { // child
515 Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
517 // create translation file
519 ofs.open(make_tmp(getpid()).c_str());
520 ofs << "gsave clippath pathbbox grestore\n"
522 << "/ury exch def /urx exch def /lly exch def "
524 << p->data->wid / 2.0 << " "
525 << p->data->hgh / 2.0 << " translate\n"
526 << p->data->angle << " rotate\n"
527 << -(p->data->raw_wid / 2.0) << " "
528 << -(p->data->raw_hgh / 2.0) << " translate\n"
529 << p->rx / 72.0 << " " << p->ry / 72.0
531 << -p->ofsx << " " << -p->ofsy << " translate\n"
533 ofs.close(); // Don't remove this.
535 // gs process - set ghostview environment first
537 t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
538 << ' ' << p->data->bitmap;
539 // now set up ghostview property on a window
540 // #warning BUG seems that the only bug here
541 // might be the hardcoded dpi.. Bummer!
543 t1 << "0 0 0 0 " << p->data->wid << ' '
544 << p->data->hgh << " 72 72 0 0 0 0";
546 if (lyxerr.debugging()) {
547 lyxerr << "Will set GHOSTVIEW property to ["
548 << t1.str() << "]" << endl;
550 // wait until property is deleted if executing multiple
552 XGrabServer(tempdisp);
554 // grab server to prevent other child
555 // interfering with setting GHOSTVIEW property
556 // The grabbing goes on for too long, is it
557 // really needed? (Lgb)
558 // I moved most of the grabs... (Lgb)
559 if (lyxerr.debugging()) {
560 lyxerr << "Grabbing the server"
563 prop = XListProperties(tempdisp,
565 figinset_canvas), &nprop);
569 for (i = 0; i < nprop; ++i) {
570 char * p = XGetAtomName(tempdisp,
572 if (compare(p, "GHOSTVIEW") == 0) {
574 // We free it when we leave so we don't leak.
580 XFree(reinterpret_cast<char *>(prop)); // jc:
582 // ok, property found, we must wait until
583 // ghostscript deletes it
584 if (lyxerr.debugging()) {
585 lyxerr << "Releasing the server\n["
587 << "] GHOSTVIEW property"
588 " found. Waiting." << endl;
590 XUngrabServer(tempdisp);
593 XGrabServer(tempdisp);
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*>(const_cast<char*>(t1.str().c_str())),
601 int(t1.str().size()));
602 XUngrabServer(tempdisp);
607 switch (p->data->flags & 3) {
608 case 0: t3 << 'H'; break; // Hidden
609 case 1: t3 << 'M'; break; // Mono
610 case 2: t3 << 'G'; break; // Gray
619 t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
620 << ' ' << background_pixel;
622 XGrabServer(tempdisp);
623 XChangeProperty(tempdisp,
624 fl_get_canvas_id(figinset_canvas),
625 XInternAtom(tempdisp,
626 "GHOSTVIEW_COLORS", false),
627 XInternAtom(tempdisp, "STRING", false),
629 reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
630 int(t3.str().size()));
631 XUngrabServer(tempdisp);
634 if (lyxerr.debugging()) {
635 lyxerr << "Releasing the server" << endl;
637 XCloseDisplay(tempdisp);
639 // set up environment
642 typedef char * char_p;
643 env = new char_p[ne + 2];
644 string tmp = t2.str().c_str();
645 env[0] = new char[tmp.size() + 1];
646 std::copy(tmp.begin(), tmp.end(), env[0]);
647 env[0][tmp.size()] = '\0';
648 ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
651 // now make gs command
653 // close(1); do NOT close. If GS writes out
654 // errors it would hang. (Matthias 290596)
656 string rbuf = "-r" + tostr(p->rx) + "x" + tostr(p->ry);
657 string gbuf = "-g" + tostr(p->data->wid) + "x" + tostr(p->data->hgh);
659 // now chdir into dir with .eps file, to be on the safe
661 lyx::chdir(OnlyPath(p->data->fname));
662 // make temp file name
663 string tmpf = make_tmp(getpid());
664 if (lyxerr.debugging()) {
665 lyxerr << "starting gs " << tmpf << " "
667 << ", pid: " << getpid() << endl;
670 int err = ::execlp(lyxrc.ps_command.c_str(),
671 lyxrc.ps_command.c_str(),
673 "-dNOPAUSE", "-dQUIET",
675 rbuf.c_str(), gbuf.c_str(), tmpf.c_str(),
676 p->data->fname.c_str(),
677 "showpage.ps", "quit.ps", "-", 0);
678 // if we are still there, an error occurred.
679 lyxerr << "Error executing ghostscript. "
680 << "Code: " << err << endl;
681 lyxerr.debug() << "Cmd: "
685 << p->data->fname << endl;
688 // normal process (parent)
689 if (lyxerr.debugging()) {
690 lyxerr << "GS [" << pid << "] started" << endl;
693 p->data->gspid = pid;
701 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
703 // recompute the stuff and put in the queue
707 p.rx = (float(data->raw_wid) * 72.0) / pswid;
708 p.ry = (float(data->raw_hgh) * 72.0) / pshgh;
714 // if possible, run the queue
720 figdata * getfigdata(int wid, int hgh, string const & fname,
721 int psx, int psy, int pswid, int pshgh,
722 int raw_wid, int raw_hgh, float angle, char flags)
724 /* first search for an exact match with fname and width/height */
726 if (fname.empty() || !IsFileReadable(fname))
729 for (bitmaps_type::iterator it = bitmaps.begin();
730 it != bitmaps.end(); ++it) {
731 if ((*it)->wid == wid && (*it)->hgh == hgh &&
732 (*it)->flags == flags && (*it)->fname == fname &&
733 (*it)->angle == angle) {
738 figdata * p = new figdata;
741 p->raw_wid = raw_wid;
742 p->raw_hgh = raw_hgh;
746 bitmaps.push_back(p);
747 XWindowAttributes wa;
748 XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
749 figinset_canvas), &wa);
751 if (lyxerr.debugging()) {
752 lyxerr << "Create pixmap disp:" << fl_get_display()
753 << " scr:" << DefaultScreen(fl_get_display())
756 << " depth:" << wa.depth << endl;
764 p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
765 figinset_canvas), wid, hgh, wa.depth);
767 // initialize reading of .eps file with correct sizes and stuff
768 addwait(psx, psy, pswid, pshgh, p);
780 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);
803 // this func is only "called" in spellchecker.C
804 void sigchldchecker(pid_t pid, int * status)
806 lyxerr.debug() << "Got pid = " << pid << endl;
807 bool pid_handled = false;
808 for (bitmaps_type::iterator it = bitmaps.begin();
809 it != bitmaps.end(); ++it) {
810 if ((*it)->reading && pid == (*it)->gspid) {
811 lyxerr.debug() << "Found pid in bitmaps" << endl;
812 // now read the file and remove it from disk
815 if ((*it)->gsdone) *status = 0;
817 lyxerr.debug() << "GS [" << pid
818 << "] exit OK." << endl;
820 lyxerr << "GS [" << pid << "] error "
822 << WIFEXITED(*status)
823 << " " << WEXITSTATUS(*status)
824 << " S:" << WIFSIGNALED(*status)
825 << " " << WTERMSIG(*status) << endl;
828 bitmap_waiting = true;
831 // remove temporary files
832 lyx::unlink(make_tmp(p->gspid));
836 makeupdatelist((*it));
843 lyxerr.debug() << "Checking pid in pidwait" << endl;
844 list<int>::iterator it = find(pidwaitlist.begin(),
845 pidwaitlist.end(), pid);
846 if (it != pidwaitlist.end()) {
847 lyxerr.debug() << "Found pid in pidwait\n"
848 << "Caught child pid of recompute "
849 "routine" << pid << endl;
850 pidwaitlist.erase(it);
854 lyxerr.debug() << "waitpid error" << endl;
857 lyxerr << "The process or process group specified by "
858 "pid does not exist or is not a child of "
859 "the calling process or can never be in the "
860 "states specified by options." << endl;
863 lyxerr << "waitpid() was interrupted due to the "
864 "receipt of a signal sent by the calling "
868 lyxerr << "An invalid value was specified for "
872 lyxerr << "Unknown error from waitpid" << endl;
875 } else if (pid == 0) {
876 lyxerr << "waitpid nohang" << endl;;
878 lyxerr.debug() << "normal exit from childhandler" << endl;
886 bitmap_waiting = false;
887 for (bitmaps_type::iterator it = bitmaps.begin();
888 it != bitmaps.end(); ++it)
889 if ((*it)->gspid > 0 && !(*it)->reading)
895 void RegisterFigure(InsetFig * fi)
897 if (figures.empty()) InitFigures();
899 Figref * tmpfig = new Figref;
902 figures.push_back(tmpfig);
905 if (lyxerr.debugging()) {
906 lyxerr << "Register Figure: buffer:["
907 << current_view->buffer() << "]" << endl;
913 void UnregisterFigure(InsetFig * fi)
918 Figref * tmpfig = fi->figure;
920 if (tmpfig->data) freefigdata(tmpfig->data);
921 if (tmpfig->inset->form) {
922 if (tmpfig->inset->form->Figure->visible) {
923 fl_set_focus_object(tmpfig->inset->form->Figure,
924 tmpfig->inset->form->OkBtn);
925 fl_hide_form(tmpfig->inset->form->Figure);
927 #if FL_REVISION == 89
928 // CHECK Reactivate this free_form calls
930 fl_free_form(tmpfig->inset->form->Figure);
931 free(tmpfig->inset->form); // Why free?
932 tmpfig->inset->form = 0;
935 figures.erase(find(figures.begin(), figures.end(), tmpfig));
938 if (figures.empty()) DoneFigures();
942 InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
952 psubfigure = subfigure = false;
953 xwid = xhgh = angle = 0;
955 raw_wid = raw_hgh = 0;
956 changedfname = false;
957 RegisterFigure(this);
958 r_ = Dialogs::redrawGUI.connect(slot(this, &InsetFig::redraw));
962 InsetFig::~InsetFig()
964 if (lyxerr.debugging()) {
965 lyxerr << "Figure destructor called" << endl;
967 UnregisterFigure(this);
972 void InsetFig::redraw()
974 if (form && form->Figure->visible)
975 fl_redraw_form(form->Figure);
979 int InsetFig::ascent(BufferView *, LyXFont const &) const
985 int InsetFig::descent(BufferView *, LyXFont const &) const
991 int InsetFig::width(BufferView *, LyXFont const &) const
997 void InsetFig::draw(BufferView * bv, LyXFont const & f,
998 int baseline, float & x, bool) const
1001 Painter & pain = bv->painter();
1003 if (bitmap_waiting) getbitmaps();
1005 // I wish that I didn't have to use this
1006 // but the figinset code is so complicated so
1007 // I don't want to fiddle with it now.
1009 if (figure && figure->data && figure->data->bitmap &&
1010 !figure->data->reading && !figure->data->broken) {
1012 pain.pixmap(int(x + 1), baseline - hgh,
1013 wid, hgh, figure->data->bitmap);
1016 pain.rectangle(int(x), baseline - hgh - 1,
1020 char const * msg = 0;
1021 string lfname = fname;
1022 if (!fname.empty() && GetExtension(fname).empty())
1025 pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
1027 if (figure && figure->data) {
1028 if (figure->data->broken) msg = _("[render error]");
1029 else if (figure->data->reading) msg = _("[rendering ... ]");
1031 else if (fname.empty())
1032 msg = _("[no file]");
1033 else if (!IsFileReadable(lfname))
1034 msg = _("[bad file name]");
1035 else if ((flags & 3) == 0)
1036 msg = _("[not displayed]");
1037 else if (lyxrc.ps_command.empty())
1038 msg = _("[no ghostscript]");
1040 if (!msg) msg = _("[unknown error]");
1042 font.setFamily(LyXFont::SANS_FAMILY);
1043 font.setSize(LyXFont::SIZE_FOOTNOTE);
1044 string justname = OnlyFilename (fname);
1045 pain.text(int(x + 8), baseline - lyxfont::maxAscent(font) - 4,
1048 font.setSize(LyXFont::SIZE_TINY);
1049 pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
1051 x += width(bv, font); // ?
1055 void InsetFig::Write(Buffer const *, ostream & os) const
1058 os << "Figure size " << wid << " " << hgh << "\n";
1059 if (!fname.empty()) {
1060 string buf1 = OnlyPath(owner->fileName());
1061 string fname2 = MakeRelPath(fname, buf1);
1062 os << "file " << fname2 << "\n";
1064 if (!subcaption.empty())
1065 os << "subcaption " << subcaption << "\n";
1066 if (wtype) os << "width " << static_cast<int>(wtype) << " " << xwid << "\n";
1067 if (htype) os << "height " << static_cast<int>(htype) << " " << xhgh << "\n";
1068 if (angle != 0) os << "angle " << angle << "\n";
1069 os << "flags " << flags << "\n";
1070 if (subfigure) os << "subfigure\n";
1074 void InsetFig::Read(Buffer const *, LyXLex & lex)
1077 bool finished = false;
1079 while (lex.IsOK() && !finished) {
1082 string const token = lex.GetString();
1083 lyxerr.debug() << "Token: " << token << endl;
1087 else if (token == "\\end_inset") {
1089 } else if (token == "file") {
1091 buf = lex.GetString();
1092 string buf1 = OnlyPath(owner->fileName());
1093 fname = MakeAbsPath(buf, buf1);
1094 changedfname = true;
1096 } else if (token == "extra") {
1098 // kept for backwards compability. Delete in 0.13.x
1099 } else if (token == "subcaption") {
1101 subcaption = lex.GetString();
1102 } else if (token == "label") {
1104 // kept for backwards compability. Delete in 0.13.x
1105 } else if (token == "angle") {
1107 angle = lex.GetFloat();
1108 } else if (token == "size") {
1110 wid = lex.GetInteger();
1112 hgh = lex.GetInteger();
1113 } else if (token == "flags") {
1115 flags = pflags = lex.GetInteger();
1116 } else if (token == "subfigure") {
1117 subfigure = psubfigure = true;
1118 } else if (token == "width") {
1121 typ = lex.GetInteger();
1123 xwid = lex.GetFloat();
1125 case DEF: wtype = DEF; break;
1126 case CM: wtype = CM; break;
1127 case IN: wtype = IN; break;
1128 case PER_PAGE: wtype = PER_PAGE; break;
1129 case PER_COL: wtype = PER_COL; break;
1131 lyxerr.debug() << "Unknown type!" << endl;
1135 } else if (token == "height") {
1138 typ = lex.GetInteger();
1140 xhgh = lex.GetFloat();
1142 case DEF: htype = DEF; break;
1143 case CM: htype = CM; break;
1144 case IN: htype = IN; break;
1145 case PER_PAGE: htype = PER_PAGE; break;
1147 lyxerr.debug() << "Unknown type!" << endl;
1158 int InsetFig::Latex(Buffer const *, ostream & os,
1159 bool /* fragile*/, bool /* fs*/) const
1162 if (!cmd.empty()) os << cmd << " ";
1167 int InsetFig::Ascii(Buffer const *, ostream &, int) const
1173 int InsetFig::Linuxdoc(Buffer const *, ostream &) const
1179 int InsetFig::DocBook(Buffer const *, ostream & os) const
1181 string buf1 = OnlyPath(owner->fileName());
1182 string figurename = MakeRelPath(fname, buf1);
1184 if (suffixIs(figurename, ".eps"))
1185 figurename.erase(figurename.length() - 4);
1187 os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
1192 void InsetFig::Validate(LaTeXFeatures & features) const
1194 features.graphics = true;
1195 if (subfigure) features.subfigure = true;
1199 Inset::EDITABLE InsetFig::Editable() const
1205 bool InsetFig::Deletable() const
1211 string const InsetFig::EditMessage() const
1213 return _("Opened figure");
1217 void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
1219 lyxerr.debug() << "Editing InsetFig." << endl;
1222 // We should have RO-versions of the form instead.
1223 // The actual prevention of altering a readonly doc
1224 // is done in CallbackFig()
1225 if (bv->buffer()->isReadonly())
1226 WarnReadonly(bv->buffer()->fileName());
1229 form = create_form_Figure();
1230 fl_set_form_atclose(form->Figure, CancelCloseBoxCB, 0);
1231 fl_set_object_return(form->Angle, FL_RETURN_ALWAYS);
1232 fl_set_object_return(form->Width, FL_RETURN_ALWAYS);
1233 fl_set_object_return(form->Height, FL_RETURN_ALWAYS);
1236 if (form->Figure->visible) {
1237 fl_raise_form(form->Figure);
1239 fl_show_form(form->Figure,
1240 FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
1246 Inset * InsetFig::Clone(Buffer const & buffer) const
1248 InsetFig * tmp = new InsetFig(100, 100, buffer);
1250 if (lyxerr.debugging()) {
1251 lyxerr << "Clone Figure: buffer:["
1253 << "], cbuffer:[xx]" << endl;
1258 tmp->raw_wid = raw_wid;
1259 tmp->raw_hgh = raw_hgh;
1264 tmp->pflags = pflags;
1265 tmp->subfigure = subfigure;
1266 tmp->psubfigure = psubfigure;
1274 if (!fname.empty() && IsFileReadable(fname)
1275 && (flags & 3) && !lyxrc.ps_command.empty()
1277 // do not display if there is
1278 // "do not display" chosen (Matthias 260696)
1279 tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
1280 pswid, pshgh, raw_wid, raw_hgh,
1281 angle, flags & (3|8));
1282 } else tmp->figure->data = 0;
1283 tmp->subcaption = subcaption;
1284 tmp->changedfname = false;
1291 Inset::Code InsetFig::LyxCode() const
1293 return Inset::GRAPHICS_CODE;
1298 string stringify(InsetFig::HWTYPE hw, float f, string suffix)
1304 case InsetFig::CM:// \resizebox*{h-length}{v-length}{text}
1305 res = tostr(f) + "cm";
1308 res = tostr(f) + "in";
1310 case InsetFig::PER_PAGE:
1311 res = tostr(f/100) + "\\text" + suffix;
1313 case InsetFig::PER_COL:
1314 // Doesn't occur for htype...
1315 res = tostr(f/100) + "\\column" + suffix;
1322 void InsetFig::Regenerate() const
1325 string resizeW, resizeH;
1326 string rotate, recmd;
1328 if (fname.empty()) {
1329 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1330 cmd += _("empty figure path");
1335 string buf1 = OnlyPath(owner->fileName());
1336 string fname2 = MakeRelPath(fname, buf1);
1338 string gcmd = "\\includegraphics{" + fname2 + '}';
1339 resizeW = stringify(wtype, xwid, "width");
1340 resizeH = stringify(htype, xhgh, "height");
1342 if (!resizeW.empty() || !resizeH.empty()) {
1343 recmd = "\\resizebox*{";
1344 if (!resizeW.empty())
1349 if (!resizeH.empty())
1358 // \rotatebox{angle}{text}
1359 rotate = "\\rotatebox{" + tostr(angle) + "}{";
1365 if (!rotate.empty()) cmdbuf += '}';
1366 if (!recmd.empty()) cmdbuf += '}';
1368 if (!subcaption.empty())
1369 cmdbuf = "\\subfigure[" + subcaption +
1370 "]{" + cmdbuf + "}";
1372 cmdbuf = "\\subfigure{" + cmdbuf + "}";
1379 void InsetFig::TempRegenerate()
1382 string resizeW, resizeH;
1383 string rotate, recmd;
1385 char const * tfname = fl_get_input(form->EpsFile);
1386 string tsubcap = fl_get_input(form->Subcaption);
1387 float tangle = atof(fl_get_input(form->Angle));
1388 float txwid = atof(fl_get_input(form->Width));
1389 float txhgh = atof(fl_get_input(form->Height));
1391 if (!tfname || !*tfname) {
1392 cmd = "\\fbox{\\rule[-0.5in]{0pt}{1in}";
1393 cmd += _("empty figure path");
1398 string buf1 = OnlyPath(owner->fileName());
1399 string fname2 = MakeRelPath(tfname, buf1);
1400 // \includegraphics*[<llx,lly>][<urx,ury>]{file}
1401 string gcmd = "\\includegraphics{" + fname2 + '}';
1403 resizeW = stringify(twtype, txwid, "width");
1404 resizeH = stringify(thtype, txhgh, "height");
1406 // \resizebox*{h-length}{v-length}{text}
1407 if (!resizeW.empty() || !resizeH.empty()) {
1408 recmd = "\\resizebox*{";
1409 if (!resizeW.empty())
1414 if (!resizeH.empty())
1422 // \rotatebox{angle}{text}
1423 rotate = "\\rotatebox{" + tostr(tangle) + "}{";
1426 cmdbuf = recmd + rotate + gcmd;
1427 if (!rotate.empty()) cmdbuf += '}';
1428 if (!recmd.empty()) cmdbuf += '}';
1429 if (psubfigure && !tsubcap.empty()) {
1430 cmdbuf = string("\\subfigure{") + tsubcap
1431 + string("}{") + cmdbuf + "}";
1436 void InsetFig::Recompute()
1441 bool changed = changedfname;
1442 int newx, newy, nraw_x, nraw_y;
1444 if (changed) GetPSSizes();
1446 float sin_a = sin (angle / DEG2PI); /* rotation; H. Zeller 021296 */
1447 float cos_a = cos (angle / DEG2PI);
1448 int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
1449 int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
1451 string lfname = fname;
1452 if (GetExtension(fname).empty())
1455 /* now recompute wid and hgh, and if that is changed, set changed */
1456 /* this depends on chosen size of the picture and its bbox */
1457 // This will be redone in 0.13 ... (hen)
1458 if (!lfname.empty() && IsFileReadable(lfname)) {
1459 // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
1467 newx = int(28.346 * xwid);
1470 newx = int(72 * xwid);
1472 case PER_PAGE: /* % of page */
1473 newx = int(5.95 * xwid);
1475 case PER_COL: /* % of col */
1476 newx = int(2.975 * xwid);
1480 if (wtype && frame_wid) newy = newx*frame_hgh/frame_wid;
1484 //lyxerr << "This should not happen!" << endl;
1487 newy = int(28.346 * xhgh);
1490 newy = int(72 * xhgh);
1492 case PER_PAGE: /* % of page */
1493 newy = int(8.42 * xhgh);
1496 // Doesn't occur; case exists to suppress
1497 // compiler warnings.
1500 if (htype && !wtype && frame_hgh)
1501 newx = newy*frame_wid/frame_hgh;
1510 nraw_x = int((1.0 * pswid * newx)/frame_wid);
1515 nraw_y = int((1.0 * pshgh * newy)/frame_hgh);
1517 // cannot be zero, actually, set it to some minimum, so its clickable
1518 if (newx < 5) newx = 5;
1519 if (newy < 5) newy = 5;
1521 if (newx != wid || newy != hgh ||
1522 nraw_x != raw_wid || nraw_y != raw_hgh ||
1523 flags != pflags || subfigure != psubfigure)
1531 subfigure = psubfigure;
1534 figdata * pf = figure->data;
1537 if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
1538 && !lyxrc.ps_command.empty()) {
1539 // do not display if there is "do not display"
1540 // chosen (Matthias 260696)
1541 figure->data = getfigdata(wid, hgh, lfname,
1542 psx, psy, pswid, pshgh,
1544 angle, flags & (3|8));
1545 } else figure->data = 0;
1547 // free the old data
1548 if (pf) freefigdata(pf);
1551 changedfname = false;
1555 void InsetFig::GetPSSizes()
1557 /* get %%BoundingBox: from postscript file */
1559 /* defaults to associated size
1560 * ..just in case the PS-file is not readable (Henner, 24-Aug-97)
1567 if (fname.empty()) return;
1569 ifstream ifs(fname.c_str());
1571 if (!ifs) return; // file not found !!!!
1573 /* defaults to A4 page */
1579 char lastchar = 0; ifs.get(lastchar);
1581 char c = 0; ifs.get(c);
1583 lyxerr.debug() << "End of (E)PS file reached and"
1584 " no BoundingBox!" << endl;
1587 if (c == '%' && lastchar == '%') {
1589 if (p.empty()) break;
1590 lyxerr.debug() << "Token: `" << p << "'" << endl;
1591 if (p == "BoundingBox:") {
1592 float fpsx, fpsy, fpswid, fpshgh;
1593 if (ifs >> fpsx >> fpsy >> fpswid >> fpshgh) {
1596 pswid = int(fpswid);
1597 pshgh = int(fpshgh);
1599 if (lyxerr.debugging()) {
1600 lyxerr << "%%%%BoundingBox:"
1618 void InsetFig::CallbackFig(long arg)
1623 if (lyxerr.debugging()) {
1624 lyxerr << "Figure callback, arg " << arg << endl;
1630 case 12: /* width type */
1637 fl_deactivate_object(form->Width);
1642 fl_activate_object(form->Width);
1647 fl_activate_object(form->Width);
1652 fl_activate_object(form->Width);
1657 fl_activate_object(form->Width);
1660 lyxerr.debug() << "Unknown type!" << endl;
1667 case 22: /* height type */
1673 fl_deactivate_object(form->Height);
1678 fl_activate_object(form->Height);
1683 fl_activate_object(form->Height);
1688 fl_activate_object(form->Height);
1691 lyxerr.debug() << "Unknown type!" << endl;
1697 pflags = pflags & ~3; /* wysiwyg0 */
1700 pflags = (pflags & ~3) | 1; /* wysiwyg1 */
1703 pflags = (pflags & ~3) | 2; /* wysiwyg2 */
1706 pflags = (pflags & ~3) | 3; /* wysiwyg3 */
1709 pflags ^= 4; /* frame */
1712 pflags ^= 8; /* do translations */
1715 psubfigure = !psubfigure; /* This is a subfigure */
1718 regen = true; /* regenerate command */
1720 case 0: /* browse file */
1724 case 1: /* preview */
1725 p = fl_get_input(form->EpsFile);
1729 case 8: /* ok (apply and close) */
1730 if (!current_view->buffer()->isReadonly()) {
1733 xwid = atof(fl_get_input(form->Width));
1734 xhgh = atof(fl_get_input(form->Height));
1735 angle = atof(fl_get_input(form->Angle));
1736 p = fl_get_input(form->EpsFile);
1738 string buf1 = OnlyPath(owner->fileName());
1739 fname = MakeAbsPath(p, buf1);
1740 changedfname = true;
1742 if (!fname.empty()) {
1743 changedfname = true;
1747 subcaption = fl_get_input(form->Subcaption);
1751 /* now update inset */
1752 if (lyxerr.debugging()) {
1753 lyxerr << "Update: ["
1754 << wid << 'x' << hgh << ']' << endl;
1756 current_view->updateInset(this, true);
1758 fl_set_focus_object(form->Figure, form->OkBtn);
1759 fl_hide_form(form->Figure);
1760 #if FL_REVISION == 89
1761 // CHECK Reactivate this free_form calls
1763 fl_free_form(form->Figure);
1764 free(form); // Why free?
1770 // The user has already been informed about RO in ::Edit
1771 if (arg == 7) // if 'Apply'
1774 case 9: /* cancel = restore and close */
1775 fl_set_focus_object(form->Figure, form->OkBtn);
1776 fl_hide_form(form->Figure);
1777 #if FL_REVISION == 89
1778 // CHECK Reactivate this free_form calls
1779 // Jug, is this still a problem?
1781 fl_free_form(form->Figure);
1782 free(form); // Why free?
1788 if (regen) TempRegenerate();
1793 void DisableFigurePanel(FD_Figure * const form)
1795 fl_deactivate_object(form->EpsFile);
1796 fl_deactivate_object(form->Browse);
1797 fl_deactivate_object(form->Width);
1798 fl_deactivate_object(form->Height);
1799 fl_deactivate_object(form->Frame);
1800 fl_deactivate_object(form->Translations);
1801 fl_deactivate_object(form->Angle);
1802 fl_deactivate_object(form->HeightGrp);
1803 fl_deactivate_object(form->page2);
1804 fl_deactivate_object(form->Default2);
1805 fl_deactivate_object(form->cm2);
1806 fl_deactivate_object(form->in2);
1807 fl_deactivate_object(form->HeightLabel);
1808 fl_deactivate_object(form->WidthLabel);
1809 fl_deactivate_object(form->DisplayGrp);
1810 fl_deactivate_object(form->Wysiwyg3);
1811 fl_deactivate_object(form->Wysiwyg0);
1812 fl_deactivate_object(form->Wysiwyg2);
1813 fl_deactivate_object(form->Wysiwyg1);
1814 fl_deactivate_object(form->WidthGrp);
1815 fl_deactivate_object(form->Default1);
1816 fl_deactivate_object(form->cm1);
1817 fl_deactivate_object(form->in1);
1818 fl_deactivate_object(form->page1);
1819 fl_deactivate_object(form->column1);
1820 fl_deactivate_object(form->Subcaption);
1821 fl_deactivate_object(form->Subfigure);
1822 fl_deactivate_object (form->OkBtn);
1823 fl_deactivate_object (form->ApplyBtn);
1824 fl_set_object_lcol (form->OkBtn, FL_INACTIVE);
1825 fl_set_object_lcol (form->ApplyBtn, FL_INACTIVE);
1830 void EnableFigurePanel(FD_Figure * const form)
1832 fl_activate_object(form->EpsFile);
1833 fl_activate_object(form->Browse);
1834 fl_activate_object(form->Width);
1835 fl_activate_object(form->Height);
1836 fl_activate_object(form->Frame);
1837 fl_activate_object(form->Translations);
1838 fl_activate_object(form->Angle);
1839 fl_activate_object(form->HeightGrp);
1840 fl_activate_object(form->page2);
1841 fl_activate_object(form->Default2);
1842 fl_activate_object(form->cm2);
1843 fl_activate_object(form->in2);
1844 fl_activate_object(form->HeightLabel);
1845 fl_activate_object(form->WidthLabel);
1846 fl_activate_object(form->DisplayGrp);
1847 fl_activate_object(form->Wysiwyg3);
1848 fl_activate_object(form->Wysiwyg0);
1849 fl_activate_object(form->Wysiwyg2);
1850 fl_activate_object(form->Wysiwyg1);
1851 fl_activate_object(form->WidthGrp);
1852 fl_activate_object(form->Default1);
1853 fl_activate_object(form->cm1);
1854 fl_activate_object(form->in1);
1855 fl_activate_object(form->page1);
1856 fl_activate_object(form->column1);
1857 fl_activate_object(form->Subcaption);
1858 fl_activate_object(form->Subfigure);
1859 fl_activate_object (form->OkBtn);
1860 fl_activate_object (form->ApplyBtn);
1861 fl_set_object_lcol (form->OkBtn, FL_BLACK);
1862 fl_set_object_lcol (form->ApplyBtn, FL_BLACK);
1866 void InsetFig::RestoreForm()
1868 EnableFigurePanel(form);
1871 fl_set_button(form->Default1, (wtype == 0));
1872 fl_set_button(form->cm1, (wtype == 1));
1873 fl_set_button(form->in1, (wtype == 2));
1874 fl_set_button(form->page1, (wtype == 3));
1875 fl_set_button(form->column1, (wtype == 4));
1877 fl_deactivate_object(form->Width);
1879 fl_activate_object(form->Width);
1882 // enable and disable should be put here.
1884 fl_set_button(form->Default2, (htype == 0));
1885 fl_set_button(form->cm2, (htype == 1));
1886 fl_set_button(form->in2, (htype == 2));
1887 fl_set_button(form->page2, (htype == 3));
1888 // enable and disable should be put here.
1890 fl_deactivate_object(form->Height);
1892 fl_activate_object(form->Height);
1895 int piflags = flags & 3;
1896 fl_set_button(form->Wysiwyg0, (piflags == 0));
1897 fl_set_button(form->Wysiwyg1, (piflags == 1));
1898 fl_set_button(form->Wysiwyg2, (piflags == 2));
1899 fl_set_button(form->Wysiwyg3, (piflags == 3));
1900 fl_set_button(form->Frame, ((flags & 4) != 0));
1901 fl_set_button(form->Translations, ((flags & 8) != 0));
1902 fl_set_button(form->Subfigure, (subfigure != 0));
1904 psubfigure = subfigure;
1905 fl_set_input(form->Width, tostr(xwid).c_str());
1906 fl_set_input(form->Height, tostr(xhgh).c_str());
1907 fl_set_input(form->Angle, tostr(angle).c_str());
1908 if (!fname.empty()){
1909 string buf1 = OnlyPath(owner->fileName());
1910 string fname2 = MakeRelPath(fname, buf1);
1911 fl_set_input(form->EpsFile, fname2.c_str());
1913 else fl_set_input(form->EpsFile, "");
1914 fl_set_input(form->Subcaption, subcaption.c_str());
1915 if (current_view->buffer()->isReadonly())
1916 DisableFigurePanel(form);
1922 void InsetFig::Preview(string const & p)
1925 if (GetExtension(tfname).empty())
1927 string buf1 = OnlyPath(owner->fileName());
1928 string buf2 = MakeAbsPath(tfname, buf1);
1929 if (!formats.View(owner, buf2, "eps"))
1930 lyxerr << "Can't view " << buf2 << endl;
1933 void InsetFig::BrowseFile()
1935 static string current_figure_path;
1936 static int once = 0;
1938 if (lyxerr.debugging()) {
1939 lyxerr << "Filename: "
1940 << owner->fileName() << endl;
1942 string p = fl_get_input(form->EpsFile);
1944 string buf = MakeAbsPath(owner->fileName());
1945 string buf2 = OnlyPath(buf);
1947 buf = MakeAbsPath(p, buf2);
1948 buf = OnlyPath(buf);
1950 buf = OnlyPath(owner->fileName());
1953 // Does user clipart directory exist?
1954 string bufclip = AddName (user_lyxdir, "clipart");
1955 FileInfo fileInfo(bufclip);
1956 if (!(fileInfo.isOK() && fileInfo.isDir()))
1957 // No - bail out to system clipart directory
1958 bufclip = AddName (system_lyxdir, "clipart");
1961 FileDialog fileDlg(current_view->owner(), _("Select an EPS figure"),
1962 LFUN_SELECT_FILE_SYNC,
1963 make_pair(string(_("Clip art")), string(bufclip)),
1964 make_pair(string(_("Documents")), string(buf)));
1968 string const path = (once) ? current_figure_path : buf;
1970 FileDialog::Result result = fileDlg.Select(path, _("*ps| PostScript documents"));
1972 string const p = result.second;
1977 buf = MakeRelPath(p, buf2);
1978 current_figure_path = OnlyPath(p);
1981 if (contains(p, "#") || contains(p, "~") || contains(p, "$")
1982 || contains(p, "%") || contains(p, " ")) {
1983 WriteAlert(_("Filename can't contain any "
1984 "of these characters:"),
1985 // xgettext:no-c-format
1986 _("space, '#', '~', '$' or '%'."));
1991 if (form) fl_set_input(form->EpsFile, buf.c_str());
1995 void GraphicsCB(FL_OBJECT * obj, long arg)
1997 /* obj->form contains the form */
1999 if (lyxerr.debugging()) {
2000 lyxerr << "GraphicsCB callback: " << arg << endl;
2003 /* find inset we were reacting to */
2004 for (figures_type::iterator it = figures.begin();
2005 it != figures.end(); ++it)
2006 if ((*it)->inset->form && (*it)->inset->form->Figure
2008 if (lyxerr.debugging()) {
2009 lyxerr << "Calling back figure "
2012 (*it)->inset->CallbackFig(arg);
2018 void HideFiguresPopups()
2020 for (figures_type::iterator it = figures.begin();
2021 it != figures.end(); ++it)
2022 if ((*it)->inset->form
2023 && (*it)->inset->form->Figure->visible) {
2024 if (lyxerr.debugging()) {
2025 lyxerr << "Hiding figure " << (*it) << endl;
2027 // hide and free the form
2028 (*it)->inset->CallbackFig(9);