Exemplo n.º 1
0
QString NewFormWidget::itemToTemplate(const QTreeWidgetItem *item, QString *errorMessage) const
{
    const QSize size = templateSize();
    // file name or string contents?
    const QVariant templateFileName = item->data(0, TemplateNameRole);
    if (templateFileName.type() == QVariant::String) {
        const QString fileName = templateFileName.toString();
        // No fixed size: just open.
        if (size.isNull())
            return readAll(fileName, errorMessage);
        // try to find a file matching the size, like "../640x480/xx.ui"
        const QFileInfo fiBase(fileName);
        QString sizeFileName;
        QTextStream(&sizeFileName) << fiBase.path() << QDir::separator()
                                   << size.width() << QLatin1Char('x') << size.height() << QDir::separator()
                                   << fiBase.fileName();
        if (QFileInfo(sizeFileName).isFile())
            return readAll(sizeFileName, errorMessage);
        // Nothing found, scale via DOM/temporary file
        QString contents = readAll(fileName, errorMessage);
        if (!contents.isEmpty())
            contents = qdesigner_internal::WidgetDataBase::scaleFormTemplate(contents, size, false);
        return contents;
    }
    // Content.
    const QString className = item->data(0, ClassNameRole).toString();
    QString contents = qdesigner_internal::WidgetDataBase::formTemplate(m_core, className, formName(className));
    if (!size.isNull())
        contents = qdesigner_internal::WidgetDataBase::scaleFormTemplate(contents, size, false);
    return contents;
}
Exemplo n.º 2
0
void QXmppSocksClient::slotReadyRead()
{
    if (m_step == ConnectState)
    {
        m_step++;

        // receive connect to server response
        QByteArray buffer = readAll();
        if (buffer.size() != 2 || buffer.at(0) != SocksVersion || buffer.at(1) != NoAuthentication)
        {
            qWarning("QXmppSocksClient received an invalid response during handshake");
            close();
            return;
        }

        // send CONNECT command
        buffer.resize(3);
        buffer[0] = SocksVersion;
        buffer[1] = ConnectCommand;
        buffer[2] = 0x00; // reserved
        buffer.append(encodeHostAndPort(
            DomainName,
            m_hostName.toLatin1(),
            m_hostPort));
        write(buffer);

    } else if (m_step == CommandState) {
        m_step++;

        // disconnect from signal
        disconnect(this, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));

        // receive CONNECT response
        QByteArray buffer = readAll();
        if (buffer.size() < 6 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) != Succeeded ||
            buffer.at(2) != 0)
        {
            qWarning("QXmppSocksClient received an invalid response to CONNECT command");
            close();
            return;
        }

        // parse host
        quint8 hostType;
        QByteArray hostName;
        quint16 hostPort;
        if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
        {
            qWarning("QXmppSocksClient could not parse type/host/port");
            close();
            return;
        }
        // FIXME : what do we do with the resulting name / port?

        // notify of connection
        emit ready();
    }
}
Exemplo n.º 3
0
std::shared_ptr<Shader> ResourceManager::shader(const Arx::String &path) {
    return inst().shaders.getOrElseUpdate(path,[&](){
        auto ret = std::make_shared<Shader>();

        auto vpath = ResourceManager::adjustedPath(path + ".vertex");
        Arx::String vsrc = readAll(vpath.path.raw());
        auto fpath = ResourceManager::adjustedPath(path + ".fragment");
        Arx::String fsrc = readAll(fpath.path.raw());

        ret->load(vsrc.raw(),fsrc.raw());
        return ret;
    });
}
Exemplo n.º 4
0
bool Socket::receive(void *data, int dataSize) {
	readAll();
	if (buffer.readBytes(data, dataSize)) {
		return true;
	}
	return false;
}
Exemplo n.º 5
0
void
ScrobSocket::onReadyRead()
{
    QByteArray bytes = readAll();
    if (bytes != "OK\n") qWarning() << bytes.trimmed();
    disconnectFromHost();
}
Exemplo n.º 6
0
void MyCtl::reply_finished(QNetworkReply *reply) {
    if (!reply->property(kAuthGetSalt).isNull()) {
        reply->deleteLater(); // let's not leak the reply
        if (reply->error() == QNetworkReply::NoError) {
            auto salt = reply->readAll();
            auto email = reply->property(kEmail).toString();
            auto password = reply->property(kPassword).toString();
            Q_ASSERT(!password.isEmpty() && !email.isEmpty());
            QCryptographicHash hasher{QCryptographicHash::Sha1};
            hasher.addData(salt); // the server must hash the same way
            hasher.addData("----");
            hasher.addData(password.toUtf8());
            auto hash = hasher.result().toBase64(QByteArray::Base64UrlEncoding);
            auto url = doAuthUrl.arg(email).arg(QString::fromLatin1(hash));
            auto reply = manager.get(QNetworkRequest{url});
            reply->setProperty(kDoAuth, true);
            reply->setProperty(kEmail, email);
        }
    }
    else if (!reply->property(kDoAuth).isNull()) {
        if (reply->error() == QNetworkReply::NoError) {
            auto email = reply->property(kEmail).toString();
            // ...
        }
    }
}
 bool LLWebRequest::request(const char* httpMethod, const char* url, const char* contentData, char* readBuffer, size_t readBufferLength)
 {
     bool result = FALSE;
     if (readBuffer) readBuffer[0] = 0; // terminate result buffer in case of failure
     
     if (sendRequest(httpMethod, url, contentData))
     {
         if (readBuffer)
         {
             // read HTTP headers:
             if (readHeaders())
             {
                 // read content data as c-string, keep 1 byte for termination:
                 int bytesRead = readAll(readBuffer, readBufferLength - 1);
                 
                 readBuffer[bytesRead] = 0; // Terminate read buffer with \0
                 result = TRUE;
             }
         }
         else
         {
             // okay, not expecting any result
             readHeaders(); // at least read headers
             result = TRUE;
         }
         stop();
     }
     return result;
 }
