file_loader.cpp

来自「ncbi源码」· C++ 代码 · 共 1,097 行 · 第 1/3 页

CPP
1,097
字号
/* * =========================================================================== * PRODUCTION $Log: file_loader.cpp,v $ * PRODUCTION Revision 1000.6  2004/06/01 20:57:37  gouriano * PRODUCTION PRODUCTION: UPGRADED [GCC34_MSVC7] Dev-tree R1.67 * PRODUCTION * =========================================================================== *//*  $Id: file_loader.cpp,v 1000.6 2004/06/01 20:57:37 gouriano Exp $ * =========================================================================== * *                            PUBLIC DOMAIN NOTICE *               National Center for Biotechnology Information * *  This software/database is a "United States Government Work" under the *  terms of the United States Copyright Act.  It was written as part of *  the author's official duties as a United States Government employee and *  thus cannot be copyrighted.  This software/database is freely available *  to the public for use. The National Library of Medicine and the U.S. *  Government have not placed any restriction on its use or reproduction. * *  Although all reasonable efforts have been taken to ensure the accuracy *  and reliability of the software and data, the NLM and the U.S. *  Government do not and cannot warrant the performance or results that *  may be obtained by using this software or data. The NLM and the U.S. *  Government disclaim all warranties, express or implied, including *  warranties of performance, merchantability or fitness for any particular *  purpose. * *  Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors:  Mike DiCuccio * * File Description: *    CDataPlugin_FileLoader - load sequence information from a file. */#include <ncbi_pch.hpp>#include "file_loader.hpp"#include <corelib/ncbifile.hpp>#include <gui/core/doc_exception.hpp>#include <gui/core/doc_manager.hpp>#include <gui/core/idocument.hpp>#include <gui/core/plugin_utils.hpp>#include <gui/core/version.hpp>#include <gui/core/obj_convert.hpp>#include <gui/plugin/PluginCommandSet.hpp>#include <gui/plugin/PluginInfo.hpp>#include <gui/plugin/PluginValueConstraint.hpp>#include <gui/utils/message_box.hpp>#include <gui/objutils/utils.hpp>#include <gui/utils/fltk_utils.hpp>#include <objmgr/util/obj_sniff.hpp>#include <objtools/readers/fasta.hpp>#include <objtools/readers/aln_reader.hpp>#include <objtools/readers/reader_exception.hpp>#include <serial/iterator.hpp>#include <serial/objistrasn.hpp>#include <serial/objistrasnb.hpp>#include <serial/objistrxml.hpp>#include <serial/objostrasn.hpp>#include <serial/serial.hpp>#include <util/format_guess.hpp>#include <util/static_map.hpp>#include <objects/seqalign/Seq_align_set.hpp>#include <algo/phy_tree/phy_tree_serial.hpp>BEGIN_NCBI_SCOPEUSING_SCOPE(objects);//// Class reads NCBI object files in number of different formats. Uses try and// fail deserialization for binary ASN.1 files//class CSniffReader : public CObjectsSniffer{public:    CSniffReader(CDataPlugin_FileLoader& loader, IDocument* doc, CPluginReply& reply);    // Event function called when parser finds a top level object    virtual void OnTopObjectFoundPre(const CObjectInfo& object,                                      size_t stream_offset);    // Event function alled after top object deserialization    virtual void OnTopObjectFoundPost(const CObjectInfo& object);    // Overload from CObjectsSniffer    virtual void OnObjectFoundPre(const CObjectInfo& object,                                   size_t stream_offset);    // Overload from CObjectsSniffer    virtual void OnObjectFoundPost(const CObjectInfo& object);    // Return success if at least one top object has been found and loaded    EMessageStatus GetLoadStatus() const { return m_LoadStatus; }    virtual void Reset();private:    CPluginReply&    m_Reply;    CDataPlugin_FileLoader&     m_FileLoader; // Parent GUI-aware class    IDocument*       m_Document;   // document into which we load    EMessageStatus   m_LoadStatus; // Status returned by m_FileLoader.Load    unsigned int     m_ObjLevel;   // Object level counter, used to identify    // the TSE};CSniffReader::CSniffReader(CDataPlugin_FileLoader& loader, IDocument* doc,                           CPluginReply& reply)    : m_Reply(reply),      m_FileLoader(loader),      m_Document(doc),      m_LoadStatus(eMessageStatus_failed),      m_ObjLevel(0){    AddCandidate(CObjectTypeInfo(CType<CSeq_entry>()));    AddCandidate(CObjectTypeInfo(CType<CBioseq>()));    AddCandidate(CObjectTypeInfo(CType<CBioseq_set>()));    AddCandidate(CObjectTypeInfo(CType<CSeq_annot>()));    AddCandidate(CObjectTypeInfo(CType<CSeq_align>()));    AddCandidate(CObjectTypeInfo(CType<CSeq_align_set>()));    AddCandidate(CObjectTypeInfo(CType<CSeq_submit>()));}void CSniffReader::Reset(){    m_ObjLevel = 0;}void CSniffReader::OnObjectFoundPre(const CObjectInfo& object,                                    size_t stream_offset){    if (m_ObjLevel == 0) {        OnTopObjectFoundPre(object, stream_offset);    }    ++m_ObjLevel;}void CSniffReader::OnObjectFoundPost(const CObjectInfo& object){    _ASSERT(m_ObjLevel > 0);    if (m_ObjLevel == 1) {        OnTopObjectFoundPost(object);    }    --m_ObjLevel;}void CSniffReader::OnTopObjectFoundPre(const CObjectInfo& object,                                       size_t stream_offset){}void CSniffReader::OnTopObjectFoundPost(const CObjectInfo& object){    m_FileLoader.Load(object, m_Document, m_Reply);    if (m_Reply.GetStatus() != eMessageStatus_failed) {        m_LoadStatus = m_Reply.GetStatus();    }}//// class CDataPlugin_FileLoaderException defines some internal exception types used in// processing files.//// This class is used internally to avoid an ad-hoc exception mechanism;// currently, it reports only errors concerning invalid format types.//class CDataPlugin_FileLoaderException : EXCEPTION_VIRTUAL_BASE public CException{public:    // Enumerated list of exception types    enum EErrCode {        eInvalidFormat    };    // Convert an enuerated exception to a human-readable string representation    // of this exception.    virtual const char* GetErrCodeString(void) const    {        switch (GetErrCode()) {        case eInvalidFormat:        return "eInvalidFormat";        default:                    return CException::GetErrCodeString();        }    }    // constructor boilerplate    NCBI_EXCEPTION_DEFAULT(CDataPlugin_FileLoaderException, CException);};//// factory implementations//typedef pair<const char*, CDataPlugin_FileLoader::EFormat> TFormatPair;static const TFormatPair sc_FormatArray[] = {    TFormatPair("Autodetect", CDataPlugin_FileLoader::eFormat_Autodetect),    TFormatPair("Binary ASN.1", CDataPlugin_FileLoader::eFormat_AsnBinary),    TFormatPair("FASTA sequence", CDataPlugin_FileLoader::eFormat_FastA),    TFormatPair("NCBI XML", CDataPlugin_FileLoader::eFormat_XML),    TFormatPair("Newick-format Phylogenetic Tree",                CDataPlugin_FileLoader::eFormat_NewickTree),    TFormatPair("Text ASN.1", CDataPlugin_FileLoader::eFormat_AsnText),    TFormatPair("Text alignment", CDataPlugin_FileLoader::eFormat_TextAlign),};typedef CStaticArrayMap<const char*, CDataPlugin_FileLoader::EFormat, PCase> TFormatMap;static const TFormatMap sc_Formats(sc_FormatArray, sizeof(sc_FormatArray));// define some brief synonyms for above stringsstatic const TFormatPair sc_SynFormatArray[] = {    TFormatPair("asnbin", CDataPlugin_FileLoader::eFormat_AsnBinary),    TFormatPair("asntext", CDataPlugin_FileLoader::eFormat_AsnText),    TFormatPair("auto", CDataPlugin_FileLoader::eFormat_Autodetect),    TFormatPair("fasta", CDataPlugin_FileLoader::eFormat_FastA),    TFormatPair("newick", CDataPlugin_FileLoader::eFormat_NewickTree),    TFormatPair("textalign", CDataPlugin_FileLoader::eFormat_TextAlign),    TFormatPair("xml", CDataPlugin_FileLoader::eFormat_XML),};static const TFormatMap sc_SynFormats(sc_SynFormatArray,                                      sizeof(sc_SynFormatArray));static CDataPlugin_FileLoader::EFormat s_GetFormatFromString(const string& fmt_str){    CDataPlugin_FileLoader::EFormat fmt = CDataPlugin_FileLoader::eFormat_Autodetect;    TFormatMap::const_iterator iter = sc_Formats.find(fmt_str.c_str());    if (iter != sc_Formats.end()) {        fmt = iter->second;    } else {        iter = sc_SynFormats.find(fmt_str.c_str());        if (iter != sc_SynFormats.end()) {            fmt = iter->second;        }    }    return fmt;}void CDataPlugin_FileLoader::GetInfo(CPluginInfo& info){    info.Reset();    // version info macro    info.SetInfo(CPluginVersion::eMajor, CPluginVersion::eMinor, 0,                 string(__DATE__) + " " + string(__TIME__),                 "CDataPlugin_FileLoader",                 "File", "File import", "");    CRef<CPluginValueConstraint> cons(CPluginValueConstraint::CreateSet());    {{        ITERATE (TFormatMap, iter, sc_Formats) {            *cons, iter->first;        }    }}    // command info    CPluginCommandSet& cmds     = info.SetCommands();    CPluginCommand& load_args   = cmds.AddDataCommand(eDataCommand_load);    load_args.AddArgument("file", "File name", CPluginArg::eFile);    load_args.AddDefaultArgument("fmt",  "Format", CPluginArg::eString,                                 "Autodetect");    load_args.SetConstraint("fmt", *cons);    CPluginCommand& import_args = cmds.AddDataCommand(eDataCommand_import);    import_args.AddArgument("document", "Document", CPluginArg::eDocument);    import_args.AddArgument("file", "File name", CPluginArg::eFile);    import_args.AddDefaultArgument("fmt",  "Format", CPluginArg::eString,                                   "Autodetect");    import_args.SetConstraint("fmt", *cons);}//// Default ctor//CDataPlugin_FileLoader::CDataPlugin_FileLoader(){}//// One and only dtor//CDataPlugin_FileLoader::~CDataPlugin_FileLoader(){}//// Load()// This is a pure virtual requirement and is the main plugin hook.// This function takes a parameterized request and attempts to perform the// requested tasks.  Loading an accession here is prohibited.  This function// calls a number of internal functions to try to determine what is the type of// file requested.//void CDataPlugin_FileLoader::Load(CPluginMessage& msg){    const CPluginCommand& args = msg.GetRequest().GetCommand();    CPluginReply& reply = msg.SetReply();    string fname   = args["file"].AsString();    if ( !CFile(fname).Exists() ) {        NcbiMessageBox("Failed to find file: " + fname);        return;    }    EFormat fmt = s_GetFormatFromString(args["fmt"].AsString());    x_LoadFile(fname, fmt, NULL, reply);    // on success, put in MRU list    if (reply.GetStatus() == eMessageStatus_success) {        int i = NStr::Find(fname, "/", 0, NPOS, NStr::eLast);        string label = "File: " + CFltkUtils::EscapeSpecialChars(fname);        CDocManager::AddMRUEntry(msg, label);    }}//// Import()// This is the main plugin hook.// This function takes a parameterized request and attempts to perform the// requested tasks.  Loading an accession here is prohibited.  This function// calls a number of internal functions to try to determine what is the type of// file requested.//void CDataPlugin_FileLoader::Import(CPluginMessage& msg){    const CPluginCommand& args = msg.GetRequest().GetCommand();    CPluginReply& reply = msg.SetReply();    IDocument& doc = const_cast<IDocument&>(args["document"].AsDocument());    string fname = args["file"].AsString();    if ( !CFile(fname).Exists() ) {        NcbiMessageBox("Failed to find file: " + fname);        return;    }    EFormat fmt = s_GetFormatFromString(args["fmt"].AsString());    x_LoadFile(fname, fmt, &doc, reply);}void CDataPlugin_FileLoader::x_LoadFile(const string& fname, EFormat user_fmt,                             IDocument* doc,

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?