pgLab/src/util.cpp

139 lines
3.1 KiB
C++

#include "util.h"
#include "csvwriter.h"
#include <QApplication>
#include <QTextStream>
#include <QClipboard>
#include <sstream>
#include <stdexcept>
// Supported range from microseconds to seconds
// min:sec to hours::min::sec
QString msfloatToHumanReadableString(float ms)
{
QString unit;
float val;
int deci = 2;
if (ms < 1.0f) {
val = ms * 1000.f;
//result = QString::asprintf("%0.3f", ms * 1000.0f);
unit = u8"μs";
}
else if (ms >= 1000.0) {
val = ms / 1000.0f;
unit = "s";
if (val >= 60.0) {
int secs = val;
int min = secs / 60.0;
secs -= min * 60;
if (min >= 60) {
int hour = min / 60;
min -= hour * 60;
return QString::asprintf("%d:%02d:%02d", hour, min, secs);
}
else {
return QString::asprintf("%02d:%02d", min, secs);
}
}
}
else {
val = ms;
unit = "ms";
}
// if (val >= 1000.f) {
// deci = 0;
// }
// else
if (val >= 100.f) {
deci = 0;
}
else if (val >= 10.f) {
deci = 1;
}
QString result = QString::asprintf("%0.*f", deci, val);
return result + unit;
}
void exportTable(const QTableView *view, QTextStream &out)
{
auto model = view->model();
if (model) {
CsvWriter csv(&out);
csv.setSeperator('\t');
csv.setQuote('"');
const int cols = model->columnCount();
const int rows = model->rowCount();
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
auto idx = model->index(row, col);
auto display_text = idx.data(Qt::DisplayRole).toString();
csv.writeField(display_text);
}
csv.nextRow();
}
out.flush();
}
}
void copySelectionToClipboard(const QTableView *view)
{
//QAbstractItemModel * model = resultModel; //view->model();
QItemSelectionModel * selection = view->selectionModel();
QModelIndexList selectedIndexes = selection->selectedIndexes();
if (selectedIndexes.count() > 0) {
QString clipboard_string;
QTextStream out(&clipboard_string, QIODevice::WriteOnly);
CsvWriter csv(&out);
csv.setSeperator('\t');
csv.setQuote('"');
int previous_row = selectedIndexes[0].row();
// for (int i = 0; i < selectedIndexes.count(); ++i) {
// QModelIndex current = selectedIndexes[i];
for (auto current : selectedIndexes) {
if (current.row() > previous_row) {
csv.nextRow();
previous_row = current.row();
}
QString display_text = current.data(Qt::DisplayRole).toString();
csv.writeField(display_text);
}
out.flush();
QApplication::clipboard()->setText(clipboard_string);
}
}
QString ConvertToMultiLineCString(const QString &in)
{
// We need to atleast escape " and \
// also any multi byte utf8 char
QString out;
out.append('"');
QByteArray ba = in.toUtf8();
for (auto c : ba) {
if (c == '\\') {
out.append("\\\\");
}
else if (c == '"') {
out.append("\\\"");
}
else if (uchar(c) > 127) {
out.append(QString("\\x%1").arg(uchar(c), 2, 16, QChar('0')));
}
else if (c == '\n') {
// at end of line we add a space and a new line in the string then we put in the end quote go to the next line and put the open quote
out.append(" \\n\"\n\"");
}
else {
out.append(c);
}
}
out.append('"');
return out;
}