Exemplo n.º 8
0
void ModelBaker::handleModelNetworkReply() {
    auto requestReply = qobject_cast<QNetworkReply*>(sender());

    if (requestReply->error() == QNetworkReply::NoError) {
        qCDebug(model_baking) << "Downloaded" << _modelURL;

        // grab the contents of the reply and make a copy in the output folder
        QFile copyOfOriginal(_originalOutputModelPath);

        qDebug(model_baking) << "Writing copy of original model file to" << _originalOutputModelPath << copyOfOriginal.fileName();

        if (!copyOfOriginal.open(QIODevice::WriteOnly)) {
            // add an error to the error list for this model stating that a duplicate of the original model could not be made
            handleError("Could not create copy of " + _modelURL.toString() + " (Failed to open " + _originalOutputModelPath + ")");
            return;
        }
        if (copyOfOriginal.write(requestReply->readAll()) == -1) {
            handleError("Could not create copy of " + _modelURL.toString() + " (Failed to write)");
            return;
        }

        // close that file now that we are done writing to it
        copyOfOriginal.close();

        // emit our signal to start the import of the model source copy
        emit modelLoaded();
    } else {
        // add an error to our list stating that the model could not be downloaded
        handleError("Failed to download " + _modelURL.toString());
    }
}
Exemplo n.º 9
0
MainWidget::MainWidget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	ui.tree->deserialize(readAll(treeFileName()));
}
Exemplo n.º 10
0
void
IrcSocket::Receive ()
{
  QByteArray bytes = readAll ();
qDebug () << __PRETTY_FUNCTION__ << " got " << bytes.size() << " bytes " << bytes;
  numBytesIn += bytes.size();
  QByteArray last2 = lineData.right(2);
  if (last2.size () < 2) {
    last2.prepend ("??");
    last2 = last2.right (2);
  }
  int nb = bytes.size();
  char byte;
  char last0, last1;
  last0 = last2[0];
  last1 = last2[1];
  for (int b=0; b< nb; b++) {
    byte = bytes[b];
    lineData.append (byte);
    last0 = last1;
    last1 = byte;
    if (last0 == '\r' && last1 == '\n') {
      emit ReceivedLine (this, lineData);
      lineData.clear ();
    }
  }
  emit IOActivity ();
}
Exemplo n.º 11
0
	void RecentReleasesFetcher::handleReplyFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		qDebug () << data;
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing reply";
			return;
		}

		const auto& docElem = doc.documentElement ();
		if (docElem.attribute ("status") != "ok")
		{
			qWarning () << Q_FUNC_INFO
					<< "reply is not ok:"
					<< docElem.attribute ("status");
			return;
		}

		QList<Media::AlbumRelease> releases;

		static auto months = { "Jan", "Feb", "Mar",
				"Apr", "May", "Jun",
				"Jul", "Aug", "Sep",
				"Oct", "Nov", "Dec" };
		const auto monthsBegin = months.begin ();
		const auto monthsEnd = months.end ();
		auto album = docElem.firstChildElement ("albums").firstChildElement ("album");
		while (!album.isNull ())
		{
			const auto& strs = album.attribute ("releasedate").split (' ', QString::SkipEmptyParts);
			const int day = strs.value (1).toInt ();
			const int month = std::distance (monthsBegin,
						std::find (monthsBegin, monthsEnd, strs.value (2))) + 1;
			const int year = strs.value (3).toInt ();

			const QUrl& thumb = GetImage (album, "large");
			const QUrl& full = GetImage (album, "extralarge");

			Media::AlbumRelease release =
			{
				album.firstChildElement ("name").text (),
				album.firstChildElement ("artist").firstChildElement ("name").text (),
				QDateTime (QDate (year, month, day)),
				thumb,
				full,
				QUrl (album.firstChildElement ("url").text ())
			};
			releases << release;

			album = album.nextSiblingElement ("album");
		}

		emit gotRecentReleases (releases);
	}
