-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.cpp
611 lines (469 loc) · 16.3 KB
/
util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/**
* Copyright (C) 2017 - 2018 Fábio Bento (fabiobento512)
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
*/
#include "util.h"
#ifdef QT_DEBUG
#include <QtGlobal> // for debug macros
#include <QDebug>
#endif
#include <QRegularExpression>
#include <QUrl>
#include <QSettings>
#include <QXmlStreamReader>
#include <QDirIterator>
#include <memory>
#include <string.h>
#ifdef QT_GUI_LIB
#include <QCheckBox>
#include <QHBoxLayout>
#include <QScreen>
#include <QGuiApplication>
#include <QDesktopWidget>
#include <QListView>
#include <QTreeView>
#endif
namespace Util{
namespace FileSystem {
QString normalizePath(QString path){
return path.replace("\\","/");
}
QString cutName(QString path){
return path.remove(0,path.lastIndexOf('/')).remove('"');
}
QString cutNameWithoutBackSlash(QString path){
return cutName(path).remove('/');
}
QString normalizeAndQuote(QString path){
return String::insertQuotes(normalizePath(path));
}
// Created from scratch
bool copyDir(const QString &fromPath, QString toPath, const bool isRecursive){
QDir fromDir(fromPath);
QDir toDir(toPath);
if(!toDir.mkdir(fromDir.dirName())){ // create the folder in the destination
return false;
}
// Update toPath to include the folder from "fromPath"
toPath = toPath + "/" + fromDir.dirName();
toDir = QDir(toPath);
for(const QFileInfo &currFileInfo : fromDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)){
if(currFileInfo.isFile()){
QFile destFile(toPath + "/" + currFileInfo.fileName());
if(!QFile::copy(currFileInfo.absoluteFilePath(),toPath + "/" + currFileInfo.fileName())){
return false;
}
}
else if(isRecursive && currFileInfo.isDir() && currFileInfo.absoluteFilePath() != fromDir.absolutePath()){
if(!copyDir(currFileInfo.absoluteFilePath(), toPath, isRecursive)){
return false;
}
}
}
return true;
}
//Copied from here: http://stackoverflow.com/questions/2536524/copy-directory-using-qt (ty roop)
bool rmDir(const QString &dirPath)
{
QDir dir(dirPath);
if (!dir.exists())
return true;
for(const QFileInfo &info : dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
if (info.isDir()) {
if (!rmDir(info.filePath()))
return false;
} else {
if (!dir.remove(info.fileName()))
return false;
}
}
QDir parentDir(QFileInfo(dirPath).path());
return parentDir.rmdir(QFileInfo(dirPath).fileName());
}
// Gets all files from a folder filtered by a given wildcard
QStringList getFolderFilesByWildcard(const QString &entryFolder, const QString &wildcard, bool isRecursive){
QStringList filesFound; // result files with absolute path
QDirIterator it(entryFolder, QDir::Files, (isRecursive ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags));
while (it.hasNext()){
filesFound << it.next();
}
return filterFilesByWildcard(filesFound, wildcard);
}
// Supports wildcards, and subdirectories with wildcard e.g.:
// *.xml
// /myXmls/*.xml
//
// online helper: https://regex101.com/
QStringList filterFilesByWildcard(const QStringList &filePaths, const QString &wildcard){
QStringList resultFiles;
QString formattedWildcard;
if(wildcard.trimmed().isEmpty()){
return resultFiles;
}
formattedWildcard=normalizePath(wildcard); // Convert slashes to work in both mac and windows
// escape the string so '.' or '(' chars get correctly escaped
formattedWildcard = QRegularExpression::escape(formattedWildcard);
// replace * by the corresponding regex
formattedWildcard.replace("\\*",".*");
// replace ? by the corresponding regex
formattedWildcard.replace("\\?",".");
// if it doesn't start with any regex wildcard or a subdirectory slash, add a slash to beginning (so the file/folder matches at least the root folder)
// We use \\/ instead of / because it was escaped
if(!formattedWildcard.startsWith("\\/") && !formattedWildcard.startsWith(".*") && !formattedWildcard.startsWith(".")){
formattedWildcard = "\\/" + formattedWildcard;
}
// if it is a subdirectory add * to match
if(formattedWildcard.startsWith("\\/")){
formattedWildcard = ".*" + formattedWildcard;
}
formattedWildcard = "^" + formattedWildcard + "$"; // we want a full match (http://stackoverflow.com/a/5752852)
QRegularExpression regex(formattedWildcard);
for(const QString ¤tFile : filePaths){
if(regex.match(currentFile).hasMatch()){
resultFiles << currentFile;
}
}
return resultFiles;
}
// Returns empty QString on failure.
// Based from here: http://www.qtcentre.org/archive/index.php/t-35674.html (thanks wysota!)
QString fileHash(const QString &fileName, QCryptographicHash::Algorithm hashAlgorithm)
{
QCryptographicHash crypto(hashAlgorithm);
QFile file(fileName);
file.open(QFile::ReadOnly);
while(!file.atEnd()){
crypto.addData(file.read(8192));
}
QByteArray hash = crypto.result();
return QString(crypto.result().toHex());
}
/**
Gets application directory. In mac os gets the .app directory
**/
QString getAppPath(){
#ifdef Q_OS_MAC
QDir dir = QDir(QCoreApplication::applicationDirPath());
if(dir.absolutePath().contains(".app")){ // include bundle, but we don't want it
dir.cdUp();
dir.cdUp();
dir.cdUp();
}
return dir.absolutePath();
#else
return QDir::currentPath();
#endif
}
bool backupFile(const QString &file, QString newFilename){
if(newFilename.isEmpty()){
newFilename = file;
}
return QFile::copy(file, newFilename+".bak");
}
}
namespace String {
QString insertApostrophes(const QString &currString){
return "'"+currString+"'";
}
QString insertQuotes(const QString &currString){
return "\""+currString+"\"";
}
QString fullTrim(QString str) {
str = str.simplified(); //convert all invisible chars in normal whitespaces
str.replace( " ", "" );
return str;
}
QStringList substring(QString myString, QString separator, Qt::CaseSensitivity cs){
QStringList result = QStringList();
int currIdx=0, nextIdx=0;
while(true){
nextIdx=myString.indexOf(separator,currIdx,cs);
result << myString.mid(currIdx,nextIdx-currIdx);
if(nextIdx==-1) break;
currIdx=nextIdx+1;
}
return result;
}
QString normalizeDecimalSeparator(QString value){
return value.replace(',','.');
}
//Searches for the QString "toSearch" in the "myString" variable backward
//Returns the index of the first match or -1 if not found
int indexOfBackward(QString myString, QString toSearch, int from){
int myStringSize=myString.size();
int toSearchSize=toSearch.size();
if(from==-1){
from=myStringSize;
}
int i=from;
while(i>=0){
for(int j=toSearchSize-1; j>=0; j--){
i--;
if(myString.at(i)!=toSearch.at(j)){
break;
}
if(j==0){
return i;
}
}
}
return -1;
}
// no problem here with "temporary" cstr
// https://stackoverflow.com/questions/1971183/when-does-c-allocate-deallocate-string-literals
const char* boolToCstr(bool currentBoolean){
return currentBoolean ? "true" : "false";
}
}
#ifdef QT_GUI_LIB
namespace Dialogs {
void showInfo(const QString &message, const bool richText){
QMessageBox msgBox;
if(richText){
msgBox.setTextFormat(Qt::RichText);
}
msgBox.setIcon(QMessageBox::Information);
msgBox.setText(message);
msgBox.exec();
}
void showWarning(const QString &message, const bool richText){
QMessageBox msgBox;
if(richText){
msgBox.setTextFormat(Qt::RichText);
}
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText(message);
msgBox.exec();
}
void showError(const QString &message, const bool richText){
QMessageBox msgBox;
if(richText){
msgBox.setTextFormat(Qt::RichText);
}
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText(message);
msgBox.exec();
}
bool showQuestion(QWidget * parent, QString message, QMessageBox::StandardButton standardButton){
return QMessageBox::question (parent, "Are you sure?", message, QMessageBox::Yes | QMessageBox::No, standardButton)==QMessageBox::Yes;
}
QMessageBox::StandardButton showQuestionWithCancel(QWidget * parent, QString message, QMessageBox::StandardButton standardButton){
return QMessageBox::question (parent, "Are you sure?", message, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, standardButton);
}
QStringList multipleDirSelection(const QString &title){
QFileDialog w;
// We need to use non native dialog, because native doesn't support multiple folder selection
w.setOption(QFileDialog::DontUseNativeDialog,true);
w.setFileMode(QFileDialog::DirectoryOnly);
w.setWindowTitle(title);
QTreeView *t = w.findChild<QTreeView*>();
if (t) {
t->setSelectionMode(QAbstractItemView::MultiSelection);
}
if(w.exec()){ //if accepted
return w.selectedFiles();
}
return QStringList(); //return empty
}
}
#endif
namespace Validation {
// Check if any string in the list is empty
bool checkEmptySpaces(QStringList toCheck){
for (const QString ¤t : toCheck){
if(current.trimmed().isEmpty()){
return true; //There are empty spaces
}
}
return false;
}
bool checkIfIntegers(QStringList toCheck){
for (const QString ¤t : toCheck){
if(!isStringInteger(current)){
return true; // Some aren't valid integers
}
}
return false;
}
bool checkIfDoubles(QStringList toCheck){
for (const QString ¤t : toCheck){
if(!isStringDouble(current)){
return true; // Some aren't valid doubles
}
}
return false;
}
bool isStringInteger(QString myString){
bool isNumber;
myString.toInt(&isNumber); //convert to int and see if it succeeds
return isNumber;
}
bool isStringDouble(QString myString){
bool isDouble;
myString.toDouble(&isDouble); //convert to double and see if it succeeds
return isDouble;
}
}
namespace System {
#ifdef QT_GUI_LIB
QRect getScreenResolution(){
return qApp->primaryScreen()->availableGeometry();
}
#endif
}
#ifdef QT_GUI_LIB
namespace TableWidget {
void addRow(QTableWidget *myTable, QStringList &columns){
//Get actual number rows
int twSize=myTable->rowCount();
//increase the rows for the new item
myTable->setRowCount(twSize+1);
//Add to table and list to
for(int i=0; i<columns.size(); i++){
QTableWidgetItem *newColumn = new QTableWidgetItem(columns[i]);
myTable->setItem(twSize,i,newColumn);
// Add a tooltip with with the cell content
myTable->item(twSize,i)->setToolTip(myTable->item(twSize,i)->text());
}
}
QModelIndexList getSelectedRows(QTableWidget *myTable){
return myTable->selectionModel()->selectedRows();
}
QModelIndexList getCurrentRows(QTableWidget *myTable){
QModelIndexList oldSelection = getSelectedRows(myTable);
myTable->selectAll();
QModelIndexList allRows = getSelectedRows(myTable);
myTable->selectionModel()->clearSelection();
// Restore old selection
for(const QModelIndex ¤tIndex : oldSelection){
myTable->selectionModel()->select(currentIndex, QItemSelectionModel::Select | QItemSelectionModel::SelectionFlag::Rows);
}
return allRows;
}
int getNumberSelectedRows(QTableWidget *myTable){
return getSelectedRows(myTable).size();
}
void clearContents(QTableWidget *myTable, const QString ¬hingToClearMessage, const QString &questionToClear){
if(myTable->rowCount()==0){
Dialogs::showInfo(nothingToClearMessage);
return;
}
if(Dialogs::showQuestion(myTable, questionToClear)){
clearContentsNoPrompt(myTable);
}
}
void clearContentsNoPrompt(QTableWidget *myTable){
myTable->clearContents();
myTable->setRowCount(0);
}
// Adapted from here:
// http://stackoverflow.com/questions/29176317/qtablewidget-checkbox-get-state-and-location
void addCheckBox(QTableWidget *myTable, int row, int column, QCheckBox *checkbox){
if(checkbox == nullptr){
checkbox = new QCheckBox();
}
QWidget *auxLayoutWidget = new QWidget(myTable);
QHBoxLayout* checkBoxLayout = new QHBoxLayout();
checkBoxLayout->setContentsMargins(0,0,0,0);
checkBoxLayout->addWidget(checkbox);
checkBoxLayout->setAlignment(Qt::AlignCenter);
checkBoxLayout->setSpacing(0);
auxLayoutWidget->setLayout(checkBoxLayout);
myTable->setCellWidget(row, column, auxLayoutWidget);
}
// Adapted from here:
// http://stackoverflow.com/questions/29176317/qtablewidget-checkbox-get-state-and-location
QCheckBox* getCheckBoxFromCell(QTableWidget *myTable, int row, int column){
return dynamic_cast<QCheckBox*>(myTable->cellWidget(row, column)->findChild<QCheckBox *>());
}
// Adapted from here:
// http://www.qtcentre.org/threads/3386-QTableWidget-move-row
// Thanks jpn
void swapRows(QTableWidget *myTable, const int indexSourceRow, const int indexDestinationRow, bool selectSwappedRow)
{
// takes and returns the whole row
auto takeRow = [&myTable](int row) -> QList<QTableWidgetItem*>
{
QList<QTableWidgetItem*> rowItems;
for (int col = 0; col < myTable->columnCount(); ++col)
{
rowItems << myTable->takeItem(row, col);
}
return rowItems;
};
// sets the whole row
auto setRow = [&myTable](int row, const QList<QTableWidgetItem*>& rowItems)
{
for (int col = 0; col < myTable->columnCount(); ++col)
{
myTable->setItem(row, col, rowItems.at(col));
}
};
// take whole rows
QList<QTableWidgetItem*> sourceItems = takeRow(indexSourceRow);
QList<QTableWidgetItem*> destItems = takeRow(indexDestinationRow);
// set back in reverse order
setRow(indexSourceRow, destItems);
setRow(indexDestinationRow, sourceItems);
if(selectSwappedRow){
myTable->selectRow(indexDestinationRow);
}
}
void deleteSelectedRows(QTableWidget *myTable){
int size = myTable->selectionModel()->selectedRows().size();
for(int i=0; i<size; i++){
myTable->removeRow(myTable->selectionModel()->selectedRows().at(size-i-1).row());
}
}
}
#endif
#ifdef QT_GUI_LIB
namespace StatusBar {
void showInfo(QStatusBar * const statusBar, const QString &message){
QPalette myPalete = QPalette();
myPalete.setColor( QPalette::WindowText, QColor(0,38,255));
statusBar->setPalette( myPalete );
statusBar->showMessage(message,10000); //display by 10 seconds
}
void showError(QStatusBar * const statusBar, const QString &message){
QPalette myPalete = QPalette();
myPalete.setColor( QPalette::WindowText, QColor(255,0,0));
statusBar->setPalette( myPalete );
statusBar->showMessage(message,10000); //display by 10 seconds
}
void showSuccess(QStatusBar * const statusBar,const QString &message){
QPalette myPalete = QPalette();
myPalete.setColor( QPalette::WindowText, QColor(0,150,0));
statusBar->setPalette( myPalete );
statusBar->showMessage(message,10000); //display by 10 seconds
}
}
#endif
}
/**
* Copyright (c) 2017 - 2018 Fábio Bento (fabiobento512)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/