Exemplo n.º 1
0
AbstractChain* SensorManager::requestChain(const QString& id)
{
    sensordLogD() << "Requesting chain: " << id;
    clearError();

    AbstractChain* chain = NULL;
    QMap<QString, ChainInstanceEntry>::iterator entryIt = chainInstanceMap_.find(id);
    if (entryIt != chainInstanceMap_.end())
    {
        if (entryIt.value().chain_ )
        {
            chain = entryIt.value().chain_;
            entryIt.value().cnt_++;
            sensordLogD() << "Found chain '" << id << "'. Ref count: " << entryIt.value().cnt_;
        }
        else
        {
            QString type = entryIt.value().type_;
            if (chainFactoryMap_.contains(type))
            {
                chain = chainFactoryMap_[type](id);
                Q_ASSERT(chain);
                sensordLogD() << "Instantiated chain '" << id << "'. Valid = " << chain->isValid();

                entryIt.value().cnt_++;
                entryIt.value().chain_ = chain;
            }
            else
            {
                setError( SmFactoryNotRegistered, QString(tr("unknown chain type '%1'").arg(type)) );
            }
        }
    }
    else
    {
        setError( SmIdNotRegistered, QString(tr("unknown chain id '%1'").arg(id)) );
    }

    return chain;
}
boost::shared_ptr< Base<EncodingT> >
ConnectionInterpreter<EncodingT>::insert(boost::shared_ptr< Base<EncodingT> > const& table,
                                         boost::shared_ptr< Base<EncodingT> > const& columns)
{
    boost::shared_ptr< Base<EncodingT> > res(new StatementInterpreter<EncodingT>());
    clearError();
    try
    {
        std::vector<typename EncodingT::string_t> nativeColumns;
        typename EncodingT::string_t nativeTable;
        if (check_string_array(columns, nativeColumns) &&
            check_string<EncodingT>(table, nativeTable))
        {
            res.reset(new StatementInterpreter<EncodingT>(m_object->insert(nativeTable, nativeColumns)));
        }
    }
    catch (std::exception& e)
    {
        setError(e);
    }
    return res;
}
Exemplo n.º 3
0
int SM_QDropbox::requestToken(bool blocking)
{
    clearError();
    QString sigmeth = signatureMethodString();

    timestamp = QDateTime::currentMSecsSinceEpoch()/1000;
    nonce = generateNonce(128);

    QUrl url;
    url.setUrl(apiurl.toString());
    url.setPath(QString("/%1/oauth/request_token").arg(_version.left(1)));

    QUrlQuery query;
    query.addQueryItem("oauth_consumer_key",_appKey);
    query.addQueryItem("oauth_nonce", nonce);
    query.addQueryItem("oauth_signature_method", sigmeth);
    query.addQueryItem("oauth_timestamp", QString::number(timestamp));
    query.addQueryItem("oauth_version", _version);

    QString signature = oAuthSign(url);
    query.addQueryItem("oauth_signature", QUrl::toPercentEncoding(signature));

    url.setQuery(query);
#ifdef SM_QTDROPBOX_DEBUG
    qDebug() << "request token url: " << url.toString() << endl << "sig: " << signature << endl;
    qDebug() << "sending request " << url.toString() << " to " << apiurl.toString() << endl;
#endif

    int reqnr = sendRequest(url);
    if(blocking)
    {
        requestMap[reqnr].type = SM_DROPBOX_REQ_RQBTOKN;
        startEventLoop();
    }
    else
        requestMap[reqnr].type = SM_DROPBOX_REQ_RQTOKEN;

    return reqnr;
}
Exemplo n.º 4
0
void CustomWizardFieldPage::initializePage()
{
    QWizardPage::initializePage();
    clearError();
    // Note that the field mechanism will always restore the value
    // set on it when entering the page, so, there is no point in
    // trying to preserve user modifications of the text.
    foreach(const LineEditData &led, m_lineEdits) {
        if (!led.defaultText.isEmpty()) {
            QString defaultText = led.defaultText;
            CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText);
            led.lineEdit->setText(defaultText);
        }
    }
    foreach(const TextEditData &ted, m_textEdits) {
        if (!ted.defaultText.isEmpty()) {
            QString defaultText = ted.defaultText;
            CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText);
            ted.textEdit->setText(defaultText);
        }
    }
}
char* Transaction::write_eventName( char* dest, char* name){
	clearError();
	//check for errors errors
	// ensure name is usable
	if( NULL == name)
		throwError( Error::TransactionNullEventName);
	 // ensure name is not empty
	else if( strlen( name) == 0)
		throwError( Error::TransactionNullEventName);
	// ensure name is not too long
	else if( strlen( name) > eventName_size)
		throwError( Error::TransactionEventNameTooLong);

	//write name
	else {
		sprintf( dest, "%-*s", eventName_size, name);
		return dest + eventName_size;}

	//handle error case
	dest[0] = '\0';
	return dest;
}
boost::shared_ptr< Base<EncodingT> > CppEnumInterpreterAccess<EncodingT>::selectOneCppEnum(boost::shared_ptr< Base<EncodingT> > const& identifier,
				const boost::shared_ptr< Base<EncodingT> >& nowait)
{
	boost::shared_ptr< Base<EncodingT> > res(new CppEnumInterpreter<EncodingT>());
	clearError();
	try
	{
		bool nativeNoWait;
		int nativeIdentifier;
		if (check_numeric(identifier, nativeIdentifier) &&
			check_bool(nowait, nativeNoWait))
		{
			res.reset(new CppEnumInterpreter<EncodingT>(m_object->selectOneCppEnum(nativeIdentifier,
				nativeNoWait)));
		}
	}
	catch (std::exception& e)
	{
		setError(e);
	}
	return res;
}
boost::shared_ptr< Base<EncodingT> >
ConnectionInterpreter<EncodingT>::deleteFrom(boost::shared_ptr< Base<EncodingT> > const& table,
                                             boost::shared_ptr< Base<EncodingT> > const& filter)
{
    boost::shared_ptr< Base<EncodingT> > res(new StatementInterpreter<EncodingT>());
    clearError();
    try
    {
        typename EncodingT::string_t nativeFilter;
        typename EncodingT::string_t nativeTable;
        if (check_string<EncodingT>(filter, nativeFilter) &&
            check_string<EncodingT>(table, nativeTable))
        {
            res.reset(new StatementInterpreter<EncodingT>(m_object->deleteFrom(nativeTable, nativeFilter)));
        }
    }
    catch (std::exception& e)
    {
        setError(e);
    }
    return res;
}
Exemplo n.º 8
0
bool Compiler::compile(const QString &url)
{
    Q_D(Compiler);
    clearError();

    // check that engine is using correct factory
    if (!qgetenv("QV4_FORCE_INTERPRETER").isEmpty()) {
        QQmlError error;
        error.setDescription("Compiler is forced to use interpreter");
        appendError(error);
        return false;
    }

    Q_ASSERT(d->compilation == NULL);
    QmlCompilation* c = new QmlCompilation(url, QUrl(url), d->engine);
    d->compilation = c;
    c->importCache = new QQmlImports(&QQmlEnginePrivate::get(d->compilation->engine)->typeLoader);
    c->importDatabase = new QQmlImportDatabase(d->compilation->engine);
    c->loadUrl = url;
    int lastSlash = url.lastIndexOf('/');
    if (lastSlash == -1)
        c->url = url;
    else if (lastSlash + 1 < url.length())
        c->url = url.mid(lastSlash + 1);
    else
        c->url = "";

    if (!loadData()) {
        delete takeCompilation();
        return false;
    }

    if (!compileData()) {
        delete takeCompilation();
        return false;
    }

    return true;
}
Exemplo n.º 9
0
void CustomWizardFieldPage::initializePage()
{
    QWizardPage::initializePage();
    clearError();
    foreach(const LineEditData &led, m_lineEdits) {
        if (!led.userChange.isNull()) {
            led.lineEdit->setText(led.userChange);
        } else if (!led.defaultText.isEmpty()) {
            QString defaultText = led.defaultText;
            CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText);
            led.lineEdit->setText(defaultText);
        }
    }
    foreach(const TextEditData &ted, m_textEdits) {
        if (!ted.userChange.isNull()) {
            ted.textEdit->setText(ted.userChange);
        } else if (!ted.defaultText.isEmpty()) {
            QString defaultText = ted.defaultText;
            CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText);
            ted.textEdit->setText(defaultText);
        }
    }
}
Exemplo n.º 10
0
QString QCharsetDetector::text(const QCharsetMatch &charsetMatch)
{
    Q_D(QCharsetDetector);
    clearError();
    QTextCodec *codec
        = QTextCodec::codecForName(charsetMatch.name().toLatin1());
    if (codec == NULL) { // there is no codec matching the name
        d->_status = U_ILLEGAL_ARGUMENT_ERROR;
        qWarning() << __PRETTY_FUNCTION__
                 << "no codec for the name" << charsetMatch.name()
                 << errorString();
        // return empty string to indicate that no conversion is possible:
        return QString();
    }
    else {
        QTextCodec::ConverterState state;
        QString text =
            codec->toUnicode(d->_ba.constData(), d->_ba.size(), &state);
        if (state.invalidChars > 0)
            d->_status = U_INVALID_CHAR_FOUND;
        return text;
    }
}
Exemplo n.º 11
0
void SensorManager::releaseChain(const QString& id)
{
    sensordLogD() << "Releasing chain: " << id;

    clearError();

    QMap<QString, ChainInstanceEntry>::iterator entryIt = chainInstanceMap_.find(id);
    if (entryIt != chainInstanceMap_.end())
    {
        if (entryIt.value().chain_)
        {
            entryIt.value().cnt_--;

            /** Fix for NB#242237
            if (entryIt.value().cnt_ == 0)
            */
            if (false)
            {
                sensordLogD() << "Chain '" << id << "' has no more references. Deleting it.";
                delete entryIt.value().chain_;
                entryIt.value().chain_ = 0;
            }
            else
            {
                sensordLogD() << "Chain '" << id << "' ref count: " << entryIt.value().cnt_;
            }
        }
        else
        {
            setError( SmNotInstantiated, QString(tr("chain '%1' not instantiated, cannot release").arg(id)) );
        }
    }
    else
    {
        setError( SmIdNotRegistered, QString(tr("unknown chain id '%1'").arg(id)) );
    }
}
Exemplo n.º 12
0
  void CETranslateWidget::updateVector()
  {
    // Check translation mode
    switch (static_cast<TranslateMode>
            (ui.combo_translateMode->currentIndex())) {

    // Translating by an arbitrary vector
    default:
    case TM_VECTOR:
      // Disable selection monitor
      m_selectionTimer.stop();

      // Reenable editing of vector
      enableVectorEditor();

      // Clear any lingering errors
      clearError();

      // Pull out the coordinates
      m_vector.x() = ui.spin_x->value();
      m_vector.y() = ui.spin_y->value();
      m_vector.z() = ui.spin_z->value();
      break;

    // If we need an atom, check for selections.
    case TM_ATOM_TO_ORIGIN:
    case TM_ATOM_TO_CELL_CENTER:
      // Start selection monitor
      m_selectionTimer.start(500);

      // Disable editing of vector
      disableVectorEditor();

      checkSelection();
      break;
    }
  }