Exemplo n.º 12
0
unsigned int CC3DataReader::readUnsignedInteger()
{
	unsigned int value;
	readAll( sizeof(value), (char*)&value );
	// return _isBigEndian ? NSSwapBigIntToHost(value) : NSSwapLittleIntToHost(value);
	return value;
}
Exemplo n.º 13
0
unsigned short CC3DataReader::readUnsignedShort()
{
	unsigned  short value;
	readAll( sizeof(value), (char*)&value );
	// return _isBigEndian ? NSSwapBigShortToHost(value) : NSSwapLittleShortToHost(value);
	return value;
}
Exemplo n.º 14
0
double CC3DataReader::readDouble()
{
	double value;
	readAll( sizeof(value), (char*)&value );
	//return _isBigEndian ? NSSwapBigDoubleToHost(value) : NSSwapLittleDoubleToHost(value);
	return value;
}
Exemplo n.º 15
0
float CC3DataReader::readFloat()
{
	float value;
	readAll( sizeof(value), (char*)&value );
	//return _isBigEndian ? NSSwapBigFloatToHost(value) : NSSwapLittleFloatToHost(value);
	return value;
}
Exemplo n.º 16
0
void DialogNewCamera::login(std::function<void(const QString &sid)> cb)
{
    QString url = authUrl;
    url += QStringLiteral("&format=2&account=%1&passwd=%2").arg(ui->dsm_username->text()).arg(ui->dsm_password->text());

    QUrl u(url);
    QNetworkRequest request(u);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    auto reply = nm->get(request);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        reply->deleteLater();
        if (reply->error() != QNetworkReply::NoError)
        {
            QMessageBox::warning(this, tr("Calaos Installer"), reply->errorString());
            cb({});
            return;
        }

        QByteArray bytes = reply->readAll();
        bool err;
        QJsonObject jdata = parseResult(bytes, err);

        if (err || !jdata["sid"].isString())
        {
            cb({});
            return;
        }

        cb(jdata["sid"].toString());
    });
}
Exemplo n.º 17
0
	void SelfAvatarFetcher::handleGetFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();
		const QImage& image = QImage::fromData (reply->readAll ());
		emit gotImage (image);
	}
Exemplo n.º 18
0
quint8 ma_log::get_hash( QString *hash)
{
    if( init() )
    {
        emit log_message( QString( Q_FUNC_INFO ), QString("Fail on init file log activity: ") + fileName() );
        return 1;
    }

    hash->clear();
    if( save() ) return 3;

    if( !exists() )
    {
        emit log_message( QString( Q_FUNC_INFO ), QString("file not exists, filename: ") + fileName() );
        return 1;
    }

    if( !open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        emit log_message( QString( Q_FUNC_INFO ), QString("can't open file: ") + fileName() );
        return 2;
    }

    QByteArray file_data = readAll();
    close();
    QByteArray md5 = QCryptographicHash::hash( file_data, QCryptographicHash::Md5 );
    file_data.append( md5 );

    *hash = ( QCryptographicHash::hash( file_data, QCryptographicHash::Sha1 ) ).toHex();
    return 0;
}
Exemplo n.º 19
0
void Script::setUrl(QUrl url)
{
    if (url == m_url)
        return;

    QNetworkRequest request(url);
    auto reply = m_networkAccessManager.get(request);
    m_status = Loading;
    emit statusChanged(m_status);
    connect(reply, &QNetworkReply::finished, [=] () {
        if (m_status == Loading) {
            if (reply->error() == QNetworkReply::NoError) {
                m_source = QString::fromUtf8(reply->readAll());
                emit sourceChanged(m_source);

                m_status = Loaded;
                emit statusChanged(m_status);
            } else {
                emit error(nullptr, QString("Failed to load “").append(url.toString()).append("”"));

                m_status = Error;
                emit statusChanged(m_status);
            }
        }

        reply->deleteLater();
    });
}
Exemplo n.º 20
0
	void AuthManager::handleAuthReplyFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& login = reply->property ("Login").toString ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			emit sidError (login, tr ("Unable to parse authentication reply."));
			return;
		}

		const auto& docElem = doc.documentElement ();
		if (docElem.firstChildElement ("status").text () != "1")
		{
			FailedAuth_ << login;
			emit sidError (login, docElem.firstChildElement ("errorMessage").text ());
			return;
		}

		Login2Sid_ [login] = docElem.firstChildElement ("session_id").text ();
		FailedAuth_.remove (login);

		emit sidReady (login);
	}
