Example #1
0
void TemplateManager::readTemplates(FileName const & path)
{
	PathChanger p(path);

	enum {
		TM_PREAMBLEDEF = 1,
		TM_PREAMBLEDEF_END,
		TM_TEMPLATE,
		TM_TEMPLATE_END
	};

	LexerKeyword templatetags[] = {
		{ "preambledef", TM_PREAMBLEDEF },
		{ "preambledefend", TM_PREAMBLEDEF_END },
		{ "template", TM_TEMPLATE },
		{ "templateend", TM_TEMPLATE_END }
	};

	Lexer lex(templatetags);

	FileName const filename = libFileSearch("", "external_templates");
	if (filename.empty() || !lex.setFile(filename)) {
		lex.printError("external::TemplateManager::readTemplates: "
			       "No template file");
		return;
	}

	char const * const preamble_end_tag =
		templatetags[TM_PREAMBLEDEF_END-1].tag;

	while (lex.isOK()) {
		switch (lex.lex()) {
		case TM_PREAMBLEDEF: {
			lex.next();
			string const name = lex.getString();
			preambledefs[name] = lex.getLongString(preamble_end_tag);
		}
		break;

		case TM_TEMPLATE: {
			lex.next();
			string const name = lex.getString();
			Template & tmp = templates[name];
			tmp.lyxName = name;
			tmp.readTemplate(lex);
		}
		break;

		case TM_TEMPLATE_END:
			lex.printError("Warning: End outside Template.");
		break;

		case TM_PREAMBLEDEF_END:
			lex.printError("Warning: End outside PreambleDef.");
		break;
		}
	}
}
Example #2
0
void Loader::Impl::resetFile(FileName const & file)
{
    FileName const old_file = cached_item_ ?
        cached_item_->filename() : FileName();

    if (file == old_file)
		return;

	// If monitoring() the current file, should continue to monitor the
	// new file.
	bool continue_monitoring = false;

    if (!old_file.empty()) {
		continue_monitoring = cached_item_->monitoring();
		// cached_item_ is going to be reset, so the connected
		// signal needs to be disconnected.
		sc_.disconnect();
		cached_item_.reset();
		if (status_ != Converting) {
			Cache::get().remove(old_file);
		} else {
			//TODO remove cache item when it is not busy any more, see #7163
		}
	}

	status_ = cached_item_ ? cached_item_->status() : WaitingToLoad;
	image_.reset();

    if (cached_item_ || file.empty())
		return;

	Cache & gc = Cache::get();
    if (!gc.inCache(file))
        gc.add(file);

	// We /must/ make a local copy of this.
    cached_item_ = gc.item(file);
	status_ = cached_item_->status();

	if (continue_monitoring && !cached_item_->monitoring())
		cached_item_->startMonitoring();

	sc_ = cached_item_->connect(bind(&Impl::statusChanged, this));
}
Example #3
0
bool File::Exists(FileName const& fn) {
  if (!fn.empty()) {
    FILE* infile = fopen(fn.full(), "rb");
    if (infile==0) {
      fileErrMsg_.assign( strerror(errno) );
      return false;
    }
    fclose(infile);
    return true;
  }
  return false;
}
Example #4
0
// ParmFile::ReadTopology()
int ParmFile::ReadTopology(Topology& Top, FileName const& fnameIn, 
                           ArgList const& argListIn, int debugIn) 
{
  if (fnameIn.empty()) {
    mprinterr("Error: No input topology name given.\n");
    return 1;
  }
  if (!File::Exists( fnameIn )) {
    mprinterr("Error: Topology '%s' does not exist.\n", fnameIn.full());
    return 1;
  }
  parmName_ = fnameIn;
  ArgList argIn = argListIn;
  ParmFormatType pfType;
  ParmIO* parmio = 0;
  Top.SetDebug( debugIn );
  // Only force bond search when 'bondsearch' is specified.
  bool bondsearch = false;
  if (argIn.Contains("bondsearch")) {
    Top.SetOffset( argIn.getKeyDouble("bondsearch", -1.0) );
    bondsearch = true;
  }
  // 'as' keyword specifies a format
  std::string as_arg = argIn.GetStringKey("as");
  if (!as_arg.empty()) {
    pfType = (ParmFormatType)FileTypes::GetFormatFromString( PF_KeyArray, as_arg, UNKNOWN_PARM );
    if (pfType == UNKNOWN_PARM) {
      mprinterr("Error: Topology format '%s' not recognized.\n", as_arg.c_str());
      return 1;
    }
    parmio = (ParmIO*)FileTypes::AllocIO( PF_AllocArray, pfType, false );
  } else
    parmio = DetectFormat( parmName_, pfType );
  if (parmio == 0) {
    mprinterr("Error: Could not determine format of topology '%s'\n", parmName_.full());
    return 1;
  }
  mprintf("\tReading '%s' as %s\n", parmName_.full(),
          FileTypes::FormatDescription(PF_AllocArray, pfType) );
  parmio->SetDebug( debugIn );
  if (parmio->processReadArgs(argIn)) return 1;
  int err = parmio->ReadParm( parmName_.Full(), Top);
  // Perform setup common to all parm files.
  if (err == 0) 
    err = Top.CommonSetup(bondsearch || parmio->NeedsBondSearch());
  else
    mprinterr("Error reading topology file '%s'\n", parmName_.full());
  delete parmio;
  if (err > 0) return 1;
  return 0;
}
Example #5
0
bool ConverterCache::copy(FileName const & orig_from, string const & to_format,
		FileName const & dest) const
{
	if (!lyxrc.use_converter_cache || orig_from.empty() || dest.empty())
		return false;
	LYXERR(Debug::FILES, orig_from << ' ' << to_format << ' ' << dest);

	// FIXME: Should not hardcode this (see bug 3819 for details)
	if (to_format == "pstex") {
		FileName const dest_eps(changeExtension(dest.absFileName(), "eps"));
		if (!copy(orig_from, "eps", dest_eps))
			return false;
	} else if (to_format == "pdftex") {
		FileName const dest_pdf(changeExtension(dest.absFileName(), "pdf"));
		if (!copy(orig_from, "pdf", dest_pdf))
			return false;
	}

	CacheItem * const item = pimpl_->find(orig_from, to_format);
	LASSERT(item, /**/);
	Mover const & mover = getMover(to_format);
	return mover.copy(item->cache_name, dest,
	                  onlyFileName(dest.absFileName()));
}
Example #6
0
string const LyXVC::getLogFile() const
{
	if (!vcs)
		return string();

	TempFile tempfile("lyxvclog");
	tempfile.setAutoRemove(false);
	FileName const tmpf = tempfile.name();
	if (tmpf.empty()) {
		LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
		return string();
	}
	LYXERR(Debug::LYXVC, "Generating logfile " << tmpf);
	vcs->getLog(tmpf);
	return tmpf.absFileName();
}
Example #7
0
void ConverterCache::remove(FileName const & orig_from,
		string const & to_format) const
{
	if (!lyxrc.use_converter_cache || orig_from.empty())
		return;
	LYXERR(Debug::FILES, orig_from << ' ' << to_format);

	CacheType::iterator const it1 = pimpl_->cache.find(orig_from);
	if (it1 == pimpl_->cache.end())
		return;
	FormatCacheType & format_cache = it1->second.cache;
	FormatCacheType::iterator const it2 = format_cache.find(to_format);
	if (it2 == format_cache.end())
		return;

	format_cache.erase(it2);
	if (format_cache.empty())
		pimpl_->cache.erase(it1);
}
Example #8
0
/** Add lowest replica file name and names from comma-separated list. */
int TrajIOarray::AddReplicasFromArgs(FileName const& name0,
                                     std::string const& commaNames)
{
  if (name0.empty()) return 1;
  if (!File::Exists( name0 )) {
    File::ErrorMsg( name0.full() );
    return 1;
  }
  replica_filenames_.push_back( name0 );
  ArgList remdtraj_list( commaNames, "," );
  for (ArgList::const_iterator fname = remdtraj_list.begin();
                               fname != remdtraj_list.end(); ++fname)
  {
    FileName trajFilename( *fname );
    if (!File::Exists( trajFilename )) {
      File::ErrorMsg( trajFilename.full() );
      return 1;
    }
    replica_filenames_.push_back( trajFilename );
  }
  return 0;
}
Example #9
0
/** Each rank checks that specified file is present. */
int TrajIOarray::AddReplicasFromArgs(FileName const& name0,
                                     std::string const& commaNames,
                                     Parallel::Comm const& ensComm,
                                     Parallel::Comm const& trajComm)
{
  // First set up filename array on all ranks.
  if (name0.empty()) return 1;
  replica_filenames_.push_back( name0 );
  ArgList remdtraj_list( commaNames, "," );
  for (ArgList::const_iterator fname = remdtraj_list.begin();
                               fname != remdtraj_list.end(); ++fname)
    replica_filenames_.push_back( FileName( *fname ) );
  if (ensComm.Size() != (int)replica_filenames_.size())
    return 1;
  else if (trajComm.Master()) { // Only traj comm master checks file
    if (!File::Exists( replica_filenames_[ ensComm.Rank() ])) {
      File::ErrorMsg( replica_filenames_[ensComm.Rank()].full() );
      rprinterr("Error: File '%s' not accessible.\n", replica_filenames_[ensComm.Rank()].full());
      return 1;
    }
  }
  return 0;
}
Example #10
0
int main(int argc, char * argv[])
{
	using namespace lyx;

	//setlocale(LC_CTYPE, "");

	lyxerr.setStream(cerr);

	os::init(argc, argv);

	easyParse(argc, argv);

	if (argc <= 1) 
		error_message("Not enough arguments.");

	try {
		init_package(internal_path(os::utf8_argv(0)),
			     cl_system_support, cl_user_support,
			     top_build_dir_is_two_levels_up);
	} catch (ExceptionMessage const & message) {
		cerr << to_utf8(message.title_) << ":\n"
		     << to_utf8(message.details_) << endl;
		if (message.type_ == ErrorException)
			return EXIT_FAILURE;
	}

	// Now every known option is parsed. Look for input and output
	// file name (the latter is optional).
	string infilename = internal_path(os::utf8_argv(1));
	infilename = makeAbsPath(infilename).absFileName();

	string outfilename;
	if (roundtrip) {
		if (argc > 2) {
			// Do not allow a user supplied output filename
			// (otherwise it could easily happen that LyX would
			// overwrite the original .tex file)
			cerr << "Error: output filename must not be given in roundtrip mode."
			     << endl;
			return EXIT_FAILURE;
		}
		outfilename = changeExtension(infilename, ".lyx.lyx");
	} else if (argc > 2) {
		outfilename = internal_path(os::utf8_argv(2));
		if (outfilename != "-")
			outfilename = makeAbsPath(outfilename).absFileName();
	} else
		outfilename = changeExtension(infilename, ".lyx");

	// Read the syntax tables
	FileName const system_syntaxfile = libFileSearch("", "syntax.default");
	if (system_syntaxfile.empty()) {
		cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
		return EXIT_FAILURE;
	}
	read_syntaxfile(system_syntaxfile);
	if (!syntaxfile.empty())
		read_syntaxfile(makeAbsPath(syntaxfile));

	// Read the encodings table.
	FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
	if (symbols_path.empty()) {
		cerr << "Error: Could not find file \"unicodesymbols\"." 
		     << endl;
		return EXIT_FAILURE;
	}
	FileName const enc_path = libFileSearch(string(), "encodings");
	if (enc_path.empty()) {
		cerr << "Error: Could not find file \"encodings\"." 
		     << endl;
		return EXIT_FAILURE;
	}
	encodings.read(enc_path, symbols_path);
	if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
		error_message("Unknown LaTeX encoding `" + default_encoding + "'");

	// Load the layouts
	LayoutFileList::get().read();
	//...and the modules
	theModuleList.read();

	// The real work now.
	masterFilePath = onlyPath(infilename);
	parentFilePath = masterFilePath;
	if (outfilename == "-") {
		if (tex2lyx(FileName(infilename), cout, default_encoding))
			return EXIT_SUCCESS;
	} else if (roundtrip) {
		if (tex2tex(infilename, FileName(outfilename), default_encoding))
			return EXIT_SUCCESS;
	} else {
		if (tex2lyx(infilename, FileName(outfilename), default_encoding))
			return EXIT_SUCCESS;
	}
	return EXIT_FAILURE;
}
Example #11
0
void ConverterCache::add(FileName const & orig_from, string const & to_format,
		FileName const & converted_file) const
{
	if (!lyxrc.use_converter_cache || orig_from.empty() ||
	    converted_file.empty())
		return;
	LYXERR(Debug::FILES, ' ' << orig_from
			     << ' ' << to_format << ' ' << converted_file);

	// FIXME: Should not hardcode this (see bug 3819 for details)
	if (to_format == "pstex") {
		FileName const converted_eps(changeExtension(converted_file.absFileName(), "eps"));
		add(orig_from, "eps", converted_eps);
	} else if (to_format == "pdftex") {
		FileName const converted_pdf(changeExtension(converted_file.absFileName(), "pdf"));
		add(orig_from, "pdf", converted_pdf);
	}

	// Is the file in the cache already?
	CacheItem * item = pimpl_->find(orig_from, to_format);

	time_t const timestamp = orig_from.lastModified();
	Mover const & mover = getMover(to_format);
	if (item) {
		LYXERR(Debug::FILES, "ConverterCache::add(" << orig_from << "):\n"
					"The file is already in the cache.");
		// First test for timestamp
		if (timestamp == item->timestamp) {
			LYXERR(Debug::FILES, "Same timestamp.");
			return;
		}
		// Maybe the contents is still the same?
		item->timestamp = timestamp;
		unsigned long const checksum = orig_from.checksum();
		if (checksum == item->checksum) {
			LYXERR(Debug::FILES, "Same checksum.");
			return;
		}
		item->checksum = checksum;
		if (!mover.copy(converted_file, item->cache_name,
		              onlyFileName(item->cache_name.absFileName()))) {
			LYXERR(Debug::FILES, "Could not copy file " << orig_from << " to "
				<< item->cache_name);
		} else if (!item->cache_name.changePermission(0600)) {
			LYXERR(Debug::FILES, "Could not change file mode"
				<< item->cache_name);
		}
	} else {
		CacheItem new_item(orig_from, to_format, timestamp,
				orig_from.checksum());
		if (mover.copy(converted_file, new_item.cache_name,
		              onlyFileName(new_item.cache_name.absFileName()))) {
			if (!new_item.cache_name.changePermission(0600)) {
				LYXERR(Debug::FILES, "Could not change file mode"
					<< new_item.cache_name);
			}
			FormatCache & format_cache = pimpl_->cache[orig_from];
			if (format_cache.from_format.empty())
				format_cache.from_format =
					formats.getFormatFromFile(orig_from);
			format_cache.cache[to_format] = new_item;
		} else
			LYXERR(Debug::FILES, "ConverterCache::add(" << orig_from << "):\n"
						"Could not copy file.");
	}
}
// Action_NativeContacts::Init()
Action::RetType Action_NativeContacts::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
# ifdef MPI
  trajComm_ = init.TrajComm();
