// This file is part of c-evo-evo. // // This software is governed by the CeCILL license under French law and // abiding by the rules of distribution of free software. You can use, // modify and/or redistribute the software under the terms of the CeCILL // license as circulated by CEA, CNRS and INRIA at the following URL // "http://www.cecill.info". // // As a counterpart to the access to the source code and rights to copy, // modify and redistribute granted by the license, users are provided only // with a limited warranty and the software's author, the holder of the // economic rights, and the successive licensors have only limited // liability. // // In this respect, the user's attention is drawn to the risks associated // with loading, using, modifying and/or developing or reproducing the // software by the user in light of its specific status of free software, // that may mean that it is complicated to manipulate, and that also // therefore means that it is reserved for developers and experienced // professionals having in-depth computer knowledge. Users are therefore // encouraged to load and test the software's suitability as regards their // requirements in conditions enabling the security of their systems and/or // data to be ensured and, more generally, to use and operate it in the // same conditions as regards security. // // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. #include "Cevo/Table.h" #include #include #include #include #include #include #include namespace Cevo { namespace { QString quoteString(const QString &text, const QString "e) { return text.isEmpty() ? text : quote + text + quote; } QString escapeHtml(const QString &text) { QString result = text; result.replace('&', QStringLiteral("&")); // must come first result.replace('<', QStringLiteral("<")); result.replace('>', QStringLiteral(">")); return result; } // Parses one CSV line (comma-separated, "-quoted fields with "" as the // escaped-quote sequence) - matches Lazarus TStringList's // StrictDelimiter+DelimitedText convention the original relied on. QStringList parseCsvLine(const QString &line) { QStringList fields; QString field; bool inQuotes = false; int i = 0; while (i < line.size()) { const QChar c = line.at(i); if (inQuotes) { if (c == '"') { if (i + 1 < line.size() && line.at(i + 1) == '"') { field += '"'; i += 2; continue; } inQuotes = false; ++i; } else { field += c; ++i; } } else if (c == '"') { inQuotes = true; ++i; } else if (c == ',') { fields.append(field); field.clear(); ++i; } else { field += c; ++i; } } fields.append(field); return fields; } QStringList splitLines(const QString &text) { QStringList lines = text.split('\n'); while (!lines.isEmpty() && lines.last().trimmed().isEmpty()) lines.removeLast(); return lines; } } // namespace QString tableFormatText(TableFormat format) { switch (format) { case TableFormat::Excel: return QStringLiteral("Excel paste"); case TableFormat::Plain: return QStringLiteral("Plain text"); case TableFormat::Csv: return QStringLiteral("CSV"); case TableFormat::Html: return QStringLiteral("HTML"); case TableFormat::ListView: return QStringLiteral("ListView"); case TableFormat::MediaWiki: return QStringLiteral("MediaWiki"); case TableFormat::Xml: return QStringLiteral("XML"); case TableFormat::Json: return QStringLiteral("JSON"); } return {}; } QString tableFormatExt(TableFormat format) { switch (format) { case TableFormat::Excel: case TableFormat::Plain: case TableFormat::MediaWiki: return QStringLiteral(".txt"); case TableFormat::Csv: return QStringLiteral(".csv"); case TableFormat::Html: return QStringLiteral(".htm"); case TableFormat::ListView: return QString(); case TableFormat::Xml: return QStringLiteral(".xml"); case TableFormat::Json: return QStringLiteral(".json"); } return {}; } void Table::clear() { columns.clear(); rows.clear(); } Row &Table::addRow() { rows.push_back(std::make_unique()); return *rows.back(); } QString Table::outputTabs() const { QString result = columns.join('\t') + '\n'; for (const auto &row : rows) result += row->cells.join('\t') + '\n'; return result; } QString Table::outputPlain() const { QString result; for (const auto &row : rows) result += row->cells.join('\n') + QStringLiteral("\n\n===========================\n\n"); return result; } QString Table::outputCsv() const { QString result; for (int j = 0; j < columns.size(); ++j) { if (j > 0) result += ','; if (!columns.at(j).isEmpty()) result += quoteString(columns.at(j), QStringLiteral("\"")); } result += '\n'; for (const auto &row : rows) { for (int j = 0; j < row->cells.size(); ++j) { if (j > 0) result += ','; if (!row->cells.at(j).isEmpty()) result += quoteString(row->cells.at(j), QStringLiteral("\"")); } result += '\n'; } return result; } QString Table::outputXml() const { QDomDocument doc; doc.appendChild( doc.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"UTF-8\""))); QDomElement tableElement = doc.createElement(QStringLiteral("table")); doc.appendChild(tableElement); if (!title.isEmpty()) { QDomElement titleElement = doc.createElement(QStringLiteral("title")); titleElement.appendChild(doc.createTextNode(title)); tableElement.appendChild(titleElement); } QDomElement rowsElement = doc.createElement(QStringLiteral("rows")); tableElement.appendChild(rowsElement); for (const auto &row : rows) { QDomElement rowElement = doc.createElement(QStringLiteral("row")); rowsElement.appendChild(rowElement); for (int j = 0; j < row->cells.size(); ++j) { if (row->cells.at(j).isEmpty()) continue; QDomElement cellElement = doc.createElement(QStringLiteral("cell")); cellElement.setAttribute(QStringLiteral("name"), columns.value(j)); cellElement.appendChild(doc.createTextNode(row->cells.at(j))); rowElement.appendChild(cellElement); } } return doc.toString(2); } QString Table::outputHtml() const { QString result = QStringLiteral("\n \n ") + escapeHtml(title) + QStringLiteral("\n \n \n \n \n"); for (const QString &column : columns) result += QStringLiteral(" \n"); result += QStringLiteral(" \n"); for (const auto &row : rows) { result += QStringLiteral(" \n"); for (const QString &cell : row->cells) result += QStringLiteral(" \n"); result += QStringLiteral(" \n"); } result += QStringLiteral("
") + escapeHtml(column).replace('\n', QStringLiteral("
")) + QStringLiteral("
") + escapeHtml(cell).replace('\n', QStringLiteral("
")) + QStringLiteral("
\n \n"); return result; } QString Table::outputMediaWiki() const { QString result = QStringLiteral("{| class=\"wikitable sortable\"\n"); for (int j = 0; j < columns.size(); ++j) result += (j == 0 ? QStringLiteral("! ") : QStringLiteral(" !! ")) + columns.at(j); result += QStringLiteral("\n|-\n"); for (size_t i = 0; i < rows.size(); ++i) { const Row &row = *rows[i]; for (int j = 0; j < row.cells.size(); ++j) result += (j == 0 ? QStringLiteral("| ") : QStringLiteral(" || ")) + row.cells.at(j); if (i + 1 < rows.size()) result += QStringLiteral("\n|-\n"); } result += QStringLiteral("\n|}"); return result; } QString Table::outputJson() const { QJsonArray array; for (const auto &row : rows) { QJsonObject object; for (int j = 0; j < row->cells.size() && j < columns.size(); ++j) if (!row->cells.at(j).isEmpty()) object.insert(columns.at(j), row->cells.at(j)); array.append(object); } return QString::fromUtf8(QJsonDocument(array).toJson(QJsonDocument::Indented)); } void Table::populateTreeWidget(QTreeWidget *tree) const { constexpr int minWidth = 120; tree->setColumnCount(columns.size()); const int newWidth = std::max(minWidth, tree->width() / std::max(1, static_cast(columns.size()))); for (int i = 0; i < columns.size(); ++i) { tree->headerItem()->setText(i, columns.at(i)); tree->setColumnWidth(i, newWidth); } tree->clear(); for (const auto &row : rows) { auto *item = new QTreeWidgetItem(tree); for (int j = 0; j < row->cells.size(); ++j) item->setText(j, row->cells.at(j)); } } QString Table::output(TableFormat format) const { switch (format) { case TableFormat::Excel: return outputTabs(); case TableFormat::Plain: return outputPlain(); case TableFormat::Csv: return outputCsv(); case TableFormat::Html: return outputHtml(); case TableFormat::MediaWiki: return outputMediaWiki(); case TableFormat::Xml: return outputXml(); case TableFormat::Json: return outputJson(); case TableFormat::ListView: break; } throw std::invalid_argument("Unsupported format"); } void Table::setInputCsv(const QString &text) { clear(); const QStringList lines = splitLines(text); for (int i = 0; i < lines.size(); ++i) { if (i == 0) columns = parseCsvLine(lines.at(i).trimmed()); else addRow().cells = parseCsvLine(lines.at(i).trimmed()); } } void Table::setInputMediaWiki(const QString &text) { clear(); Row *row = nullptr; bool insideTable = false; for (const QString &rawLine : splitLines(text)) { const QString line = rawLine.trimmed(); if (!insideTable) { if (line.startsWith(QStringLiteral("{|"))) insideTable = true; continue; } if (line.startsWith(QStringLiteral("|}"))) { insideTable = false; } else if (line.startsWith('!')) { QString remaining = line.mid(1).trimmed(); for (;;) { const int index = remaining.indexOf(QStringLiteral("!!")); if (index < 0) { columns.append(remaining.trimmed()); break; } columns.append(remaining.left(index).trimmed()); remaining = remaining.mid(index + 2); } } else if (line.startsWith(QStringLiteral("|-"))) { row = &addRow(); } else if (line.startsWith('|')) { if (row) { QString remaining = line.mid(1).trimmed(); for (;;) { const int index = remaining.indexOf(QStringLiteral("||")); if (index < 0) { row->cells.append(remaining.trimmed()); break; } row->cells.append(remaining.left(index).trimmed()); remaining = remaining.mid(index + 2); } while (row->cells.size() < columns.size()) row->cells.append(QString()); } } } } void Table::setInputJson(const QString &text) { clear(); const QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8()); if (!doc.isArray()) return; for (const QJsonValue &rowValue : doc.array()) { if (!rowValue.isObject()) continue; const QJsonObject object = rowValue.toObject(); Row &row = addRow(); for (auto it = object.constBegin(); it != object.constEnd(); ++it) { int columnIndex = columns.indexOf(it.key()); if (columnIndex < 0) { columns.append(it.key()); columnIndex = columns.size() - 1; } while (row.cells.size() <= columnIndex) row.cells.append(QString()); row.cells[columnIndex] = it.value().toVariant().toString(); } } } void Table::setInputXml(const QString &text) { clear(); QDomDocument doc; if (!doc.setContent(text)) return; const QDomElement tableElement = doc.documentElement(); if (tableElement.tagName() != QStringLiteral("table")) return; QDomElement rowElement = tableElement.firstChildElement(QStringLiteral("rows")).firstChildElement(QStringLiteral("row")); while (!rowElement.isNull()) { Row &row = addRow(); QDomElement cellElement = rowElement.firstChildElement(QStringLiteral("cell")); while (!cellElement.isNull()) { const QString cellName = cellElement.attribute(QStringLiteral("name")); int columnIndex = columns.indexOf(cellName); if (columnIndex < 0) { columns.append(cellName); columnIndex = columns.size() - 1; } while (row.cells.size() <= columnIndex) row.cells.append(QString()); row.cells[columnIndex] = cellElement.text(); cellElement = cellElement.nextSiblingElement(QStringLiteral("cell")); } rowElement = rowElement.nextSiblingElement(QStringLiteral("row")); } } void Table::setInput(TableFormat format, const QString &text) { switch (format) { case TableFormat::Csv: setInputCsv(text); return; case TableFormat::MediaWiki: setInputMediaWiki(text); return; case TableFormat::Json: setInputJson(text); return; case TableFormat::Xml: setInputXml(text); return; default: throw std::invalid_argument("Unsupported format"); } } QList Table::inputFormats() { return { TableFormat::Csv, TableFormat::Json, TableFormat::MediaWiki, TableFormat::Xml }; } } // namespace Cevo