Exemplo n.º 21
0
void PremiumizeMeDownloadHandler::generateLinkReplyFinished()
{
    auto reply = static_cast< QNetworkReply *>(sender());

    QString data(QString::fromLatin1(reply->readAll()));
    reply->deleteLater();

    QRegularExpressionMatch match = LOCATION_REGEXP.match(data);
    if(!match.hasMatch()) {
        m_download->setMessage("No download url found: "+data);
        m_download->setEnabled(false);
        return;
    }

    QString downloadUrl = match.captured(1);
    downloadUrl.replace(QLatin1String("\\/"), QLatin1String("/"));

    m_download->setRedirectedUrl(QUrl(downloadUrl));
    m_download->setMessage("Getting file information...");
    Controller::downloadsDao()->update(m_download);

    m_downloader->setUrl(m_download->redirectedUrl());
    m_downloader->getMetaData();

    QObject::connect(m_downloader, &Downloader::metaDataChanged, [&]() {
        m_download->setRedirectedUrl(m_downloader->redirectedUrl());
        m_download->setFileName(m_downloader->fileName());
        m_download->setFileSize(m_downloader->fileSize());
        m_download->setMessage("");
        Controller::downloadsDao()->update(m_download);

        emit downloadInformationReady();
    });
}
Exemplo n.º 22
0
	void FinalPage::handleReplyFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();
		QString text;

		QDomDocument doc;
		if (!doc.setContent (reply->readAll ()))
		{
			text = tr ("I'm very sorry to say that, but seems like "
					"we're unable to handle your report at the time :(");
			Ui_.Status_->setText (text);
			return;
		}

		auto root = doc.documentElement ();
		const auto& id = root.firstChildElement ("id").text ();
		text = tr ("Report has been sent successfully. Thanks for your time!");
		if (!id.isEmpty ())
		{
			text += "<br />";
			text += (tr ("Your issue number is %1. You can view it here:") +
						" <a href='http://dev.leechcraft.org/issues/%1'>#%1</a>").arg (id);
		}
		Ui_.Status_->setText (text);
	}
Exemplo n.º 23
0
	void CurrenciesManager::gotRateReply ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();

		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
			return;
		}

		const auto& now = QDateTime::currentDateTime ();

		bool changed = false;
		auto rateElem = doc.documentElement ()
				.firstChildElement ("results")
				.firstChildElement ("rate");
		while (!rateElem.isNull ())
		{
			std::shared_ptr<void> guard (nullptr,
					[&rateElem] (void*) { rateElem = rateElem.nextSiblingElement ("rate"); });

			const auto& toValue = rateElem.attribute ("id").mid (3);
			if (toValue.size () != 3)
			{
				qWarning () << "incorrect `to` value"
						<< toValue;
				continue;
			}

			const auto newRate = rateElem.firstChildElement ("Rate").text ().toDouble ();
			if (std::fabs (newRate - RatesFromUSD_ [toValue]) > std::numeric_limits<double>::epsilon ())
			{
				RatesFromUSD_ [toValue] = newRate;
				changed = true;
			}

			Rate rate { 0, toValue, now, newRate };
			Core::Instance ().GetStorage ()->AddRate (rate);
		}

		LastFetch_ = QDateTime::currentDateTime ();

		QSettings settings (QCoreApplication::organizationName (),
			QCoreApplication::applicationName () + "_Poleemery");
		settings.beginGroup ("Currencies");
		settings.setValue ("LastFetch", LastFetch_);
		if (changed)
		{
			emit currenciesUpdated ();
			for (auto i = RatesFromUSD_.constBegin (); i != RatesFromUSD_.constEnd (); ++i)
				settings.setValue (i.key (), *i);
		}
		settings.endGroup ();
	}
