bool BuildDirManager::hasConfigChanged() { checkConfiguration(); const QByteArray GENERATOR_KEY = "CMAKE_GENERATOR"; const QByteArray EXTRA_GENERATOR_KEY = "CMAKE_EXTRA_GENERATOR"; const QByteArray CMAKE_COMMAND_KEY = "CMAKE_COMMAND"; const QByteArray CMAKE_C_COMPILER_KEY = "CMAKE_C_COMPILER"; const QByteArray CMAKE_CXX_COMPILER_KEY = "CMAKE_CXX_COMPILER"; const QByteArrayList criticalKeys = {GENERATOR_KEY, CMAKE_COMMAND_KEY, CMAKE_C_COMPILER_KEY, CMAKE_CXX_COMPILER_KEY}; const CMakeConfig currentConfig = takeCMakeConfiguration(); const CMakeTool *tool = m_parameters.cmakeTool(); QTC_ASSERT(tool, return false); // No cmake... we should not have ended up here in the first place const QString extraKitGenerator = m_parameters.extraGenerator; const QString mainKitGenerator = m_parameters.generator; CMakeConfig targetConfig = m_parameters.configuration; targetConfig.append(CMakeConfigItem(GENERATOR_KEY, CMakeConfigItem::INTERNAL, QByteArray(), mainKitGenerator.toUtf8())); if (!extraKitGenerator.isEmpty()) targetConfig.append(CMakeConfigItem(EXTRA_GENERATOR_KEY, CMakeConfigItem::INTERNAL, QByteArray(), extraKitGenerator.toUtf8())); targetConfig.append(CMakeConfigItem(CMAKE_COMMAND_KEY, CMakeConfigItem::INTERNAL, QByteArray(), tool->cmakeExecutable().toUserOutput().toUtf8())); Utils::sort(targetConfig, CMakeConfigItem::sortOperator()); bool mustReparse = false; auto ccit = currentConfig.constBegin(); auto kcit = targetConfig.constBegin(); while (ccit != currentConfig.constEnd() && kcit != targetConfig.constEnd()) { if (ccit->key == kcit->key) { if (ccit->value != kcit->value) { if (criticalKeys.contains(kcit->key)) { clearCache(); return false; // no need to trigger a new reader, clearCache will do that } mustReparse = true; } ++ccit; ++kcit; } else { if (ccit->key < kcit->key) { ++ccit; } else { ++kcit; mustReparse = true; } } } // If we have keys that do not exist yet, then reparse. // // The critical keys *must* be set in cmake configuration, so those were already // handled above. return mustReparse || kcit != targetConfig.constEnd(); }
void SftpSession::handleLsOutput(SftpJobId jobId, const QByteArray &output) { QList<SftpFileInfo> allFileInfo; for (const QByteArray &line : output.split('\n')) { if (line.startsWith("ls") || line.isEmpty()) continue; const QByteArrayList components = line.simplified().split(' '); if (components.size() < 9) { qCWarning(sshLog) << "Don't know how to parse sftp ls output:" << line; continue; } const QByteArray typeAndPermissions = components.first(); if (typeAndPermissions.size() != 10) { qCWarning(sshLog) << "Don't know how to parse sftp ls output:" << line; continue; } SftpFileInfo fileInfo; fileInfo.type = typeFromLsOutput(typeAndPermissions.at(0)); fileInfo.permissions = permissionsFromLsOutput(QByteArray::fromRawData( typeAndPermissions.constData() + 1, typeAndPermissions.size() - 1)); bool isNumber; fileInfo.size = components.at(4).toULongLong(&isNumber); if (!isNumber) { qCWarning(sshLog) << "Don't know how to parse sftp ls output:" << line; continue; } // TODO: This will not work for file names with weird whitespace combinations fileInfo.name = QFileInfo(QString::fromUtf8(components.mid(8).join(' '))).fileName(); allFileInfo << fileInfo; } emit fileInfoAvailable(jobId, allFileInfo); }
void tst_QByteArrayList::joinEmptiness() const { QByteArrayList list; QByteArray string = list.join(QByteArray()); QVERIFY(string.isEmpty()); QVERIFY(string.isNull()); }
static QByteArrayList argumentList(const DwarfDie *die) { QByteArrayList args; foreach (const auto child, die->children()) { if (child->tag() == DW_TAG_formal_parameter) { args.push_back(child->typeName()); } } return args; }
void LocalDiscoveryTracker::startSyncPartialDiscovery() { if (lcLocalDiscoveryTracker().isDebugEnabled()) { QByteArrayList paths; for (auto &path : _localDiscoveryPaths) paths.append(path); qCDebug(lcLocalDiscoveryTracker) << "partial discovery with paths: " << paths; } _previousLocalDiscoveryPaths = std::move(_localDiscoveryPaths); _localDiscoveryPaths.clear(); }
void QScxmlcGenerator::parseIssues(const QByteArray &processStderr) { QList<ProjectExplorer::Task> issues; foreach (const QByteArray &line, processStderr.split('\n')) { QByteArrayList tokens = line.split(':'); if (tokens.length() > 4) { Utils::FileName file = Utils::FileName::fromUtf8(tokens[0]); int line = tokens[1].toInt(); // int column = tokens[2].toInt(); <- nice, but not needed for now. ProjectExplorer::Task::TaskType type = tokens[3].trimmed() == "error" ? ProjectExplorer::Task::Error : ProjectExplorer::Task::Warning; QString message = QString::fromUtf8(tokens.mid(4).join(':').trimmed()); issues.append(ProjectExplorer::Task(type, message, file, line, TaskCategory)); } } setCompileIssues(issues); }
void GsmTrack::slReadSerial() { QByteArray data = gsmSerial->readAll().trimmed(); //qDebug() << "the date:: " << data << endl; emit sendData(data); if(data.contains("+CSQ: ")){ int csq; int csq_tail; std::sscanf(data.data(), "+CSQ: %d,%d", &csq, &csq_tail); qDebug("the csq is:: %d\n", csq); if(csq <= 10 || csq > 31){ emit sendCsq(0); return; } emit sendCsq(csq); } // 读取网络类型与网路配置 if(data.contains("^SYSCFG: ")){ int type; std::sscanf(data.data(), "^SYSCFG: %d", &type); if(type == 13){ emit sendText("2G network it is!!"); }else if(type == 2){ emit sendText("3G network it is!!"); } } // 基站信息 // BASE:: "AT+CREG=2;+CREG?" // OUT :: +CREG: 2,1,"A5D3","19E420F",2 if(data.contains("+CREG: ")){ qDebug() << data << endl; QByteArrayList cregList = data.split(','); emit sendBase(QLatin1String( cregList.at(2) + "," + cregList.at(3) )); } }
HttpInfo::HttpInfo(const QByteArray &data, PackageType type): m_httpVersion("HTTP/1.1"), m_errorCode(NoError) { m_url.setScheme("http"); QStringList list = QString::fromUtf8(data).split("\r\n"); if(!list.isEmpty()){ QByteArrayList tmp = list.first().toUtf8().split(' '); if(tmp.count() == 3){ if(type == Request){ setMethod(tmp[0]); QByteArray path = tmp[1].split('?').first(); m_url.setPath(path); if(path.count() < tmp[1].count()) m_url.setQuery(tmp[1].mid(path.count() + 1)); setHttpVersion(tmp[2]); }else{ setHttpVersion(tmp[0]); setError(ErrorCode(tmp[1].toInt())); setErrorString(tmp[2]); } }else{ setError(BadRequest); setErrorString(QString("%1 Bad Request").arg(BadRequest)); return; } int i = 1; for(; i < tmp.count(); ++i){ tmp = list[i].toUtf8().split(':'); if(tmp.count() == 2){ setRawHeader(tmp.first(), tmp.last().trimmed()); if(tmp.first() == "Host") m_url.setHost(tmp.last().trimmed()); }else{ setError(BadRequest); setErrorString(QString("%1 Bad Request").arg(BadRequest)); return; } } }else{ setError(BadRequest); setErrorString(QString("%1 Bad Request").arg(BadRequest)); return; } }
void SqliteTableModel::fetchData(unsigned int from, unsigned to) { int currentsize = m_data.size(); QString sLimitQuery; if(m_sQuery.startsWith("PRAGMA", Qt::CaseInsensitive) || m_sQuery.startsWith("EXPLAIN", Qt::CaseInsensitive)) { sLimitQuery = m_sQuery; } else { // Remove trailing trailing semicolon QString queryTemp = rtrimChar(m_sQuery, ';'); // If the query ends with a LIMIT statement take it as it is, if not append our own LIMIT part for lazy population if(queryTemp.contains(QRegExp("LIMIT\\s+\\d+\\s*(,\\s*\\d+\\s*)?$", Qt::CaseInsensitive))) sLimitQuery = queryTemp; else sLimitQuery = QString("%1 LIMIT %2, %3;").arg(queryTemp).arg(from).arg(to-from); } m_db->logSQL(sLimitQuery, kLogMsg_App); QByteArray utf8Query = sLimitQuery.toUtf8(); sqlite3_stmt *stmt; int status = sqlite3_prepare_v2(m_db->_db, utf8Query, utf8Query.size(), &stmt, NULL); if(SQLITE_OK == status) { while(sqlite3_step(stmt) == SQLITE_ROW) { QByteArrayList rowdata; for (int i = 0; i < m_headers.size(); ++i) rowdata.append(QByteArray(static_cast<const char*>(sqlite3_column_blob(stmt, i)), sqlite3_column_bytes(stmt, i))); m_data.push_back(rowdata); } } sqlite3_finalize(stmt); beginInsertRows(QModelIndex(), currentsize, m_data.size()-1); endInsertRows(); }
void GvCore::save(const QUrl &url) { Document::Ptr doc = DocumentFactory::instance()->load(url); QByteArray format = doc->format(); const QByteArrayList availableTypes = QImageWriter::supportedImageFormats(); if (availableTypes.contains(format)) { DocumentJob* job = doc->save(url, format); connect(job, SIGNAL(result(KJob*)), SLOT(slotSaveResult(KJob*))); } else { // We don't know how to save in 'format', ask the user for a format we can // write to. KGuiItem saveUsingAnotherFormat = KStandardGuiItem::saveAs(); saveUsingAnotherFormat.setText(i18n("Save using another format")); int result = KMessageBox::warningContinueCancel( d->mMainWindow, i18n("Gwenview cannot save images in '%1' format.", QString(format)), QString() /* caption */, saveUsingAnotherFormat ); if (result == KMessageBox::Continue) { saveAs(url); } } }
void TagHandle::onFileDelete(const QByteArrayList &files) { if (!files.isEmpty()) { QList<DUrl> url_list{}; for (const QByteArray &byte_array : files) { bool result{ DAnythingMonitorFilter::instance()->whetherFilterCurrentPath(byte_array) }; if (result) { DUrl url{ DUrl::fromLocalFile(byte_array) }; url_list.push_back(url); } } TagManager::deleteFiles(url_list); } }
void LyricsParser_KFN::parse(QIODevice * file, LyricsLoader::Container& output, LyricsLoader::Properties &properties) { // Parse the song.ini and fill up the sync and text arrays QByteArrayList texts; QList< int > syncs; // Analyze each line int idx_text = 0, idx_sync = 0; QByteArrayList lines = load( file ).split( '\n' ); bool inGeneral = false; for ( int i = 0; i < lines.size(); i++ ) { QByteArray line = lines[i]; // Section detector if ( line.startsWith( '[' ) && line.endsWith( ']') ) { inGeneral = (line == "[General]"); continue; } if ( inGeneral ) { if ( line.startsWith( "Title=" ) ) { QString v = QString::fromUtf8( line.mid(6) ).trimmed(); if ( !v.isEmpty() ) properties[ LyricsLoader::PROP_TITLE ] = v; } if ( line.startsWith( "Artist=" ) ) { QString v = QString::fromUtf8( line.mid(7) ).trimmed(); if ( !v.isEmpty() ) properties[ LyricsLoader::PROP_ARTIST ] = v; } } // Try to match the sync first char matchbuf[128]; sprintf( matchbuf, "Sync%d=", idx_sync ); if ( line.startsWith( matchbuf ) ) { idx_sync++; // Syncs are split by comma QByteArrayList values = line.mid( strlen(matchbuf) ).split( ',' ); for ( int v = 0; v < values.size(); v++ ) syncs.push_back( values[v].toInt() ); } // Now the text sprintf( matchbuf, "Text%d=", idx_text ); if ( line.startsWith( matchbuf ) ) { idx_text++; QByteArray textvalue = line.mid( strlen(matchbuf) ); if ( !textvalue.isEmpty() ) { // Text is split by word and optionally by the slash QByteArrayList values = textvalue.split(' '); for ( int v = 0; v < values.size(); v++ ) { QByteArrayList morevalues = values[v].split( '/' ); for ( int vv = 0; vv < morevalues.size(); vv++ ) texts.push_back( morevalues[vv] ); // We split by space, so add it at the end of each word texts.last() = texts.last() + " "; } } // Line matched, so make it a line if ( texts.size() > 2 && texts[ texts.size() - 2 ] != "\n" ) texts.push_back( "\n" ); } } int curr_sync = 0; bool has_linefeed = false; int lines_no_block = 0; int lastsync = -1; // The original timing marks are not necessarily sorted, so we add them into a map // and then output them from that map QMap< int, QByteArray > sortedLyrics; for ( int i = 0; i < texts.size(); i++ ) { if ( texts[i] == "\n" ) { if ( lastsync == -1 ) continue; if ( has_linefeed ) lines_no_block = 0; else if ( ++lines_no_block > 6 ) { lines_no_block = 0; sortedLyrics[ lastsync ] += "\n"; } has_linefeed = true; sortedLyrics[ lastsync ] += "\n"; continue; } else has_linefeed = false; // Get the time if we have it if ( curr_sync >= syncs.size() ) continue; lastsync = syncs[ curr_sync++ ]; sortedLyrics.insert( lastsync, texts[i] ); } // Generate the content for encoding detection QByteArray lyricsForEncoding; for ( QMap< int, QByteArray >::const_iterator it = sortedLyrics.begin(); it != sortedLyrics.end(); ++it ) lyricsForEncoding.append( it.value() ); // Detect the encoding QTextCodec * codec = detectEncoding( lyricsForEncoding, properties ); for ( QMap< int, QByteArray >::const_iterator it = sortedLyrics.begin(); it != sortedLyrics.end(); ++it ) { qint64 timing = it.key() * 10; Lyric lyr( timing, codec->toUnicode( it.value() ) ); // Last line? if ( lyr.text.endsWith( '\n') ) { // Remove the \n lyr.text.chop( 1 ); output.push_back( lyr ); // and add an empty lyric output.push_back( Lyric( timing ) ); } else { output.push_back( lyr ); } } }
QVariantMap System::exec(const QString & prog, const QStringList & args) { pid_t pid = fork(); if (pid == 0) { int cargs_len = args.length() + 2; char * cargs[cargs_len]; cargs[cargs_len - 1] = NULL; QByteArrayList as; as.push_back(prog.toLocal8Bit()); std::transform(args.begin(), args.end(), std::back_inserter(as), [](const QString & s) { return s.toLocal8Bit(); }); for (int i = 0; i < as.length(); ++i) { cargs[i] = as[i].data(); } execvp(cargs[0], cargs); // in case execvp fails, terminate the child process immediately _exit(errno); } else if (pid < 0) { goto fail; } else { sigset_t mask; sigset_t orig_mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) { goto fail; } struct timespec timeout; timeout.tv_sec = 0; timeout.tv_nsec = 10 * 1000 * 1000; while (true) { int ret = sigtimedwait(&mask, NULL, &timeout); if (ret < 0) { if (errno == EAGAIN) { // timeout goto win; } else { // error goto fail; } } else { if (errno == EINTR) { // not SIGCHLD continue; } else { siginfo_t si; if (waitid(P_PID, pid, &si, WEXITED) < 0) { goto fail; } else { return { { "errno", si.si_status } , { "error", strerror(si.si_status) } }; } } } } } win: return {}; fail: return { { "errno", errno }, { "error", strerror(errno) } }; }
void ExtendedTableWidget::copy(const bool withHeaders) { QModelIndexList indices = selectionModel()->selectedIndexes(); // Remove all indices from hidden columns, because if we don't we might copy data from hidden columns as well which is very // unintuitive; especially copying the rowid column when selecting all columns of a table is a problem because pasting the data // won't work as expected. QMutableListIterator<QModelIndex> i(indices); while (i.hasNext()) { if (isColumnHidden(i.next().column())) i.remove(); } // Abort if there's nothing to copy if (indices.isEmpty()) return; SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // Clear internal copy-paste buffer m_buffer.clear(); // If a single cell is selected, copy it to clipboard if (!withHeaders && indices.size() == 1) { QImage img; QVariant data = m->data(indices.first(), Qt::EditRole); if (img.loadFromData(data.toByteArray())) { // If it's an image, copy the image data to the clipboard qApp->clipboard()->setImage(img); return; } else { // It it's not an image, check if it's an empty field if (data.toByteArray().isEmpty()) { // The field is either NULL or empty. Those are are handled via the internal copy-paste buffer qApp->clipboard()->setText(QString()); // Calling clear() alone doesn't seem to work on all systems qApp->clipboard()->clear(); m_buffer.push_back(QByteArrayList{data.toByteArray()}); return; } // The field isn't empty. Copy the text to the clipboard without quoting (for general plain text clipboard) qApp->clipboard()->setText(data.toByteArray()); return; } } // If we got here, there are multiple selected cells, or copy with headers was requested. // In this case, we copy selected data into internal copy-paste buffer and then // we write a table both in HTML and text formats to the system clipboard. // Copy selected data into internal copy-paste buffer int last_row = indices.first().row(); QByteArrayList lst; for(int i=0;i<indices.size();i++) { if(indices.at(i).row() != last_row) { m_buffer.push_back(lst); lst.clear(); } lst << indices.at(i).data(Qt::EditRole).toByteArray(); last_row = indices.at(i).row(); } m_buffer.push_back(lst); QString result; QString htmlResult = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"; htmlResult.append("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"); htmlResult.append("<title></title>"); // The generator-stamp is later used to know whether the data in the system clipboard is still ours. // In that case we will give precedence to our internal copy buffer. QString now = QDateTime::currentDateTime().toString("YYYY-MM-DDTHH:mm:ss.zzz"); m_generatorStamp = QString("<meta name=\"generator\" content=\"%1\"><meta name=\"date\" content=\"%2\">").arg(QApplication::applicationName().toHtmlEscaped(), now); htmlResult.append(m_generatorStamp); // TODO: is this really needed by Excel, since we use <pre> for multi-line cells? htmlResult.append("<style type=\"text/css\">br{mso-data-placement:same-cell;}</style></head><body><table>"); int currentRow = indices.first().row(); const QString fieldSepHtml = "</td><td>"; const QString rowSepHtml = "</td></tr><tr><td>"; const QString fieldSepText = "\t"; const QString rowSepText = "\r\n"; // Table headers if (withHeaders) { htmlResult.append("<tr><th>"); int firstColumn = indices.front().column(); for(int i = firstColumn; i <= indices.back().column(); i++) { QByteArray headerText = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toByteArray(); if (i != firstColumn) { result.append(fieldSepText); htmlResult.append("</th><th>"); } result.append(escapeCopiedData(headerText)); htmlResult.append(headerText); } result.append(rowSepText); htmlResult.append("</th></tr>"); } // Table data rows for(const QModelIndex& index : indices) { // Separators. For first cell, only opening table row tags must be added for the HTML and nothing for the text version. if (indices.first() == index) htmlResult.append("<tr><td>"); else if (index.row() != currentRow) { result.append(rowSepText); htmlResult.append(rowSepHtml); } else { result.append(fieldSepText); htmlResult.append(fieldSepHtml); } currentRow = index.row(); QImage img; QVariant data = index.data(Qt::EditRole); // Table cell data: image? Store it as an embedded image in HTML and as base 64 in text version if (img.loadFromData(data.toByteArray())) { QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); buffer.close(); QString imageBase64 = ba.toBase64(); htmlResult.append("<img src=\"data:image/png;base64,"); htmlResult.append(imageBase64); result.append(QString()); htmlResult.append("\" alt=\"Image\">"); } else { QByteArray text; if (!m->isBinary(index)) text = data.toByteArray(); // Table cell data: text if (text.contains('\n') || text.contains('\t')) htmlResult.append("<pre>" + QString(text).toHtmlEscaped() + "</pre>"); else htmlResult.append(QString(text).toHtmlEscaped()); result.append(escapeCopiedData(text)); } } QMimeData *mimeData = new QMimeData; mimeData->setHtml(htmlResult + "</td></tr></table></body></html>"); mimeData->setText(result); qApp->clipboard()->setMimeData(mimeData); }