# endif
  masterDSL_ = init.DslPtr();
  debug_ = debugIn;
  // Get Keywords
  image_.InitImaging( !(actionArgs.hasKey("noimage")) );
  double dist = actionArgs.getKeyDouble("distance", 7.0);
  byResidue_ = actionArgs.hasKey("byresidue");
  resoffset_ = actionArgs.getKeyInt("resoffset", 0) + 1;
  if (resoffset_ < 1) {
    mprinterr("Error: Residue offset must be >= 0\n");
    return Action::ERR;
  }
  includeSolvent_ = actionArgs.hasKey("includesolvent");
  series_ = actionArgs.hasKey("series");
  saveNonNative_ = actionArgs.hasKey("savenonnative");
  if (actionArgs.hasKey("skipnative"))
    determineNativeContacts_ = false;
  if (!determineNativeContacts_ && !saveNonNative_) {
    mprintf("Warning: 'skipnative' specified; implies 'savenonnative'.\n");
    saveNonNative_ = true;
  }
# ifdef MPI
  if (saveNonNative_) {
    mprinterr("Error: Saving non-native contact data not yet supported for MPI\n");
    return Action::ERR;
  }
# endif
  distance_ = dist * dist; // Square the cutoff
  first_ = actionArgs.hasKey("first");
  DataFile* outfile = init.DFL().AddDataFile( actionArgs.GetStringKey("out"), actionArgs );
  Rseries_ = NO_RESSERIES;
  if (series_) {
    seriesout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("seriesout"), actionArgs);
    init.DSL().SetDataSetsPending( true );
    if (saveNonNative_)
      seriesNNout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("seriesnnout"), actionArgs);
    std::string rs_arg = actionArgs.GetStringKey("resseries");
    if (!rs_arg.empty()) {
      if (rs_arg == "present")
        Rseries_ = RES_PRESENT;
      else if (rs_arg == "sum")
        Rseries_ = RES_SUM;
      else {
        mprinterr("Error: '%s' is not a valid 'resseries' keyword.\n", rs_arg.c_str());
        return Action::ERR;
      }
      seriesRout_ = init.DFL().AddDataFile(actionArgs.GetStringKey("resseriesout"), actionArgs);
    }
  } else {
    if (KeywordError(actionArgs,"seriesout")) return Action::ERR;
    if (KeywordError(actionArgs,"seriesnnout")) return Action::ERR;
    if (KeywordError(actionArgs,"resseries")) return Action::ERR;
    if (KeywordError(actionArgs,"resseriesout")) return Action::ERR;
  }
  cfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("writecontacts"), "Native Contacts",
                               DataFileList::TEXT, true);
  pfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("contactpdb"), "Contact PDB",
                               DataFileList::PDB);
  if (saveNonNative_)
    nfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("nncontactpdb"),
                                       "Non-native Contact PDB", DataFileList::PDB);
  rfile_ = init.DFL().AddCpptrajFile(actionArgs.GetStringKey("resout"), "Contact Res Pairs",
                               DataFileList::TEXT, true);
  if (cfile_ == 0 || rfile_ == 0) return Action::ERR;
  pdbcut_ = (float)actionArgs.getKeyDouble("pdbcut", -1.0);
  usepdbcut_ = (pdbcut_ > -1.0);
  // Get reference for native contacts. Do this even if we wont be
  // determining native contacts in order to set up contact lists.
  ReferenceFrame REF = init.DSL().GetReferenceFrame( actionArgs );
  if (!first_) {
    if (REF.error()) return Action::ERR;
    if (REF.empty()) {
      mprintf("Warning: No reference structure specified. Defaulting to first.\n");
      first_ = true;
    }
  } else {
    if (!REF.empty()) {
      mprinterr("Error: Must only specify 'first' or a reference structure, not both.\n");
      return Action::ERR;
    }
  }
  
  // Create data sets
  std::string name = actionArgs.GetStringKey("name");
  if (name.empty())
    name = init.DSL().GenerateDefaultName("Contacts");
  numnative_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(name, "native"));
  nonnative_ = init.DSL().AddSet(DataSet::INTEGER, MetaData(name, "nonnative"));
  if (outfile != 0) {
    outfile->AddDataSet(numnative_);
    outfile->AddDataSet(nonnative_);
  }
  if (numnative_ == 0 || nonnative_ == 0) return Action::ERR;
  if (actionArgs.hasKey("mindist")) {
    mindist_ = init.DSL().AddSet(DataSet::DOUBLE, MetaData(name, "mindist"));
    if (mindist_ == 0) return Action::ERR;
    if (outfile != 0) outfile->AddDataSet(mindist_);
  }
  if (actionArgs.hasKey("maxdist")) {
    maxdist_ = init.DSL().AddSet(DataSet::DOUBLE, MetaData(name, "maxdist"));
    if (maxdist_ == 0) return Action::ERR;
    if (outfile != 0) outfile->AddDataSet(maxdist_);
  }
  DataFile *natmapfile = 0, *nonmapfile = 0;
  if (actionArgs.hasKey("map")) {
    nativeMap_ = (DataSet_MatrixDbl*)init.DSL().AddSet(DataSet::MATRIX_DBL, MetaData(name, "nativemap"));
    if (nativeMap_ == 0) return Action::ERR;
    nonnatMap_ = (DataSet_MatrixDbl*)init.DSL().AddSet(DataSet::MATRIX_DBL, MetaData(name, "nonnatmap"));
    if (nonnatMap_ == 0) return Action::ERR;
    FileName mapFilename;
    mapFilename.SetFileName( actionArgs.GetStringKey("mapout") );
    if (!mapFilename.empty()) {
      natmapfile = init.DFL().AddDataFile(mapFilename.PrependFileName("native."));
      if (natmapfile != 0) natmapfile->AddDataSet(nativeMap_);
      nonmapfile = init.DFL().AddDataFile(mapFilename.PrependFileName("nonnative."));
      if (nonmapfile != 0) nonmapfile->AddDataSet(nonnatMap_);
    }
  }
  // Get Masks
  if (Mask1_.SetMaskString( actionArgs.GetMaskNext() )) return Action::ERR;
  std::string mask2 = actionArgs.GetMaskNext();
  if (!mask2.empty()) {
    if (Mask2_.SetMaskString( mask2 )) return Action::ERR;
  }
  mprintf("    NATIVECONTACTS: Mask1='%s'", Mask1_.MaskString());
  if (Mask2_.MaskStringSet())
    mprintf(" Mask2='%s'", Mask2_.MaskString());
  if (determineNativeContacts_) {
    mprintf(", native contacts set up based on");
    if (first_)
      mprintf(" first frame.\n");
    else
      mprintf("'%s'.\n", REF.refName());
  } else {
    mprintf(", skipping native contacts set up.\n");
  }
  if (byResidue_) {
    mprintf("\tContacts will be ignored for residues spaced < %i apart.\n", resoffset_);
    if (nativeMap_ != 0)
      mprintf("\tMap will be printed by residue.\n");
  }
  if (saveNonNative_)
    mprintf("\tSaving non-native contacts as well (may use a lot of memory).\n");
  mprintf("\tDistance cutoff is %g Angstroms,", sqrt(distance_));
  if (!image_.UseImage())
    mprintf(" imaging is off.\n");
  else
    mprintf(" imaging is on.\n");
  if (includeSolvent_)
    mprintf("\tMask selection will including solvent.\n");
  else
    mprintf("\tMask selection will not include solvent.\n");
  mprintf("\tData set name: %s\n", name.c_str());
  if (maxdist_ != 0)
    mprintf("\tSaving maximum observed distances in set '%s'\n", maxdist_->legend());
  if (mindist_ != 0)
    mprintf("\tSaving minimum observed distances in set '%s'\n", mindist_->legend());
  if (outfile != 0)
    mprintf("\tOutput to '%s'\n", outfile->DataFilename().full());
  mprintf("\tContact stats will be written to '%s'\n", cfile_->Filename().full());
  mprintf("\tContact res pairs will be written to '%s'\n", rfile_->Filename().full());
  if (pfile_ != 0) {
    mprintf("\tContact PDB will be written to '%s'\n", pfile_->Filename().full());
    if (usepdbcut_) mprintf("\tOnly atoms with values > %g will be written to PDB.\n", pdbcut_);
  }
  if (nfile_ != 0) {
    mprintf("\tNon-native contact PDB will be written to '%s'\n", nfile_->Filename().full());
    if (usepdbcut_) mprintf("\tOnly atoms with values > %g will be written to PDB.\n", pdbcut_);
  }
  if (nativeMap_ != 0) {
    mprintf("\tNative contacts map will be saved as set '%s'\n"
            "\tNon-native contacts map will be saved as set '%s'\n",
            nativeMap_->legend(), nonnatMap_->legend());
    if (natmapfile!=0) mprintf("\tNative map output to '%s'\n",natmapfile->DataFilename().full());
    if (nonmapfile!=0) mprintf("\tNative map output to '%s'\n",nonmapfile->DataFilename().full());
  }
  if (series_) {
    mprintf("\tSaving native contact time series %s[NC].\n", name.c_str());
    if (seriesout_ != 0) mprintf("\tWriting native contact time series to %s\n",
                                 seriesout_->DataFilename().full());
    if (saveNonNative_) {
      mprintf("\tSaving non-native contact time series %s[NN]\n", name.c_str());
      if (seriesNNout_ != 0) mprintf("\tWriting non-native contact time series to %s\n",
                                     seriesNNout_->DataFilename().full());
    }
    if (Rseries_ != NO_RESSERIES) {
      if (Rseries_ == RES_PRESENT)
        mprintf("\tResidue contact time series will reflect presence of individual contacts.\n");
      else if (Rseries_ == RES_SUM)
        mprintf("\tResidue contact time series will reflect sum of individual contacts.\n");
      if (seriesRout_ != 0) mprintf("\tWriting residue contact time series to %s\n",
                                    seriesRout_->DataFilename().full());
    }
  }
  // Set up reference if necessary.
  if (!first_) {
    // Set up imaging info for ref parm
    image_.SetupImaging( REF.CoordsInfo().TrajBox().Type() );
    if (image_.ImageType() == NONORTHO)
      REF.Coord().BoxCrd().ToRecip(ucell_, recip_);
    if (DetermineNativeContacts( REF.Parm(), REF.Coord() )) return Action::ERR;
  }
  return Action::OK;
}
Example #13
0
FileName GuiClipboard::getAsGraphics(Cursor const & cur, GraphicsType type) const
{
	// get the filename from the user
	FileName filename = getPastedGraphicsFileName(cur, type);
	if (filename.empty())
		return FileName();

	// handle image cases first
	if (type == PngGraphicsType || type == JpegGraphicsType) {
		// get image from QImage from clipboard
		QImage image = qApp->clipboard()->image();
		if (image.isNull()) {
			LYXERR(Debug::ACTION, "No image in clipboard");
			return FileName();
		}

		// convert into graphics format
		QByteArray ar;
		QBuffer buffer(&ar);
		buffer.open(QIODevice::WriteOnly);
		if (type == PngGraphicsType)
			image.save(toqstr(filename.absFileName()), "PNG");
		else if (type == JpegGraphicsType)
			image.save(toqstr(filename.absFileName()), "JPEG");
		else
			LATTEST(false);
		
		return filename;
	}
	
	// get mime for type
	QString mime;
	switch (type) {
	case PdfGraphicsType: mime = pdfMimeType(); break;
	case LinkBackGraphicsType: mime = pdfMimeType(); break;
	case EmfGraphicsType: mime = emfMimeType(); break;
	case WmfGraphicsType: mime = wmfMimeType(); break;
	default: LASSERT(false, return FileName());
	}
	
	// get data
	if (!cache_.hasFormat(mime))
		return FileName();
	// data from ourself or some other LyX instance
	QByteArray const ar = cache_.data(mime);
	LYXERR(Debug::ACTION, "Getting from clipboard: mime = " << mime.constData()
	       << "length = " << ar.count());

	QFile f(toqstr(filename.absFileName()));
	if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		LYXERR(Debug::ACTION, "Error opening file "
		       << filename.absFileName() << " for writing");
		return FileName();
	}
	
	// write the (LinkBack) PDF data
	f.write(ar);
	if (type == LinkBackGraphicsType) {
#ifdef Q_WS_MACX
		void const * linkBackData;
		unsigned linkBackLen;
		getLinkBackData(&linkBackData, &linkBackLen);
		f.write((char *)linkBackData, linkBackLen);
		quint32 pdfLen = ar.size();
		QDataStream ds(&f);
		ds << pdfLen; // big endian by default
#else
		// only non-Mac this should never happen
		LATTEST(false);
#endif // Q_WS_MACX
	}

	f.close();
	return filename;
}
Example #14
0
// Much of this is borrowed from LayoutFileList::read()
bool ModuleList::read()
{
	FileName const real_file = libFileSearch("", "lyxmodules.lst");
	LYXERR(Debug::TCLASS, "Reading modules from `" << real_file << '\'');

	if (real_file.empty()) {
		LYXERR0("unable to find modules file `lyxmodules.lst'.\n"
			<< "No modules will be available.");
		return false;
	}

	Lexer lex;
	if (!lex.setFile(real_file)) {
		LYXERR0("lyxlex was not able to set file: "
			<< real_file << ".\nNo modules will be available.");
		return false;
	}

	if (!lex.isOK()) {
		LYXERR0("unable to open modules file  `"
			<< to_utf8(makeDisplayPath(real_file.absFileName(), 1000))
			<< "'\nNo modules will be available.");
		return false;
	}

	bool finished = false;
	// Parse modules files
	LYXERR(Debug::TCLASS, "Starting parsing of lyxmodules.lst");
	while (lex.isOK() && !finished) {
		LYXERR(Debug::TCLASS, "\tline by line");
		switch (lex.lex()) {
		case Lexer::LEX_FEOF:
			finished = true;
			break;
		default:
			string const modname = lex.getString();
			LYXERR(Debug::TCLASS, "Module name: " << modname);
			if (!lex.next())
				break;
			string const fname = lex.getString();
			LYXERR(Debug::TCLASS, "Filename: " << fname);
			if (!lex.next(true))
				break;
			string const desc = lex.getString();
			LYXERR(Debug::TCLASS, "Description: " << desc);
			//FIXME Add packages
			if (!lex.next())
				break;
			string str = lex.getString();
			LYXERR(Debug::TCLASS, "Packages: " << str);
			vector<string> pkgs;
			while (!str.empty()) {
				string p;
				str = split(str, p, ',');
				pkgs.push_back(p);
			}
			if (!lex.next())
				break;
			str = lex.getString();
			LYXERR(Debug::TCLASS, "Required: " << str);
			vector<string> req;
			while (!str.empty()) {
				string p;
				str = split(str, p, '|');
				req.push_back(p);
			}
			if (!lex.next())
				break;
			str = lex.getString();
			LYXERR(Debug::TCLASS, "Excluded: " << str);
			vector<string> exc;
			while (!str.empty()) {
				string p;
				str = split(str, p, '|');
				exc.push_back(p);
			}
			if (!lex.next())
				break;
			string const catgy = lex.getString();
			LYXERR(Debug::TCLASS, "Category: " << catgy);
			if (!lex.next())
				break;
			bool const local = lex.getString() == "true";
			LYXERR(Debug::TCLASS, "Local: " << local);
			// This code is run when we have
			// modName, fname, desc, pkgs, req, exc, catgy, and local
			addLayoutModule(modname, fname, desc, pkgs, req, exc, catgy, local);
		} // end switch
	} //end while

	LYXERR(Debug::TCLASS, "End of parsing of lyxmodules.lst");

	if (!theModuleList.empty())
		sort(theModuleList.begin(), theModuleList.end(), ModuleSorter());
	return true;
}
Example #15
0
// Action_Spam::init()
Action::RetType Action_Spam::Init(ArgList& actionArgs, TopologyList* PFL, DataSetList* DSL, DataFileList* DFL, int debugIn)
{
  // Always use imaged distances
  InitImaging(true);
  // This is needed everywhere in this function scope
  FileName filename;

  // See if we're doing pure water. If so, we don't need a peak file
  purewater_ = actionArgs.hasKey("purewater");

  if (purewater_) {
    // We still need the cutoff
    double cut = actionArgs.getKeyDouble("cut", 12.0);
    cut2_ = cut * cut;
    doublecut_ = 2 * cut;
    onecut2_ = 1 / cut2_;
    // See if we write to a data file
    datafile_ = actionArgs.GetStringKey("out");
    // Generate the data set name, and hold onto the master data set list
    std::string ds_name = actionArgs.GetStringKey("name");
    if (ds_name.empty())
      ds_name = myDSL_.GenerateDefaultName("SPAM");
    // We only have one data set averaging over every water. Add it here
    myDSL_.AddSet(DataSet::DOUBLE, ds_name, NULL);
    solvname_ = actionArgs.GetStringKey("solv");
    if (solvname_.empty())
      solvname_ = std::string("WAT");
  }else {
    // Get the file name with the peaks defined in it
    filename.SetFileName( actionArgs.GetStringNext() );

    if (filename.empty() || !File::Exists(filename)) {
      mprinterr("Spam: Error: Peak file [%s] does not exist!\n", filename.full());
      return Action::ERR;
    }

    // Get the remaining optional arguments
    solvname_ = actionArgs.GetStringKey("solv");
    if (solvname_.empty())
      solvname_ = std::string("WAT");
    reorder_ = actionArgs.hasKey("reorder");
    bulk_ = actionArgs.getKeyDouble("bulk", 0.0);
    double cut = actionArgs.getKeyDouble("cut", 12.0);
    cut2_ = cut * cut;
    doublecut_ = 2 * cut;
    onecut2_ = 1 / cut2_;
    std::string infoname = actionArgs.GetStringKey("info");
    if (infoname.empty())
      infoname = std::string("spam.info");
    infofile_ = DFL->AddCpptrajFile(infoname, "SPAM info");
    if (infofile_ == 0) return Action::ERR;
    // The default maskstr is the Oxygen atom of the solvent
    summaryfile_ = actionArgs.GetStringKey("summary");
    // Divide site size by 2 to make it half the edge length (or radius)
    site_size_ = actionArgs.getKeyDouble("site_size", 2.5) / 2.0;
    sphere_ = actionArgs.hasKey("sphere");
    // If it's a sphere, square the radius to compare with
    if (sphere_)
      site_size_ *= site_size_;
    datafile_ = actionArgs.GetStringKey("out");
    std::string ds_name = actionArgs.GetStringKey("name");
    if (ds_name.empty())
      ds_name = myDSL_.GenerateDefaultName("SPAM");

    // Parse through the peaks file and extract the peaks
    CpptrajFile peakfile;
    if (peakfile.OpenRead(filename)) {
      mprinterr("SPAM: Error: Could not open %s for reading!\n", filename.full());
      return Action::ERR;
    }
    std::string line = peakfile.GetLine();
    int npeaks = 0;
    while (!line.empty()) {
      if (sscanf(line.c_str(), "%d", &npeaks) != 1) {
        line = peakfile.GetLine();
        continue;
      }
      line = peakfile.GetLine();
      break;
    }
    while (!line.empty()) {
      double x, y, z, dens;
      if (sscanf(line.c_str(), "C %lg %lg %lg %lg", &x, &y, &z, &dens) != 4) {
        line = peakfile.GetLine();
        continue;
      }
      line = peakfile.GetLine();
      peaks_.push_back(Vec3(x, y, z));
    }
    peakfile.CloseFile();
    // Check that our initial number of peaks matches our parsed peaks. Warn
    // otherwise
    if (npeaks != (int)peaks_.size())
      mprinterr("SPAM: Warning: %s claims to have %d peaks, but really has %d!\n",
                filename.full(), npeaks, peaks_.size());
    // Now add all of the data sets
    MetaData md(ds_name);
    for (int i = 0; i < (int)peaks_.size(); i++) {
      md.SetAspect( integerToString(i+1) ); // TODO: Should this be Idx?
      if (myDSL_.AddSet(DataSet::DOUBLE, md) == 0) return Action::ERR;
      // Add a new list of integers to keep track of omitted frames
      std::vector<int> vec;
      peakFrameData_.push_back(vec);
    }
  }

  // Print info now
  if (purewater_) {
    mprintf("SPAM: Calculating bulk value for pure solvent\n");
    if (!datafile_.empty())
      mprintf("SPAM: Printing solvent energies to %s\n", datafile_.c_str());
    mprintf("SPAM: Using a %.2f Angstrom non-bonded cutoff with shifted EEL.\n",
            sqrt(cut2_));
    if (reorder_)
      mprintf("SPAM: Warning: Re-ordering makes no sense for pure solvent.\n");
    if (!summaryfile_.empty())
      mprintf("SPAM: Printing solvent SPAM summary to %s\n", summaryfile_.c_str());
  }else {
    mprintf("SPAM: Solvent [%s] density peaks taken from %s.\n",
            solvname_.c_str(), filename.base());
    mprintf("SPAM: %d density peaks will be analyzed from %s.\n",
            peaks_.size(), filename.base());
    mprintf("SPAM: Occupation information printed to %s.\n", infofile_->Filename().full());
    mprintf("SPAM: Sites are ");
    if (sphere_)
      mprintf("spheres with diameter %.3lf\n", site_size_);
    else
      mprintf("boxes with edge length %.3lf\n", site_size_);
    if (reorder_) {
      mprintf("SPAM: Re-ordering trajectory so each site always has ");
      mprintf("the same water molecule.\n");
    }
    if (summaryfile_.empty() && datafile_.empty()) {
      if (!reorder_) {
        mprinterr("SPAM: Error: Not re-ordering trajectory or calculating energies. ");
        mprinterr("Nothing to do!\n");
        return Action::ERR;
      }
      mprintf("SPAM: Not calculating any SPAM energies\n");
    }else {
      mprintf("SPAM: Using a non-bonded cutoff of %.2lf Ang. with a EEL shifting function.\n",
              sqrt(cut2_));
      mprintf("SPAM: Bulk solvent SPAM energy taken as %.3lf kcal/mol\n", bulk_);
    }
  }
  mprintf("#Citation: Cui, G.; Swails, J.M.; Manas, E.S.; \"SPAM: A Simple Approach\n"
          "#          for Profiling Bound Water Molecules\"\n"
          "#          J. Chem. Theory Comput., 2013, 9 (12), pp 5539–5549.\n");

  return Action::OK;
}
Example #16
0
// Reads a textclass structure from file.
TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
{
	if (!lexrc.isOK())
		return ERROR;

	// Format of files before the 'Format' tag was introduced
	int format = 1;
	bool error = false;

	// parsing
	while (lexrc.isOK() && !error) {
		int le = lexrc.lex();

		switch (le) {
		case Lexer::LEX_FEOF:
			continue;

		case Lexer::LEX_UNDEF:
			lexrc.printError("Unknown TextClass tag `$$Token'");
			error = true;
			continue;

		default:
			break;
		}

		// used below to track whether we are in an IfStyle or IfCounter tag.
		bool ifstyle    = false;
		bool ifcounter  = false;

		switch (static_cast<TextClassTags>(le)) {

		case TC_FORMAT:
			if (lexrc.next())
				format = lexrc.getInteger();
			break;

		case TC_OUTPUTFORMAT:
			if (lexrc.next())
				outputFormat_ = lexrc.getString();
			break;

		case TC_OUTPUTTYPE:
			readOutputType(lexrc);
			switch(outputType_) {
			case LATEX:
				outputFormat_ = "latex";
				break;
			case DOCBOOK:
				outputFormat_ = "docbook";
				break;
			case LITERATE:
				outputFormat_ = "literate";
				break;
			}
			break;

		case TC_INPUT: // Include file
			if (lexrc.next()) {
				string const inc = lexrc.getString();
				FileName tmp = libFileSearch("layouts", inc,
							    "layout");

				if (tmp.empty()) {
					lexrc.printError("Could not find input file: " + inc);
					error = true;
				} else if (!read(tmp, MERGE)) {
					lexrc.printError("Error reading input file: " + tmp.absFileName());
					error = true;
				}
			}
			break;

		case TC_DEFAULTSTYLE:
			if (lexrc.next()) {
				docstring const name = from_utf8(subst(lexrc.getString(),
							  '_', ' '));
				defaultlayout_ = name;
			}
			break;

		case TC_IFSTYLE:
			ifstyle = true;
			// fall through
		case TC_STYLE: {
			if (!lexrc.next()) {
				lexrc.printError("No name given for style: `$$Token'.");
				error = true;
				break;
			}
			docstring const name = from_utf8(subst(lexrc.getString(),
							'_', ' '));
			if (name.empty()) {
				string s = "Could not read name for style: `$$Token' "
					+ lexrc.getString() + " is probably not valid UTF-8!";
				lexrc.printError(s);
				Layout lay;
				// Since we couldn't read the name, we just scan the rest
				// of the style and discard it.
				error = !readStyle(lexrc, lay);
			} else if (hasLayout(name)) {
				Layout & lay = operator[](name);
				error = !readStyle(lexrc, lay);
			} else if (!ifstyle) {
				Layout layout;
				layout.setName(name);
				error = !readStyle(lexrc, layout);
				if (!error)
					layoutlist_.push_back(layout);

				if (defaultlayout_.empty()) {
					// We do not have a default layout yet, so we choose
					// the first layout we encounter.
					defaultlayout_ = name;
				}
			}
			else {
				// this was an ifstyle where we didn't have the style
				// scan the rest and discard it
				Layout lay;
				readStyle(lexrc, lay);
			}

			// reset flag
			ifstyle = false;
			break;
		}

		case TC_NOSTYLE:
			if (lexrc.next()) {
				docstring const style = from_utf8(subst(lexrc.getString(),
						     '_', ' '));
				if (!deleteLayout(style))
					lyxerr << "Cannot delete style `"
					       << to_utf8(style) << '\'' << endl;
			}
			break;

		case TC_COLUMNS:
			if (lexrc.next())
				columns_ = lexrc.getInteger();
			break;

		case TC_SIDES:
			if (lexrc.next()) {
				switch (lexrc.getInteger()) {
				case 1: sides_ = OneSide; break;
				case 2: sides_ = TwoSides; break;
				default:
					lyxerr << "Impossible number of page"
						" sides, setting to one."
					       << endl;
					sides_ = OneSide;
					break;
				}
			}
			break;

		case TC_PAGESTYLE:
			lexrc.next();
			pagestyle_ = rtrim(lexrc.getString());
			break;

		case TC_DEFAULTFONT:
			defaultfont_ = lyxRead(lexrc);
			if (!defaultfont_.resolved()) {
				lexrc.printError("Warning: defaultfont should "
						 "be fully instantiated!");
				defaultfont_.realize(sane_font);
			}
			break;

		case TC_SECNUMDEPTH:
			lexrc.next();
			secnumdepth_ = lexrc.getInteger();
			break;

		case TC_TOCDEPTH:
			lexrc.next();
			tocdepth_ = lexrc.getInteger();
			break;

		// First step to support options
		case TC_CLASSOPTIONS:
			readClassOptions(lexrc);
			break;

		case TC_PREAMBLE:
			preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
			break;

		case TC_HTMLPREAMBLE:
			htmlpreamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
			break;
		
		case TC_HTMLTOCSECTION:
			html_toc_section_ = from_utf8(trim(lexrc.getString()));
			break;

		case TC_ADDTOPREAMBLE:
			preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
			break;

		case TC_ADDTOHTMLPREAMBLE:
			htmlpreamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
			break;

		case TC_PROVIDES: {
			lexrc.next();
			string const feature = lexrc.getString();
			lexrc.next();
			if (lexrc.getInteger())
				provides_.insert(feature);
			else
				provides_.erase(feature);
			break;
		}

		case TC_REQUIRES: {
			lexrc.eatLine();
			vector<string> const req 
				= getVectorFromString(lexrc.getString());
			requires_.insert(req.begin(), req.end());
			break;
		}

		case TC_DEFAULTMODULE: {
			lexrc.next();
			string const module = lexrc.getString();
			if (find(default_modules_.begin(), default_modules_.end(), module) == default_modules_.end())
				default_modules_.push_back(module);
			break;
		}

		case TC_PROVIDESMODULE: {
			lexrc.next();
			string const module = lexrc.getString();
			if (find(provided_modules_.begin(), provided_modules_.end(), module) == provided_modules_.end())
				provided_modules_.push_back(module);
			break;
		}

		case TC_EXCLUDESMODULE: {
			lexrc.next();
			string const module = lexrc.getString();
			// modules already have their own way to exclude other modules
			if (rt == MODULE) {
				LYXERR0("ExcludesModule tag cannot be used in a module!");
				break;
			}
			if (find(excluded_modules_.begin(), excluded_modules_.end(), module) == excluded_modules_.end())
				excluded_modules_.push_back(module);
			break;
		}

		case TC_LEFTMARGIN:	// left margin type
			if (lexrc.next())
				leftmargin_ = lexrc.getDocString();
			break;

		case TC_RIGHTMARGIN:	// right margin type
			if (lexrc.next())
				rightmargin_ = lexrc.getDocString();
			break;

		case TC_INSETLAYOUT: {
			if (!lexrc.next()) {
				lexrc.printError("No name given for InsetLayout: `$$Token'.");
				error = true;
				break;
			}
			docstring const name = subst(lexrc.getDocString(), '_', ' ');
			if (name.empty()) {
				string s = "Could not read name for InsetLayout: `$$Token' "
					+ lexrc.getString() + " is probably not valid UTF-8!";
				lexrc.printError(s);
				InsetLayout il;
				// Since we couldn't read the name, we just scan the rest
				// of the style and discard it.
				il.read(lexrc, *this);
				// Let's try to continue rather than abort.
				// error = true;
			} else if (hasInsetLayout(name)) {
				InsetLayout & il = insetlayoutlist_[name];
				error = !il.read(lexrc, *this);
			} else {
				InsetLayout il;
				il.setName(name);
				error = !il.read(lexrc, *this);
				if (!error)
					insetlayoutlist_[name] = il;
			}
			break;
		}

		case TC_FLOAT:
			error = !readFloat(lexrc);
			break;
		
		case TC_CITEFORMAT:
			readCiteFormat(lexrc);
			break;

		case TC_IFCOUNTER:
			ifcounter = true;
		case TC_COUNTER:
			if (lexrc.next()) {
				docstring const name = lexrc.getDocString();
				if (name.empty()) {
					string s = "Could not read name for counter: `$$Token' "
							+ lexrc.getString() + " is probably not valid UTF-8!";
					lexrc.printError(s.c_str());
					Counter c;
					// Since we couldn't read the name, we just scan the rest
					// and discard it.
					c.read(lexrc);
				} else
					error = !counters_.read(lexrc, name, !ifcounter);
			}
			else {
				lexrc.printError("No name given for style: `$$Token'.");
				error = true;
			}
			// reset flag
			ifcounter = false;
			break;

		case TC_TITLELATEXTYPE:
			readTitleType(lexrc);
			break;

		case TC_TITLELATEXNAME:
			if (lexrc.next())
				titlename_ = lexrc.getString();
			break;

		case TC_NOFLOAT:
			if (lexrc.next()) {
				string const nofloat = lexrc.getString();
				floatlist_.erase(nofloat);
			}
			break;
		} // end of switch

		// Note that this is triggered the first time through the loop unless
		// we hit a format tag.
		if (format != LAYOUT_FORMAT)
			return FORMAT_MISMATCH;
	}

	// at present, we abort if we encounter an error,
	// so there is no point continuing.
	if (error)
		return ERROR;

	if (rt != BASECLASS)
		return (error ? ERROR : OK);

	if (defaultlayout_.empty()) {
		LYXERR0("Error: Textclass '" << name_
						<< "' is missing a defaultstyle.");
		return ERROR;
	}
		
	// Try to erase "stdinsets" from the provides_ set. 
	// The
	//   Provides stdinsets 1
	// declaration simply tells us that the standard insets have been
	// defined. (It's found in stdinsets.inc but could also be used in
	// user-defined files.) There isn't really any such package. So we
	// might as well go ahead and erase it.
	// If we do not succeed, then it was not there, which means that
	// the textclass did not provide the definitions of the standard
	// insets. So we need to try to load them.
	int erased = provides_.erase("stdinsets");
	if (!erased) {
		FileName tmp = libFileSearch("layouts", "stdinsets.inc");

		if (tmp.empty()) {
			frontend::Alert::warning(_("Missing File"),
				_("Could not find stdinsets.inc! This may lead to data loss!"));
			error = true;
		} else if (!read(tmp, MERGE)) {
			frontend::Alert::warning(_("Corrupt File"),
				_("Could not read stdinsets.inc! This may lead to data loss!"));
			error = true;
		}
	}

	min_toclevel_ = Layout::NOT_IN_TOC;
	max_toclevel_ = Layout::NOT_IN_TOC;
	const_iterator lit = begin();
	const_iterator len = end();
	for (; lit != len; ++lit) {
		int const toclevel = lit->toclevel;
		if (toclevel != Layout::NOT_IN_TOC) {
			if (min_toclevel_ == Layout::NOT_IN_TOC)
				min_toclevel_ = toclevel;
			else
				min_toclevel_ = min(min_toclevel_, toclevel);
			max_toclevel_ = max(max_toclevel_, toclevel);
		}
	}
	LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
		<< ", maximum is " << max_toclevel_);

	return (error ? ERROR : OK);
}