Exemplo n.º 24
0
	void SingleAccAuth::handleSubmission ()
	{
		const auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		const auto& split = data.split ('\n');

		int timeout = 10 * 1000;
		if (split.value (0).trimmed () != "OK")
		{
			Queue_ << LastSubmit_;
			timeout *= 6;
		}
		else
			qDebug () << Q_FUNC_INFO
					<< "submitted to"
					<< BaseURL_
					<< Login_;

		LastSubmit_.Clear ();
		SaveQueue ();
		QTimer::singleShot (timeout,
				this,
				SLOT (rotateSubmitQueue ()));
	}
Exemplo n.º 25
0
pid_t dmtcp::Util::getTracerPid(pid_t tid)
{
  if (!dmtcp_real_to_virtual_pid) {
    return 0;
  }

  char buf[512];
  char *str;
  static int tracerStrLen = strlen(TRACER_PID_STR);
  int fd;

  if (tid == -1) {
    tid = gettid();
  }
  sprintf(buf, "/proc/%d/status", tid);
  fd = _real_open(buf, O_RDONLY, 0);
  JASSERT(fd != -1) (buf) (JASSERT_ERRNO);
  readAll(fd, buf, sizeof buf);
  _real_close(fd);
  str = strstr(buf, TRACER_PID_STR);
  JASSERT(str != NULL);
  str += tracerStrLen;

  while (*str == ' ' || *str == '\t') {
    str++;
  }

  pid_t tracerPid = (pid_t) strtol(str, NULL, 10);
  return tracerPid == 0 ? tracerPid : dmtcp_real_to_virtual_pid(tracerPid);
}
Exemplo n.º 26
0
bool Socket::peek(void *data, int dataSize) {
	readAll();
	if (buffer.peekBytes(data, dataSize)) {
		return true;
	}
	return false;
}
Exemplo n.º 27
0
		QIODevice_ptr ResourceLoader::Load (const QStringList& pathVariants, bool open) const
		{
			const auto& path = GetPath (pathVariants);
			if (path.isNull ())
				return {};

			if (CachePathContents_.contains (path))
			{
				auto result = std::make_shared<QBuffer> ();
				result->setData (*CachePathContents_ [path]);
				if (open)
					result->open (QIODevice::ReadOnly);
				return result;
			}

			auto result = std::make_shared<QFile> (path);

			if (!result->isSequential () &&
					result->size () < CachePathContents_.maxCost () / 2)
			{
				if (result->open (QIODevice::ReadOnly))
				{
					const auto& data = result->readAll ();
					CachePathContents_.insert (path, new QByteArray { data }, data.size ());
					result->close ();
				}
			}

			if (open)
				result->open (QIODevice::ReadOnly);

			return result;
		}
Exemplo n.º 28
0
void
replaceStringInFile(const char *filename, const string &toFind, const string &replaceWith) {
	FILE *f = fopen(filename, "r");
	if (f == NULL) {
		int e = errno;
		string message = "Cannot open file '";
		message.append(filename);
		message.append("' for reading");
		throw FileSystemException(message, e, filename);
	}
	string content(readAll(fileno(f)));
	fclose(f);
	
	f = fopen(filename, "w");
	if (f == NULL) {
		int e = errno;
		string message = "Cannot open file '";
		message.append(filename);
		message.append("' for writing");
		throw FileSystemException(message, e, filename);
	}
	content = replaceString(content, toFind, replaceWith);
	fwrite(content.data(), 1, content.size(), f);
	fclose(f);
}
Exemplo n.º 29
0
void _pf_cm_file_readAll(_pf_Stack *stack)
/* Read all of file. */
{
struct file *file = stack[0].v;
_pf_nil_check(file);
stack[0].String = readAll(file->f);
}
Exemplo n.º 30
0
  void Connection::onDataReady() {
    buffer = readAll();

    // The TCP protocol might stack multiple packets into a bigger one
    // if the packets are sufficiently small. Therefore, we have to keep
    // reading until we are sure we have received it all.
  
  start:
    if (readSize == 0) {
      // Wait until we have enough data to read the 32-bit int.
      if (buffer.size() < sizeof(readSize)) {
        return;
      }

      QDataStream stream(&buffer, QIODevice::ReadOnly);
      stream >> readSize;

      // Remove the data of the size just read from the buffer.
      buffer = buffer.mid(sizeof(readSize));
    }

    if (buffer.size() == readSize) {
      emit packetReceived(StatePacket::fromData(buffer.left(readSize)));
      buffer = buffer.mid(readSize);
      readSize = 0;

      // See if there's more.
      goto start;
    }
  }