本文整理汇总了C++中QStringList类的典型用法代码示例。如果您正苦于以下问题:C++ QStringList类的具体用法?C++ QStringList怎么用?C++ QStringList使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QStringList类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: SocketHandler
bool FileServerHandler::HandleAnnounce(MythSocket *socket,
QStringList &commands, QStringList &slist)
{
if (commands[1] == "FileServer")
{
if (slist.size() >= 3)
{
SocketHandler *handler =
new SocketHandler(socket, m_parent, commands[2]);
handler->BlockShutdown(true);
handler->AllowStandardEvents(true);
handler->AllowSystemEvents(true);
QWriteLocker wlock(&m_fsLock);
m_fsMap.insert(commands[2], handler);
m_parent->AddSocketHandler(handler);
slist.clear();
slist << "OK";
handler->SendStringList(slist);
return true;
}
return false;
}
if (commands[1] != "FileTransfer")
return false;
if (slist.size() < 3)
return false;
if ((commands.size() < 3) || (commands.size() > 6))
return false;
FileTransfer *ft = NULL;
QString hostname = "";
QString filename = "";
bool writemode = false;
bool usereadahead = true;
int timeout_ms = 2000;
switch (commands.size())
{
case 6:
timeout_ms = commands[5].toInt();
case 5:
usereadahead = commands[4].toInt();
case 4:
writemode = commands[3].toInt();
default:
hostname = commands[2];
}
QStringList::const_iterator it = slist.begin();
QUrl qurl = *(++it);
QString wantgroup = *(++it);
QStringList checkfiles;
while (++it != slist.end())
checkfiles += *(it);
slist.clear();
LOG(VB_GENERAL, LOG_DEBUG, "FileServerHandler::HandleAnnounce");
LOG(VB_GENERAL, LOG_INFO, QString("adding: %1 as remote file transfer")
.arg(hostname));
if (writemode)
{
if (wantgroup.isEmpty())
wantgroup = "Default";
StorageGroup sgroup(wantgroup, gCoreContext->GetHostName(), false);
QString dir = sgroup.FindNextDirMostFree();
if (dir.isEmpty())
{
LOG(VB_GENERAL, LOG_ERR, "Unable to determine directory "
"to write to in FileTransfer write command");
slist << "ERROR" << "filetransfer_directory_not_found";
socket->writeStringList(slist);
return true;
}
QString basename = qurl.path();
if (basename.isEmpty())
{
LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
"filename is empty in url '%1'.")
.arg(qurl.toString()));
slist << "ERROR" << "filetransfer_filename_empty";
socket->writeStringList(slist);
return true;
}
if ((basename.contains("/../")) ||
(basename.startsWith("../")))
{
LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
//.........这里部分代码省略.........
示例2: convertStudents
static bool convertStudents(QString csvFilePath, int offset = 0) {
QFile studentsCsv(csvFilePath);
QTextStream studentsStream;
QString insertStudentQueryString;
QSqlQuery query;
QString student;
QStringList splittedStudent;
NameMorpher nameMorpher;
NameMorpher::MorphedName morphedName;
studentsStream.setDevice(&studentsCsv);
studentsStream.setCodec("UTF-8");
if (!studentsCsv.open(QIODevice::ReadOnly)) {
return false;
}
insertStudentQueryString = "INSERT INTO student"
" (lastname, firstname, middlename,"
" lastname_datum, firstname_datum, middlename_datum,"
" lastname_accusative, firstname_accusative, middlename_accusative,"
" dob, university_group_id, decree_enrollment_number,"
" decree_expulsion_number, expulsion_reason_id,"
" expulsed_from_id)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
query.prepare(insertStudentQueryString);
while (!studentsStream.atEnd()) {
student = studentsStream.readLine()
.replace("не сданы зачеты ТП, УАТ; 17 пропусков занятий",
"не сданы зачеты ТП, УАТ. 17 пропусков занятий")
.replace("не сдан зачет по УАТ; 45 пропусков занятий",
"не сдан зачет по УАТ. 45 пропусков занятий")
.replace("Не сдал зачеты по УАТ, ТП; пропустил 102 ч занятий",
"Не сдал зачеты по УАТ, ТП. пропустил 102 ч занятий")
.replace("Не сдал зачеты УАТ, ТП; пропустил 52 ч занятий",
"Не сдал зачеты УАТ, ТП. пропустил 52 ч занятий")
.replace("Не сдал зачеты ТП, УАТ; пропущено 96 ч. Занятий",
"Не сдал зачеты ТП, УАТ. пропущено 96 ч. Занятий")
.replace("Не сдал зачеты УАТ,ТП; пропустил 98 часов занятий",
"Не сдал зачеты УАТ,ТП. пропустил 98 часов занятий");
if (student.isEmpty()) {
continue;
}
splittedStudent = student.split(';');
query.addBindValue(splittedStudent.at(offset + 2));
query.addBindValue(splittedStudent.at(offset + 3));
query.addBindValue(splittedStudent.at(offset + 4));
morphedName = nameMorpher.getMorphedName(
splittedStudent.at(offset + 2), splittedStudent.at(offset + 3),
splittedStudent.at(offset + 4),
true); // TODO: remove "true" in production
query.addBindValue(morphedName.lastnameDatum);
query.addBindValue(morphedName.firstnameDatum);
query.addBindValue(morphedName.middlenameDatum);
query.addBindValue(morphedName.lastnameAccusative);
query.addBindValue(morphedName.firstnameAccusative);
query.addBindValue(morphedName.middlenameAccusative);
query.addBindValue(QVariant());
if (splittedStudent.at(offset + 12) == "2007") {
qDebug() << "WOWOWOW, I'VE CATCHED HIM!";
return false;
}
int groupId = CSVOldFormatConverter::getGroupId(
splittedStudent.at(offset + 5), splittedStudent.at(offset + 10),
splittedStudent.at(offset + 12),
offset == 0 ? splittedStudent.at(1) : QString(),
splittedStudent.at(offset + 6), splittedStudent.at(offset + 11));
query.addBindValue(groupId);
query.addBindValue(splittedStudent.at(offset + 6));
query.addBindValue(QVariant());
query.addBindValue(QVariant());
query.addBindValue(QVariant());
if (!query.exec()) {
qDebug() << query.lastError().text();
return false;
}
int studentId = query.lastInsertId().toInt();
if (!fillMarks(splittedStudent, studentId, groupId, offset)) {
return false;
}
}
return true;
}
示例3: getEvaluationId
static int getEvaluationId(QString subject, QString controlType,
QString teacher, int groupId, QString date) {
// qDebug() << groupId;
QSqlQuery query;
query.prepare("SELECT id FROM control_type WHERE type = ?");
query.addBindValue(controlType);
if (!execAndNextQuery(query)) {
qDebug() << "unknown control type" << controlType;
return 0;
}
int controlTypeId = query.record().value("id").toInt();
query.prepare("SELECT troop_id FROM university_group WHERE id = ?");
query.addBindValue(groupId);
if (!execAndNextQuery(query)) {
return 0;
}
QVariant troopId = query.record().value("troop_id");
query.prepare("SELECT id FROM subject WHERE name = ?");
query.addBindValue(subject);
if (!execAndNextQuery(query)) {
qDebug() << "unknown subject" << subject;
return 0;
}
int subjectId = query.record().value("id").toInt();
teacher = teacher.simplified();
int teacherId = 0;
if (!teacher.isEmpty()) {
query.prepare("SELECT id FROM teacher WHERE name = ?");
query.addBindValue(teacher);
if (!execAndNextQuery(query)) {
QStringList splittedTeacher = teacher.split(" ");
query.prepare("SELECT id FROM teacher WHERE name LIKE '%" +
splittedTeacher.at(splittedTeacher.length() - 2) + " " +
splittedTeacher.last() + "'");
if (!execAndNextQuery(query)) {
query.prepare("INSERT INTO teacher (name) VALUES (?)");
query.addBindValue(teacher);
if (!execQuery(query)) {
qDebug() << "teacher insertion error";
return 0;
} else {
teacherId = query.lastInsertId().toInt();
}
}
}
if (!teacherId) {
teacherId = query.record().value("id").toInt();
}
}
date = date.simplified();
QDate oDate = QDate(1970, 1, 1);
if (!date.isEmpty()) {
oDate = QDate::fromString(date.split(" ").at(0), "dd.MM.yyyy");
}
query.prepare("SELECT id FROM evaluation WHERE subject_id = ? AND"
" control_type_id = ? AND troop_id = ? AND date = ?");
query.addBindValue(subjectId);
query.addBindValue(controlTypeId);
query.addBindValue(troopId);
query.addBindValue(oDate);
if (!execQuery(query)) {
qDebug() << "ALARMEEEE";
return 0;
}
if (query.next()) {
return query.record().value("id").toInt();
}
query.prepare("INSERT INTO evaluation (subject_id, control_type_id,"
" teacher_id, troop_id, date) VALUES (?, ?, ?, ?, ?)");
query.addBindValue(subjectId);
query.addBindValue(controlTypeId);
query.addBindValue(teacherId ? teacherId : QVariant());
query.addBindValue(troopId);
query.addBindValue(oDate);
if (!execQuery(query)) {
qDebug() << "OPA ZHOPA STYLE";
return 0;
}
return query.lastInsertId().toInt();
}
示例4: QLatin1String
bool DeviceSkinParameters::read(QTextStream &ts, ReadMode rm, QString *errorMessage)
{
QStringList closedAreas;
QStringList toggleAreas;
QStringList toggleActiveAreas;
int nareas = 0;
screenDepth = 0;
QString mark;
ts >> mark;
hasMouseHover = true; // historical default
if ( mark == QLatin1String("[SkinFile]") ) {
const QString UpKey = QLatin1String("Up");
const QString DownKey = QLatin1String("Down");
const QString ClosedKey = QLatin1String("Closed");
const QString ClosedAreasKey = QLatin1String("ClosedAreas");
const QString ScreenKey = QLatin1String("Screen");
const QString ScreenDepthKey = QLatin1String("ScreenDepth");
const QString BackScreenKey = QLatin1String("BackScreen");
const QString ClosedScreenKey = QLatin1String("ClosedScreen");
const QString CursorKey = QLatin1String("Cursor");
const QString AreasKey = QLatin1String("Areas");
const QString ToggleAreasKey = QLatin1String("ToggleAreas");
const QString ToggleActiveAreasKey = QLatin1String("ToggleActiveAreas");
const QString HasMouseHoverKey = QLatin1String("HasMouseHover");
// New
while (!nareas) {
QString line = ts.readLine();
if ( line.isNull() )
break;
if ( line[0] != QLatin1Char('#') && !line.isEmpty() ) {
int eq = line.indexOf(QLatin1Char('='));
if ( eq >= 0 ) {
const QString key = line.left(eq);
eq++;
while (eq<line.length()-1 && line[eq].isSpace())
eq++;
const QString value = line.mid(eq);
if ( key == UpKey ) {
skinImageUpFileName = value;
} else if ( key == DownKey ) {
skinImageDownFileName = value;
} else if ( key == ClosedKey ) {
skinImageClosedFileName = value;
} else if ( key == ClosedAreasKey ) {
closedAreas = value.split(QLatin1Char(' '));
} else if ( key == ScreenKey ) {
parseRect( value, &screenRect);
} else if ( key == ScreenDepthKey ) {
screenDepth = value.toInt();
} else if ( key == BackScreenKey ) {
parseRect(value, &backScreenRect);
} else if ( key == ClosedScreenKey ) {
parseRect( value, &closedScreenRect );
} else if ( key == CursorKey ) {
QStringList l = value.split(QLatin1Char(' '));
skinCursorFileName = l[0];
cursorHot = QPoint(l[1].toInt(),l[2].toInt());
} else if ( key == AreasKey ) {
nareas = value.toInt();
} else if ( key == ToggleAreasKey ) {
toggleAreas = value.split(QLatin1Char(' '));
} else if ( key == ToggleActiveAreasKey ) {
toggleActiveAreas = value.split(QLatin1Char(' '));
} else if ( key == HasMouseHoverKey ) {
hasMouseHover = value == QLatin1String("true") || value == QLatin1String("1");
}
} else {
*errorMessage = DeviceSkin::tr("Syntax error: %1").arg(line);
return false;
}
}
}
} else {
// Old
skinImageUpFileName = mark;
QString s;
int x,y,w,h,na;
ts >> s >> x >> y >> w >> h >> na;
skinImageDownFileName = s;
screenRect.setRect(x, y, w, h);
nareas = na;
}
// Done for short mode
if (rm == ReadSizeOnly)
return true;
// verify skin files exist
skinImageUpFileName.insert(0, prefix);
if (!QFile(skinImageUpFileName).exists()) {
*errorMessage = DeviceSkin::tr("The skin \"up\" image file '%1' does not exist.").arg(skinImageUpFileName);
return false;
}
if (!skinImageUp.load(skinImageUpFileName)) {
*errorMessage = msgImageNotLoaded(skinImageUpFileName);
return false;
}
skinImageDownFileName.insert(0, prefix);
if (!QFile(skinImageDownFileName).exists()) {
*errorMessage = DeviceSkin::tr("The skin \"down\" image file '%1' does not exist.").arg(skinImageDownFileName);
return false;
//.........这里部分代码省略.........
示例5: QWidget
RecoveryWidget::RecoveryWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::RecoveryWidget)
{
ui->setupUi(this);
this->setLayout(this->ui->layoutRecovery);
QSettings settings;
this->sdk=settings.value("sdkPath").toString();
this->dialog = NULL;
this->recoverySDmounted=false;
QProcess *nandroid = new QProcess;
QString output, tmp;
QStringList tmpLines;
nandroid->start("\"" + sdk + "\"adb shell su -c 'find /sbin -name nandroid-mobile*.sh'");
nandroid->waitForFinished(-1);
output = nandroid->readAll();
tmpLines = output.split("\n", QString::SkipEmptyParts);
this->nandroidScript.clear();
while (tmpLines.size() > 0)
{
tmp = tmpLines.takeFirst();
if (tmp.contains("find"))
{
continue;
}
else
{
this->nandroidScript = tmp;
}
}
if (this->nandroidScript.isEmpty())
{
this->ui->buttonNandroidBackup->setDisabled(true);
this->ui->buttonNandroidRestore->setDisabled(true);
}
else
{
this->ui->buttonNandroidBackup->setDisabled(false);
this->ui->buttonNandroidRestore->setDisabled(false);
}
QProcess *process=new QProcess();
process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/wipe'");
process->waitForFinished(-1);
tmp = process->readAll();
if (tmp.contains("No such file"))
this->ui->buttonClearBattery->setDisabled(true);
else
this->ui->buttonClearBattery->setEnabled(true);
process->terminate();
delete process;
process=new QProcess();
process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/ums_toggle'");
process->waitForFinished(-1);
tmp = process->readAll();
if (tmp.contains("No such file"))
this->ui->buttonMountSD->setDisabled(true);
else
this->ui->buttonMountSD->setEnabled(true);
process->terminate();
delete process;
process=new QProcess();
process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/fix_permissions'");
process->waitForFinished(-1);
tmp = process->readAll();
if (tmp.contains("No such file"))
this->ui->buttonFixUID->setDisabled(true);
else
this->ui->buttonFixUID->setEnabled(true);
process->terminate();
delete process;
this->ui->stackedRecovery->setCurrentWidget(this->ui->pageRecoveryStart);
ui->pageWipeData->setLayout(ui->layoutWipeData);
ui->pageFixUID->setLayout(ui->layoutFixUID);
ui->pageFlashZIP->setLayout(ui->layoutFlashZIP);
ui->pageNandroidBackup->setLayout(ui->layoutNandroidBackup);
ui->pageNandroidRestore->setLayout(ui->layoutNandroidRestore);
ui->pageRecoveryStart->setLayout(ui->layoutRecoveryStart);
connect(this->ui->buttonClearBattery, SIGNAL(clicked()), this, SLOT(wipeBattery()));
connect(this->ui->buttonFixUID, SIGNAL(clicked()), this, SLOT(fixUID()));
connect(this->ui->buttonMountSD, SIGNAL(clicked()), this, SLOT(mountSDcard()));
connect(this->ui->buttonNandroidBackup, SIGNAL(clicked()), this, SLOT(nandroidBackupPage()));
connect(this->ui->buttonNandroidRestore, SIGNAL(clicked()), this, SLOT(nandroidRestorePage()));
connect(this->ui->checkNandroidBackupPath, SIGNAL(toggled(bool)), this, SLOT(nandroidBackupEdit()));
connect(this->ui->checkNandroidBackupString, SIGNAL(toggled(bool)), this, SLOT(nandroidBackupEdit()));
connect(this->ui->buttonNandroidBackupStart, SIGNAL(clicked()), this, SLOT(nandroidBackup()));
connect(this->ui->buttonNandroidRestoreStart, SIGNAL(clicked()), this, SLOT(nandroidRestore()));
connect(this->ui->comboNandroidRestore, SIGNAL(currentIndexChanged(QString)), this, SLOT(nandroidRestoreCombo()));
connect(this->ui->buttonWipeData, SIGNAL(clicked()), this, SLOT(wipeData()));
}
示例6: hasScaleBasedVisibility
bool QgsMapLayer::writeXML( QDomNode & layer_node, QDomDocument & document )
{
// general layer metadata
QDomElement maplayer = document.createElement( "maplayer" );
// use scale dependent visibility flag
maplayer.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
maplayer.setAttribute( "minimumScale", QString::number( minimumScale() ) );
maplayer.setAttribute( "maximumScale", QString::number( maximumScale() ) );
// ID
QDomElement layerId = document.createElement( "id" );
QDomText layerIdText = document.createTextNode( id() );
layerId.appendChild( layerIdText );
maplayer.appendChild( layerId );
// data source
QDomElement dataSource = document.createElement( "datasource" );
QString src = source();
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
// TODO: what about postgres, mysql and others, they should not go through writePath()
if ( vlayer && vlayer->providerType() == "spatialite" )
{
QgsDataSourceURI uri( src );
QString database = QgsProject::instance()->writePath( uri.database() );
uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
src = uri.uri();
}
else if ( vlayer && vlayer->providerType() == "ogr" )
{
QStringList theURIParts = src.split( "|" );
theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] );
src = theURIParts.join( "|" );
}
else if ( vlayer && vlayer->providerType() == "delimitedtext" )
{
QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) );
urlDest.setQueryItems( urlSource.queryItems() );
src = QString::fromAscii( urlDest.toEncoded() );
}
else
{
src = QgsProject::instance()->writePath( src );
}
QDomText dataSourceText = document.createTextNode( src );
dataSource.appendChild( dataSourceText );
maplayer.appendChild( dataSource );
// layer name
QDomElement layerName = document.createElement( "layername" );
QDomText layerNameText = document.createTextNode( name() );
layerName.appendChild( layerNameText );
// layer title
QDomElement layerTitle = document.createElement( "title" ) ;
QDomText layerTitleText = document.createTextNode( title() );
layerTitle.appendChild( layerTitleText );
// layer abstract
QDomElement layerAbstract = document.createElement( "abstract" );
QDomText layerAbstractText = document.createTextNode( abstract() );
layerAbstract.appendChild( layerAbstractText );
maplayer.appendChild( layerName );
maplayer.appendChild( layerTitle );
maplayer.appendChild( layerAbstract );
// timestamp if supported
if ( timestamp() > QDateTime() )
{
QDomElement stamp = document.createElement( "timestamp" );
QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
stamp.appendChild( stampText );
maplayer.appendChild( stamp );
}
maplayer.appendChild( layerName );
// zorder
// This is no longer stored in the project file. It is superfluous since the layers
// are written and read in the proper order.
// spatial reference system id
QDomElement mySrsElement = document.createElement( "srs" );
mCRS->writeXML( mySrsElement, document );
maplayer.appendChild( mySrsElement );
// <transparencyLevelInt>
QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
QDomText transparencyLevelIntText = document.createTextNode( QString::number( getTransparency() ) );
transparencyLevelIntElement.appendChild( transparencyLevelIntText );
maplayer.appendChild( transparencyLevelIntElement );
// now append layer node to map layer node
//.........这里部分代码省略.........
示例7: splitString
bool SvgFileSplitter::splitString(QString & contents, const QString & elementID)
{
m_byteArray.clear();
// gets rid of some crap inserted by illustrator which can screw up polygons and paths
contents.replace('\t', ' ');
contents.replace('\n', ' ');
contents.replace('\r', ' ');
// get rid of inkscape stuff too
TextUtils::cleanSodipodi(contents);
QString errorStr;
int errorLine;
int errorColumn;
if (!m_domDocument.setContent(contents, true, &errorStr, &errorLine, &errorColumn)) {
//DebugDialog::debug(QString("parse error: %1 l:%2 c:%3\n\n%4").arg(errorStr).arg(errorLine).arg(errorColumn).arg(contents));
return false;
}
QDomElement root = m_domDocument.documentElement();
if (root.isNull()) {
return false;
}
if (root.tagName() != "svg") {
return false;
}
root.removeAttribute("space");
QDomElement element = TextUtils::findElementWithAttribute(root, "id", elementID);
if (element.isNull()) {
return false;
}
QStringList superTransforms;
QDomNode parent = element.parentNode();
while (!parent.isNull()) {
QDomElement e = parent.toElement();
if (!e.isNull()) {
QString transform = e.attribute("transform");
if (!transform.isEmpty()) {
superTransforms.append(transform);
}
}
parent = parent.parentNode();
}
if (!superTransforms.isEmpty()) {
element.removeAttribute("id");
}
QDomDocument document;
QDomNode node = document.importNode(element, true);
document.appendChild(node);
QString elementText = document.toString();
if (!superTransforms.isEmpty()) {
for (int i = 0; i < superTransforms.count() - 1; i++) {
elementText = QString("<g transform='%1'>%2</g>").arg(superTransforms[i]).arg(elementText);
}
elementText = QString("<g id='%1' transform='%2'>%3</g>")
.arg(elementID)
.arg(superTransforms[superTransforms.count() - 1])
.arg(elementText);
}
while (!root.firstChild().isNull()) {
root.removeChild(root.firstChild());
}
// at this point the document should contain only the <svg> element and possibly svg info strings
QString svgOnly = m_domDocument.toString();
int ix = svgOnly.lastIndexOf("/>");
if (ix < 0) return false;
svgOnly[ix] = ' ';
svgOnly += elementText;
svgOnly += "</svg>";
if (!m_domDocument.setContent(svgOnly, true, &errorStr, &errorLine, &errorColumn)) {
return false;
}
m_byteArray = m_domDocument.toByteArray();
//QString s = m_domDocument.toString();
//DebugDialog::debug(s);
return true;
}
示例8: tvalue2json
void tvalue2json(rapidjson::Value & output, const QVariant & input, rapidjson::Value::AllocatorType & allocator)
{
switch(input.type())
{
case QVariant::Invalid:
{
output.SetNull();
break;
}
case QVariant::Bool:
{
output.SetBool(input.toBool());
break;
}
case QVariant::Int:
{
output.SetInt64(input.toInt());
break;
}
case QVariant::LongLong:
{
output.SetInt64(input.toLongLong());
break;
}
case QVariant::Double:
{
output.SetDouble(input.toDouble());
break;
}
case QVariant::String:
{
QByteArray str = input.toString().toUtf8();
output.SetString(str.data(), str.size(), allocator);
break;
}
case QVariant::StringList:
{
QStringList list = input.toStringList();
output.SetArray();
output.Reserve(list.size(), allocator);
rapidjson::Value temp;
for(QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
{
QByteArray str = it->toUtf8();
temp.SetString(str.data(), str.size(), allocator);
output.PushBack(temp, allocator);
}
break;
}
case QVariant::List:
{
QList<QVariant> list = input.toList();
output.SetArray();
output.Reserve(list.size(), allocator);
rapidjson::Value temp;
for(QList<QVariant>::const_iterator it = list.begin(); it != list.end(); ++it)
{
tvalue2json(temp, *it, allocator);
output.PushBack(temp, allocator);
}
break;
}
case QVariant::Map:
{
output.SetObject();
rapidjson::Value tempK, tempV;
QMap<QString, QVariant> qmap = input.toMap();
for(QMap<QString, QVariant>::const_iterator it = qmap.begin(); it != qmap.end(); ++it)
{
tvalue2json(tempK, it.key(), allocator);
tvalue2json(tempV, it.value(), allocator);
output.AddMember(tempK, tempV, allocator);
}
break;
}
case QVariant::Point:
{
QPoint pt = input.toPoint();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
break;
}
case QVariant::PointF:
{
QPointF pt = input.toPointF();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
//.........这里部分代码省略.........
示例9: json2tvalue
void json2tvalue(QVariant & output, const rapidjson::Value & input, int itype)
{
if(input.IsNull())
{
output.clear();
}
else if(input.IsInt64())
{
output = QVariant(input.GetInt64());
}
else if(input.IsInt())
{
output = QVariant(input.GetInt());
}
else if(input.IsDouble())
{
output = QVariant(input.GetDouble());
}
else if(input.IsBool())
{
output = QVariant(input.GetBool());
}
else if(input.IsString())
{
output = QVariant(QString(input.GetString()));
}
else if(input.IsArray())
{
switch(itype)
{
case QVariant::Point:
{
assert(input.Size() == 2);
output = QPoint(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::PointF:
{
assert(input.Size() == 2);
output = QPointF(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Size:
{
assert(input.Size() == 2);
output = QSize(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::SizeF:
{
assert(input.Size() == 2);
output = QSizeF(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Rect:
{
assert(input.Size() == 4);
output = QRect(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::RectF:
{
assert(input.Size() == 4);
output = QRectF(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::Vector2D:
{
assert(input.Size() == 2);
output = QVector2D(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Vector3D:
{
assert(input.Size() == 3);
output = QVector3D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble());
break;
}
case QVariant::Vector4D:
{
assert(input.Size() == 4);
output = QVector4D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::Color:
{
assert(input.Size() == 4);
output = QColor(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::StringList:
{
QStringList list;
list.reserve(input.Size());
for(rapidjson::Value::ConstValueIterator it = input.Begin(); it != input.End(); ++it)
{
QString tmp(it->GetString());
list.append(tmp);
}
//.........这里部分代码省略.........
示例10: QString
bool FileServerHandler::HandleDownloadFile(SocketHandler *socket,
QStringList &slist)
{
QStringList res;
if (slist.size() != 4)
{
res << "ERROR" << QString("Bad %1 command").arg(slist[0]);
socket->SendStringList(res);
return true;
}
bool synchronous = (slist[0] == "DOWNLOAD_FILE_NOW");
QString srcURL = slist[1];
QString storageGroup = slist[2];
QString filename = slist[3];
StorageGroup sgroup(storageGroup, gCoreContext->GetHostName(), false);
QString outDir = sgroup.FindNextDirMostFree();
QString outFile;
QStringList retlist;
if (filename.isEmpty())
{
QFileInfo finfo(srcURL);
filename = finfo.fileName();
}
if (outDir.isEmpty())
{
LOG(VB_GENERAL, LOG_ERR, QString("Unable to determine directory "
"to write to in %1 write command").arg(slist[0]));
res << "ERROR" << "downloadfile_directory_not_found";
socket->SendStringList(res);
return true;
}
if ((filename.contains("/../")) ||
(filename.startsWith("../")))
{
LOG(VB_GENERAL, LOG_ERR, QString("ERROR: %1 write "
"filename '%2' does not pass sanity checks.")
.arg(slist[0]).arg(filename));
res << "ERROR" << "downloadfile_filename_dangerous";
socket->SendStringList(res);
return true;
}
outFile = outDir + "/" + filename;
if (synchronous)
{
if (GetMythDownloadManager()->download(srcURL, outFile))
{
res << "OK"
<< gCoreContext->GetMasterHostPrefix(storageGroup)
+ filename;
}
else
res << "ERROR";
}
else
{
QMutexLocker locker(&m_downloadURLsLock);
m_downloadURLs[outFile] =
gCoreContext->GetMasterHostPrefix(storageGroup) +
StorageGroup::GetRelativePathname(outFile);
GetMythDownloadManager()->queueDownload(srcURL, outFile, this);
res << "OK"
<< gCoreContext->GetMasterHostPrefix(storageGroup) + filename;
}
socket->SendStringList(res);
return true;
}
示例11: foreach
void WelcomeBrowser::loadData()
{
QString data = m_templateData;
QStringList sessionList;
sessionList.append("<ul>");
sessionList.append(QString("<li><a href=\"session:default\">default</a></li>"));
sessionList.append("</ul>");
QStringList list;
QStringList schemeList;
//schemeList = m_liteApp->fileManager()->schemeList();
schemeList << "folder" << "file";
schemeList.append(m_liteApp->fileManager()->schemeList());
schemeList.removeDuplicates();
foreach (QString scheme, schemeList) {
QString s = scheme.left(1).toUpper()+scheme.right(scheme.length()-1);
list.append(QString("<h3><i>Recent %1</i></h3>").arg(s));
list.append("<table border=\"0\"><tr><td>");
list.append("<ul>");
QStringList recentProjects = m_liteApp->fileManager()->recentFiles(scheme);
int count = 0;
foreach (QString file, recentProjects) {
QFileInfo info(file);
list.append(QString("<li><a href=\"%1:%2\">%3</a> <span class=\"recent\">%4</span></li>")
.arg(scheme)
.arg(info.filePath())
.arg(info.fileName())
.arg(QDir::toNativeSeparators(info.filePath())));
if (count++ > 8) {
break;
}
}
示例12: HandleQueryFileTransfer
bool FileServerHandler::HandleQueryFileTransfer(SocketHandler *socket,
QStringList &commands, QStringList &slist)
{
if (commands.size() != 2)
return false;
if (slist.size() < 2)
return false;
QStringList res;
int recnum = commands[1].toInt();
FileTransfer *ft;
{
QReadLocker rlock(&m_ftLock);
if (!m_ftMap.contains(recnum))
{
if (slist[1] == "DONE")
res << "ok";
else
{
LOG(VB_GENERAL, LOG_ERR,
QString("Unknown file transfer socket: %1").arg(recnum));
res << "ERROR"
<< "unknown_file_transfer_socket";
}
socket->SendStringList(res);
return true;
}
ft = m_ftMap[recnum];
ft->UpRef();
}
if (slist[1] == "IS_OPEN")
{
res << QString::number(ft->isOpen());
}
else if (slist[1] == "DONE")
{
ft->Stop();
res << "ok";
}
else if (slist[1] == "REQUEST_BLOCK")
{
if (slist.size() != 3)
{
LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
"REQUEST_BLOCK call");
res << "ERROR" << "invalid_call";
}
else
{
int size = slist[2].toInt();
res << QString::number(ft->RequestBlock(size));
}
}
else if (slist[1] == "WRITE_BLOCK")
{
if (slist.size() != 3)
{
LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
"WRITE_BLOCK call");
res << "ERROR" << "invalid_call";
}
else
{
int size = slist[2].toInt();
res << QString::number(ft->WriteBlock(size));
}
}
else if (slist[1] == "SEEK")
{
if (slist.size() != 5)
{
LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER SEEK call");
res << "ERROR" << "invalid_call";
}
else
{
long long pos = slist[2].toLongLong();
int whence = slist[3].toInt();
long long curpos = slist[4].toLongLong();
res << QString::number(ft->Seek(curpos, pos, whence));
}
}
else if (slist[1] == "SET_TIMEOUT")
{
if (slist.size() != 3)
{
LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
"SET_TIMEOUT call");
res << "ERROR" << "invalid_call";
}
else
{
bool fast = slist[2].toInt();
ft->SetTimeout(fast);
//.........这里部分代码省略.........
示例13: HandleGetFileList
bool FileServerHandler::HandleGetFileList(SocketHandler *socket,
QStringList &slist)
{
QStringList res;
bool fileNamesOnly = false;
if (slist.size() == 5)
fileNamesOnly = slist[4].toInt();
else if (slist.size() != 4)
{
LOG(VB_GENERAL, LOG_ERR, QString("Invalid Request. %1")
.arg(slist.join("[]:[]")));
res << "EMPTY LIST";
socket->SendStringList(res);
return true;
}
QString host = gCoreContext->GetHostName();
QString wantHost = slist[1];
QString groupname = slist[2];
QString path = slist[3];
LOG(VB_FILE, LOG_INFO,
QString("HandleSGGetFileList: group = %1 host = %2 "
"path = %3 wanthost = %4")
.arg(groupname).arg(host).arg(path).arg(wantHost));
if ((host.toLower() == wantHost.toLower()) ||
(gCoreContext->GetSetting("BackendServerIP") == wantHost))
{
StorageGroup sg(groupname, host);
LOG(VB_FILE, LOG_INFO, "Getting local info");
if (fileNamesOnly)
res = sg.GetFileList(path);
else
res = sg.GetFileInfoList(path);
if (res.count() == 0)
res << "EMPTY LIST";
}
else
{
// handle request on remote server
SocketHandler *remsock = NULL;
{
QReadLocker rlock(&m_fsLock);
if (m_fsMap.contains(wantHost))
{
remsock = m_fsMap[wantHost];
remsock->UpRef();
}
}
if (remsock)
{
LOG(VB_FILE, LOG_INFO, "Getting remote info");
res << "QUERY_SG_GETFILELIST" << wantHost << groupname << path
<< QString::number(fileNamesOnly);
remsock->SendReceiveStringList(res);
remsock->DownRef();
}
else
{
LOG(VB_FILE, LOG_ERR, QString("Failed to grab slave socket : %1 :")
.arg(wantHost));
res << "SLAVE UNREACHABLE: " << wantHost;
}
}
socket->SendStringList(res);
return true;
}
示例14: HandleQueryFileExists
/**
* \addtogroup myth_network_protocol
* \par QUERY_FILE_EXISTS \e storagegroup \e filename
*/
bool FileServerHandler::HandleQueryFileExists(SocketHandler *socket,
QStringList &slist)
{
QString storageGroup = "Default";
QStringList res;
if (slist.size() == 3)
{
if (!slist[2].isEmpty())
storageGroup = slist[2];
}
else if (slist.size() != 2)
return false;
QString filename = slist[1];
if ((filename.isEmpty()) ||
(filename.contains("/../")) ||
(filename.startsWith("../")))
{
LOG(VB_GENERAL, LOG_ERR,
QString("ERROR checking for file, filename '%1' "
"fails sanity checks").arg(filename));
res << "";
socket->SendStringList(res);
return true;
}
StorageGroup sgroup(storageGroup, gCoreContext->GetHostName());
QString fullname = sgroup.FindFile(filename);
if (!fullname.isEmpty())
{
res << "1"
<< fullname;
// TODO: convert me to QFile
struct stat fileinfo;
if (stat(fullname.toLocal8Bit().constData(), &fileinfo) >= 0)
{
res << QString::number(fileinfo.st_dev)
<< QString::number(fileinfo.st_ino)
<< QString::number(fileinfo.st_mode)
<< QString::number(fileinfo.st_nlink)
<< QString::number(fileinfo.st_uid)
<< QString::number(fileinfo.st_gid)
<< QString::number(fileinfo.st_rdev)
<< QString::number(fileinfo.st_size)
#ifdef USING_MINGW
<< "0"
<< "0"
#else
<< QString::number(fileinfo.st_blksize)
<< QString::number(fileinfo.st_blocks)
#endif
<< QString::number(fileinfo.st_atime)
<< QString::number(fileinfo.st_mtime)
<< QString::number(fileinfo.st_ctime);
}
}
else
res << "0";
socket->SendStringList(res);
return true;
}
示例15: lifeFile
//------------------------------------------------------------------------------
void Logical::loadFromFile(QString fileName) {
QFile lifeFile(fileName);
if (!lifeFile.open(QIODevice::ReadOnly)) {
QMessageBox::critical(0, tr("Error"),
tr("Can't load file"));
return;
} else {
QTextStream lifeStream(&lifeFile);
//Очистка буфера
for (int i = 0; i < useHeight; ++i) {
for (int j = 0; j < useWidth; ++j)
lBuffer[i][j] = 0;
}
int lineCounter = 0;
int positionI = 0;
int positionJ = 0;
int positionLastJ = 0;
while (!lifeStream.atEnd()) {
QString line = lifeStream.readLine();
if (lineCounter == 0) {
//Сделать проверку первой строки формата
if (line.indexOf("#Life 1.05") == -1) {
QMessageBox::critical(0, tr("Error"),
tr("Format isn't supported"));
return;
}
}
if (
(line[0] == '.')
||
(line[0] == '*')) {
//Заполнять поле
for (int i = 0; i < line.length(); ++i) {
if (line[i] == '.') {
lBuffer[positionI][positionJ] = 0;
positionJ++;
} else if (line[i] == '*') {
lBuffer[positionI][positionJ] = 1;
positionJ++;
}
}
positionI++;
}
QStringList splitted = line.split(' ');
if (splitted[0] == "#P") {
//Сменить начальную позицию
//Размерность поделить на двое, чтобы получить -x 0 +x
positionLastJ = (useWidth / 2) + splitted.at(1).toInt();
positionI = (useHeight / 2) + splitted.at(2).toInt();
}
positionJ = positionLastJ;
lineCounter++;
}
lifeFile.close();
//Перенести буферное поле в реальное, а перед этим сделать очистку
for (int i = 0; i < useHeight; ++i) {
for (int j = 0; j < useWidth; ++j)
lPole[i][j] = lBuffer[i][j];
}
}
}