Exemplo n.º 13
0
WinSerialPort::EState WinSerialPort::waitFor(OVERLAPPED& ovWait, const unsigned long timeoutInterval, const bool isSending, size_t& transferredBytes)
{
/*
	if (!::GetOverlappedResult(hComPort_, &ovWait, (DWORD *)&transferredBytes, TRUE))
	//if (!::GetOverlappedResult(hComPort_, &ovWait, (DWORD *)&transferredBytes, FALSE))
	{
		const DWORD err = GetLastError();
		std::cerr << (isSending ? "send error: " : "recv error: ") << err << std::endl;
		if (ERROR_IO_INCOMPLETE != err)
		{
			clearError();
			return WinSerialPort::E_ERROR;
		}
	}

	return WinSerialPort::E_OK;
*/
	switch(::WaitForSingleObject(ovWait.hEvent, timeoutInterval))
	{
	case WAIT_OBJECT_0:
		if (!GetOverlappedResult(hComPort_, &ovWait, (DWORD *)&transferredBytes, FALSE))
		{
			const DWORD err = GetLastError();
			std::cerr << (isSending ? "sending wait error: " : "receiving wait error: ") << err << std::endl;
			if (ERROR_IO_INCOMPLETE != err)
			{
				clearError();
				return WinSerialPort::E_ERROR;
			}
		}
		return WinSerialPort::E_OK;
	case WAIT_TIMEOUT:
		return WinSerialPort::E_TIMEOUT;
	default:
		return WinSerialPort::E_ERROR;
	}
}
Exemplo n.º 14
0
bool Utilities::isError()
{
    GLenum error = glGetError();
    if (GL_NO_ERROR != error)
    {
        switch (error)
        {
            case GL_INVALID_ENUM:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_INVALID_ENUM");
                break;
            case GL_INVALID_VALUE:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_INVALID_VALUE");
                break;
            case GL_INVALID_OPERATION:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_INVALID_OPERATION");
                break;
        #if defined(GL_INVALID_FRAMEBUFFER_OPERATION)
            case GL_INVALID_FRAMEBUFFER_OPERATION:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_INVALID_FRAMEBUFFER_OPERATION");
                break;
        #endif
            case GL_OUT_OF_MEMORY:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_OUT_OF_MEMORY");
                break;
            case GL_STACK_UNDERFLOW:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_STACK_UNDERFLOW");
                break;
            case GL_STACK_OVERFLOW:
                Log::get().warn("%s:%d: %s\n", __FILE__, __LINE__, "GL_STACK_OVERFLOW");
                break;
        };
        clearError();
        return true;
    }
    return false;
}
Exemplo n.º 15
0
Soprano::Node Soprano::N3NodeParser::parseNode( QTextStream& s, Node::N3ParserFlags flags ) const
{
    clearError();

    s.skipWhiteSpace();

    Node node;

    // we treat the empty string as an empty node without an error
    if ( s.atEnd() ) {
        return Node();
    }

    QChar c;
    s >> c;

    // parser resource node
    // ============================================
    if ( c == '<' ) {
        QString str;
        if ( scanStream( s, &str, '>' ) ) {
            node = Soprano::Node( QUrl::fromEncoded( str.toLatin1(), flags&Node::StrictUris ? QUrl::StrictMode : QUrl::TolerantMode ) );
        }
    }

    // parse blank node
    // ============================================
    else if ( c == '_' ) {
        s >> c;
        if ( c == ':' ) {
            // TODO: restrict the charset
            QString str;
            s >> str;
            if ( !str.isEmpty() )
                node = Soprano::Node::createBlankNode( str );
        }
Exemplo n.º 16
0
bool SQLiteAdminTools::vacuum(const KexiDB::ConnectionData& data, const QString& databaseName)
{
    clearError();
#ifdef SQLITE2
    Q_UNUSED(data);
    Q_UNUSED(databaseName);
    return false;
#else
    KexiDB::DriverManager manager;
    KexiDB::Driver *drv = manager.driver(data.driverName);
    QString title(i18n("Could not compact database \"%1\".", QDir::convertSeparators(databaseName)));
    if (!drv) {
        setError(&manager, title);
        return false;
    }
    SQLiteVacuum vacuum(data.dbPath() + QDir::separator() + databaseName);
    tristate result = vacuum.run();
    if (!result) {
        setError(title);
        return false;
    } else //success or cancelled
        return true;
#endif
}
/**
 * Determines the transaction code based on the enumeration value received
 *
 * @param transaction_code
 * @return
 **/
char* Transaction::write_code( char* dest, Transaction::Code code){
	clearError();
	switch( code){
		case Transaction::Create:{
			char digit[] = "01";
			strcpy( dest, digit);
			break;}
		case Transaction::Delete:{
			char digit[] = "02";
			strcpy( dest, digit);
			break;}
		case Transaction::Sell:{
			char digit[] = "03";
			strcpy( dest, digit);
			break;}
		case Transaction::Buy:{
			char digit[] = "04";
			strcpy( dest, digit);
			break;}
		case Transaction::Refund:{
			char digit[] = "05";
			strcpy( dest, digit);
			break;}
		case Transaction::AddCredit:{
			char digit[] = "06";
			strcpy( dest, digit);
			break;}
		case Transaction::Test:{
			char digit[] = "00";
			strcpy( dest, digit);
			break;}
		default:{
			throwError( Error::TransactionNullCode);
			return dest;}}
	return dest + code_size;
}
char* Transaction::write_type( char* dest, Account::Type type){
	clearError();
	switch( type){
		case Account::Admin:{
			char typeString_admin[] = "AA";
			strcpy( dest, typeString_admin);
			break;}
		case Account::Buy:{
			char typeString_buy[] = "BS";
			strcpy( dest, typeString_buy);
			break;}
		case Account::Sell:{
			char typeString_sell[] = "SS";
			strcpy( dest, typeString_sell);
			break;}
		case Account::Full:{
			char typeString_full[] = "FS";
			strcpy( dest, typeString_full);
			break;}
		default:{
			throwError( Error::TransactionNullAccountType);
			return dest;}}
	return dest + type_size;
}
Exemplo n.º 19
0
bool Maya4Model::ReadMAFile(const char* mdlfile)
{
  clearError();

  if (mdlfile == 0 || strlen(mdlfile) == 0)
    return setError("MA filename is 0");

  MayaInputFile file(mdlfile);

  if (!file.IsValid())
    return setError("MA filename is 0");

  while (!file.EndOfFile())
  {
    csString   tok;
    file.GetToken(tok);

    if (tok == "createNode")
    {
      if (!CreateNode(file,tree))
      {
        this->setError(file.GetError() );
        break;
      }
    }
  }

  // If file has loaded with no anim curves, create a default 0 anim curve
  if (!animnode)
  {
	csPrintf("Creating default animcurveTL...\n");
    animnode = new NodeAnimCurveTL(meshnode->CountVertices()); // position paths for each vertex
	animnode->CreateDefault();
  }
  return true;
}
Exemplo n.º 20
0
WinSerialPort::EState WinSerialPort::send(const unsigned char* data, const size_t dataSize, const unsigned long timeoutInterval_msec /*= 100*/)
{
	size_t sentBytes, totalSentBytes = 0;
	while (totalSentBytes < dataSize)
	{
		sentBytes = 0;
		if (WriteFile(hComPort_, data, (DWORD)dataSize, (DWORD *)&sentBytes, &ovSend_))
		{
			if (0 == sentBytes)
			{
#if defined(_DEBUG)
				std::cout << "send 0 byte" << std::endl;
#endif
				continue;
			}
		}
		else
		{
			if (ERROR_IO_PENDING == GetLastError())  // I/O operation pending
			{
				const WinSerialPort::EState state = waitFor(ovSend_, timeoutInterval_msec, true, sentBytes);
				if (WinSerialPort::E_OK != state) return state;
			}
			else
			{
				std::cerr << "wait failed with error: " << GetLastError() << std::endl;
				clearError();
				return WinSerialPort::E_ERROR;
			}
		}

		totalSentBytes += sentBytes;
	}
	
	return WinSerialPort::E_OK;
}
Exemplo n.º 21
0
void QCharsetDetector::enableInputFilter(bool enable)
{
    Q_D(QCharsetDetector);
    clearError();
    ucsdet_enableInputFilter(d->_uCharsetDetector, UBool(enable));
}
void SessionWidget::stopSession()
{
    clearError();
    session->stop();
    updateSession();
}
void SessionWidget::closeSession()
{
    clearError();
    session->close();
    updateSession();
}
void SessionWidget::openSession()
{
    clearError();
    session->open();
    updateSession();
}
Exemplo n.º 25
0
bool QgsProject::write()
{
  clearError();

  // if we have problems creating or otherwise writing to the project file,
  // let's find out up front before we go through all the hand-waving
  // necessary to create all the Dom objects
  if ( !imp_->file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
  {
    imp_->file.close();         // even though we got an error, let's make
    // sure it's closed anyway

    setError( tr( "Unable to save to file %1" ).arg( imp_->file.fileName() ) );
    return false;
  }
  QFileInfo myFileInfo( imp_->file );
  if ( !myFileInfo.isWritable() )
  {
    // even though we got an error, let's make
    // sure it's closed anyway
    imp_->file.close();
    setError( tr( "%1 is not writable. Please adjust permissions (if possible) and try again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  QDomImplementation DomImplementation;

  QDomDocumentType documentType =
    DomImplementation.createDocumentType( "qgis", "http://mrcc.com/qgis.dtd",
                                          "SYSTEM" );
  std::auto_ptr < QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( documentType ) );


  QDomElement qgisNode = doc->createElement( "qgis" );
  qgisNode.setAttribute( "projectname", title() );
  qgisNode.setAttribute( "version", QString( "%1" ).arg( QGis::QGIS_VERSION ) );

  doc->appendChild( qgisNode );

  // title
  QDomElement titleNode = doc->createElement( "title" );
  qgisNode.appendChild( titleNode );

  QDomText titleText = doc->createTextNode( title() );  // XXX why have title TWICE?
  titleNode.appendChild( titleText );

  // let map canvas and legend write their information
  emit writeProject( *doc );

  // within top level node save list of layers
  QMap<QString, QgsMapLayer*> & layers = QgsMapLayerRegistry::instance()->mapLayers();

  // Iterate over layers in zOrder
  // Call writeXML() on each
  QDomElement projectLayersNode = doc->createElement( "projectlayers" );
  projectLayersNode.setAttribute( "layercount", qulonglong( layers.size() ) );

  QMap<QString, QgsMapLayer*>::iterator li = layers.begin();
  while ( li != layers.end() )
  {
    //QgsMapLayer *ml = QgsMapLayerRegistry::instance()->mapLayer(*li);
    QgsMapLayer* ml = li.value();

    if ( ml )
    {
      QString externalProjectFile = layerIsEmbedded( ml->id() );
      QHash< QString, QPair< QString, bool> >::const_iterator emIt = mEmbeddedLayers.find( ml->id() );
      if ( emIt == mEmbeddedLayers.constEnd() )
      {
        ml->writeXML( projectLayersNode, *doc );
      }
      else //layer defined in an external project file
      {
        //only save embedded layer if not managed by a legend group
        if ( emIt.value().second )
        {
          QDomElement mapLayerElem = doc->createElement( "maplayer" );
          mapLayerElem.setAttribute( "embedded", 1 );
          mapLayerElem.setAttribute( "project", writePath( emIt.value().first ) );
          mapLayerElem.setAttribute( "id", ml->id() );
          projectLayersNode.appendChild( mapLayerElem );
        }
      }
    }
    li++;
  }

  qgisNode.appendChild( projectLayersNode );

  // now add the optional extra properties

  dump_( imp_->properties_ );

  QgsDebugMsg( QString( "there are %1 property scopes" ).arg( static_cast<int>( imp_->properties_.count() ) ) );

  if ( !imp_->properties_.isEmpty() ) // only worry about properties if we
    // actually have any properties
  {
    imp_->properties_.writeXML( "properties", qgisNode, *doc );
  }

  // now wrap it up and ship it to the project file
  doc->normalize();             // XXX I'm not entirely sure what this does

  //QString xml = doc->toString(4); // write to string with indentation of four characters
  // (yes, four is arbitrary)

  // const char * xmlString = xml; // debugger probe point
  // qDebug( "project file output:\n\n" + xml );

  QTextStream projectFileStream( &imp_->file );

  //projectFileStream << xml << endl;
  doc->save( projectFileStream, 4 );  // save as utf-8
  imp_->file.close();

  // check if the text stream had no error - if it does
  // the user will get a message so they can try to resolve the
  // situation e.g. by saving project to a volume with more space
  //
  if ( projectFileStream.pos() == -1  || imp_->file.error() != QFile::NoError )
  {
    setError( tr( "Unable to save to file %1. Your project "
                  "may be corrupted on disk. Try clearing some space on the volume and "
                  "check file permissions before pressing save again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  dirty( false );               // reset to pristine state

  emit projectSaved();

  return true;
} // QgsProject::write
Exemplo n.º 26
0
/**
   presuming that the caller has already reset the map canvas, map registry, and legend
 */
bool QgsProject::read()
{
  clearError();

  std::auto_ptr< QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( "qgis" ) );

  if ( !imp_->file.open( QIODevice::ReadOnly ) )
  {
    imp_->file.close();

    setError( tr( "Unable to open %1" ).arg( imp_->file.fileName() ) );

    return false;
  }

  // location of problem associated with errorMsg
  int line, column;
  QString errorMsg;

  if ( !doc->setContent( &imp_->file, &errorMsg, &line, &column ) )
  {
    // want to make this class as GUI independent as possible; so commented out
#if 0
    QMessageBox::critical( 0, tr( "Project File Read Error" ),
                           tr( "%1 at line %2 column %3" ).arg( errorMsg ).arg( line ).arg( column ) );
#endif

    QString errorString = tr( "Project file read error: %1 at line %2 column %3" )
                          .arg( errorMsg ).arg( line ).arg( column );

    QgsDebugMsg( errorString );

    imp_->file.close();

    setError( tr( "%1 for file %2" ).arg( errorString ).arg( imp_->file.fileName() ) );

    return false;
  }

  imp_->file.close();


  QgsDebugMsg( "Opened document " + imp_->file.fileName() );
  QgsDebugMsg( "Project title: " + imp_->title );

  // get project version string, if any
  QgsProjectVersion fileVersion =  _getVersion( *doc );
  QgsProjectVersion thisVersion( QGis::QGIS_VERSION );

  if ( thisVersion > fileVersion )
  {
    QgsLogger::warning( "Loading a file that was saved with an older "
                        "version of qgis (saved in " + fileVersion.text() +
                        ", loaded in " + QGis::QGIS_VERSION +
                        "). Problems may occur." );

    QgsProjectFileTransform projectFile( *doc, fileVersion );

    //! Shows a warning when an old project file is read.
    emit oldProjectVersionWarning( fileVersion.text() );
    QgsDebugMsg( "Emitting oldProjectVersionWarning(oldVersion)." );

    projectFile.dump();

    projectFile.updateRevision( thisVersion );

    projectFile.dump();

  }

  // before we start loading everything, let's clear out the current set of
  // properties first so that we don't have the properties from the previous
  // project still hanging around

  imp_->clear();
  mEmbeddedLayers.clear();

  // now get any properties
  _getProperties( *doc, imp_->properties_ );

  QgsDebugMsg( QString::number( imp_->properties_.count() ) + " properties read" );

  dump_( imp_->properties_ );


  // restore the canvas' area of interest

  // now get project title
  _getTitle( *doc, imp_->title );


  // get the map layers
  QPair< bool, QList<QDomNode> > getMapLayersResults =  _getMapLayers( *doc );

  // review the integrity of the retrieved map layers
  bool clean = getMapLayersResults.first;

  if ( !clean )
  {
    QgsDebugMsg( "Unable to get map layers from project file." );

    if ( ! getMapLayersResults.second.isEmpty() )
    {
      QgsDebugMsg( "there are " + QString::number( getMapLayersResults.second.size() ) + " broken layers" );
    }

    // we let a custom handler to decide what to do with missing layers
    // (default implementation ignores them, there's also a GUI handler that lets user choose correct path)
    mBadLayerHandler->handleBadLayers( getMapLayersResults.second, *doc );
  }

  // read the project: used by map canvas and legend
  emit readProject( *doc );

  // if all went well, we're allegedly in pristine state
  if ( clean )
    dirty( false );

  return true;

} // QgsProject::read
Exemplo n.º 27
0
Parser::Parser()
{
	initializingMacro = false;
	overrideFileInfo = false;
	clearError();
}
Exemplo n.º 28
0
WinSerialPort::EState WinSerialPort::receive(GuardedByteBuffer& recvBuf, const unsigned long timeoutInterval_msec /*= 100*/, const size_t bufferLen /*= 0*/)
{
	//
	DWORD eventMask = 0L;
	if (WaitCommEvent(hComPort_, &eventMask, &ovRecv_))
	{
		if ((EV_DSR & eventMask) == EV_DSR)
		{
#if defined(_DEBUG)
			std::cout << "DSR" << std::endl;
#endif
			// TODO [add] >>
		}
		if ((EV_CTS & eventMask) == EV_CTS)
		{
#if defined(_DEBUG)
			std::cout << "CTS" << std::endl;
#endif
			// TODO [add] >>
		}
		if ((EV_RXCHAR & eventMask) == EV_RXCHAR)
		{
#if defined(_DEBUG)
			std::cout << "RXCHAR" << std::endl;
#endif
			// TODO [add] >>
		}
	}
	else
	{
		if (ERROR_IO_PENDING == GetLastError())  // I/O operation pending
		{
			size_t recvBytes = 0;
			const WinSerialPort::EState state = waitFor(ovRecv_, timeoutInterval_msec, false, recvBytes);
			if (WinSerialPort::E_OK != state) return state;
		}
		else
		{
			std::cerr << "wait failed with error: " << GetLastError() << std::endl;
			//clearError();
			return WinSerialPort::E_ERROR;
		}
	}

	//
	size_t recvBytes = 0;
	const size_t bufLen = bufferLen ? bufferLen : 8192;

	std::vector<unsigned char> buf(bufLen, 0);
	if (::ReadFile(hComPort_, &buf[0], (DWORD)bufLen, (DWORD *)&recvBytes, &ovRecv_))
	{
		if (0 == recvBytes)
		{
#if defined(_DEBUG)
			std::cout << "receive 0 byte" << std::endl;
#endif
			return WinSerialPort::E_OK;
		}
	}
	else
	{
		switch (GetLastError())
		{
		case ERROR_HANDLE_EOF:
			return WinSerialPort::E_OK;
		case ERROR_IO_PENDING:  // I/O operation pending
			{
				const WinSerialPort::EState state = waitFor(ovRecv_, timeoutInterval_msec, false, recvBytes);
				if (WinSerialPort::E_OK != state) return state;
			}
			break;
		default:
			std::cerr << "wait failed with error: " << GetLastError() << std::endl;;
			clearError();
			return WinSerialPort::E_ERROR;
		}
	}

	return recvBuf.push((GuardedByteBuffer::value_type *)(&buf[0]), (size_t)recvBytes) ? WinSerialPort::E_OK : WinSerialPort::E_ERROR;
}
Exemplo n.º 29
0
QStringList QCharsetDetector::getAllDetectableCharsets()
{
    Q_D(QCharsetDetector);

    if (!d->_allDetectableCharsets.isEmpty())
        return d->_allDetectableCharsets;

    // Codecs supported by QTextCodec (Qt 4.7):
    //
    // ISO-2022-JP JIS7 EUC-KR GB2312 Big5 Big5-ETen CP950 GB18030
    // EUC-JP Shift_JIS SJIS MS_Kanji System UTF-8 ISO-8859-1 latin1
    // CP819 IBM819 iso-ir-100 csISOLatin1 ISO-8859-15 latin9 UTF-32LE
    // UTF-32BE UTF-32 UTF-16LE UTF-16BE UTF-16 mulelao-1 roman8
    // hp-roman8 csHPRoman8 TIS-620 ISO 8859-11 WINSAMI2 WS2 Apple
    // Roman macintosh MacRoman windows-1258 CP1258 windows-1257
    // CP1257 windows-1256 CP1256 windows-1255 CP1255 windows-1254
    // CP1254 windows-1253 CP1253 windows-1252 CP1252 windows-1251
    // CP1251 windows-1250 CP1250 IBM866 CP866 csIBM866 IBM874 CP874
    // IBM850 CP850 csPC850Multilingual ISO-8859-16 iso-ir-226 latin10
    // ISO-8859-14 iso-ir-199 latin8 iso-celtic ISO-8859-13
    // ISO-8859-10 iso-ir-157 latin6 ISO-8859-10:1992 csISOLatin6
    // ISO-8859-9 iso-ir-148 latin5 csISOLatin5 ISO-8859-8 ISO
    // 8859-8-I iso-ir-138 hebrew csISOLatinHebrew ISO-8859-7 ECMA-118
    // greek iso-ir-126 csISOLatinGreek ISO-8859-6 ISO-8859-6-I
    // ECMA-114 ASMO-708 arabic iso-ir-127 csISOLatinArabic ISO-8859-5
    // cyrillic iso-ir-144 csISOLatinCyrillic ISO-8859-4 latin4
    // iso-ir-110 csISOLatin4 ISO-8859-3 latin3 iso-ir-109 csISOLatin3
    // ISO-8859-2 latin2 iso-ir-101 csISOLatin2 KOI8-U KOI8-RU KOI8-R
    // csKOI8R Iscii-Mlm Iscii-Knd Iscii-Tlg Iscii-Tml Iscii-Ori
    // Iscii-Gjr Iscii-Pnj Iscii-Bng Iscii-Dev TSCII GBK gb2312.1980-0
    // gbk-0 CP936 MS936 windows-936 jisx0201*-0 jisx0208*-0
    // ksc5601.1987-0 cp949 Big5-HKSCS big5-0 big5hkscs-0

    QStringList availableCodecsQt;
    foreach(const QByteArray &ba, QTextCodec::availableCodecs())
        availableCodecsQt << QString::fromLatin1(ba);

    // Charsets detectable by libicu 4.4.2:
    QStringList allDetectableCharsetsICU;
    allDetectableCharsetsICU
    << QLatin1String("UTF-8")
    << QLatin1String("UTF-16BE")
    << QLatin1String("UTF-16LE")
    << QLatin1String("UTF-32BE")
    << QLatin1String("UTF-32LE")
    << QLatin1String("ISO-8859-1")
    << QLatin1String("ISO-8859-2")
    << QLatin1String("ISO-8859-5")
    << QLatin1String("ISO-8859-6")
    << QLatin1String("ISO-8859-7")
    << QLatin1String("ISO-8859-8-I")
    << QLatin1String("ISO-8859-8")
    << QLatin1String("ISO-8859-9")
    << QLatin1String("KOI8-R")
    << QLatin1String("Shift_JIS")
    << QLatin1String("GB18030")
    << QLatin1String("EUC-JP")
    << QLatin1String("EUC-KR")
    << QLatin1String("Big5")
    << QLatin1String("ISO-2022-JP")
    << QLatin1String("ISO-2022-KR")
    << QLatin1String("ISO-2022-CN")
    << QLatin1String("IBM424_rtl")
    << QLatin1String("IBM424_ltr")
    << QLatin1String("IBM420_rtl")
    << QLatin1String("IBM420_ltr")
    << QLatin1String("windows-1250")
    << QLatin1String("windows-1251")
    << QLatin1String("windows-1252")
    << QLatin1String("windows-1253")
    << QLatin1String("windows-1255")
    << QLatin1String("windows-1256")
    << QLatin1String("windows-1254");

    // The charsets detectable by libicu can be determined by
    // ucsdet_getAllDetectableCharsets() and the documentation for
    // that function at
    // http://icu-project.org/apiref/icu4c/ucsdet_8h.html says:
    //
    //     “The state of the Charset detector that is passed in does
    //     not affect the result of this function, but requiring a
    //     valid, open charset detector as a parameter insures that
    //     the charset detection service has been safely initialized
    //     and that the required detection data is available.”
    //
    // but that does not seem to be completely true, in fact it
    // *does* depend on the state of the charset detector. For example
    // sometimes "windows-1250" *is* among the returned charsets.
    // This happens if some non-ASCII text
    // is in the detector and a detection is attempted and *then*
    // ucsdet_getAllDetectableCharsets() is called.
    // And sometimes "windows-1250" is *not* among the returned
    // charsets. This happens when an empty charset detector is created
    // and then ucsdet_getAllDetectableCharsets() is called.
    // If ucsdet_getAllDetectableCharsets() has been called once
    // the list of returned charsets never seems to change anymore,
    // even if the text in the detector is changed again and
    // another detection attempted which would result in a different
    // list if ucsdet_getAllDetectableCharsets() were called first
    // in that state.
    //
    // Sometimes ucsdet_getAllDetectableCharsets() reports charsets
    // multiple times depending on the number of languages it can
    // detect for that charsets, i.e. it may report ISO-8859-2 four
    // times because it can detect the languages “cs”, “hu”,
    // “pl”, and “ro” with that charset.
    //
    // This looks like a bug to me, to get a reliable list,
    // I have hardcoded the complete list of charsets which
    // ucsdet_getAllDetectableCharsets() can possibly return
    // for all states of the detector above.
    //
    // Therefore, the following code should not any extra charsets
    // anymore, at least not for libicu 4.4.2:
    clearError();
    UEnumeration *en =
        ucsdet_getAllDetectableCharsets(d->_uCharsetDetector, &(d->_status));
    if (!hasError()) {
        qint32 len;
        const UChar *uc;
        while ((uc = uenum_unext(en, &len, &(d->_status))) != NULL) {
            if(uc && !hasError())
                allDetectableCharsetsICU << QString::fromUtf16(uc, len);
        }
    }
    uenum_close(en);

    // remove all charsets not supported by QTextCodec and all duplicates:
    foreach(const QString &cs, allDetectableCharsetsICU) {
        if(availableCodecsQt.contains(cs) && !d->_allDetectableCharsets.contains(cs))
            d->_allDetectableCharsets << cs;
    }

    std::sort(d->_allDetectableCharsets.begin(), d->_allDetectableCharsets.end());

    return d->_allDetectableCharsets;
}
Exemplo n.º 30
0
bool QCharsetDetector::isInputFilterEnabled()
{
    Q_D(QCharsetDetector);
    clearError();
    return bool(ucsdet_isInputFilterEnabled(d->_uCharsetDetector));
}