]> git.lyx.org Git - lyx.git/blobdiff - src/insets/InsetGraphics.cpp
Cleanup mouse/selection/context-menu interactions.
[lyx.git] / src / insets / InsetGraphics.cpp
index 26e8be32c80e023c6a7513d841101bdf2d553bbf..eb98501ee81e56dc2c58c61dad112a80012dd6e5 100644 (file)
@@ -15,7 +15,6 @@ TODO
     * What advanced features the users want to do?
       Implement them in a non latex dependent way, but a logical way.
       LyX should translate it to latex or any other fitting format.
-    * Add a way to roll the image file into the file format.
     * When loading, if the image is not found in the expected place, try
       to find it in the clipart, or in the same directory with the image.
     * The image choosing dialog could show thumbnails of the image formats
@@ -23,8 +22,6 @@ TODO
       filename.
     * Add support for the 'picins' package.
     * Add support for the 'picinpar' package.
-    * Improve support for 'subfigure' - Allow to set the various options
-      that are possible.
 */
 
 /* NOTES:
@@ -56,14 +53,13 @@ TODO
 #include "BufferView.h"
 #include "Converter.h"
 #include "Cursor.h"
-#include "support/debug.h"
 #include "DispatchResult.h"
+#include "EmbeddedFiles.h"
 #include "ErrorList.h"
 #include "Exporter.h"
 #include "Format.h"
 #include "FuncRequest.h"
 #include "FuncStatus.h"
-#include "support/gettext.h"
 #include "LaTeXFeatures.h"
 #include "Length.h"
 #include "Lexer.h"
@@ -71,13 +67,16 @@ TODO
 #include "Mover.h"
 #include "OutputParams.h"
 #include "sgml.h"
-#include "EmbeddedFiles.h"
+#include "TocBackend.h"
 
 #include "frontends/alert.h"
 
 #include "support/convert.h"
+#include "support/debug.h"
 #include "support/docstream.h"
+#include "support/ExceptionMessage.h"
 #include "support/filetools.h"
+#include "support/gettext.h"
 #include "support/lyxlib.h"
 #include "support/lstrings.h"
 #include "support/os.h"
@@ -94,6 +93,8 @@ using namespace lyx::support;
 
 namespace lyx {
 
+namespace Alert = frontend::Alert;
+
 namespace {
 
 /// Find the most suitable image format for images in \p format
@@ -153,21 +154,37 @@ InsetGraphics::~InsetGraphics()
 }
 
 
+void InsetGraphics::setBuffer(Buffer & buffer)
+{
+       if (buffer_) {
+               try {
+                       // a file may not be copied successfully when, e.g. buffer_
+                       // has already been closed.
+                       params_.filename = params_.filename.copyTo(&buffer);
+               } catch (ExceptionMessage const & message) {
+                       Alert::error(message.title_, message.details_);
+                       // failed to embed
+                       params_.filename.setEmbed(false);
+               }
+       }
+       Inset::setBuffer(buffer);
+}
+
+
 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
 {
        switch (cmd.action) {
        case LFUN_GRAPHICS_EDIT: {
-               Buffer const & buffer = cur.bv().buffer();
-               InsetGraphicsParams p;
-               InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
-               editGraphics(p, buffer);
+               InsetGraphicsParams p = params();
+               if (!cmd.argument().empty())
+                       InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
+               editGraphics(p, buffer());
                break;
        }
 
        case LFUN_INSET_MODIFY: {
-               Buffer const & buffer = cur.buffer();
                InsetGraphicsParams p;
-               InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
+               InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
                if (!p.filename.empty())
                        setParams(p);
                else
@@ -180,7 +197,7 @@ void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
                break;
 
        case LFUN_MOUSE_RELEASE:
-               if (!cur.selection())
+               if (!cur.selection() && cmd.button() == mouse_button::button1)
                        InsetGraphicsMailer(*this).showDialog(&cur.bv());
                break;
 
@@ -207,26 +224,20 @@ bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
 }
 
 
-void InsetGraphics::registerEmbeddedFiles(Buffer const &, 
-       EmbeddedFiles & files) const
+void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
 {
-       files.registerFile(params().filename.absFilename(), 
-               false, this);
+       files.registerFile(params().filename, this, buffer());
 }
 
 
-void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
-       EmbeddedFile const & file)
+void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
 {
-       BOOST_ASSERT(buf.embeddedFiles().enabled());
+       // only properties of an embedded file can be changed here.
        params_.filename = file;
-       LYXERR(Debug::FILES, "Update InsetGraphic with File " 
-               << params_.filename.toFilesystemEncoding() 
-               << ", embedding status: " << params_.filename.embedded());
 }
 
 
-void InsetGraphics::edit(Cursor & cur, bool)
+void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
 {
        InsetGraphicsMailer(*this).showDialog(&cur.bv());
 }
@@ -250,32 +261,23 @@ Inset::EDITABLE InsetGraphics::editable() const
 }
 
 
-void InsetGraphics::write(Buffer const & buf, ostream & os) const
+void InsetGraphics::write(ostream & os) const
 {
        os << "Graphics\n";
-       params().Write(os, buf);
+       params().Write(os, buffer());
 }
 
 
-void InsetGraphics::read(Buffer const & buf, Lexer & lex)
+void InsetGraphics::read(Lexer & lex)
 {
        string const token = lex.getString();
 
        if (token == "Graphics")
-               readInsetGraphics(lex, buf.filePath());
+               readInsetGraphics(lex, buffer().filePath());
        else
                LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
 
-       // InsetGraphics is read, with filename in params_. We do not know if this file actually
-       // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
-       if (buf.embeddedFiles().enabled()) {
-               EmbeddedFiles::EmbeddedFileList::const_iterator it = 
-                       buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
-               if (it != buf.embeddedFiles().end())
-                       // using available file, embedded or external, depending on file availability and
-                       // embedding status.
-                       params_.filename = *it;
-       }
+       params_.filename.enable(buffer().embedded(), &buffer(), false);
        graphic_->update(params().as_grfxParams());
 }
 
@@ -298,7 +300,7 @@ void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
                } else {
                        if (!params_.Read(lex, token, bufpath))
                                lyxerr << "Unknown token, " << token << ", skipping."
-                                       << std::endl;
+                                       << endl;
                }
        }
 }
@@ -468,7 +470,7 @@ enum GraphicsCopyStatus {
 };
 
 
-std::pair<GraphicsCopyStatus, FileName> const
+pair<GraphicsCopyStatus, FileName> const
 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
 {
        LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
@@ -477,32 +479,30 @@ copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
 
        if (checksum_in == checksum_out)
                // Nothing to do...
-               return std::make_pair(IDENTICAL_CONTENTS, file_out);
+               return make_pair(IDENTICAL_CONTENTS, file_out);
 
        Mover const & mover = getMover(formats.getFormatFromFile(file_in));
        bool const success = mover.copy(file_in, file_out);
        if (!success) {
                // FIXME UNICODE
                LYXERR(Debug::GRAPHICS,
-                       to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
+                       to_utf8(bformat(_("Could not copy the file\n%1$s\n"
                                                           "into the temporary directory."),
                                                from_utf8(file_in.absFilename()))));
        }
 
        GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
-       return std::make_pair(status, file_out);
+       return make_pair(status, file_out);
 }
 
 
-std::pair<GraphicsCopyStatus, FileName> const
+pair<GraphicsCopyStatus, FileName> const
 copyToDirIfNeeded(DocFileName const & file, string const & dir)
 {
-       using support::rtrim;
-
        string const file_in = file.absFilename();
-       string const only_path = support::onlyPath(file_in);
-       if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
-               return std::make_pair(IDENTICAL_PATHS, file_in);
+       string const only_path = onlyPath(file_in);
+       if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
+               return make_pair(IDENTICAL_PATHS, file_in);
 
        string mangled = file.mangledFilename();
        if (file.isZipped()) {
@@ -516,7 +516,7 @@ copyToDirIfNeeded(DocFileName const & file, string const & dir)
                string::size_type const ext_len = file_in.length() - base.length();
                mangled[mangled.length() - ext_len] = '.';
        }
-       FileName const file_out(support::makeAbsPath(mangled, dir));
+       FileName const file_out(makeAbsPath(mangled, dir));
 
        return copyFileIfNeeded(file, file_out);
 }
@@ -535,13 +535,10 @@ string const stripExtensionIfPossible(string const & file, bool nice)
        // dots with a macro whose definition is just a dot ;-)
        // The automatic format selection does not work if the file
        // name is escaped.
-       string const latex_name = latex_path(file,
-                                            support::EXCLUDE_EXTENSION);
+       string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
        if (!nice || contains(latex_name, '"'))
                return latex_name;
-       return latex_path(removeExtension(file),
-                         support::PROTECT_EXTENSION,
-                         support::ESCAPE_DOTS);
+       return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
 }
 
 
@@ -556,21 +553,21 @@ string const stripExtensionIfPossible(string const & file, string const & to, bo
            (to_format == "eps" && file_format ==  "ps") ||
            (to_format ==  "ps" && file_format == "eps"))
                return stripExtensionIfPossible(file, nice);
-       return latex_path(file, support::EXCLUDE_EXTENSION);
+       return latex_path(file, EXCLUDE_EXTENSION);
 }
 
 } // namespace anon
 
 
-string const InsetGraphics::prepareFile(Buffer const & buf,
-                                       OutputParams const & runparams) const
+string InsetGraphics::prepareFile(OutputParams const & runparams) const
 {
        // The following code depends on non-empty filenames
        if (params().filename.empty())
                return string();
 
-       string const orig_file = params().filename.absFilename();
-       string const rel_file = params().filename.relFilename(buf.filePath());
+       string const orig_file = params().filename.availableFile().absFilename();
+       // this is for dryrun and display purposes, do not use latexFilename
+       string const rel_file = params().filename.relFilename(buffer().filePath());
 
        // previewing source code, no file copying or file format conversion
        if (runparams.dryrun)
@@ -578,11 +575,11 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
 
        // temp_file will contain the file for LaTeX to act on if, for example,
        // we move it to a temp dir or uncompress it.
-       FileName temp_file = params().filename;
+       FileName temp_file = params().filename.availableFile();
 
        // The master buffer. This is useful when there are multiple levels
        // of include files
-       Buffer const * masterBuffer = buf.masterBuffer();
+       Buffer const * masterBuffer = buffer().masterBuffer();
 
        // Return the output name if we are inside a comment or the file does
        // not exist.
@@ -598,7 +595,7 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
 
        GraphicsCopyStatus status;
        boost::tie(status, temp_file) =
-                       copyToDirIfNeeded(params().filename, temp_path);
+                       copyToDirIfNeeded(params().filename.availableFile(), temp_path);
 
        if (status == FAILURE)
                return orig_file;
@@ -654,8 +651,7 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
                                        source_file, output_file);
                        // We can't strip the extension, because we don't know
                        // the unzipped file format
-                       return latex_path(output_file,
-                                         support::EXCLUDE_EXTENSION);
+                       return latex_path(output_file, EXCLUDE_EXTENSION);
                }
 
                FileName const unzipped_temp_file =
@@ -694,7 +690,7 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
                        // the file format from the extension, so we must
                        // change it.
                        FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
-                       if (support::rename(temp_file, new_file)) {
+                       if (temp_file.moveTo(new_file)) {
                                temp_file = new_file;
                                output_file = changeExtension(output_file, ext);
                                source_file = FileName(changeExtension(source_file.absFilename(), ext));
@@ -735,7 +731,7 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
 
        // FIXME (Abdel 12/08/06): Is there a need to show these errors?
        ErrorList el;
-       if (theConverters().convert(&buf, temp_file, to_file, params().filename,
+       if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
                               from, to, el,
                               Converters::try_default | Converters::try_cache)) {
                runparams.exportdata->addExternalFile(tex_format,
@@ -748,7 +744,7 @@ string const InsetGraphics::prepareFile(Buffer const & buf,
 }
 
 
-int InsetGraphics::latex(Buffer const & buf, odocstream & os,
+int InsetGraphics::latex(odocstream & os,
                         OutputParams const & runparams) const
 {
        // If there is no file specified or not existing,
@@ -756,9 +752,6 @@ int InsetGraphics::latex(Buffer const & buf, odocstream & os,
        LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
                << params().filename.absFilename());
 
-       string const relative_file =
-               params().filename.relFilename(buf.filePath());
-
        bool const file_exists = !params().filename.empty()
                        && params().filename.isReadableFile();
        string const message = file_exists ?
@@ -773,13 +766,6 @@ int InsetGraphics::latex(Buffer const & buf, odocstream & os,
        // after the actual includegraphics command.
        string before;
        string after;
-       // Do we want subcaptions?
-       if (params().subcaption) {
-               if (runparams.moving_arg)
-                       before += "\\protect";
-               before += "\\subfigure[" + params().subcaptionText + "]{";
-               after = '}';
-       }
 
        if (runparams.moving_arg)
                before += "\\protect";
@@ -802,19 +788,18 @@ int InsetGraphics::latex(Buffer const & buf, odocstream & os,
        // Convert the file if necessary.
        // Remove the extension so LaTeX will use whatever is appropriate
        // (when there are several versions in different formats)
-       latex_str += prepareFile(buf, runparams);
+       latex_str += prepareFile(runparams);
        latex_str += '}' + after;
        // FIXME UNICODE
        os << from_utf8(latex_str);
 
        LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
        // Return how many newlines we issued.
-       return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
+       return int(count(latex_str.begin(), latex_str.end(),'\n'));
 }
 
 
-int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
-                            OutputParams const &) const
+int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
 {
        // No graphics in ascii output. Possible to use gifscii to convert
        // images to ascii approximation.
@@ -824,7 +809,7 @@ int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
        // FIXME UNICODE
        // FIXME: We have no idea what the encoding of the filename is
 
-       docstring const str = bformat(buf.B_("Graphics file: %1$s"),
+       docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
                                      from_utf8(params().filename.absFilename()));
        os << '<' << str << '>';
 
@@ -838,7 +823,7 @@ static int writeImageObject(char const * format, odocstream & os,
 {
        if (runparams.flavor != OutputParams::XML)
                os << "<![ %output.print." << format
-                        << "; [" << std::endl;
+                        << "; [" << endl;
 
        os <<"<imageobject><imagedata fileref=\"&"
                 << graphic_label
@@ -855,7 +840,7 @@ static int writeImageObject(char const * format, odocstream & os,
        os << "</imageobject>";
 
        if (runparams.flavor != OutputParams::XML)
-               os << std::endl << "]]>" ;
+               os << endl << "]]>" ;
 
        return runparams.flavor == OutputParams::XML ? 0 : 2;
 }
@@ -864,7 +849,7 @@ static int writeImageObject(char const * format, odocstream & os,
 // For explanation on inserting graphics into DocBook checkout:
 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
 // See also the docbook guide at http://www.docbook.org/
-int InsetGraphics::docbook(Buffer const &, odocstream & os,
+int InsetGraphics::docbook(odocstream & os,
                           OutputParams const & runparams) const
 {
        // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
@@ -908,9 +893,6 @@ void InsetGraphics::validate(LaTeXFeatures & features) const
                if (contains(rel_file, "."))
                        features.require("lyxdot");
        }
-
-       if (params().subcaption)
-               features.require("subfigure");
 }
 
 
@@ -945,6 +927,25 @@ void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
 }
 
 
+void InsetGraphics::addToToc(ParConstIterator const & cpit) const
+{
+       TocBackend & backend = buffer().tocBackend();
+
+       docstring str = params_.filename.displayName();
+       if (params_.filename.embedded()) {
+               backend.toc("embedded").push_back(TocItem(cpit, 0, str));
+               str += _(" (embedded)");
+       }
+       backend.toc("graphics").push_back(TocItem(cpit, 0, str));
+}
+
+
+docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
+{
+       return from_ascii("context-graphics");
+}
+
+
 string const InsetGraphicsMailer::name_("graphics");
 
 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)