]> git.lyx.org Git - lyx.git/blobdiff - src/insets/figinset.C
reformatting and remove using delc
[lyx.git] / src / insets / figinset.C
index 1b66a0fc15ba836a7f2636a837b6f22dbd3d6581..d80165688c7c6cfe32821a65b88c70f0dac623b1 100644 (file)
@@ -33,6 +33,7 @@
 #include <list>
 #include <algorithm>
 #include <vector>
+#include <utility>
 
 #include <unistd.h>
 #include <csignal>
 #include <cmath>
 
 #include "figinset.h"
-#include "lyx.h"
 #include "lyx_main.h"
 #include "buffer.h"
-#include "filedlg.h"
+#include "frontends/FileDialog.h"
 #include "support/filetools.h"
 #include "LyXView.h" // just because of form_main
 #include "debug.h"
@@ -61,6 +61,8 @@
 #include "font.h"
 #include "bufferview_funcs.h"
 #include "ColorHandler.h"
+#include "converter.h"
+#include "frontends/Dialogs.h" // redrawGUI
 
 using std::ostream;
 using std::istream;
@@ -72,16 +74,23 @@ using std::vector;
 using std::find;
 using std::flush;
 using std::endl;
-#ifdef HAVE_SSTREAM
 using std::ostringstream;
-#endif
+using std::copy;
+using std::pair;
+using std::make_pair;
 
 extern BufferView * current_view;
 extern FL_OBJECT * figinset_canvas;
 
 extern char ** environ; // is this only redundtant on linux systems? Lgb.
 
