]> git.lyx.org Git - lyx.git/blobdiff - src/insets/insetgraphics.C
2001-12-28 Lars Gullik Bj�nnes <larsbj@birdstep.com>
[lyx.git] / src / insets / insetgraphics.C
index 5dff21009079afcfc000e8af664ba4d5dd4f7627..b4f7f7cd5ea4255c4f5d571a557725c3b0ba559f 100644 (file)
@@ -28,10 +28,7 @@ Known BUGS:
        We should probably use what the user asks to use... but when he chooses
        by the file dialog we normally get an absolute path and this may not be 
        what the user meant.
-    * Bug in FileDlg class (src/filedlg.[hC]) when selecting a file and then
-        pressing ok, it counts as if no real selection done. Apparently
-        when choosing a file it doesn't update the select file input line.
-               
+
        * If we are trying to create a file in a read-only directory and there
                are graphics that need converting, the converting will fail because
                it is done in-place, into the same directory as the original image.
@@ -41,6 +38,14 @@ Known BUGS:
        * We do not dither or resize the image in a WYSIWYM way, we load it at
                its original size and color, resizing is done in the final output,
                but not in the LyX window.
+
+       * The scale option is only handled for the horizontal part, the vertical
+               part will not work. For now it is also shown only for horizontal
+               resizing on the form.
+
+       * EPS figures are not fully detected, they may have a lot of possible
+               suffixes so we need to read the file and detect if it's EPS or not.
+               [Implemented, need testing]
                
 TODO Before initial production release:
     * Replace insetfig everywhere
@@ -146,6 +151,7 @@ TODO Extended features:
 #include "lyxtext.h"
 #include "lyxrc.h"
 #include "font.h" // For the lyxfont class.
+#include "fstream" // for ifstream in isEPS
 #include <algorithm> // For the std::max
 #include "support/lyxmanip.h"
 #include "debug.h"
@@ -153,11 +159,13 @@ TODO Extended features:
 
 extern string system_tempdir;
 
+using std::ifstream;
 using std::ostream;
 using std::endl;
 
 
 // This function is a utility function
+// ... that should be with ChangeExtension ...
 inline
 string const RemoveExtension(string const & filename)
 {
@@ -246,11 +254,23 @@ int InsetGraphics::width(BufferView *, LyXFont const & font) const
        if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
                return pixmap->getWidth();
        else {
-               string const msg = statusMessage();
                int font_width = 0;
-               
-               if (!msg.empty())
-                       font_width = lyxfont::width(msg, font);
+
+               LyXFont msgFont(font);
+               msgFont.setFamily(LyXFont::SANS_FAMILY);
+
+               string const justname = OnlyFilename (params.filename);
+               if (!justname.empty()) {
+                       msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
+                       font_width = lyxfont::width(justname, msgFont);
+               }
+
+               string const msg = statusMessage();
+               if (!msg.empty()) {
+                       msgFont.setSize(LyXFont::SIZE_TINY);
+                       int const msg_width = lyxfont::width(msg, msgFont);
+                       font_width = std::max(font_width, msg_width);
+               }
                
                return std::max(50, font_width + 15);
        }
@@ -281,7 +301,9 @@ void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
                
                // Get the image status, default to unknown error.
                GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
-               if (cacheHandle.get())
+               if (lyxrc.display_graphics != "no" &&
+                   params.display != InsetGraphicsParams::NONE &&
+                   cacheHandle.get())
                        status = cacheHandle->getImageStatus();
                
                // Check if the image is now ready.
@@ -293,22 +315,25 @@ void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
                        return;
                }
 
-               
                paint.rectangle(old_x + 2, baseline - lascent,
                                lwidth - 4,
                                lascent + ldescent);
 
-               string const msg = statusMessage();
-               if (!msg.empty()) {
-                       // Print the message.
-                       LyXFont msgFont(font);
-                       msgFont.setFamily(LyXFont::SANS_FAMILY);
+               // Print the file name.
+               LyXFont msgFont(font);
+               msgFont.setFamily(LyXFont::SANS_FAMILY);
+
+               string const justname = OnlyFilename (params.filename);
+               if (!justname.empty()) {
                        msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
-                       string const justname = OnlyFilename (params.filename);
                        paint.text(old_x + 8, 
-                                  baseline - lyxfont::maxAscent(msgFont) - 4,
-                                  justname, msgFont);
+                                  baseline - lyxfont::maxAscent(msgFont) - 4,
+                                  justname, msgFont);
+               }
 
