Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include <fstream>
00031
00032 #include <yaml-cpp/emitter.h>
00033
00034 #include "rviz/yaml_config_writer.h"
00035
00036 namespace rviz
00037 {
00038
00040 YamlConfigWriter::YamlConfigWriter()
00041 : error_( false )
00042 {}
00043
00046 void YamlConfigWriter::writeFile( const Config& config, const QString& filename )
00047 {
00048 try
00049 {
00050 std::ofstream out( qPrintable( filename ));
00051 if( out )
00052 {
00053 writeStream( config, out, filename );
00054 }
00055 else
00056 {
00057 error_ = true;
00058 message_ = "Failed to open " + filename + " for writing.";
00059 }
00060 }
00061 catch( std::exception ex )
00062 {
00063 error_ = true;
00064 message_ = ex.what();
00065 }
00066 }
00067
00071 QString YamlConfigWriter::writeString( const Config& config, const QString& filename )
00072 {
00073 std::stringstream out;
00074 writeStream( config, out, filename );
00075 if( !error_ )
00076 {
00077 return QString::fromStdString( out.str() );
00078 }
00079 else
00080 {
00081 return "";
00082 }
00083 }
00084
00087 void YamlConfigWriter::writeStream( const Config& config, std::ostream& out, const QString& filename )
00088 {
00089 error_ = false;
00090 message_ = "";
00091 YAML::Emitter emitter;
00092 writeConfigNode( config, emitter );
00093 if( !error_ )
00094 {
00095 out << emitter.c_str() << std::endl;
00096 }
00097 }
00098
00100 bool YamlConfigWriter::error()
00101 {
00102 return error_;
00103 }
00104
00105 QString YamlConfigWriter::errorMessage()
00106 {
00107 return message_;
00108 }
00109
00110 void YamlConfigWriter::writeConfigNode( const Config& config, YAML::Emitter& emitter )
00111 {
00112 switch( config.getType() )
00113 {
00114 case Config::List:
00115 {
00116 emitter << YAML::BeginSeq;
00117 for( int i = 0; i < config.listLength(); i++ )
00118 {
00119 writeConfigNode( config.listChildAt( i ), emitter );
00120 }
00121 emitter << YAML::EndSeq;
00122 break;
00123 }
00124 case Config::Map:
00125 {
00126 emitter << YAML::BeginMap;
00127 Config::MapIterator map_iter = config.mapIterator();
00128 while( map_iter.isValid() )
00129 {
00130 Config child = map_iter.currentChild();
00131
00132 emitter << YAML::Key;
00133 emitter << map_iter.currentKey().toStdString();
00134 emitter << YAML::Value;
00135 writeConfigNode( child, emitter );
00136
00137 map_iter.advance();
00138 }
00139 emitter << YAML::EndMap;
00140 break;
00141 }
00142 case Config::Value:
00143 {
00144 QString value = config.getValue().toString();
00145 if( value.size() == 0 )
00146 {
00147 emitter << YAML::DoubleQuoted << "";
00148 }
00149 else
00150 {
00151 emitter << value.toStdString();
00152 }
00153 break;
00154 }
00155 default:
00156 emitter << YAML::Null;
00157 break;
00158 }
00159 }
00160
00161 }