-static float const DEG2PI = 57.295779513;
+// xforms doesn't define this (but it should be in <forms.h>).
+extern "C"
+FL_APPEVENT_CB fl_set_preemptive_callback(Window, FL_APPEVENT_CB, void *);
+
+namespace {
+
+float const DEG2PI = 57.295779513;
 
 struct queue_element {
        float rx, ry;          // resolution x and y
@@ -89,51 +98,45 @@ struct queue_element {
        figdata * data;        // we are doing it for this data
 };
 
-static int const MAXGS = 3;                    /* maximum 3 gs's at a time */
+int const MAXGS = 3;                   /* maximum 3 gs's at a time */
 
 typedef vector<Figref *> figures_type;
 typedef vector<figdata *> bitmaps_type;
-static figures_type figures; // all figures
-static bitmaps_type bitmaps; // all bitmaps
+figures_type figures; // all figures
+bitmaps_type bitmaps; // all bitmaps
 
-static queue<queue_element> gsqueue; // queue for ghostscripting
+queue<queue_element> gsqueue; // queue for ghostscripting
 
-static int gsrunning = 0;      /* currently so many gs's are running */
-static bool bitmap_waiting = false; /* bitmaps are waiting finished */
-static char bittable[256];     /* bit reversion table */
+int gsrunning = 0;     /* currently so many gs's are running */
+bool bitmap_waiting = false; /* bitmaps are waiting finished */
 
-static bool gs_color;                  // do we allocate colors for gs?
-static bool color_visual;              // is the visual color?
-static bool gs_xcolor = false;         // allocated extended colors
-static unsigned long gs_pixels[128];   // allocated pixels
-static int gs_num_pixels;              // number of pixels allocated
-static int gs_spc;                     // shades per color
-static bool gs_gray;                   // is grayscale?
-static int gs_allcolors;               // number of all colors
+bool gs_color;                 // do we allocate colors for gs?
+bool color_visual;                     // is the visual color?
+bool gs_xcolor = false;                // allocated extended colors
+unsigned long gs_pixels[128];  // allocated pixels
+int gs_spc;                    // shades per color
+int gs_allcolors;              // number of all colors
 
-static list<int> pidwaitlist; // pid wait list
+list<int> pidwaitlist; // pid wait list
 
-static
 GC createGC()
 {
        XGCValues val;
-       val.foreground = BlackPixel(fl_display
-                                   DefaultScreen(fl_display));
+       val.foreground = BlackPixel(fl_get_display()
+                                   DefaultScreen(fl_get_display()));
        
        val.function=GXcopy;
        val.graphics_exposures = false;
        val.line_style = LineSolid;
        val.line_width = 0;
-       return XCreateGC(fl_display, RootWindow(fl_display, 0), 
+       return XCreateGC(fl_get_display(), RootWindow(fl_get_display(), 0), 
                         GCForeground | GCFunction | GCGraphicsExposures
                         | GCLineWidth | GCLineStyle , &val);
 }
 
-static
 GC local_gc_copy;
 
 
-static
 void addpidwait(int pid)
 {
        // adds pid to pid wait list
@@ -141,39 +144,38 @@ void addpidwait(int pid)
 
        if (lyxerr.debugging()) {
                lyxerr << "Pids to wait for: \n";
-               for (list<int>::const_iterator cit = pidwaitlist.begin();
-                    cit != pidwaitlist.end(); ++cit) {
-                       lyxerr << (*cit) << '\n';
-               }
+               copy(pidwaitlist.begin(), pidwaitlist.end(),
+                    std::ostream_iterator<int>(lyxerr, "\n"));
                lyxerr << flush;
        }
 }
 
 
-static
 string make_tmp(int pid)
 {
        return system_tempdir + "/~lyxgs" + tostr(pid) + ".ps";
 }
 
 
-static
 void kill_gs(int pid, int sig)
 {
        if (lyxerr.debugging()) 
                lyxerr << "Killing gs " << pid << endl;
        lyx::kill(pid, sig);
-       unlink(make_tmp(pid).c_str());
+       lyx::unlink(make_tmp(pid));
 }
 
 
-extern "C" // static
-int GhostscriptMsg(FL_OBJECT *, Window, int, int,
-                  XEvent * ev, void *)
+extern "C"
+int GhostscriptMsg(XEvent * ev, void *)
 {
+       // bin all events not of interest
+       if (ev->type != ClientMessage)
+               return FL_PREEMPT;
+
        XClientMessageEvent * e = reinterpret_cast<XClientMessageEvent*>(ev);
 
-       if(lyxerr.debugging()) {
+       if (lyxerr.debugging()) {
                lyxerr << "ClientMessage, win:[xx] gs:[" << e->data.l[0]
                       << "] pm:[" << e->data.l[1] << "]" << endl;
        }
@@ -197,7 +199,6 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                                register XImage * im;
                                int i;
                                int y;
-                               int wid1;
                                int spc1 = gs_spc - 1;
                                int spc2 = gs_spc * gs_spc;
                                int wid = p->wid;
@@ -205,11 +206,11 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                                Display * tmpdisp;
                                GC gc = local_gc_copy;
 
-                               XGetWindowAttributes(fl_display,
+                               XGetWindowAttributes(fl_get_display(),
                                                     fl_get_canvas_id(
                                                             figinset_canvas),
                                                     &wa);
-                               XFlush(fl_display);
+                               XFlush(fl_get_display());
                                if (lyxerr.debugging()) {
                                        lyxerr << "Starting image translation "
                                               << p->bitmap << " "
@@ -224,7 +225,7 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                                        lyxerr.debug()
                                                << "Cannot fork, using slow "
                                                "method for pixmap translation." << endl;
-                                       tmpdisp = fl_display;
+                                       tmpdisp = fl_get_display();
                                } else if (forkstat > 0) { // parent
                                        // register child
                                        if (lyxerr.debugging()) {
@@ -234,7 +235,7 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                                        addpidwait(forkstat);
                                        break;
                                } else {  // child
-                                       tmpdisp = XOpenDisplay(XDisplayName(0));
+                                       tmpdisp = XOpenDisplay(DisplayString(fl_get_display()));
                                        XFlush(tmpdisp);
                                }
                                im = XGetImage(tmpdisp, p->bitmap, 0, 0,
@@ -258,7 +259,6 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                                                     .colormap, cmap,
                                                     gs_allcolors);
                                        XFlush(tmpdisp);
-                                       wid1 = p->wid - 1;
                                // now we process all the image
                                        for (y = 0; y < p->hgh; ++y) {
                                                for (int x = 0; x < wid; ++x) {
@@ -299,11 +299,10 @@ int GhostscriptMsg(FL_OBJECT *, Window, int, int,
                        }
                        break;
                }
-       return 0;
+       return FL_PREEMPT;
 }
 
 
-static
 void AllocColors(int num)
 // allocate color cube numxnumxnum, if possible
 {
@@ -320,16 +319,16 @@ void AllocColors(int num)
        if (num > 5) num = 5;
        XColor xcol;
        for (int i = 0; i < num * num * num; ++i) {
-               xcol.red = 65535 * (i / (num * num)) / (num - 1);
-               xcol.green = 65535 * ((i / num) % num) / (num - 1);
-               xcol.blue = 65535 * (i % num) / (num - 1);
+               xcol.red = short(65535 * (i / (num * num)) / (num - 1));
+               xcol.green = short(65535 * ((i / num) % num) / (num - 1));
+               xcol.blue = short(65535 * (i % num) / (num - 1));
                xcol.flags = DoRed | DoGreen | DoBlue;
-               if (!XAllocColor(fl_display,
+               if (!XAllocColor(fl_get_display(),
                                 fl_state[fl_get_vclass()].colormap, &xcol)) {
-                       if (i) XFreeColors(fl_display,
+                       if (i) XFreeColors(fl_get_display(),
                                           fl_state[fl_get_vclass()].colormap,
                                           gs_pixels, i, 0);
-                       if(lyxerr.debugging()) {
+                       if (lyxerr.debugging()) {
                                lyxerr << "Cannot allocate color cube "
                                       << num << endl;;
                        }
@@ -339,14 +338,11 @@ void AllocColors(int num)
                gs_pixels[i] = xcol.pixel;
        }
        gs_color = true;
-       gs_gray = false;
        gs_spc = num;
-       gs_num_pixels = num * num * num;
 }
 
 
 // allocate grayscale ramp
-static
 void AllocGrays(int num)
 {
        if (lyxerr.debugging()) {
@@ -362,11 +358,11 @@ void AllocGrays(int num)
        if (num > 128) num = 128;
        XColor xcol;
        for (int i = 0; i < num; ++i) {
-               xcol.red = xcol.green = xcol.blue = 65535 * i / (num - 1);
+               xcol.red = xcol.green = xcol.blue = short(65535 * i / (num - 1));
                xcol.flags = DoRed | DoGreen | DoBlue;
-               if (!XAllocColor(fl_display,
+               if (!XAllocColor(fl_get_display(),
                                 fl_state[fl_get_vclass()].colormap, &xcol)) {
-                       if (i) XFreeColors(fl_display,
+                       if (i) XFreeColors(fl_get_display(),
                                           fl_state[fl_get_vclass()].colormap,
                                           gs_pixels, i, 0);
                        if (lyxerr.debugging()) {
@@ -379,38 +375,27 @@ void AllocGrays(int num)
                gs_pixels[i] = xcol.pixel;
        }
        gs_color = true;
-       gs_gray = false;
-       gs_num_pixels = num;
 }
 
-
-static
 void InitFigures()
 {
        // if bitmaps and figures are not empty we will leak mem
        figures.clear();
        bitmaps.clear();
 
-       unsigned int k;
-       for (unsigned int i = 0; i < 256; ++i) {
-               k = 0;
-               for (unsigned int j = 0; j < 8; ++j)
-                       if (i & (1 << (7-j))) k |= 1 << j;
-               bittable[i] = char(~k);
-       }
-
        // allocate color cube on pseudo-color display
        // first get visual
        gs_color = false;
        if (lyxrc.use_gui) {
-               fl_add_canvas_handler(figinset_canvas, ClientMessage,
-                                     GhostscriptMsg,
-                                     current_view->owner()->getMainForm());
+               /* we want to capture every event, in order to work around an
+                * xforms bug.
+                */
+               fl_set_preemptive_callback(fl_get_canvas_id(figinset_canvas), GhostscriptMsg, 0);
 
                local_gc_copy = createGC();
 
-               Visual * vi = DefaultVisual(fl_display,
-                                           DefaultScreen(fl_display));
+               Visual * vi = DefaultVisual(fl_get_display(),
+                                           DefaultScreen(fl_get_display()));
                if (lyxerr.debugging()) {
                        printf("Visual ID: %ld, class: %d, bprgb: %d, mapsz: %d\n", 
                               vi->visualid, vi->c_class, 
@@ -436,7 +421,6 @@ void InitFigures()
 }
 
 
-static
 void DoneFigures()
 {
        // if bitmaps and figures are not empty we will leak mem
@@ -444,13 +428,9 @@ void DoneFigures()
        figures.clear();
        
        lyxerr.debug() << "Unregistering figures..." << endl;
-
-       fl_remove_canvas_handler(figinset_canvas, ClientMessage,
-                                GhostscriptMsg);
 }
 
 
-static
 void freefigdata(figdata * tmpdata)
 {
        tmpdata->ref--;
@@ -463,13 +443,12 @@ void freefigdata(figdata * tmpdata)
                kill_gs(pid, SIGKILL);
        }
 
-       if (tmpdata->bitmap) XFreePixmap(fl_display, tmpdata->bitmap);
+       if (tmpdata->bitmap) XFreePixmap(fl_get_display(), tmpdata->bitmap);
        bitmaps.erase(find(bitmaps.begin(), bitmaps.end(), tmpdata));
        delete tmpdata;
 }
 
 
-static
 void runqueue()
 {
        // This _have_ to be set before the fork!
@@ -517,7 +496,7 @@ void runqueue()
                if (pid == 0) { // child
                        char ** env;
                        int ne = 0;
-                       Display * tempdisp = XOpenDisplay(XDisplayName(0));
+                       Display * tempdisp = XOpenDisplay(DisplayString(fl_get_display()));
 
                        // create translation file
                        ofstream ofs;
@@ -538,31 +517,15 @@ void runqueue()
                        ofs.close(); // Don't remove this.
 
                        // gs process - set ghostview environment first
-#ifdef HAVE_SSTREAM
                        ostringstream t2;
-#else
-                       char tbuf2[80];
-                       ostrstream t2(tbuf2, sizeof(tbuf2));
-#endif
                        t2 << "GHOSTVIEW=" << fl_get_canvas_id(figinset_canvas)
                           << ' ' << p->data->bitmap;
-#ifndef HAVE_SSTREAM
-                       t2 << '\0';
-#endif
                        // now set up ghostview property on a window
                        // #warning BUG seems that the only bug here
                        // might be the hardcoded dpi.. Bummer!
-#ifdef HAVE_SSTREAM
                        ostringstream t1;
-#else
-                       char tbuf[384];
-                       ostrstream t1(tbuf, sizeof(tbuf));
-#endif
                        t1 << "0 0 0 0 " << p->data->wid << ' '
                           << p->data->hgh << " 72 72 0 0 0 0";
-#ifndef HAVE_SSTREAM
-                       t1 << '\0';
-#endif
                        
                        if (lyxerr.debugging()) {
                                lyxerr << "Will set GHOSTVIEW property to ["
@@ -590,8 +553,10 @@ void runqueue()
                                for (i = 0; i < nprop; ++i) {
                                        char * p = XGetAtomName(tempdisp,
                                                                prop[i]);
-                                       if (strcmp(p, "GHOSTVIEW") == 0) {
+                                       if (compare(p, "GHOSTVIEW") == 0) {
                                                err = false;
+                                               // We free it when we leave so we don't leak.
+                                               XFree(p);
                                                break;
                                        }
                                        XFree(p);
@@ -611,33 +576,18 @@ void runqueue()
                                ::sleep(1);
                                XGrabServer(tempdisp);
                        }
-#ifdef HAVE_SSTREAM
                        XChangeProperty(tempdisp, 
                                        fl_get_canvas_id(figinset_canvas),
                                        XInternAtom(tempdisp, "GHOSTVIEW", false),
                                        XInternAtom(tempdisp, "STRING", false),
                                        8, PropModeAppend, 
                                        reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str().c_str())),
-                                       t1.str().size());
-#else
-                       
-                       XChangeProperty(tempdisp, 
-                                       fl_get_canvas_id(figinset_canvas),
-                                       XInternAtom(tempdisp, "GHOSTVIEW", false),
-                                       XInternAtom(tempdisp, "STRING", false),
-                                       8, PropModeAppend, 
-                                       reinterpret_cast<unsigned char*>(const_cast<char*>(t1.str())),
-                                       ::strlen(t1.str()));
-#endif
+                                       int(t1.str().size()));
                        XUngrabServer(tempdisp);
                        XFlush(tempdisp);
 
-#ifdef HAVE_SSTREAM
                        ostringstream t3;
-#else
-                       //char tbuf[384];
-                       ostrstream t3(tbuf, sizeof(tbuf));
-#endif
+
                        switch (p->data->flags & 3) {
                        case 0: t3 << 'H'; break; // Hidden
                        case 1: t3 << 'M'; break; // Mono
@@ -652,12 +602,8 @@ void runqueue()
        
                        t3 << ' ' << BlackPixelOfScreen(DefaultScreenOfDisplay(tempdisp))
                           << ' ' << background_pixel;
-#ifndef HAVE_SSTREAM
-                       t3 << '\0';
-#endif
 
                        XGrabServer(tempdisp);
-#ifdef HAVE_SSTREAM
                        XChangeProperty(tempdisp, 
                                        fl_get_canvas_id(figinset_canvas),
                                        XInternAtom(tempdisp,
@@ -665,17 +611,7 @@ void runqueue()
                                        XInternAtom(tempdisp, "STRING", false),
                                        8, PropModeReplace, 
                                        reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str().c_str())),
-                                       t3.str().size());
-#else
-                       XChangeProperty(tempdisp, 
-                                       fl_get_canvas_id(figinset_canvas),
-                                       XInternAtom(tempdisp,
-                                                   "GHOSTVIEW_COLORS", false),
-                                       XInternAtom(tempdisp, "STRING", false),
-                                       8, PropModeReplace, 
-                                       reinterpret_cast<unsigned char*>(const_cast<char*>(t3.str())),
-                                       ::strlen(t3.str()));
-#endif
+                                       int(t3.str().size()));
                        XUngrabServer(tempdisp);
                        XFlush(tempdisp);
                        
@@ -689,14 +625,10 @@ void runqueue()
                                ++ne;
                        typedef char * char_p;
                        env = new char_p[ne + 2];
-#ifdef HAVE_SSTREAM
                        string tmp = t2.str().c_str();
                        env[0] = new char[tmp.size() + 1];
                        std::copy(tmp.begin(), tmp.end(), env[0]);
                        env[0][tmp.size()] = '\0';
-#else
-                       env[0] = tbuf2;
-#endif
                        ::memcpy(&env[1], environ, sizeof(char*) * (ne + 1));
                        environ = env;
 
@@ -710,7 +642,7 @@ void runqueue()
 
                        // now chdir into dir with .eps file, to be on the safe
                        // side
-                       ::chdir(OnlyPath(p->data->fname).c_str());
+                       lyx::chdir(OnlyPath(p->data->fname));
                        // make temp file name
                        string tmpf = make_tmp(getpid());
                        if (lyxerr.debugging()) {
@@ -733,7 +665,7 @@ void runqueue()
                        lyxerr.debug() << "Cmd: " 
                                       << lyxrc.ps_command
                                       << " -sDEVICE=x11 "
-                                      << tmpf.c_str() << ' '
+                                      << tmpf << ' '
                                       << p->data->fname << endl;
                        _exit(0);       // no gs?
                }
@@ -749,7 +681,6 @@ void runqueue()
 }
 
 
-static
 void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
 {
        // recompute the stuff and put in the queue
@@ -768,7 +699,6 @@ void addwait(int psx, int psy, int pswid, int pshgh, figdata * data)
 }
 
 
-static
 figdata * getfigdata(int wid, int hgh, string const & fname, 
                     int psx, int psy, int pswid, int pshgh, 
                     int raw_wid, int raw_hgh, float angle, char flags)
@@ -797,12 +727,12 @@ figdata * getfigdata(int wid, int hgh, string const & fname,
        p->flags = flags;
        bitmaps.push_back(p);
        XWindowAttributes wa;
-       XGetWindowAttributes(fl_display, fl_get_canvas_id(
+       XGetWindowAttributes(fl_get_display(), fl_get_canvas_id(
                figinset_canvas), &wa);
 
        if (lyxerr.debugging()) {
-               lyxerr << "Create pixmap disp:" << fl_display
-                      << " scr:" << DefaultScreen(fl_display)
+               lyxerr << "Create pixmap disp:" << fl_get_display()
+                      << " scr:" << DefaultScreen(fl_get_display())
                       << " w:" << wid
                       << " h:" << hgh
                       << " depth:" << wa.depth << endl;
@@ -813,7 +743,7 @@ figdata * getfigdata(int wid, int hgh, string const & fname,
        p->broken = false;
        p->gspid = -1;
        if (flags) {
-               p->bitmap = XCreatePixmap(fl_display, fl_get_canvas_id(
+               p->bitmap = XCreatePixmap(fl_get_display(), fl_get_canvas_id(
                        figinset_canvas), wid, hgh, wa.depth);
                p->gsdone = false;
                // initialize reading of .eps file with correct sizes and stuff
@@ -828,17 +758,15 @@ figdata * getfigdata(int wid, int hgh, string const & fname,
 }
 
 
-static
 void getbitmap(figdata * p)
 {
        p->gspid = -1;
 }
 
 
-static
 void makeupdatelist(figdata * p)
 {
-       for(figures_type::iterator it = figures.begin();
+       for (figures_type::iterator it = figures.begin();
            it != figures.end(); ++it)
                if ((*it)->data == p) {
                        if (lyxerr.debugging()) {
@@ -851,6 +779,8 @@ void makeupdatelist(figdata * p)
                }
 }
 
+} // namespace anon
+
 
 // this func is only "called" in spellchecker.C
 void sigchldchecker(pid_t pid, int * status)
@@ -881,7 +811,7 @@ void sigchldchecker(pid_t pid, int * status)
                                p->broken = false;
                        } else {
                                // remove temporary files
-                               unlink(make_tmp(p->gspid).c_str());
+                               lyx::unlink(make_tmp(p->gspid));
                                p->gspid = -1;
                                p->broken = true;
                        }
@@ -932,7 +862,8 @@ void sigchldchecker(pid_t pid, int * status)
 }
 
 
-static
+namespace {
+
 void getbitmaps()
 {
        bitmap_waiting = false;
@@ -943,7 +874,6 @@ void getbitmaps()
 }
 
 
-static
 void RegisterFigure(InsetFig * fi)
 {
        if (figures.empty()) InitFigures();
@@ -961,9 +891,11 @@ void RegisterFigure(InsetFig * fi)
 }
 
 
-static
 void UnregisterFigure(InsetFig * fi)
 {
+       if (!lyxrc.use_gui)
+               return;
+
        Figref * tmpfig = fi->figure;
 
        if (tmpfig->data) freefigdata(tmpfig->data);
@@ -987,9 +919,11 @@ void UnregisterFigure(InsetFig * fi)
        if (figures.empty()) DoneFigures();
 }
 
+} // namespace anon
+
 
-InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
-       : owner(o)
+InsetFig::InsetFig(int tmpx, int tmpy, Buffer const & o)
+       : owner(&o)
 {
        wid = tmpx;
        hgh = tmpy;
@@ -1004,6 +938,7 @@ InsetFig::InsetFig(int tmpx, int tmpy, Buffer * o)
        raw_wid = raw_hgh = 0;
        changedfname = false;
        RegisterFigure(this);
+       r_ = Dialogs::redrawGUI.connect(SigC::slot(this, &InsetFig::redraw));
 }
 
 
@@ -1013,31 +948,40 @@ InsetFig::~InsetFig()
                lyxerr << "Figure destructor called" << endl;
        }
        UnregisterFigure(this);
+       r_.disconnect();
+}
+
+
+void InsetFig::redraw()
+{
+       if (form && form->Figure->visible)
+               fl_redraw_form(form->Figure);
 }
 
 
-int InsetFig::ascent(Painter &, LyXFont const &) const
+int InsetFig::ascent(BufferView *, LyXFont const &) const
 {
        return hgh + 3;
 }
 
 
-int InsetFig::descent(Painter &, LyXFont const &) const
+int InsetFig::descent(BufferView *, LyXFont const &) const
 {
        return 1;
 }
 
 
-int InsetFig::width(Painter &, LyXFont const &) const
+int InsetFig::width(BufferView *, LyXFont const &) const
 {
        return wid + 2;
 }
 
 
-void InsetFig::draw(Painter & pain, LyXFont const & f,
-                   int baseline, float & x) const
+void InsetFig::draw(BufferView * bv, LyXFont const & f,
+                   int baseline, float & x, bool) const
 {
        LyXFont font(f);
+       Painter & pain = bv->painter();
        
        if (bitmap_waiting) getbitmaps();
        
@@ -1056,7 +1000,10 @@ void InsetFig::draw(Painter & pain, LyXFont const & f,
                                       wid + 1, hgh + 1);
                
        } else {
-               char * msg = 0;
+               char const * msg = 0;
+               string lfname = fname;
+               if (!fname.empty() && GetExtension(fname).empty())
+                   lfname += ".eps";
                // draw frame
                pain.rectangle(int(x), baseline - hgh - 1, wid + 1, hgh + 1);
 
@@ -1066,7 +1013,7 @@ void InsetFig::draw(Painter & pain, LyXFont const & f,
                } 
                else if (fname.empty()) 
                        msg = _("[no file]");
-               else if (!IsFileReadable(fname))
+               else if (!IsFileReadable(lfname))
                        msg = _("[bad file name]");
                else if ((flags & 3) == 0) 
                        msg = _("[not displayed]");
@@ -1084,7 +1031,7 @@ void InsetFig::draw(Painter & pain, LyXFont const & f,
                font.setSize(LyXFont::SIZE_TINY);
                pain.text(int(x + 8), baseline - 4, msg, strlen(msg), font);
        }
-       x += width(pain, font);    // ?
+       x += width(bv, font);    // ?
 }
 
 
@@ -1200,7 +1147,7 @@ int InsetFig::Latex(Buffer const *, ostream & os,
 }
 
 
-int InsetFig::Ascii(Buffer const *, ostream &) const
+int InsetFig::Ascii(Buffer const *, ostream &, int) const
 {
        return 0;
 }
@@ -1217,8 +1164,8 @@ int InsetFig::DocBook(Buffer const *, ostream & os) const
        string buf1 = OnlyPath(owner->fileName());
        string figurename = MakeRelPath(fname, buf1);
 
-       if(suffixIs(figurename, ".eps"))
-               figurename.erase(fname.length() - 4);
+       if (suffixIs(figurename, ".eps"))
+               figurename.erase(figurename.length() - 4);
 
        os << "@<graphic fileref=\"" << figurename << "\"></graphic>";
        return 0;
@@ -1244,7 +1191,7 @@ bool InsetFig::Deletable() const
 }
 
 
-char const * InsetFig::EditMessage() const 
+string const InsetFig::EditMessage() const 
 {
        return _("Opened figure");
 }
@@ -1258,7 +1205,7 @@ void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
        // We should have RO-versions of the form instead.
        // The actual prevention of altering a readonly doc
        // is done in CallbackFig()
-       if(bv->buffer()->isReadonly()) 
+       if (bv->buffer()->isReadonly()) 
                WarnReadonly(bv->buffer()->fileName());
 
        if (!form) {
@@ -1272,19 +1219,20 @@ void InsetFig::Edit(BufferView * bv, int, int, unsigned int)
        if (form->Figure->visible) {
                fl_raise_form(form->Figure);
        } else {
-               fl_show_form(form->Figure, FL_PLACE_MOUSE | FL_PLACE_SIZE,
-                            FL_FULLBORDER, _("Figure"));
+               fl_show_form(form->Figure,
+                            FL_PLACE_MOUSE | FL_FREE_SIZE, FL_TRANSIENT,
+                            _("Figure"));
        }
 }
 
 
-Inset * InsetFig::Clone() const
+Inset * InsetFig::Clone(Buffer const & buffer) const
 {
-       InsetFig * tmp = new InsetFig(100, 100, owner);
+       InsetFig * tmp = new InsetFig(100, 100, buffer);
 
        if (lyxerr.debugging()) {
                lyxerr << "Clone Figure: buffer:["
-                      << current_view->buffer()
+                      << &buffer
                       << "], cbuffer:[xx]" << endl;
        }
 
@@ -1306,12 +1254,15 @@ Inset * InsetFig::Clone() const
        tmp->pswid = pswid;
        tmp->pshgh = pshgh;
        tmp->fname = fname;
-       if (!fname.empty() && IsFileReadable(fname) 
+       string lfname = fname;
+       if (!fname.empty() && GetExtension(fname).empty())
+               lfname += ".eps";
+       if (!fname.empty() && IsFileReadable(lfname) 
            && (flags & 3) && !lyxrc.ps_command.empty()
            && lyxrc.use_gui) { 
                // do not display if there is
                // "do not display" chosen (Matthias 260696)
-               tmp->figure->data = getfigdata(wid, hgh, fname, psx, psy,
+               tmp->figure->data = getfigdata(wid, hgh, lfname, psx, psy,
                                               pswid, pshgh, raw_wid, raw_hgh,
                                               angle, flags & (3|8));
        } else tmp->figure->data = 0;
@@ -1329,8 +1280,9 @@ Inset::Code InsetFig::LyxCode() const
 }
 
 
-static
-string stringify(InsetFig::HWTYPE hw, float f, string suffix)
+namespace {
+
+string const stringify(InsetFig::HWTYPE hw, float f, string suffix)
 {
        string res;
        switch (hw) {
@@ -1353,6 +1305,8 @@ string stringify(InsetFig::HWTYPE hw, float f, string suffix)
        return res;
 }
 
+} // namespace anon
+
 
 void InsetFig::Regenerate() const
 {
@@ -1470,6 +1424,9 @@ void InsetFig::TempRegenerate()
 
 void InsetFig::Recompute()
 {
+       if (!lyxrc.use_gui)
+               return;
+
        bool changed = changedfname;
        int newx, newy, nraw_x, nraw_y;
 
@@ -1480,10 +1437,14 @@ void InsetFig::Recompute()
        int frame_wid = int(ceil(fabs(cos_a * pswid) + fabs(sin_a * pshgh)));
        int frame_hgh= int(ceil(fabs(cos_a * pshgh) + fabs(sin_a * pswid)));
 
+       string lfname = fname;
+       if (GetExtension(fname).empty())
+           lfname += ".eps";
+
        /* now recompute wid and hgh, and if that is changed, set changed */
        /* this depends on chosen size of the picture and its bbox */
        // This will be redone in 0.13 ... (hen)
-       if (!fname.empty() && IsFileReadable(fname)) {
+       if (!lfname.empty() && IsFileReadable(lfname)) {
                // say, total width is 595 pts, as A4 in TeX, thats in 1/72" */
 
                newx = frame_wid;
@@ -1562,11 +1523,11 @@ void InsetFig::Recompute()
                figdata * pf = figure->data;
 
                // get new data
-               if (!fname.empty() && IsFileReadable(fname) && (flags & 3)
+               if (!lfname.empty() && IsFileReadable(lfname) && (flags & 3)
                    && !lyxrc.ps_command.empty()) {
                        // do not display if there is "do not display"
                        // chosen (Matthias 260696)
-                       figure->data = getfigdata(wid, hgh, fname,
+                       figure->data = getfigdata(wid, hgh, lfname,
                                                  psx, psy, pswid, pshgh,
                                                  raw_wid, raw_hgh,
                                                  angle, flags & (3|8));
@@ -1594,7 +1555,10 @@ void InsetFig::GetPSSizes()
 
        if (fname.empty()) return;
        string p;
-       ifstream ifs(fname.c_str());
+       string lfname = fname;
+       if (GetExtension(fname).empty())
+               lfname += ".eps";
+       ifstream ifs(lfname.c_str());
 
        if (!ifs) return;       // file not found !!!!
 
@@ -1755,7 +1719,7 @@ void InsetFig::CallbackFig(long arg)
                break;
        case 7:                         /* apply */
        case 8:                         /* ok (apply and close) */
-               if(!current_view->buffer()->isReadonly()) {
+               if (!current_view->buffer()->isReadonly()) {
                        wtype = twtype;
                        htype = thtype;
                        xwid = atof(fl_get_input(form->Width));
@@ -1796,7 +1760,7 @@ void InsetFig::CallbackFig(long arg)
                        break;
                } //if not readonly
                //  The user has already been informed about RO in ::Edit
-               if(arg == 7) // if 'Apply'
+               if (arg == 7) // if 'Apply'
                        break;
                // fall through
        case 9:                         /* cancel = restore and close */
@@ -1940,43 +1904,28 @@ void InsetFig::RestoreForm()
        }
        else fl_set_input(form->EpsFile, "");
        fl_set_input(form->Subcaption, subcaption.c_str());
-       if(current_view->buffer()->isReadonly()) 
+       if (current_view->buffer()->isReadonly()) 
                DisableFigurePanel(form);
 
        TempRegenerate();
 }
 
 
-void InsetFig::Preview(char const * p)
+void InsetFig::Preview(string const & p)
 {
-       int pid = fork();
-
-       if (pid == -1) {
-               lyxerr << "Cannot fork process!" << endl;
-               return;         // error
-       }
-       if (pid > 0) {
-               addpidwait(pid);
-               return;         // parent process
-       }
-
+       string tfname = p;
+       if (GetExtension(tfname).empty())
+           tfname += ".eps";
        string buf1 = OnlyPath(owner->fileName());
-       string buf2 = MakeAbsPath(p, buf1);
-       
-       lyxerr << "Error during rendering "
-              << execlp(lyxrc.view_pspic_command.c_str(),
-                        lyxrc.view_pspic_command.c_str(),
-                        buf2.c_str(), 0)
-              << endl;
-       _exit(0);
+       string buf2 = MakeAbsPath(tfname, buf1);
+       if (!formats.View(owner, buf2, "eps"))
+               lyxerr << "Can't view " << buf2 << endl;
 }
 
-
 void InsetFig::BrowseFile()
 {
        static string current_figure_path;
        static int once = 0;
-       LyXFileDlg fileDlg;
 
        if (lyxerr.debugging()) {
                lyxerr << "Filename: "
@@ -1990,7 +1939,7 @@ void InsetFig::BrowseFile()
                buf = MakeAbsPath(p, buf2);
                buf = OnlyPath(buf);
        } else {
-               buf = OnlyPath(owner->fileName().c_str());
+               buf = OnlyPath(owner->fileName());
        }
        
        // Does user clipart directory exist?
@@ -2001,23 +1950,21 @@ void InsetFig::BrowseFile()
                bufclip = AddName (system_lyxdir, "clipart");   
 
 
-       fileDlg.SetButton(0, _("Clipart"), bufclip); 
-       fileDlg.SetButton(1, _("Document"), buf); 
+       FileDialog fileDlg(current_view->owner(), _("Select an EPS figure"),
+               LFUN_SELECT_FILE_SYNC,
+               make_pair(string(_("Clip art")), string(bufclip)),
+               make_pair(string(_("Documents")), string(buf)));
 
        bool error = false;
        do {
-               ProhibitInput(current_view);
-               if (once) {
-                       p = fileDlg.Select(_("EPS Figure"),
-                                          current_figure_path,
-                                          "*ps", string());
-               } else {
-                       p = fileDlg.Select(_("EPS Figure"), buf,
-                                          "*ps", string());
-               }
-               AllowInput(current_view);
+               string const path = (once) ? current_figure_path : buf;
+
+               FileDialog::Result result = fileDlg.Select(path, _("*ps| PostScript documents"));
 
-               if (p.empty()) return;
+               string const p = result.second;
+
+               if (p.empty())
+                       return;
 
                buf = MakeRelPath(p, buf2);
                current_figure_path = OnlyPath(p);