+               // Print the message.
+               string const msg = statusMessage();
+               if (!msg.empty()) {
                        msgFont.setSize(LyXFont::SIZE_TINY);
                        paint.text(old_x + 8, baseline - 4, msg, msgFont);
                }
@@ -344,7 +369,7 @@ void InsetGraphics::write(Buffer const * buf, ostream & os) const
 
 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
 {
-       string const token = lex.GetString();
+       string const token = lex.getString();
 
        if (token == "Graphics")
                readInsetGraphics(buf, lex);
@@ -360,10 +385,10 @@ void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
 {
        bool finished = false;
 
-       while (lex.IsOK() && !finished) {
+       while (lex.isOK() && !finished) {
                lex.next();
 
-               string const token = lex.GetString();
+               string const token = lex.getString();
                lyxerr[Debug::INFO] << "Token: '" << token << '\'' 
                                    << std::endl;
 
@@ -373,7 +398,7 @@ void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
                        finished = true;
                } else if (token == "FormatVersion") {
                        lex.next();
-                       int version = lex.GetInteger();
+                       int version = lex.getInteger();
                        if (version > 1)
                                lyxerr
                                << "This document was created with a newer Graphics widget"
@@ -395,10 +420,10 @@ void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
 {
        bool finished = false;
        
-       while (lex.IsOK() && !finished) {
+       while (lex.isOK() && !finished) {
                lex.next();
 
-               string const token = lex.GetString();
+               string const token = lex.getString();
                lyxerr[Debug::INFO] << "Token: " << token << endl;
                
                if (token.empty())
@@ -407,7 +432,7 @@ void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
                        finished = true;
                } else if (token == "file") {
                        if (lex.next()) {
-                               string const name = lex.GetString();
+                               string const name = lex.getString();
                                string const path = OnlyPath(buf->fileName());
                                params.filename = MakeAbsPath(name, path);
                        }
@@ -415,25 +440,27 @@ void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
                        if (lex.next());
                        // kept for backwards compability. Delete in 0.13.x
                } else if (token == "subcaption") {
-                       if (lex.EatLine())
-                               params.subcaptionText = lex.GetString();
+                       if (lex.eatLine())
+                               params.subcaptionText = lex.getString();
                } else if (token == "label") {
                        if (lex.next());
                        // kept for backwards compability. Delete in 0.13.x
                } else if (token == "angle") {
                        if (lex.next())
-                               params.rotateAngle = lex.GetFloat();
+                               params.rotateAngle = lex.getFloat();
                } else if (token == "size") {
                        // Size of image on screen is ignored in InsetGraphics, just eat
                        // the input.
-                       if (lex.next())
-                               lex.GetInteger();
-                       if (lex.next())
-                               lex.GetInteger();
+                       if (lex.next()) {
+                               lex.getInteger();
+                       }
+                       if (lex.next()) {
+                               lex.getInteger();
+                       }
                } else if (token == "flags") {
                        InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
                        if (lex.next())
-                               switch (lex.GetInteger()) {
+                               switch (lex.getInteger()) {
                                case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
                                case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
                                }
@@ -441,15 +468,19 @@ void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
                } else if (token == "subfigure") {
                        params.subcaption = true;
                } else if (token == "width") {
-                       if (lex.next())
-                               params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
-                       if (lex.next())
-                               params.widthSize = lex.GetFloat();
+                       if (lex.next()) {
+                               params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.getInteger());
+                       }
+                       if (lex.next()) {
+                               params.widthSize = lex.getFloat();
+                       }
                } else if (token == "height") {
-                       if (lex.next())
-                               params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
-                       if (lex.next())
-                               params.heightSize = lex.GetFloat();
+                       if (lex.next()) {
+                               params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.getInteger());
+                       }
+                       if (lex.next()) {
+                               params.heightSize = lex.getFloat();
+                       }
                }
        }
 }
@@ -480,6 +511,8 @@ void formatResize(ostream & os, string const & key,
                os << key << '=' << size / 100 << "\\column" << key << ',';
                break;
 
+       case InsetGraphicsParams::SCALE:
+               os << "scale" << '=' << size/100 << ',';
        }
 }
 
@@ -499,7 +532,7 @@ InsetGraphics::createLatexOptions() const
 
        // Make sure it's not very close to zero, a float can be effectively
        // zero but not exactly zero.
-       if (lyx::float_equal(params.rotateAngle, 0, 0.001)) {
+       if (!lyx::float_equal(params.rotateAngle, 0, 0.001)) {
                options << "angle="
                        << params.rotateAngle << ',';
        }
@@ -511,28 +544,85 @@ InsetGraphics::createLatexOptions() const
 }
 
 namespace {
-       
-string decideOutputImageFormat(string const & in_fmt)
+
+enum FileType {
+       EPS,
+       PNG,
+       JPEG,
+       GIF,
+       PDF,
+       UNKNOWN
+};
+
+bool isEPS(string const & filename)
+{
+       if (filename.empty() || !IsFileReadable(filename)) return false;
+
+       ifstream ifs(filename.c_str());
+
+       if (!ifs) return false; // Couldn't open file...
+
+       bool is_eps = false; // Have we recognized the file as EPS?
+       string to_find = "%!PS-Adobe-"; // The string we use to recognize
+       int const max_attempts = 500; // Maximum strings to read to attempt recognition
+       int count = 0; // Counter of attempts.
+       string str;
+       for (; count < max_attempts; ++count) {
+               if (ifs.eof()) {
+                       lyxerr[Debug::INFO] << "InsetGraphics (isEPS)"
+                               " End of file reached and it wasn't found to be EPS!" << endl;
+                       break;
+               }
+
+               ifs >> str;
+               if (str.find(to_find)) {
+                       is_eps = true;
+                       break;
+               }
+       }
+
+       return is_eps;
+}
+
+enum FileType classifyFileType(string const & filename, string const & suffix)
+{
+       if (suffix == "png")
+               return PNG;
+       else if (suffix == "jpg" || suffix == "jpeg")
+               return JPEG;
+       else if (suffix == "gif")
+               return GIF;
+       else if (suffix == "pdf")
+               return PDF;
+       else if (isEPS(filename))
+               return EPS;
+
+       return UNKNOWN;
+}
+
+string decideOutputImageFormat(string const & suffix, enum FileType type)
 {
        // lyxrc.pdf_mode means:
        // Are we creating a PDF or a PS file?
        // (Should actually mean, are we using latex or pdflatex).
        
        if (lyxrc.pdf_mode) {
-               if (in_fmt == "eps" || in_fmt == "epsi" || in_fmt == "pdf")
+               if (type == EPS || type == EPS || type == PDF)
                        return "pdf";
-               else if (in_fmt == "jpg" || in_fmt == "jpeg")
-                       return in_fmt;
+               else if (type == JPEG)
+                       return suffix;
                else
                        return "png";
        }
 
        // If it's postscript, we always do eps.
-       // Garst has many eps files with various extensions, we just assume
-       // whatever goes in (except those we know to be otherwise) is eps
-       if (in_fmt == "gif" || in_fmt == "png" || in_fmt == "jpg")
-               return "eps";
-       return in_fmt;
+       // There are many suffixes that are actually EPS (ask Garst for example)
+       // so we detect if it's an EPS by looking in the file, if it is, we return
+       // the same suffix of the file so it won't be converted.
+       if (type == EPS)
+               return suffix;
+       
+       return "eps";
 }
 
 } // Anon. namespace
@@ -559,10 +649,11 @@ InsetGraphics::prepareFile(Buffer const *buf) const
        
        // Get the extension (format) of the original file.
        string const extension = GetExtension(params.filename);
+       FileType type = classifyFileType(params.filename, extension);
        
        // Are we creating a PDF or a PS file?
        // (Should actually mean, are we usind latex or pdflatex).
-       string const image_target = decideOutputImageFormat(extension);
+       string const image_target = decideOutputImageFormat(extension, type);
 
        if (extension == image_target)
                return params.filename;
@@ -670,7 +761,7 @@ int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
 // For explanation on inserting graphics into DocBook checkout:
 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
 // See also the docbook guide at http://www.docbook.org/
-int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
+int InsetGraphics::docbook(Buffer const * buf, ostream & os) const
 {
        // Change the path to be relative to the main file.
        string const buffer_dir = OnlyPath(buf->fileName());
@@ -691,10 +782,10 @@ void InsetGraphics::validate(LaTeXFeatures & features) const
        if (params.filename.empty())
                return ;
 
-       features.graphicx = true;
+       features.require("graphicx");
 
        if (params.subcaption)
-               features.subfigure = true;
+               features.require("subfigure");
 }
 
 
@@ -707,7 +798,9 @@ void InsetGraphics::updateInset() const
 
        // We do it this way so that in the face of some error, we will still
        // be in a valid state.
-       if (!params.filename.empty()) {
+       if (!params.filename.empty() &&
+           lyxrc.display_graphics != "no" &&
+           params.display != InsetGraphicsParams::NONE) {
                temp = gc.addFile(params.filename);
        }