From b956d3dddbada78b71e194cf99659f06236813c1 Mon Sep 17 00:00:00 2001 From: Keshav Bhatt Date: Sat, 27 May 2023 23:55:40 +0530 Subject: [PATCH] minor improvements --- .gitignore | 52 ++ src/controlbutton.h | 11 +- src/error.cpp | 23 +- src/error.h | 15 +- src/glate.pro.user | 509 +++-------- src/history.cpp | 252 +++--- src/history.h | 39 +- src/linebyline.cpp | 104 +-- src/linebyline.h | 33 +- src/main.cpp | 19 +- src/mainwindow.cpp | 1510 ++++++++++++++++----------------- src/mainwindow.h | 154 ++-- src/mainwindow.ui | 4 +- src/request.cpp | 84 +- src/request.h | 31 +- src/settings.cpp | 175 ++-- src/settings.h | 51 +- src/settings.ui | 25 +- src/share.cpp | 505 +++++------ src/share.h | 71 +- src/slider.cpp | 308 ++++--- src/slider.h | 73 +- src/slider.ui | 4 +- src/slides/0.html | 8 +- src/translationdownloader.cpp | 95 ++- src/translationdownloader.h | 32 +- src/utils.cpp | 272 +++--- src/utils.h | 121 +-- src/waitingspinnerwidget.cpp | 305 ++++--- src/waitingspinnerwidget.h | 127 ++- 30 files changed, 2318 insertions(+), 2694 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f147edf --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# C++ objects and libs +*.slo +*.lo +*.o +*.a +*.la +*.lai +*.so +*.so.* +*.dll +*.dylib + +# Qt-es +object_script.*.Release +object_script.*.Debug +*_plugin_import.cpp +/.qmake.cache +/.qmake.stash +*.pro.user +*.pro.user.* +*.qbs.user +*.qbs.user.* +*.moc +moc_*.cpp +moc_*.h +qrc_*.cpp +ui_*.h +*.qmlc +*.jsc +Makefile* +*build-* +*.qm +*.prl + +# Qt unit tests +target_wrapper.* + +# QtCreator +*.autosave + +# QtCreator Qml +*.qmlproject.user +*.qmlproject.user.* + +# QtCreator CMake +CMakeLists.txt.user* + +# QtCreator 4.8< compilation database +compile_commands.json + +# QtCreator local machine specific files for imported projects +*creator.user* diff --git a/src/controlbutton.h b/src/controlbutton.h index 8959c95..8758863 100644 --- a/src/controlbutton.h +++ b/src/controlbutton.h @@ -4,19 +4,18 @@ #include #include -class controlButton : public QPushButton -{ - Q_OBJECT +class controlButton : public QPushButton { + Q_OBJECT public: - controlButton(QWidget *parent = 0); + controlButton(QWidget *parent = 0); signals: public slots: protected slots: - void mouseMoveEvent(QMouseEvent *e); - bool eventFilter(QObject *obj, QEvent *event); + void mouseMoveEvent(QMouseEvent *e); + bool eventFilter(QObject *obj, QEvent *event); }; #endif // CONTROLBUTTON_H diff --git a/src/error.cpp b/src/error.cpp index 0cf7376..d7df4d9 100644 --- a/src/error.cpp +++ b/src/error.cpp @@ -1,24 +1,15 @@ #include "error.h" #include "ui_error.h" -Error::Error(QWidget *parent) : - QWidget(parent), - ui(new Ui::Error) -{ - ui->setupUi(this); +Error::Error(QWidget *parent) : QWidget(parent), ui(new Ui::Error) { + ui->setupUi(this); } -void Error::setError(QString shortMessage,QString detail){ - ui->detail->setText(detail); - ui->message->setText(shortMessage); +void Error::setError(QString shortMessage, QString detail) { + ui->detail->setText(detail); + ui->message->setText(shortMessage); } -Error::~Error() -{ - delete ui; -} +Error::~Error() { delete ui; } -void Error::on_ok_clicked() -{ - this->close(); -} +void Error::on_ok_clicked() { this->close(); } diff --git a/src/error.h b/src/error.h index d12c883..a9930ab 100644 --- a/src/error.h +++ b/src/error.h @@ -7,21 +7,20 @@ namespace Ui { class Error; } -class Error : public QWidget -{ - Q_OBJECT +class Error : public QWidget { + Q_OBJECT public: - explicit Error(QWidget *parent = nullptr); - ~Error(); + explicit Error(QWidget *parent = nullptr); + ~Error(); public slots: - void setError(QString shortMessage, QString detail); + void setError(QString shortMessage, QString detail); private slots: - void on_ok_clicked(); + void on_ok_clicked(); private: - Ui::Error *ui; + Ui::Error *ui; }; #endif // ERROR_H diff --git a/src/glate.pro.user b/src/glate.pro.user index 605d887..68bdaf9 100644 --- a/src/glate.pro.user +++ b/src/glate.pro.user @@ -1,14 +1,14 @@ - + EnvironmentId - {42be5509-3837-4f9c-b0f5-209496d7cd57} + {52ccd6bd-3a22-4cc8-ac7f-c62635314a35} ProjectExplorer.Project.ActiveTarget - 0 + 0 ProjectExplorer.Project.EditorSettings @@ -28,7 +28,7 @@ QmlJSGlobal - 2 + 2 UTF-8 false 4 @@ -37,6 +37,7 @@ true true 1 + false true false 0 @@ -45,549 +46,235 @@ 0 8 true + false 1 true true true + *.md, *.MD, Makefile false + true + true ProjectExplorer.Project.PluginSettings - - - - ProjectExplorer.Project.Target.0 - Desktop Qt 5.13.0 GCC 64bit - Desktop Qt 5.13.0 GCC 64bit - qt.qt5.5130.gcc_64_kit - 1 - 0 - 0 - - /home/bulld/code/build-glate-Desktop_Qt_5_13_0_GCC_64bit-Debug - - - true - qmake - - QtProjectManager.QMakeBuildStep - true - - false - false - false - - - true - Make - - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - - ProjectExplorer.BuildSteps.Build - - - - true - Make - - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Debug - Debug - Qt4ProjectManager.Qt4BuildConfiguration - 2 - true + + true + false + true + true + true + true - - /home/bulld/code/build-glate-Desktop_Qt_5_13_0_GCC_64bit-Release - - - true - qmake - - QtProjectManager.QMakeBuildStep - false - - false - false - true - - - true - Make - - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - - ProjectExplorer.BuildSteps.Build - - - - true - Make - - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Release - Release - Qt4ProjectManager.Qt4BuildConfiguration - 0 - true + + 0 + true + + true + true + Builtin.DefaultTidyAndClazy + 4 + + + + true - - /home/bulld/code/build-glate-Desktop_Qt_5_13_0_GCC_64bit-Profile - - - true - qmake - - QtProjectManager.QMakeBuildStep - true - - false - true - true - - - true - Make - - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - - ProjectExplorer.BuildSteps.Build - - - - true - Make - - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Profile - Profile - Qt4ProjectManager.Qt4BuildConfiguration - 0 - true - - 3 - - - 0 - Deploy - - ProjectExplorer.BuildSteps.Deploy - - 1 - Deploy Configuration - - ProjectExplorer.DefaultDeployConfiguration - - 1 - - - dwarf - - cpu-cycles - - - 250 - -F - true - 4096 - false - false - 1000 - - true - - false - false - false - false - true - 0.01 - 10 - true - kcachegrind - 1 - 25 - - 1 - true - false - true - valgrind - - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - - 2 - - glate - glate2 - Qt4ProjectManager.Qt4RunConfiguration:/home/bulld/code/glate/src/glate.pro - - 3768 - false - true - true - false - false - true - - /home/bulld/code/build-glate-Desktop_Qt_5_13_0_GCC_64bit-Release - - 1 - ProjectExplorer.Project.Target.1 + ProjectExplorer.Project.Target.0 - Qt 5.5.1 in PATH (qt5)GCC (x86 64bit in /usr/bin) - Qt 5.5.1 in PATH (qt5)GCC (x86 64bit in /usr/bin) - {724101f7-4cf1-475c-885c-14115ea32f8c} - 0 - 0 - 0 + Desktop + Desktop + Desktop + {c30aca17-4197-4e81-826e-1373071ecf4e} + 0 + 0 + 0 - /home/bulld/code/build-glate-Qt_5_5_1_in_PATH_qt5_GCC_x86_64bit_in_usr_bin-Debug + 0 + /home/commander/Code/glate/src/../build-glate-Desktop-Debug + /home/commander/Code/glate/build-glate-Desktop-Debug true - qmake - QtProjectManager.QMakeBuildStep - true - false - false - false + true - Make - Qt4ProjectManager.MakeStep - - false - - - false - 2 + 2 Build - + Build ProjectExplorer.BuildSteps.Build true - Make - Qt4ProjectManager.MakeStep - - true clean - - false - 1 + 1 Clean - + Clean ProjectExplorer.BuildSteps.Clean 2 false + + false - Debug Debug Qt4ProjectManager.Qt4BuildConfiguration 2 - true - /home/bulld/code/build-glate-Qt_5_5_1_in_PATH_qt5_GCC_x86_64bit_in_usr_bin-Release + /home/commander/Code/glate/src/../build-glate-Desktop-Release + /home/commander/Code/glate/build-glate-Desktop-Release true - qmake - QtProjectManager.QMakeBuildStep - false - false - false - false + true - Make - Qt4ProjectManager.MakeStep - - false - - - false - 2 + 2 Build - + Build ProjectExplorer.BuildSteps.Build true - Make - Qt4ProjectManager.MakeStep - - true clean - - false - 1 + 1 Clean - + Clean ProjectExplorer.BuildSteps.Clean 2 false + + false - Release Release Qt4ProjectManager.Qt4BuildConfiguration 0 - true + 0 - /home/bulld/code/build-glate-Qt_5_5_1_in_PATH_qt5_GCC_x86_64bit_in_usr_bin-Profile + 0 + /home/commander/Code/glate/src/../build-glate-Desktop-Profile + /home/commander/Code/glate/build-glate-Desktop-Profile true - qmake - QtProjectManager.QMakeBuildStep - true - false - true - false + true - Make - Qt4ProjectManager.MakeStep - - false - - - false - 2 + 2 Build - + Build ProjectExplorer.BuildSteps.Build true - Make - Qt4ProjectManager.MakeStep - - true clean - - false - 1 + 1 Clean - + Clean ProjectExplorer.BuildSteps.Clean 2 false + + false - Profile Profile Qt4ProjectManager.Qt4BuildConfiguration 0 - true + 0 + 0 - 3 + 3 - 0 + 0 Deploy - + Deploy ProjectExplorer.BuildSteps.Deploy 1 - Deploy Configuration - + + false ProjectExplorer.DefaultDeployConfiguration - 1 - + 1 - dwarf - - cpu-cycles - - - 250 - -F true - 4096 - false - false - 1000 - true - - false - false - false - false - true - 0.01 - 10 - true - kcachegrind - 1 - 25 - - 1 + true - false - true - valgrind + /usr/bin/valgrind - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 + 11 + 14 + 12 + 13 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 0 + 1 + 2 - glate - - Qt4ProjectManager.Qt4RunConfiguration:/home/bulld/code/glate/glate.pro - - 3768 + ProjectExplorer.CustomExecutableRunConfiguration + false true - true - false false true - - - 1 + 1 ProjectExplorer.Project.TargetCount - 2 + 1 ProjectExplorer.Project.Updater.FileVersion - 21 + 22 Version - 21 + 22 diff --git a/src/history.cpp b/src/history.cpp index e22d641..4fd383b 100644 --- a/src/history.cpp +++ b/src/history.cpp @@ -4,151 +4,147 @@ #include #include -History::History(QWidget *parent) : - QWidget(parent), - ui(new Ui::History) -{ - ui->setupUi(this); - ui->historyList->setSelectionRectVisible(true); - ui->historyList->setAlternatingRowColors(true); - ui->historyList->setDragEnabled(false); - ui->historyList->setDropIndicatorShown(false); - ui->historyList->setDragDropMode(QAbstractItemView::NoDragDrop); +History::History(QWidget *parent) : QWidget(parent), ui(new Ui::History) { + ui->setupUi(this); + ui->historyList->setSelectionRectVisible(true); + ui->historyList->setAlternatingRowColors(true); + ui->historyList->setDragEnabled(false); + ui->historyList->setDropIndicatorShown(false); + ui->historyList->setDragDropMode(QAbstractItemView::NoDragDrop); } -History::~History() -{ - delete ui; -} +History::~History() { delete ui; } -void History::on_clearall_clicked() -{ - QDir dir(utils::returnPath("history")); - if(dir.removeRecursively()){ - ui->historyList->clear(); - ui->clearall->setEnabled(false); - } +void History::on_clearall_clicked() { + QDir dir(utils::returnPath("history")); + if (dir.removeRecursively()) { + ui->historyList->clear(); + ui->clearall->setEnabled(false); + } } -void History::insertItem(QStringList meta,bool fromHistory,QString translationId){ - QWidget *histWid = new QWidget(); - if(meta.count()>=5){ - QString from, to, src1, src2, date; - from = meta.at(0); - to = meta.at(1); - src1 = meta.at(2); - src2 = meta.at(3); - date = meta.at(4); - history_item_ui.setupUi(histWid); - histWid->setObjectName("widget_"+translationId); - histWid->setStyleSheet("QWidget#widget_"+translationId+"{background: transparent;}"); - history_item_ui.remove->setObjectName("remove_"+translationId); - history_item_ui.load->setObjectName("load_"+translationId); - connect(history_item_ui.remove,&QPushButton::clicked,[=](){ - QFile file(utils::returnPath("history")+"/"+translationId+".json"); - if(file.remove()){ - loadHistory(); - } - }); +void History::insertItem(QStringList meta, bool fromHistory, + QString translationId) { + QWidget *histWid = new QWidget(); + if (meta.count() >= 5) { + QString from, to, src1, src2, date; + from = meta.at(0); + to = meta.at(1); + src1 = meta.at(2); + src2 = meta.at(3); + date = meta.at(4); + history_item_ui.setupUi(histWid); + histWid->setObjectName("widget_" + translationId); + histWid->setStyleSheet("QWidget#widget_" + translationId + + "{background: transparent;}"); + history_item_ui.remove->setObjectName("remove_" + translationId); + history_item_ui.load->setObjectName("load_" + translationId); + connect(history_item_ui.remove, &QPushButton::clicked, [=]() { + QFile file(utils::returnPath("history") + "/" + translationId + ".json"); + if (file.remove()) { + loadHistory(); + } + }); - connect(history_item_ui.load,&QPushButton::clicked,[=](){ - emit setTranslationId(translationId); - loadHistoryItem(utils::returnPath("history")+"/"+translationId+".json"); - }); - history_item_ui.time->setText(date); - history_item_ui.from->setText(from); - history_item_ui.to->setText(to); - history_item_ui.src1->setText(src1.left(100)+"...."); - history_item_ui.src2->setText(src2.left(100)+"...."); - QListWidgetItem* item; - item = new QListWidgetItem(ui->historyList); - ui->historyList->setItemWidget(item,histWid); - item->setSizeHint(histWid->minimumSizeHint()); - this->setMinimumWidth(histWid->width()+60); - ui->historyList->addItem(item); - ui->clearall->setEnabled(true); - if(!fromHistory){ - save(meta,translationId); - } + connect(history_item_ui.load, &QPushButton::clicked, [=]() { + emit setTranslationId(translationId); + loadHistoryItem(utils::returnPath("history") + "/" + translationId + + ".json"); + }); + history_item_ui.time->setText(date); + history_item_ui.from->setText(from); + history_item_ui.to->setText(to); + history_item_ui.src1->setText(src1.left(100) + "...."); + history_item_ui.src2->setText(src2.left(100) + "...."); + QListWidgetItem *item; + item = new QListWidgetItem(ui->historyList); + ui->historyList->setItemWidget(item, histWid); + item->setSizeHint(histWid->minimumSizeHint()); + this->setMinimumWidth(histWid->width() + 60); + ui->historyList->addItem(item); + ui->clearall->setEnabled(true); + if (!fromHistory) { + save(meta, translationId); } + } } -void History::loadHistoryItem(QString itemPath){ - QFile file(itemPath); - if(file.exists()){ - //open file , read it to stringlist pass it to insertItem - QJsonDocument doc = loadJson(itemPath); - QJsonObject jsonObject = doc.object(); - QString from, to, src1, src2,date; - from = jsonObject.value("from").toString(); - to = jsonObject.value("to").toString(); - src1 = jsonObject.value("src1").toString(); - src2 = jsonObject.value("src2").toString(); - date = jsonObject.value("date").toString(); - emit historyItemMeta(QStringList()<=5){ - QString from, to, src1, src2, date; - from = meta.at(0); - to = meta.at(1); - src1 = meta.at(2); - src2 = meta.at(3); - date = meta.at(4); - QString history_file_path = utils::returnPath("history")+"/"+translationId+".json"; - QVariantMap map; - map.insert("date",date); - map.insert("from", from); - map.insert("to", to); - map.insert("src1",src1); - map.insert("src2", src2); - QJsonObject object = QJsonObject::fromVariantMap(map); - QJsonDocument document; - document.setObject(object); - saveJson(document,history_file_path); - } +void History::save(QStringList meta, QString translationId) { + if (meta.count() >= 5) { + QString from, to, src1, src2, date; + from = meta.at(0); + to = meta.at(1); + src1 = meta.at(2); + src2 = meta.at(3); + date = meta.at(4); + QString history_file_path = + utils::returnPath("history") + "/" + translationId + ".json"; + QVariantMap map; + map.insert("date", date); + map.insert("from", from); + map.insert("to", to); + map.insert("src1", src1); + map.insert("src2", src2); + QJsonObject object = QJsonObject::fromVariantMap(map); + QJsonDocument document; + document.setObject(object); + saveJson(document, history_file_path); + } } - QJsonDocument History::loadJson(QString fileName) { - QFile jsonFile(fileName); - jsonFile.open(QFile::ReadOnly); - QByteArray data = jsonFile.readAll(); - jsonFile.close(); - return QJsonDocument().fromJson(data); + QFile jsonFile(fileName); + jsonFile.open(QFile::ReadOnly); + QByteArray data = jsonFile.readAll(); + jsonFile.close(); + return QJsonDocument().fromJson(data); } void History::saveJson(QJsonDocument document, QString fileName) { - QFile jsonFile(fileName); - jsonFile.open(QFile::WriteOnly); - jsonFile.write(document.toJson()); - jsonFile.close(); + QFile jsonFile(fileName); + jsonFile.open(QFile::WriteOnly); + jsonFile.write(document.toJson()); + jsonFile.close(); } -void History::loadHistory() -{ - ui->historyList->clear(); - QString history_path = utils::returnPath("history"); - QDir dir(history_path); - dir.setSorting(QDir::Time); - QStringList filter; - filter<< +"*.json"; - QFileInfoList files = dir.entryInfoList(filter); - ui->clearall->setEnabled(files.isEmpty()==false); - foreach (QFileInfo fileInfo, files) - { - //open file , read it to stringlist pass it to insertItem - QJsonDocument doc = loadJson(fileInfo.filePath()); - QJsonObject jsonObject = doc.object(); - QString from, to, src1, src2,date; - from = jsonObject.value("from").toString(); - to = jsonObject.value("to").toString(); - src1 = jsonObject.value("src1").toString(); - src2 = jsonObject.value("src2").toString(); - date = jsonObject.value("date").toString(); - insertItem(QStringList()<historyList->clear(); + QString history_path = utils::returnPath("history"); + QDir dir(history_path); + dir.setSorting(QDir::Time); + QStringList filter; + filter << +"*.json"; + QFileInfoList files = dir.entryInfoList(filter); + ui->clearall->setEnabled(files.isEmpty() == false); + foreach (QFileInfo fileInfo, files) { + // open file , read it to stringlist pass it to insertItem + QJsonDocument doc = loadJson(fileInfo.filePath()); + QJsonObject jsonObject = doc.object(); + QString from, to, src1, src2, date; + from = jsonObject.value("from").toString(); + to = jsonObject.value("to").toString(); + src1 = jsonObject.value("src1").toString(); + src2 = jsonObject.value("src2").toString(); + date = jsonObject.value("date").toString(); + insertItem(QStringList() + << from << to << src1.left(100) << src2.left(100) << date, + true, fileInfo.baseName()); + } } diff --git a/src/history.h b/src/history.h index 03d54ec..cb58ff3 100644 --- a/src/history.h +++ b/src/history.h @@ -1,41 +1,40 @@ #ifndef HISTORY_H #define HISTORY_H -#include +#include "ui_history_item.h" +#include #include #include -#include -#include "ui_history_item.h" - +#include namespace Ui { class History; } -class History : public QWidget -{ - Q_OBJECT +class History : public QWidget { + Q_OBJECT public: - explicit History(QWidget *parent = nullptr); - ~History(); + explicit History(QWidget *parent = nullptr); + ~History(); signals: - void historyItemMeta(QStringList historyItemMeta); - void setTranslationId(QString transId); + void historyItemMeta(QStringList historyItemMeta); + void setTranslationId(QString transId); public slots: - void loadHistory(); - void save(QStringList meta, QString translationId); - void insertItem(QStringList meta, bool fromHistory, QString translationId); - void loadHistoryItem(QString itemPath); + void loadHistory(); + void save(QStringList meta, QString translationId); + void insertItem(QStringList meta, bool fromHistory, QString translationId); + void loadHistoryItem(QString itemPath); private slots: - void on_clearall_clicked(); - QJsonDocument loadJson(QString fileName); - void saveJson(QJsonDocument document, QString fileName); + void on_clearall_clicked(); + QJsonDocument loadJson(QString fileName); + void saveJson(QJsonDocument document, QString fileName); + private: - Ui::History *ui; - Ui::history_item history_item_ui; + Ui::History *ui; + Ui::history_item history_item_ui; }; #endif // HISTORY_H diff --git a/src/linebyline.cpp b/src/linebyline.cpp index 659f6a7..321814c 100644 --- a/src/linebyline.cpp +++ b/src/linebyline.cpp @@ -2,78 +2,66 @@ #include "ui_linebyline.h" #include -LineByLine::LineByLine(QWidget *parent, QClipboard *clipborad) : - QWidget(parent), - ui(new Ui::LineByLine) -{ - ui->setupUi(this); - this->clipborad = clipborad; - connect(ui->src1->verticalScrollBar(),&QScrollBar::valueChanged,[=](int val){ - ui->src2->verticalScrollBar()->setValue(val); - }); - connect(ui->src2->verticalScrollBar(),&QScrollBar::valueChanged,[=](int val){ - ui->src1->verticalScrollBar()->setValue(val); - }); +LineByLine::LineByLine(QWidget *parent, QClipboard *clipborad) + : QWidget(parent), ui(new Ui::LineByLine) { + ui->setupUi(this); + this->clipborad = clipborad; + connect(ui->src1->verticalScrollBar(), &QScrollBar::valueChanged, + [=](int val) { ui->src2->verticalScrollBar()->setValue(val); }); + connect(ui->src2->verticalScrollBar(), &QScrollBar::valueChanged, + [=](int val) { ui->src1->verticalScrollBar()->setValue(val); }); } -LineByLine::~LineByLine() -{ - delete ui; -} +LineByLine::~LineByLine() { delete ui; } -void LineByLine::setData(QList currentTranslationData,QString sLang,QString tLang,QString tId){ - translationId = tId; - ui->sLang->setText(sLang); - ui->tLang->setText(tLang); - foreach (QStringList translationFregments, currentTranslationData) { - ui->src2->addItem(translationFregments.at(0)); //translation - ui->src1->addItem(translationFregments.at(1)); //source - } - if(ui->src1->count()>0) - ui->src1->setCurrentRow(0); - if(ui->src2->count()>0) - ui->src2->setCurrentRow(0); +void LineByLine::setData(QList currentTranslationData, + QString sLang, QString tLang, QString tId) { + translationId = tId; + ui->sLang->setText(sLang); + ui->tLang->setText(tLang); + foreach (QStringList translationFregments, currentTranslationData) { + ui->src2->addItem(translationFregments.at(0)); // translation + ui->src1->addItem(translationFregments.at(1)); // source + } + if (ui->src1->count() > 0) + ui->src1->setCurrentRow(0); + if (ui->src2->count() > 0) + ui->src2->setCurrentRow(0); } -void LineByLine::clearData(){ - ui->src1->blockSignals(true); - ui->src2->blockSignals(true); +void LineByLine::clearData() { + ui->src1->blockSignals(true); + ui->src2->blockSignals(true); - ui->src1->clear(); - ui->src2->clear(); + ui->src1->clear(); + ui->src2->clear(); - ui->src1->blockSignals(false); - ui->src2->blockSignals(false); + ui->src1->blockSignals(false); + ui->src2->blockSignals(false); } -void LineByLine::on_src1_currentRowChanged(int currentRow) -{ - ui->src2->blockSignals(true); - ui->src2->setCurrentRow(currentRow); - ui->src2Browser->setText(ui->src2->item(currentRow)->text()); - ui->src1Browser->setText(ui->src1->item(currentRow)->text()); - ui->src2->blockSignals(false); +void LineByLine::on_src1_currentRowChanged(int currentRow) { + ui->src2->blockSignals(true); + ui->src2->setCurrentRow(currentRow); + ui->src2Browser->setText(ui->src2->item(currentRow)->text()); + ui->src1Browser->setText(ui->src1->item(currentRow)->text()); + ui->src2->blockSignals(false); } -void LineByLine::on_src2_currentRowChanged(int currentRow) -{ - ui->src1->blockSignals(true); - ui->src1->setCurrentRow(currentRow); - ui->src1Browser->setText(ui->src1->item(currentRow)->text()); - ui->src2Browser->setText(ui->src2->item(currentRow)->text()); - ui->src1->blockSignals(false); +void LineByLine::on_src2_currentRowChanged(int currentRow) { + ui->src1->blockSignals(true); + ui->src1->setCurrentRow(currentRow); + ui->src1Browser->setText(ui->src1->item(currentRow)->text()); + ui->src2Browser->setText(ui->src2->item(currentRow)->text()); + ui->src1->blockSignals(false); } -QString LineByLine::getTId(){ - return translationId; -} +QString LineByLine::getTId() { return translationId; } -void LineByLine::on_copySrc2_clicked() -{ - clipborad->setText(ui->src2Browser->toPlainText()); +void LineByLine::on_copySrc2_clicked() { + clipborad->setText(ui->src2Browser->toPlainText()); } -void LineByLine::on_copySrc1_clicked() -{ - clipborad->setText(ui->src1Browser->toPlainText()); +void LineByLine::on_copySrc1_clicked() { + clipborad->setText(ui->src1Browser->toPlainText()); } diff --git a/src/linebyline.h b/src/linebyline.h index c53e502..8c7f56c 100644 --- a/src/linebyline.h +++ b/src/linebyline.h @@ -1,38 +1,39 @@ #ifndef LINEBYLINE_H #define LINEBYLINE_H -#include #include +#include namespace Ui { class LineByLine; } -class LineByLine : public QWidget -{ - Q_OBJECT +class LineByLine : public QWidget { + Q_OBJECT public: - explicit LineByLine(QWidget *parent = nullptr,QClipboard *clipborad = nullptr); - ~LineByLine(); + explicit LineByLine(QWidget *parent = nullptr, + QClipboard *clipborad = nullptr); + ~LineByLine(); public slots: - void setData(QList data, QString sLang, QString tLang, QString tId); - void clearData(); - QString getTId(); + void setData(QList data, QString sLang, QString tLang, + QString tId); + void clearData(); + QString getTId(); private slots: - void on_src1_currentRowChanged(int currentRow); + void on_src1_currentRowChanged(int currentRow); - void on_src2_currentRowChanged(int currentRow); + void on_src2_currentRowChanged(int currentRow); - void on_copySrc2_clicked(); + void on_copySrc2_clicked(); - void on_copySrc1_clicked(); + void on_copySrc1_clicked(); private: - Ui::LineByLine *ui; - QString translationId; - QClipboard *clipborad = nullptr; + Ui::LineByLine *ui; + QString translationId; + QClipboard *clipborad = nullptr; }; #endif // LINEBYLINE_H diff --git a/src/main.cpp b/src/main.cpp index 7a1f8bb..a310ccd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,15 +1,16 @@ #include "mainwindow.h" #include -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - QApplication::setApplicationName("Glate"); - QApplication::setOrganizationName("org.keshavnrj.ubuntu"); - QApplication::setApplicationVersion("2.0"); - MainWindow w; +int main(int argc, char *argv[]) { + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); - w.show(); + QApplication a(argc, argv); + QApplication::setApplicationName("Glate"); + QApplication::setOrganizationName("org.keshavnrj.ubuntu"); + QApplication::setApplicationVersion("3.0"); + MainWindow w; - return a.exec(); + w.show(); + + return a.exec(); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e6b2ad6..5743af1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,785 +1,779 @@ #include "mainwindow.h" #include "ui_mainwindow.h" -#include #include #include +#include -#include +#include #include +#include #include -#include -#include -#include -#include #include +#include +#include +#include -#include -#include #include +#include +#include -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow) -{ - ui->setupUi(this); - this->setWindowTitle(QApplication::applicationName()+" v"+QApplication::applicationVersion()); - this->setWindowIcon(QIcon(":/icons/app/icon-256.png")); - - setStyle(":/qbreeze/"+settings.value("theme","dark").toString()+".qss"); - - //set layout - _translate = new controlButton(ui->translationWidget); - _translate->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum); - _translate->setFixedSize(36,36); - _translate->setMouseTracking(true); - _translate->setToolTip("Translate (Shift + Enter)"); - _translate->setStyleSheet("border:none;border-radius:18px;"); - _translate->setIconSize(QSize(28,28)); - QShortcut *shortcut = new QShortcut(QKeySequence(tr("Shift+Return","Translate")), _translate,SLOT(click())); - shortcut->setContext(Qt::ApplicationShortcut); - _translate->setIcon(QIcon(":/icons/arrow-right-circle-line.png")); - QTimer::singleShot(100,this,SLOT(resizeFix())); - connect(_translate,SIGNAL(clicked()),this,SLOT(translate_clicked())); - - - // text option widget - init_textOptionWidget(); - - //read language codes and initialize vars - readLangCode(); - - //populate lang combos - ui->lang1->blockSignals(true); - ui->lang2->blockSignals(true); - - ui->lang1->addItem(QIcon(":/icons/translate-2.png"),"Auto Detect"); - ui->lang1->addItems(_langName); - ui->lang2->addItems(_langName); - for (int i = 0; i < ui->lang1->count(); i++) { - if(i==0){ - ui->lang1->setItemIcon(i,QIcon(":/icons/magic-line.png")); - }else{ - ui->lang1->setItemIcon(i,QIcon(":/icons/translate-2.png")); - } - } - for (int i = 0; i < ui->lang2->count(); i++) { - ui->lang2->setItemIcon(i,QIcon(":/icons/translate-2.png")); - } - - //load settings - ui->lang1->setCurrentIndex(settings.value("lang1",0).toInt()); - ui->lang2->setCurrentIndex(settings.value("lang2",20).toInt()); - - ui->switch_lang->setEnabled(ui->lang1->currentIndex()!=0); - - ui->lang1->blockSignals(false); - ui->lang2->blockSignals(false); - - ui->lang1->setMinimumWidth(150); - ui->lang2->setMinimumWidth(150); - - // loader is the child of wall_view - _loader = new WaitingSpinnerWidget(_translate,true,true); - _loader->setRoundness(70.0); - _loader->setMinimumTrailOpacity(15.0); - _loader->setTrailFadePercentage(70.0); - _loader->setNumberOfLines(30); - _loader->setLineLength(14); - _loader->setLineWidth(2); - _loader->setInnerRadius(2); - _loader->setRevolutionsPerSecond(3); - _loader->setColor(QColor(67,124,198)); - - if(settings.value("geometry").isValid()){ - restoreGeometry(settings.value("geometry").toByteArray()); - if(settings.value("windowState").isValid()){ - restoreState(settings.value("windowState").toByteArray()); - }else{ - QScreen* pScreen = QGuiApplication::screenAt(this->mapToGlobal({this->width()/2,0})); - QRect availableScreenSize = pScreen->availableGeometry(); - this->move(availableScreenSize.center()-this->rect().center()); - } - } +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), ui(new Ui::MainWindow) { + ui->setupUi(this); + this->setWindowTitle(QApplication::applicationName() + " v" + + QApplication::applicationVersion()); + this->setWindowIcon(QIcon(":/icons/app/icon-64.png")); + + setStyle(":/qbreeze/" + settings.value("theme", "dark").toString() + ".qss"); + + // set layout + _translate = new controlButton(ui->translationWidget); + _translate->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + _translate->setFixedSize(36, 36); + _translate->setMouseTracking(true); + _translate->setToolTip("Translate (Shift + Enter)"); + _translate->setStyleSheet("border:none;border-radius:18px;"); + _translate->setIconSize(QSize(28, 28)); + QShortcut *shortcut = new QShortcut( + QKeySequence(tr("Shift+Return", "Translate")), _translate, SLOT(click())); + shortcut->setContext(Qt::ApplicationShortcut); + _translate->setIcon(QIcon(":/icons/arrow-right-circle-line.png")); + QTimer::singleShot(100, this, SLOT(resizeFix())); + connect(_translate, &QAbstractButton::clicked, this, + &MainWindow::translate_clicked); + + // read language codes and initialize vars + readLangCode(); + + // populate lang combos + ui->lang1->blockSignals(true); + ui->lang2->blockSignals(true); + + ui->lang1->addItem(QIcon(":/icons/translate-2.png"), "Auto Detect"); + ui->lang1->addItems(_langName); + ui->lang2->addItems(_langName); + for (int i = 0; i < ui->lang1->count(); i++) { + if (i == 0) { + ui->lang1->setItemIcon(i, QIcon(":/icons/magic-line.png")); + } else { + ui->lang1->setItemIcon(i, QIcon(":/icons/translate-2.png")); + } + } + for (int i = 0; i < ui->lang2->count(); i++) { + ui->lang2->setItemIcon(i, QIcon(":/icons/translate-2.png")); + } + + // load settings + ui->lang1->setCurrentIndex(settings.value("lang1", 0).toInt()); + ui->lang2->setCurrentIndex(settings.value("lang2", 20).toInt()); + + ui->switch_lang->setEnabled(ui->lang1->currentIndex() != 0); + + ui->lang1->blockSignals(false); + ui->lang2->blockSignals(false); + + ui->lang1->setMinimumWidth(150); + ui->lang2->setMinimumWidth(150); + + // loader is the child of wall_view + _loader = new WaitingSpinnerWidget(_translate, true, true); + _loader->setRoundness(70.0); + _loader->setMinimumTrailOpacity(15.0); + _loader->setTrailFadePercentage(70.0); + _loader->setNumberOfLines(30); + _loader->setLineLength(14); + _loader->setLineWidth(2); + _loader->setInnerRadius(2); + _loader->setRevolutionsPerSecond(3); + _loader->setColor(QColor(67, 124, 198)); + + if (settings.value("geometry").isValid()) { + restoreGeometry(settings.value("geometry").toByteArray()); + if (settings.value("windowState").isValid()) { + restoreState(settings.value("windowState").toByteArray()); + } else { + QScreen *pScreen = + QGuiApplication::screenAt(this->mapToGlobal({this->width() / 2, 0})); + QRect availableScreenSize = pScreen->availableGeometry(); + this->move(availableScreenSize.center() - this->rect().center()); + } + } + + // init media player + _player = new QMediaPlayer(this, QMediaPlayer::StreamPlayback); + _player->setVolume(100); + connect(_player, &QMediaPlayer::stateChanged, this, + [=](QMediaPlayer::State state) { + QPushButton *playBtn = this->findChild( + _player->objectName().split("_").last()); + if (playBtn != nullptr && state == QMediaPlayer::StoppedState) { + playBtn->setIcon(QIcon(":/icons/volume-up-line.png")); + playSelected = false; + selectedText.clear(); + } + if (playBtn != nullptr && state == QMediaPlayer::PlayingState) { + playBtn->setIcon(QIcon(":/icons/stop-line.png")); + } + }); - //init media player - _player = new QMediaPlayer(this,QMediaPlayer::StreamPlayback); - _player->setVolume(100); - connect(_player,&QMediaPlayer::stateChanged,[=](QMediaPlayer::State state){ - QPushButton *playBtn = this->findChild(_player->objectName().split("_").last()); - if(playBtn != nullptr && state == QMediaPlayer::StoppedState){ - playBtn->setIcon(QIcon(":/icons/volume-up-line.png")); + connect(_player, QOverload::of(&QMediaPlayer::error), + this, [=](QMediaPlayer::Error error) { + Q_UNUSED(error); playSelected = false; selectedText.clear(); + QPushButton *playBtn = this->findChild( + _player->objectName().split("_").last()); + if (playBtn != nullptr) + playBtn->setIcon(QIcon(":/icons/volume-up-line.png")); + showError(_player->errorString()); + }); + + connect(_player, &QMediaPlayer::mediaStatusChanged, this, + [=](QMediaPlayer::MediaStatus mediastate) { + QPushButton *playBtn = this->findChild( + _player->objectName().split("_").last()); + if (playBtn != nullptr && + (mediastate == QMediaPlayer::LoadingMedia || + mediastate == QMediaPlayer::BufferingMedia)) { + playBtn->setIcon(QIcon(":/icons/loader-2-fill.png")); + } + if (playBtn != nullptr && + (mediastate == QMediaPlayer::BufferedMedia)) { + playBtn->setIcon(QIcon(":/icons/stop-line.png")); + } + }); + + // load src1 + ui->counter->setText("5000/5000"); + int minWid = + ui->counter->fontMetrics().boundingRect(ui->counter->text()).width(); + ui->counter->setText(QString::number(ui->src1->toPlainText().count()) + + "/5000"); + + ui->counter->setMinimumWidth(minWid); + ui->counter_2->setMinimumWidth(minWid); + + clipboard = QApplication::clipboard(); + + // init share + _share = new Share(this); + _share->setWindowTitle(QApplication::applicationName() + + " | Share translation"); + _share->setWindowFlag(Qt::Dialog); + _share->setWindowModality(Qt::NonModal); + + _lineByLine = new LineByLine(this, clipboard); + _lineByLine->setWindowTitle(QApplication::applicationName() + + " | LineByLine translation"); + _lineByLine->setWindowFlag(Qt::Dialog); + _lineByLine->setWindowModality(Qt::NonModal); + + // init settings + init_settings(); + + // init history + init_history(); + + if (settings.value("lastTranslation").isValid()) { + QFileInfo check(QFile(utils::returnPath("history") + "/" + + settings.value("lastTranslation").toString() + + ".json")); + if (check.exists()) { + translationId = settings.value("lastTranslation").toString(); + historyWidget->loadHistoryItem(utils::returnPath("history") + "/" + + translationId + ".json"); + } + } + + if (settings.value("firstRun").isValid() == false) { + on_help_clicked(); + settings.setValue("firstRun", false); + } +} + +// TODO skip duplicate history item by checking translationId + +void MainWindow::init_history() { + utils::returnPath("history"); + historyWidget = new History(this); + historyWidget->setWindowTitle(QApplication::applicationName() + " | History"); + historyWidget->setWindowFlag(Qt::Dialog); + historyWidget->setWindowModality(Qt::NonModal); + connect(historyWidget, &History::setTranslationId, this, + [=](QString transId) { this->translationId = transId; }); + connect(historyWidget, &History::historyItemMeta, this, + [=](QStringList historyItemMeta) { + if (historyItemMeta.count() >= 4) { + currentTranslationData.clear(); + settings.setValue( + "lastTranslation", + translationId); // translation id is set before this functor + // is called via signal + QString from, to, src1, src2; + from = historyItemMeta.at(0); + to = historyItemMeta.at(1); + src1 = historyItemMeta.at(2); + src2 = historyItemMeta.at(3); + ui->src1->setText(src1); + ui->src2->setText(src2); + ui->lang1->setCurrentText(from); + ui->lang2->setCurrentText(to); + } + }); +} + +void MainWindow::init_settings() { + nativeHotkey = new QHotkey(this); + settingsWidget = new Settings(this, nativeHotkey); + settingsWidget->setWindowTitle(QApplication::applicationName() + + " | Settings"); + settingsWidget->setWindowFlag(Qt::Dialog); + settingsWidget->setWindowModality(Qt::NonModal); + connect(settingsWidget, &Settings::translationRequest, this, + [=](const QString selected) { + ui->src1->setText(selected); + ui->lang1->setCurrentIndex(0); + _translate->click(); + this->setWindowState((this->windowState() & ~Qt::WindowMinimized) | + Qt::WindowActive); + this->show(); + }); + connect(settingsWidget, &Settings::themeToggled, this, [=]() { + setStyle(":/qbreeze/" + settings.value("theme", "dark").toString() + + ".qss"); + }); + if (nativeHotkey->isRegistered() == false) { + showError("Unable to register Global Hotkey.\nIs another instance of " + + QApplication::applicationName() + + "running ?\nIf yes close it and restart the application."); + } +} + +void MainWindow::textSelectionChanged(QTextEdit *editor) { + QString selection = editor->textCursor().selectedText().trimmed(); + if (!selection.isEmpty()) { + textOptionWidget->setObjectName("selection_" + editor->objectName()); + textOptionWidget->move(QCursor::pos().x(), QCursor::pos().y() + 10); + textOptionWidget->resize(textOptionWidget->minimumSizeHint()); + textOptionWidget->adjustSize(); + textOptionWidget->show(); + + textOptionForm.readPushButton->disconnect(); + textOptionForm.copyPushButton->disconnect(); + + connect(textOptionForm.readPushButton, &QPushButton::clicked, this, [=]() { + if (this->findChild(textOptionWidget->objectName() + .split("selection_") + .last() + .trimmed()) != nullptr) { + playSelected = true; + selectedText = selection; + if (textOptionWidget->objectName() + .split("selection_") + .last() + .trimmed() == "src1") { + on_play1_clicked(); + } else { + on_play2_clicked(); } - if(playBtn != nullptr && state == QMediaPlayer::PlayingState){ - playBtn->setIcon(QIcon(":/icons/stop-line.png")); - } + textOptionWidget->hide(); + } }); - connect(_player, QOverload::of(&QMediaPlayer::error), - [=](QMediaPlayer::Error error){ - Q_UNUSED(error); - playSelected = false; - selectedText.clear(); - QPushButton *playBtn = this->findChild(_player->objectName().split("_").last()); - if(playBtn != nullptr ) - playBtn->setIcon(QIcon(":/icons/volume-up-line.png")); - showError(_player->errorString()); - }); - - connect(_player,&QMediaPlayer::mediaStatusChanged,[=](QMediaPlayer::MediaStatus mediastate){ - QPushButton *playBtn = this->findChild(_player->objectName().split("_").last()); - if(playBtn != nullptr && (mediastate == QMediaPlayer::LoadingMedia|| - mediastate == QMediaPlayer::BufferingMedia)){ - playBtn->setIcon(QIcon(":/icons/loader-2-fill.png")); - } - if(playBtn != nullptr && (mediastate == QMediaPlayer::BufferedMedia) ){ - playBtn->setIcon(QIcon(":/icons/stop-line.png")); - } + connect(textOptionForm.copyPushButton, &QPushButton::clicked, this, [=]() { + clipboard->setText(selection); + textOptionWidget->hide(); }); - - - //load src1 - ui->counter->setText("5000/5000"); - int minWid = ui->counter->fontMetrics().boundingRect(ui->counter->text()).width(); - ui->counter->setText(QString::number(ui->src1->toPlainText().count())+"/5000"); - - ui->counter->setMinimumWidth(minWid); - ui->counter_2->setMinimumWidth(minWid); - - clipboard = QApplication::clipboard(); - - //init share - _share = new Share(this); - _share->setWindowTitle(QApplication::applicationName()+" | Share translation"); - _share->setWindowFlag(Qt::Dialog); - _share->setWindowModality(Qt::NonModal); - - - _lineByLine = new LineByLine(this,clipboard); - _lineByLine->setWindowTitle(QApplication::applicationName()+" | LineByLine translation"); - _lineByLine->setWindowFlag(Qt::Dialog); - _lineByLine->setWindowModality(Qt::NonModal); - - //init settings - init_settings(); - - //init history - init_history(); - - if(settings.value("lastTranslation").isValid()){ - QFileInfo check(QFile(utils::returnPath("history")+"/"+settings.value("lastTranslation").toString()+".json")); - if(check.exists()){ - translationId = settings.value("lastTranslation").toString(); - historyWidget->loadHistoryItem(utils::returnPath("history")+"/"+translationId+".json"); - } - } - - if(settings.value("firstRun").isValid()==false){ - on_help_clicked(); - settings.setValue("firstRun",false); - } -} - -//TODO skip duplicate history item by checking translationId - -void MainWindow::init_history() -{ - utils::returnPath("history"); - historyWidget = new History(this); - historyWidget->setWindowTitle(QApplication::applicationName()+" | History"); - historyWidget->setWindowFlag(Qt::Dialog); - historyWidget->setWindowModality(Qt::NonModal); - connect(historyWidget,&History::setTranslationId,[=](QString transId){ - this->translationId = transId; + } else { + playSelected = false; + selectedText.clear(); + } +} + +bool MainWindow::eventFilter(QObject *o, QEvent *e) { + // simulate translate shortcut instead of going to new line when cursor is on + // textEdit widgets. + if (e->type() == QEvent::KeyRelease || e->type() == QEvent::KeyPress || + e->type() == QEvent::ShortcutOverride) { + if (o == ui->src1 || o == ui->src2) { + QKeyEvent *keyEvent = static_cast(e); + if ((keyEvent->key() == Qt::Key_Return) && + keyEvent->modifiers() & (Qt::ShiftModifier)) { + _translate->click(); + return true; + } else { + return false; + } + } + } + return QMainWindow::eventFilter(o, e); +} + +void MainWindow::resizeFix() { + this->resize(this->width() + 1, this->height()); + ui->left_buttons_widget->setMinimumWidth(ui->right_button_widget->width()); + ui->left_buttons_widget->resize(ui->right_button_widget->width(), + ui->left_buttons_widget->height()); +} + +void MainWindow::closeEvent(QCloseEvent *event) { + settings.setValue("geometry", saveGeometry()); + settings.setValue("windowState", saveState()); + + // save quick trans shortcut + settings.setValue("quicktrans_shortcut", + settingsWidget->keySequenceEditKeySequence()); + + // save quicktrans settings + settings.setValue("quicktrans", settingsWidget->quickResultCheckBoxChecked()); + + QMainWindow::closeEvent(event); +} + +void MainWindow::resizeEvent(QResizeEvent *event) { + int x = + ui->translationWidget->geometry().center().x() - _translate->width() / 2; + int y = ui->translationWidget->geometry().center().y() - + (_translate->height() + _translate->height() / 2); + _translate->move(x, y); + ui->switch_lang->move(x, ui->switch_lang->y()); + ui->left_buttons_widget->resize(ui->right_button_widget->width(), + ui->left_buttons_widget->height()); + QMainWindow::resizeEvent(event); +} + +void MainWindow::readLangCode() { + QFile lang(":/resources/lang.glate"); + if (!lang.open(QIODevice::ReadOnly)) { + qWarning("Unable to open file"); + return; + } + while (!lang.atEnd()) { + QString langLine = QString(lang.readLine()); + QStringList langItem = langLine.split("<=>"); + _langName.append(langItem.at(0).trimmed()); + _langCode.append(langItem.at(1).trimmed()); + } + lang.close(); + + // TTS + QFile tts(":/resources/tts.glate"); + if (!tts.open(QIODevice::ReadOnly)) { + qWarning("Unable to open file"); + return; + } + while (!tts.atEnd()) { + QString ttsCode = QString(tts.readLine()); + _supportedTts.append(ttsCode.trimmed()); + } + tts.close(); +} + +void MainWindow::setStyle(QString fname) { + QFile styleSheet(fname); + if (!styleSheet.open(QIODevice::ReadOnly)) { + qWarning("Unable to open file"); + return; + } + qApp->setStyleSheet(styleSheet.readAll()); + styleSheet.close(); +} + +MainWindow::~MainWindow() { delete ui; } + +void MainWindow::translate_clicked() { + // clear processor vars + currentTranslationData.clear(); + ui->src2->clear(); + + if (_request != nullptr) { + _request->blockSignals(true); + _request->deleteLater(); + _request->blockSignals(false); + _request = nullptr; + _loader->stop(); + } + + if (_request == nullptr) { + _request = new Request(this); + connect(_request, &Request::requestStarted, this, + [=]() { _loader->start(); }); + connect(_request, &Request::requestFinished, this, [=](QString reply) { + // save cache for line by line use + saveByTransId(translationId, reply); + // load to view + processTranslation(reply); + _loader->stop(); + settings.setValue("lastTranslation", translationId); }); - connect(historyWidget,&History::historyItemMeta,[=](QStringList historyItemMeta){ - if(historyItemMeta.count()>=4){ - currentTranslationData.clear(); - settings.setValue("lastTranslation",translationId); //translation id is set before this functor is called via signal - QString from, to, src1, src2; - from = historyItemMeta.at(0); - to = historyItemMeta.at(1); - src1 = historyItemMeta.at(2); - src2 = historyItemMeta.at(3); - ui->src1->setText(src1); - ui->src2->setText(src2); - ui->lang1->setCurrentText(from); - ui->lang2->setCurrentText(to); - } + connect(_request, &Request::downloadError, this, [=](QString errorString) { + _loader->stop(); + showError(errorString); }); -} - -void MainWindow::init_settings() -{ - nativeHotkey=new QHotkey(this); - settingsWidget = new Settings(this,nativeHotkey); - settingsWidget->setWindowTitle(QApplication::applicationName()+" | Settings"); - settingsWidget->setWindowFlag(Qt::Dialog); - settingsWidget->setWindowModality(Qt::NonModal); - connect(settingsWidget,&Settings::translationRequest,[=](const QString selected){ - ui->src1->setText(selected); - ui->lang1->setCurrentIndex(0); - _translate->click(); - this->setWindowState((this->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); - this->show(); + QString src1 = ui->src1->toPlainText().replace("&", "and").replace("#", ""); + QString urlStr = + "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + + getSourceLang() + "&tl=" + getTransLang() + "&dt=t&q=" + src1; + QString url = QUrl(urlStr).toString(QUrl::FullyEncoded); + qDebug() << url; + if (url.isEmpty()) { + showError("Invalid Input."); + } else { + _request->get(QUrl(url)); + translationId = utils::generateRandomId(20); + } + } +} + +void MainWindow::saveByTransId(QString translationId, QString reply) { + QFile jsonFile(utils::returnPath("cache") + "/" + translationId + ".glate"); + jsonFile.open(QFile::WriteOnly); + jsonFile.write(reply.toUtf8()); + jsonFile.close(); +} + +void MainWindow::processTranslation(QString reply) { + currentTranslationData.clear(); + QJsonDocument jsonResponse = QJsonDocument::fromJson(reply.toUtf8()); + if (jsonResponse.isEmpty()) { + showError( + "Empty response returned.\n Please report to keshavnrj@gmail.com"); + return; + } + QJsonArray jsonArray = jsonResponse.array(); + foreach (const QJsonValue &val, jsonArray) { + if (val.isArray() && !val.toArray().isEmpty()) { + foreach (const QJsonValue &val2, val.toArray()) { + if (val2.isArray() && !val2.toArray().isEmpty() && + val2.toArray().count() >= 2) { + QStringList translationFregments; + translationFregments << val2.toArray().at(0).toString(); + translationFregments << val2.toArray().at(1).toString(); + currentTranslationData.append(translationFregments); + } + } + } + } + foreach (QStringList translationFregments, currentTranslationData) { + ui->src2->append(translationFregments.at(0)); + } + // scroll to top + ui->src2->verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum); + // history save + historyWidget->insertItem( + QStringList() << getLangName(getSourceLang()) + << getLangName(getTransLang()) << ui->src1->toPlainText() + << ui->src2->toPlainText() + << QDateTime::currentDateTime().toLocalTime().toString(), + false, translationId); +} + +QString MainWindow::getSourceLang() { + int indexLang1 = ui->lang1->currentIndex(); + if (indexLang1 == 0) { + return "auto"; + } else { + return _langCode.at(indexLang1 - 1).trimmed(); + } +} + +QString MainWindow::getTransLang() { + int indexLang2 = ui->lang2->currentIndex(); + return _langCode.at(indexLang2).trimmed(); +} + +void MainWindow::showError(QString message) { + if (message.contains("host", Qt::CaseInsensitive) || + message.contains("translate.googleapis.com")) { + message.replace("translate.googleapis.com", "host"); + } + // init error + _error = new Error(this); + _error->setAttribute(Qt::WA_DeleteOnClose); + _error->setWindowTitle(QApplication::applicationName() + " | Error dialog"); + _error->setWindowFlag(Qt::Dialog); + _error->setWindowModality(Qt::NonModal); + _error->setError("An Error ocurred while processing your request!", message); + _error->show(); +} + +void MainWindow::on_clear_clicked() { + ui->src1->clear(); + ui->src2->clear(); + + if (_request != nullptr) { + _request->blockSignals(true); + _request->deleteLater(); + _request->blockSignals(false); + _request = nullptr; + _loader->stop(); + } + currentTranslationData.clear(); + translationId.clear(); + _lineByLine->clearData(); +} + +void MainWindow::on_paste_clicked() { + const QMimeData *mimeData = clipboard->mimeData(); + if (mimeData->hasText()) { + ui->src1->setPlainText(mimeData->text()); + } +} + +void MainWindow::on_switch_lang_clicked() { + int index1 = ui->lang1->currentIndex(); + int index2 = ui->lang2->currentIndex(); + + ui->lang1->setCurrentIndex(index2 + 1); + ui->lang2->setCurrentIndex(index1 - 1); + + if (ui->src2->toPlainText().trimmed().isEmpty() == false) { + QString src1 = ui->src1->toPlainText(); + QString src2 = ui->src2->toPlainText(); + + ui->src2->setText(src1); + ui->src1->setText(src2); + } +} + +void MainWindow::on_lang1_currentIndexChanged(int index) { + ui->switch_lang->setEnabled(index != 0); + settings.setValue("lang1", index); + _translate->setToolTip( + "Translate from " + ui->lang1->itemText(index) + " to " + + ui->lang2->itemText(ui->lang2->currentIndex()) + "(Shift + Enter)"); +} + +void MainWindow::on_lang2_currentIndexChanged(int index) { + settings.setValue("lang2", index); + _translate->setToolTip("Translate from " + + ui->lang1->itemText(ui->lang1->currentIndex()) + + " to " + ui->lang2->itemText(index)); +} + +void MainWindow::on_play2_clicked() { + bool player1Playing = _player->objectName().split("_").last() == "play1" && + _player->state() == QMediaPlayer::PlayingState; + + if (_player->state() != QMediaPlayer::PlayingState) { + if (_supportedTts.contains(getTransLang(), Qt::CaseInsensitive) == false) { + showError("Selected language '" + getTransLang() + + "' is not supported by TTS Engine.\nPlease choose different " + "Language."); + return; + } + _player->setObjectName("player_play2"); + QString text = ui->src2->toPlainText(); + if (playSelected) + text = selectedText; + + QStringList src2Parts; + QMediaPlaylist *src2playlist = new QMediaPlaylist(_player); + src2playlist->setPlaybackMode(QMediaPlaylist::Sequential); + connect(src2playlist, &QMediaPlaylist::currentIndexChanged, [=](int pos) { + qDebug() << "Playist for player2 pos changed" << pos; }); - connect(settingsWidget,&Settings::themeToggled,[=](){ - setStyle(":/qbreeze/"+settings.value("theme","dark").toString()+".qss"); + if (utils::splitString(text, 1500, src2Parts)) { + foreach (QString src2Url, src2Parts) { + QUrl url("https://www.google.com/speech-api/v1/synthesize"); + QUrlQuery params; + params.addQueryItem("ie", "UTF-8"); + params.addQueryItem("lang", getTransLang()); + params.addQueryItem("text", QUrl::toPercentEncoding(src2Url.toUtf8())); + url.setQuery(params); + src2playlist->addMedia(QMediaContent(url)); + } + } + _player->setPlaylist(src2playlist); + _player->play(); + ui->play2->setIcon(QIcon(":/icons/loader-2-fill.png")); + } else { + _player->blockSignals(true); + _player->stop(); + ui->play1->setIcon(QIcon(":/icons/volume-up-line.png")); + ui->play2->setIcon(QIcon(":/icons/volume-up-line.png")); + _player->blockSignals(false); + } + + if (player1Playing) { + on_play2_clicked(); + } +} + +void MainWindow::on_play1_clicked() { + bool player2Playing = _player->objectName().split("_").last() == "play2" && + _player->state() == QMediaPlayer::PlayingState; + + if (_player->state() != QMediaPlayer::PlayingState) { + if (_supportedTts.contains(getSourceLang(), Qt::CaseInsensitive) == false) { + showError("Selected language '" + getSourceLang() + + "' is not supported by TTS Engine.\nPlease choose different " + "Language."); + return; + } + _player->setObjectName("player_play1"); + QString text = ui->src1->toPlainText(); + if (playSelected) + text = selectedText; + + QStringList src1Parts; + QMediaPlaylist *src1playlist = new QMediaPlaylist(_player); + src1playlist->setPlaybackMode(QMediaPlaylist::Sequential); + connect(src1playlist, &QMediaPlaylist::currentIndexChanged, [=](int pos) { + qDebug() << "Playist for player1 pos changed" << pos; }); - if(nativeHotkey->isRegistered()==false){ - showError("Unable to register Global Hotkey.\nIs another instance of "+QApplication::applicationName()+"running ?\nIf yes close it and restart the application."); - } -} - -void MainWindow::init_textOptionWidget() -{ - textOptionWidget = new QWidget(0); - textOptionForm.setupUi(textOptionWidget); - textOptionWidget->setWindowFlags(Qt::Popup); - - textOptionWidget->move(QCursor::pos()); - textOptionWidget->resize(textOptionWidget->minimumSizeHint()); - textOptionWidget->adjustSize(); - - ui->src1->viewport()->installEventFilter(this); - ui->src2->viewport()->installEventFilter(this); - ui->src1->installEventFilter(this); - ui->src2->installEventFilter(this); -} - -void MainWindow::textSelectionChanged(QTextEdit *editor) -{ - QString selection = editor->textCursor().selectedText().trimmed(); - if(!selection.isEmpty()){ - textOptionWidget->setObjectName("selection_"+editor->objectName()); - textOptionWidget->move(QCursor::pos().x(),QCursor::pos().y()+10); - textOptionWidget->resize(textOptionWidget->minimumSizeHint()); - textOptionWidget->adjustSize(); - textOptionWidget->show(); - - textOptionForm.readPushButton->disconnect(); - textOptionForm.copyPushButton->disconnect(); - - connect(textOptionForm.readPushButton,&QPushButton::clicked,[=](){ - if(this->findChild(textOptionWidget->objectName().split("selection_").last().trimmed())!= nullptr){ - playSelected = true; - selectedText = selection; - if(textOptionWidget->objectName().split("selection_").last().trimmed()=="src1"){ - on_play1_clicked(); - }else{ - on_play2_clicked(); - } - textOptionWidget->hide(); - } - }); - - connect(textOptionForm.copyPushButton,&QPushButton::clicked,[=](){ - clipboard->setText(selection); - textOptionWidget->hide(); - }); - }else{ - playSelected = false; - selectedText.clear(); - } -} - -bool MainWindow::eventFilter(QObject* o, QEvent* e) -{ - if(e->type() == QEvent::MouseButtonRelease) - { - if(o == ui->src1->viewport() || o == ui->src2->viewport()){ - textSelectionChanged(qobject_cast(o->parent())); - } - } - //simulate translate shortcut instead of going to new line when cursor is on textEdit widgets. - if(e->type() == QEvent::KeyRelease || e->type() == QEvent::KeyPress || e->type() == QEvent::ShortcutOverride) - { - if(o == ui->src1 || o == ui->src2){ - QKeyEvent *keyEvent = static_cast(e); - if((keyEvent->key() == Qt::Key_Return) && - keyEvent->modifiers() & (Qt::ShiftModifier)){ - _translate->click(); - return true; - }else{ - return false; - } - } - } - return QMainWindow::eventFilter(o, e); -} - - -void MainWindow::resizeFix(){ - this->resize(this->width()+1,this->height()); - ui->left_buttons_widget->setMinimumWidth(ui->right_button_widget->width()); - ui->left_buttons_widget->resize(ui->right_button_widget->width(),ui->left_buttons_widget->height()); -} - -void MainWindow::closeEvent(QCloseEvent *event){ - settings.setValue("geometry",saveGeometry()); - settings.setValue("windowState", saveState()); - - //save quick trans shortcut - settings.setValue("quicktrans_shortcut",settingsWidget->keySequenceEditKeySequence()); - - //save quicktrans settings - settings.setValue("quicktrans",settingsWidget->quickResultCheckBoxChecked()); - - QMainWindow::closeEvent(event); -} - -void MainWindow::resizeEvent(QResizeEvent *event) -{ - int x = ui->translationWidget->geometry().center().x()-_translate->width()/2; - int y = ui->translationWidget->geometry().center().y()-(_translate->height()+_translate->height()/2); - _translate->move(x,y); - ui->switch_lang->move(x,ui->switch_lang->y()); - ui->left_buttons_widget->resize(ui->right_button_widget->width(),ui->left_buttons_widget->height()); - QMainWindow::resizeEvent(event); -} - -void MainWindow::readLangCode() -{ - QFile lang(":/resources/lang.glate"); - if (!lang.open(QIODevice::ReadOnly)) { - qWarning("Unable to open file"); - return; } - while(!lang.atEnd()) - { - QString langLine = QString(lang.readLine()); - QStringList langItem = langLine.split("<=>"); - _langName.append(langItem.at(0).trimmed()); - _langCode.append(langItem.at(1).trimmed()); - } - lang.close(); - - //TTS - QFile tts(":/resources/tts.glate"); - if (!tts.open(QIODevice::ReadOnly)) { - qWarning("Unable to open file"); - return; } - while(!tts.atEnd()) - { - QString ttsCode = QString(tts.readLine()); - _supportedTts.append(ttsCode.trimmed()); - } - tts.close(); -} - -void MainWindow::setStyle(QString fname) -{ - QFile styleSheet(fname); - if (!styleSheet.open(QIODevice::ReadOnly)) - { - qWarning("Unable to open file"); - return; - } - qApp->setStyleSheet(styleSheet.readAll()); - styleSheet.close(); -} - -MainWindow::~MainWindow() -{ - delete ui; -} - - -void MainWindow::translate_clicked() -{ - //clear processor vars - currentTranslationData.clear(); - ui->src2->clear(); - - if(_request!= nullptr){ - _request->blockSignals(true); - _request->deleteLater(); - _request->blockSignals(false); - _request = nullptr; - _loader->stop(); - } - - if(_request==nullptr){ - _request = new Request(this); - connect(_request,&Request::requestStarted,[=]() - { - _loader->start(); - }); - connect(_request,&Request::requestFinished,[=](QString reply) - { - //save cache for line by line use - saveByTransId(translationId,reply); - //load to view - processTranslation(reply); - _loader->stop(); - settings.setValue("lastTranslation",translationId); - }); - connect(_request,&Request::downloadError,[=](QString errorString) - { - _loader->stop(); - showError(errorString); - }); - - QString src1 = ui->src1->toPlainText().replace("&","and"); - QString urlStr = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="+ - getSourceLang()+"&tl="+getTransLang()+"&dt=t&q="+ - src1; - QString url = QUrl(urlStr).toString(QUrl::EncodeSpaces); - if(url.isEmpty()){ - showError("Invalid Input."); - }else{ - _request->get(QUrl(url)); - translationId = utils::generateRandomId(20); - } - } -} - -void MainWindow::saveByTransId(QString translationId,QString reply){ - QFile jsonFile(utils::returnPath("cache")+"/"+translationId+".glate"); - jsonFile.open(QFile::WriteOnly); - jsonFile.write(reply.toUtf8()); - jsonFile.close(); -} - -void MainWindow::processTranslation(QString reply){ - currentTranslationData.clear(); - QJsonDocument jsonResponse = QJsonDocument::fromJson(reply.toUtf8()); - if(jsonResponse.isEmpty()){ - showError("Empty response returned.\n Please report to keshavnrj@gmail.com"); - return; - } - QJsonArray jsonArray = jsonResponse.array(); - foreach (const QJsonValue &val, jsonArray) { - if(val.isArray() && !val.toArray().isEmpty()) { - foreach (const QJsonValue &val2, val.toArray()) { - if(val2.isArray() && !val2.toArray().isEmpty()&& val2.toArray().count()>=2) { - QStringList translationFregments; - translationFregments<src2->append(translationFregments.at(0)); - } - //scroll to top - ui->src2->verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum); - //history save - historyWidget->insertItem(QStringList()<src1->toPlainText() - <src2->toPlainText() - <lang1->currentIndex(); - if(indexLang1==0){ - return "auto"; - }else{ - return _langCode.at(indexLang1-1).trimmed(); - } -} - -QString MainWindow::getTransLang(){ - int indexLang2 = ui->lang2->currentIndex(); - return _langCode.at(indexLang2).trimmed(); -} - -void MainWindow::showError(QString message) -{ - if(message.contains("host",Qt::CaseInsensitive)|| message.contains("translate.googleapis.com")){ - message.replace("translate.googleapis.com","host"); - } - //init error - _error = new Error(this); - _error->setAttribute(Qt::WA_DeleteOnClose); - _error->setWindowTitle(QApplication::applicationName()+" | Error dialog"); - _error->setWindowFlag(Qt::Dialog); - _error->setWindowModality(Qt::NonModal); - _error->setError("An Error ocurred while processing your request!", - message); - _error->show(); -} - -void MainWindow::on_clear_clicked() -{ - ui->src1->clear(); - ui->src2->clear(); - - if(_request!= nullptr){ - _request->blockSignals(true); - _request->deleteLater(); - _request->blockSignals(false); - _request = nullptr; - _loader->stop(); - } - currentTranslationData.clear(); - translationId.clear(); - _lineByLine->clearData(); -} - -void MainWindow::on_paste_clicked() -{ - const QMimeData *mimeData = clipboard->mimeData(); - if(mimeData->hasText()){ - ui->src1->setPlainText(mimeData->text()); - } -} - -void MainWindow::on_switch_lang_clicked() -{ - int index1= ui->lang1->currentIndex(); - int index2 = ui->lang2->currentIndex(); - - ui->lang1->setCurrentIndex(index2+1); - ui->lang2->setCurrentIndex(index1-1); - - if(ui->src2->toPlainText().trimmed().isEmpty()==false){ - QString src1 = ui->src1->toPlainText(); - QString src2 = ui->src2->toPlainText(); - - ui->src2->setText(src1); - ui->src1->setText(src2); - } -} - -void MainWindow::on_lang1_currentIndexChanged(int index) -{ - ui->switch_lang->setEnabled(index!=0); - settings.setValue("lang1",index); - _translate->setToolTip("Translate from "+ui->lang1->itemText(index)+" to "+ui->lang2->itemText(ui->lang2->currentIndex()) + "(Shift + Enter)"); -} - -void MainWindow::on_lang2_currentIndexChanged(int index) -{ - settings.setValue("lang2",index); - _translate->setToolTip("Translate from "+ui->lang1->itemText(ui->lang1->currentIndex())+" to "+ui->lang2->itemText(index)); -} - -void MainWindow::on_play2_clicked() -{ - bool player1Playing = _player->objectName().split("_").last()=="play1" && - _player->state() == QMediaPlayer::PlayingState; - - if(_player->state() != QMediaPlayer::PlayingState){ - if(_supportedTts.contains(getTransLang(),Qt::CaseInsensitive)==false){ - showError("Selected language '"+getTransLang()+"' is not supported by TTS Engine.\nPlease choose different Language."); - return; - } - _player->setObjectName("player_play2"); - QString text = ui->src2->toPlainText(); - if(playSelected) text = selectedText; - - QStringList src2Parts; - QMediaPlaylist * src2playlist = new QMediaPlaylist(_player); - src2playlist->setPlaybackMode(QMediaPlaylist::Sequential); - connect(src2playlist,&QMediaPlaylist::currentIndexChanged,[=](int pos){ - qDebug()<<"Playist for player2 pos changed"<addMedia(QMediaContent(url)); - } - } - _player->setPlaylist(src2playlist); - _player->play(); - ui->play2->setIcon(QIcon(":/icons/loader-2-fill.png")); - }else{ - _player->blockSignals(true); - _player->stop(); - ui->play1->setIcon(QIcon(":/icons/volume-up-line.png")); - ui->play2->setIcon(QIcon(":/icons/volume-up-line.png")); - _player->blockSignals(false); - } - - if(player1Playing) - { - on_play2_clicked(); - } -} - -void MainWindow::on_play1_clicked() -{ - bool player2Playing = _player->objectName().split("_").last()=="play2"&& - _player->state() == QMediaPlayer::PlayingState; - - if(_player->state() != QMediaPlayer::PlayingState){ - if(_supportedTts.contains(getSourceLang(),Qt::CaseInsensitive)==false){ - showError("Selected language '"+getSourceLang()+"' is not supported by TTS Engine.\nPlease choose different Language."); - return; - } - _player->setObjectName("player_play1"); - QString text = ui->src1->toPlainText(); - if(playSelected) text = selectedText; - - QStringList src1Parts; - QMediaPlaylist * src1playlist = new QMediaPlaylist(_player); - src1playlist->setPlaybackMode(QMediaPlaylist::Sequential); - connect(src1playlist,&QMediaPlaylist::currentIndexChanged,[=](int pos){ - qDebug()<<"Playist for player1 pos changed"<addMedia(QMediaContent(url)); } - } - _player->setPlaylist(src1playlist); - _player->play(); - ui->play1->setIcon(QIcon(":/icons/loader-2-fill.png")); - }else{ - _player->blockSignals(true); - _player->stop(); - ui->play1->setIcon(QIcon(":/icons/volume-up-line.png")); - ui->play2->setIcon(QIcon(":/icons/volume-up-line.png")); - _player->blockSignals(false); - } - - if(player2Playing) - { - on_play1_clicked(); - } -} - - -void MainWindow::on_src1_textChanged() -{ - ui->counter->setText(QString::number(ui->src1->toPlainText().count())+"/5000"); - if(ui->src1->toPlainText().count()>5000){ - int diff = ui->src1->toPlainText().length() - 5000; - QString newStr = ui->src1->toPlainText(); - newStr.chop(diff); - ui->src1->setText(newStr); - QTextCursor cursor(ui->src1->textCursor()); - cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); - ui->src1->setTextCursor(cursor); - } - ui->play1->setEnabled(!ui->src1->toPlainText().isEmpty()); -} - -void MainWindow::on_src2_textChanged() -{ - //enable disable play button if text is not empty - ui->play2->setEnabled(!ui->src2->toPlainText().isEmpty()); -} - -void MainWindow::on_copy_clicked() -{ - const QString text = ui->src2->toPlainText(); - if(!text.isEmpty()){ - clipboard->setText(text); - } -} - -void MainWindow::on_share_clicked() -{ - _share->setTranslation(ui->src2->toPlainText(),translationId); - if(_share->isVisible()==false){ - _share->showNormal(); - } -} - -void MainWindow::on_settings_clicked() -{ - if(settingsWidget->isVisible()==false){ - settingsWidget->adjustSize(); - QScreen* pScreen = QGuiApplication::screenAt(this->mapToGlobal({settingsWidget->width()/2,0})); - QRect availableScreenSize = pScreen->availableGeometry(); - settingsWidget->move(availableScreenSize.center()-settingsWidget->rect().center()); - settingsWidget->showNormal(); - } -} - -void MainWindow::on_history_clicked() -{ - if(historyWidget->isVisible()==false){ - historyWidget->loadHistory(); - QScreen* pScreen = QGuiApplication::screenAt(this->mapToGlobal({historyWidget->width()/2,0})); - QRect availableScreenSize = pScreen->availableGeometry(); - historyWidget->move(availableScreenSize.center()-historyWidget->rect().center()); - historyWidget->showNormal(); - } -} - -void MainWindow::on_lineByline_clicked() -{ - if(translationId.isEmpty()){ - showError("Translate something first."); - return; - } - if(_lineByLine->isVisible()==false){ - if(translationId != _lineByLine->getTId()){ - _lineByLine->clearData(); - if(currentTranslationData.isEmpty()==false){ - _lineByLine->setData(currentTranslationData,getLangName(getSourceLang()) - ,getLangName(getTransLang()),translationId); - }else{ - //load translation from cache; - QFile jsonFile(utils::returnPath("cache")+"/"+translationId+".glate"); - jsonFile.open(QFile::ReadOnly); - currentTranslationData.clear(); - processTranslation(jsonFile.readAll()); - _lineByLine->setData(currentTranslationData,getLangName(getSourceLang()) - ,getLangName(getTransLang()),translationId); - } - } - QScreen* pScreen = QGuiApplication::screenAt(this->mapToGlobal({_lineByLine->width()/2,0})); - QRect availableScreenSize = pScreen->availableGeometry(); - _lineByLine->move(availableScreenSize.center()-_lineByLine->rect().center()); - _lineByLine->showNormal(); - } + if (utils::splitString(text, 1500, src1Parts)) { + foreach (QString src1Url, src1Parts) { + QUrl url("https://www.google.com/speech-api/v1/synthesize"); + QUrlQuery params; + params.addQueryItem("ie", "UTF-8"); + params.addQueryItem("lang", getSourceLang()); + params.addQueryItem("text", QUrl::toPercentEncoding(src1Url.toUtf8())); + url.setQuery(params); + src1playlist->addMedia(QMediaContent(url)); + } + } + _player->setPlaylist(src1playlist); + _player->play(); + ui->play1->setIcon(QIcon(":/icons/loader-2-fill.png")); + } else { + _player->blockSignals(true); + _player->stop(); + ui->play1->setIcon(QIcon(":/icons/volume-up-line.png")); + ui->play2->setIcon(QIcon(":/icons/volume-up-line.png")); + _player->blockSignals(false); + } + + if (player2Playing) { + on_play1_clicked(); + } +} + +void MainWindow::on_src1_textChanged() { + ui->counter->setText(QString::number(ui->src1->toPlainText().count()) + + "/5000"); + if (ui->src1->toPlainText().count() > 5000) { + int diff = ui->src1->toPlainText().length() - 5000; + QString newStr = ui->src1->toPlainText(); + newStr.chop(diff); + ui->src1->setText(newStr); + QTextCursor cursor(ui->src1->textCursor()); + cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); + ui->src1->setTextCursor(cursor); + } + ui->play1->setEnabled(!ui->src1->toPlainText().isEmpty()); +} + +void MainWindow::on_src2_textChanged() { + // enable disable play button if text is not empty + ui->play2->setEnabled(!ui->src2->toPlainText().isEmpty()); +} + +void MainWindow::on_copy_clicked() { + const QString text = ui->src2->toPlainText(); + if (!text.isEmpty()) { + clipboard->setText(text); + } +} + +void MainWindow::on_share_clicked() { + _share->setTranslation(ui->src2->toPlainText(), translationId); + if (_share->isVisible() == false) { + _share->showNormal(); + } +} + +void MainWindow::on_settings_clicked() { + if (settingsWidget->isVisible() == false) { + settingsWidget->adjustSize(); + QScreen *pScreen = QGuiApplication::screenAt( + this->mapToGlobal({settingsWidget->width() / 2, 0})); + QRect availableScreenSize = pScreen->availableGeometry(); + settingsWidget->move(availableScreenSize.center() - + settingsWidget->rect().center()); + settingsWidget->showNormal(); + } +} + +void MainWindow::on_history_clicked() { + if (historyWidget->isVisible() == false) { + historyWidget->loadHistory(); + QScreen *pScreen = QGuiApplication::screenAt( + this->mapToGlobal({historyWidget->width() / 2, 0})); + QRect availableScreenSize = pScreen->availableGeometry(); + historyWidget->move(availableScreenSize.center() - + historyWidget->rect().center()); + historyWidget->showNormal(); + } +} + +void MainWindow::on_lineByline_clicked() { + if (translationId.isEmpty()) { + showError("Translate something first."); + return; + } + if (_lineByLine->isVisible() == false) { + if (translationId != _lineByLine->getTId()) { + _lineByLine->clearData(); + if (currentTranslationData.isEmpty() == false) { + _lineByLine->setData(currentTranslationData, + getLangName(getSourceLang()), + getLangName(getTransLang()), translationId); + } else { + // load translation from cache; + QFile jsonFile(utils::returnPath("cache") + "/" + translationId + + ".glate"); + jsonFile.open(QFile::ReadOnly); + currentTranslationData.clear(); + processTranslation(jsonFile.readAll()); + _lineByLine->setData(currentTranslationData, + getLangName(getSourceLang()), + getLangName(getTransLang()), translationId); + } + } + QScreen *pScreen = QGuiApplication::screenAt( + this->mapToGlobal({_lineByLine->width() / 2, 0})); + QRect availableScreenSize = pScreen->availableGeometry(); + _lineByLine->move(availableScreenSize.center() - + _lineByLine->rect().center()); + _lineByLine->showNormal(); + } } // convert lang code to lang name. -QString MainWindow::getLangName(QString langCode){ - if(langCode == "auto" ){ - return "Auto Detected"; - }else{ - QStringList langNameList = _langName; - langNameList.removeAt(0);//remove auto detect - QString langName = langNameList.at(_langCode.lastIndexOf(langCode)-1); - return langName; - } -} - - -//not tested not being used yet -QString MainWindow::getLangCode(QString langName){ - if(langName.contains("auto",Qt::CaseInsensitive)){ - return "auto"; - }else{ - QStringList langCodeList = _langCode; - QString langCode = langCodeList.at(_langName.lastIndexOf(langName)-1); - return langCode; - } -} - -void MainWindow::on_help_clicked() -{ - if(slider==nullptr){ - slider = new Slider(this); - slider->setWindowTitle(QApplication::applicationName()+" | Introduction"); - slider->setWindowFlag(Qt::Dialog); - slider->setWindowModality(Qt::ApplicationModal); - slider->setMinimumSize(680,420); - } - if(slider->isVisible()==false){ - slider->showNormal(); - slider->start(); - } +QString MainWindow::getLangName(QString langCode) { + if (langCode == "auto") { + return "Auto Detected"; + } else { + QStringList langNameList = _langName; + langNameList.removeAt(0); // remove auto detect + QString langName = langNameList.at(_langCode.lastIndexOf(langCode) - 1); + return langName; + } +} + +// not tested not being used yet +QString MainWindow::getLangCode(QString langName) { + if (langName.contains("auto", Qt::CaseInsensitive)) { + return "auto"; + } else { + QStringList langCodeList = _langCode; + QString langCode = langCodeList.at(_langName.lastIndexOf(langName) - 1); + return langCode; + } +} + +void MainWindow::on_help_clicked() { + if (slider == nullptr) { + slider = new Slider(this); + slider->setWindowTitle(QApplication::applicationName() + " | Introduction"); + slider->setWindowFlag(Qt::Dialog); + slider->setWindowModality(Qt::ApplicationModal); + slider->setMinimumSize(680, 420); + } + if (slider->isVisible() == false) { + slider->showNormal(); + slider->start(); + } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 6bb4e42..738a3c8 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -1,133 +1,127 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include -#include +#include #include +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include "share.h" -#include "waitingspinnerwidget.h" -#include "request.h" +#include "controlbutton.h" #include "error.h" -#include "settings.h" #include "history.h" -#include "ui_textoptionform.h" -#include "controlbutton.h" -#include "utils.h" #include "linebyline.h" +#include "request.h" +#include "settings.h" +#include "share.h" #include "slider.h" - +#include "ui_textoptionform.h" +#include "utils.h" +#include "waitingspinnerwidget.h" namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ - Q_OBJECT +class MainWindow : public QMainWindow { + Q_OBJECT public: - explicit MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow(); protected slots: - void resizeEvent(QResizeEvent *event); - void closeEvent(QCloseEvent *event); - bool eventFilter(QObject *o, QEvent *e); + void resizeEvent(QResizeEvent *event); + void closeEvent(QCloseEvent *event); + bool eventFilter(QObject *o, QEvent *e); private slots: - void setStyle(QString fname); + void setStyle(QString fname); - void readLangCode(); + void readLangCode(); - void resizeFix(); + void resizeFix(); - void translate_clicked(); + void translate_clicked(); - void showError(QString message); + void showError(QString message); - void on_clear_clicked(); + void on_clear_clicked(); - void on_paste_clicked(); + void on_paste_clicked(); - void on_switch_lang_clicked(); + void on_switch_lang_clicked(); - void on_lang1_currentIndexChanged(int index); + void on_lang1_currentIndexChanged(int index); - void on_lang2_currentIndexChanged(int index); + void on_lang2_currentIndexChanged(int index); - QString getTransLang(); + QString getTransLang(); - QString getSourceLang(); + QString getSourceLang(); - void processTranslation(QString reply); + void processTranslation(QString reply); - void on_play2_clicked(); + void on_play2_clicked(); - void on_play1_clicked(); + void on_play1_clicked(); - void on_src1_textChanged(); + void on_src1_textChanged(); - void on_copy_clicked(); + void on_copy_clicked(); - void on_src2_textChanged(); + void on_src2_textChanged(); - void on_share_clicked(); + void on_share_clicked(); - void init_settings(); + void init_settings(); - void on_settings_clicked(); + void on_settings_clicked(); - void init_textOptionWidget(); + void textSelectionChanged(QTextEdit *editor); + void on_history_clicked(); - void textSelectionChanged(QTextEdit *editor); - void on_history_clicked(); + void init_history(); + void on_lineByline_clicked(); - void init_history(); - void on_lineByline_clicked(); + QString getLangName(QString langCode); - QString getLangName(QString langCode); + QString getLangCode(QString langName); - QString getLangCode(QString langName); + void saveByTransId(QString translationId, QString reply); - void saveByTransId(QString translationId, QString reply); - - void on_help_clicked(); + void on_help_clicked(); private: - Ui::MainWindow *ui; - Ui::textOptionForm textOptionForm; - QStringList _langName,_langCode,_supportedTts; - controlButton *_translate = nullptr; - WaitingSpinnerWidget *_loader = nullptr; - QSettings settings; - Request *_request = nullptr; - Share *_share = nullptr; - LineByLine *_lineByLine = nullptr; - - Error * _error = nullptr; - QList currentTranslationData; - QMediaPlayer *_player = nullptr; - QClipboard *clipboard = nullptr; - - Settings *settingsWidget = nullptr; - History *historyWidget = nullptr; - - QHotkey *nativeHotkey = nullptr; - - QWidget *textOptionWidget = nullptr; - QString selectedText; - bool playSelected = false; - QString translationId; - - Slider * slider = nullptr; - - + Ui::MainWindow *ui; + Ui::textOptionForm textOptionForm; + QStringList _langName, _langCode, _supportedTts; + controlButton *_translate = nullptr; + WaitingSpinnerWidget *_loader = nullptr; + QSettings settings; + Request *_request = nullptr; + Share *_share = nullptr; + LineByLine *_lineByLine = nullptr; + + Error *_error = nullptr; + QList currentTranslationData; + QMediaPlayer *_player = nullptr; + QClipboard *clipboard = nullptr; + + Settings *settingsWidget = nullptr; + History *historyWidget = nullptr; + + QHotkey *nativeHotkey = nullptr; + + QWidget *textOptionWidget = nullptr; + QString selectedText; + bool playSelected = false; + QString translationId; + + Slider *slider = nullptr; }; #endif // MAINWINDOW_H diff --git a/src/mainwindow.ui b/src/mainwindow.ui index 67edbb9..0619d0b 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -6,8 +6,8 @@ 0 0 - 768 - 316 + 842 + 494 diff --git a/src/request.cpp b/src/request.cpp index 17feba6..3444ec9 100644 --- a/src/request.cpp +++ b/src/request.cpp @@ -1,63 +1,35 @@ #include "request.h" -Request::Request(QObject *parent) : QObject(parent) -{ - setParent(parent); - _cache_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); +Request::Request(QObject *parent) : QObject(parent) { + _cache_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); } -Request::~Request() -{ - this->deleteLater(); +Request::~Request() {} + +void Request::get(const QUrl &url) { + QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this); + QNetworkDiskCache *diskCache = new QNetworkDiskCache(this); + diskCache->setCacheDirectory(_cache_path); + m_netwManager->setCache(diskCache); + connect(m_netwManager, &QNetworkAccessManager::finished, this, + [=](QNetworkReply *rep) { + if (rep->error() == QNetworkReply::NoError) { + QString repStr = rep->readAll(); + emit requestFinished(repStr); + } else { + emit downloadError(rep->errorString()); + } + rep->deleteLater(); + m_netwManager->deleteLater(); + }); + + QNetworkRequest request(url); + m_netwManager->get(request); + emit requestStarted(); } -void Request::get(const QUrl url){ - QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this); - QNetworkDiskCache* diskCache = new QNetworkDiskCache(this); - diskCache->setCacheDirectory(_cache_path); - m_netwManager->setCache(diskCache); - connect(m_netwManager,&QNetworkAccessManager::finished,[=](QNetworkReply* rep){ - if(rep->error() == QNetworkReply::NoError){ - QString repStr = rep->readAll(); - emit requestFinished(repStr); - }else{ - emit downloadError(rep->errorString()); - } - rep->deleteLater(); - m_netwManager->deleteLater(); - }); - QNetworkRequest request(url); - m_netwManager->get(request); - emit requestStarted(); -} - - - -void Request::download_wallpaper(const QUrl url){ - QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this); - QNetworkDiskCache* diskCache = new QNetworkDiskCache(this); - diskCache->setCacheDirectory(_cache_path); - m_netwManager->setCache(diskCache); - connect(m_netwManager,&QNetworkAccessManager::finished,[=](QNetworkReply* rep){ - if(rep->error() == QNetworkReply::NoError){ - emit downloadFinished(*rep); - }else { - emit downloadError(rep->errorString()); - } - }); - QNetworkRequest request(url); - QString imageFileName = url.toString().split("/").last(); - request.setAttribute(QNetworkRequest::User,imageFileName); - - QNetworkReply *reply = m_netwManager->get(request); - connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(downloadProgress(qint64,qint64))); - emit downloadStarted(); -} - -void Request::downloadProgress(qint64 got,qint64 tot){ - double downloaded_Size = (double)got; - double total_Size = (double)tot; - double progress = (downloaded_Size/total_Size) * 100; - int intProgress = static_cast(progress); - emit _downloadProgress(intProgress); +void Request::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { + double progress = (double)bytesReceived / bytesTotal * 100.0; + int intProgress = static_cast(progress); + emit _downloadProgress(intProgress); } diff --git a/src/request.h b/src/request.h index 5c94265..21f2d0e 100644 --- a/src/request.h +++ b/src/request.h @@ -1,31 +1,30 @@ #ifndef REQUEST_H #define REQUEST_H -#include #include +#include -class Request : public QObject -{ - Q_OBJECT +class Request : public QObject { + Q_OBJECT public: - Request(QObject* parent=0); - virtual ~Request(); + Request(QObject *parent = 0); + virtual ~Request(); public slots: - void get(const QUrl url); - void download_wallpaper(const QUrl url); + void get(const QUrl &url); signals: - void requestFinished(QString rep); - void requestStarted(); - void downloadFinished(QNetworkReply &rep); - void downloadStarted(); - void _downloadProgress(int progress); - void downloadError(QString errorString); + void requestFinished(QString rep); + void requestStarted(); + void downloadFinished(QNetworkReply &rep); + void downloadStarted(); + void _downloadProgress(int progress); + void downloadError(QString errorString); private slots: - void downloadProgress(qint64 got, qint64 tot); + void downloadProgress(qint64 got, qint64 tot); + private: - QString _cache_path; + QString _cache_path; }; #endif // REQUEST_H diff --git a/src/settings.cpp b/src/settings.cpp index bbf27f3..88cdad6 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,117 +1,118 @@ #include "settings.h" #include "ui_settings.h" -#include - -Settings::Settings(QWidget *parent, QHotkey *hotKey) : - QWidget(parent), - ui(new Ui::Settings) -{ - ui->setupUi(this); - this->nativeHotkey = hotKey; - readSettings(); - connect(this->nativeHotkey, &QHotkey::activated, - this, &Settings::get_selected_word_fromX11); - - connect(ui->quickResultCheckBox, &QCheckBox::toggled, - this->nativeHotkey, &QHotkey::setRegistered); - - connect(ui->keySequenceEdit, &QKeySequenceEdit::keySequenceChanged, - this, &Settings::setShortcut); - - ui->dark->setChecked(settings.value("theme","dark").toString()=="dark"); - ui->light->setChecked(settings.value("theme").toString()=="light"); +Settings::Settings(QWidget *parent, QHotkey *hotKey) + : QWidget(parent), ui(new Ui::Settings) { + ui->setupUi(this); + this->nativeHotkey = hotKey; + readSettings(); + connect(this->nativeHotkey, &QHotkey::activated, this, + &Settings::get_selected_word_fromX11); + + connect(ui->quickResultCheckBox, &QCheckBox::toggled, this->nativeHotkey, + &QHotkey::setRegistered); + + connect(ui->keySequenceEdit, &QKeySequenceEdit::keySequenceChanged, this, + &Settings::setShortcut); + + ui->dark->setChecked(settings.value("theme", "dark").toString() == "dark"); + ui->light->setChecked(settings.value("theme").toString() == "light"); + + QString aboutTxt = + R"(

Glate

+

Designed and Developed

+

by Keshav Bhatt + <keshavnrj@gmail.com>

+

Website: https://ktechpit.com

+

Runtime: %1

+

Version: %2

)"; + + ui->aboutTextBrowser->setText( + aboutTxt.arg(qVersion(), qApp->applicationVersion())); } -Settings::~Settings() -{ - delete ui; -} +Settings::~Settings() { delete ui; } -void Settings::setShortcut(const QKeySequence &sequence){ - this->nativeHotkey->setShortcut(sequence,ui->quickResultCheckBox->isChecked()); - //save quick trans shortcut instanty - settings.setValue("quicktrans_shortcut",sequence); +void Settings::setShortcut(const QKeySequence &sequence) { + this->nativeHotkey->setShortcut(sequence, + ui->quickResultCheckBox->isChecked()); + // save quick trans shortcut instanty + settings.setValue("quicktrans_shortcut", sequence); } -void Settings::readSettings(){ - - //quick trans settings - if(settings.value("quicktrans").isValid()){ - ui->quickResultCheckBox->setChecked(settings.value("quicktrans").toBool()); - }else if(settings.value("quicktrans").isValid()){ - ui->quickResultCheckBox->setChecked(true); - }else{ - ui->quickResultCheckBox->setChecked(false); - } - //quick trans key sequence - if(settings.value("quicktrans_shortcut").isValid()){ - QKeySequence k = QKeySequence(settings.value("quicktrans_shortcut").toString()); - ui->keySequenceEdit->setKeySequence(k); - this->nativeHotkey->setShortcut(k.toString(),settings.value("quicktrans").toBool()); - } - else{ - //default value if value not founds - QKeySequence k = QKeySequence::fromString(tr("Ctrl+Shift+Space")); - ui->keySequenceEdit->setKeySequence(k); - this->nativeHotkey->setShortcut(k.toString(),true); - ui->quickResultCheckBox->setChecked(true); - } +void Settings::readSettings() { + + // quick trans settings + if (settings.value("quicktrans").isValid()) { + ui->quickResultCheckBox->setChecked(settings.value("quicktrans").toBool()); + } else if (settings.value("quicktrans").isValid()) { + ui->quickResultCheckBox->setChecked(true); + } else { + ui->quickResultCheckBox->setChecked(false); + } + // quick trans key sequence + if (settings.value("quicktrans_shortcut").isValid()) { + QKeySequence k = + QKeySequence(settings.value("quicktrans_shortcut").toString()); + ui->keySequenceEdit->setKeySequence(k); + this->nativeHotkey->setShortcut(k.toString(), + settings.value("quicktrans").toBool()); + } else { + // default value if value not founds + QKeySequence k = QKeySequence::fromString(tr("Ctrl+Shift+Space")); + ui->keySequenceEdit->setKeySequence(k); + this->nativeHotkey->setShortcut(k.toString(), true); + ui->quickResultCheckBox->setChecked(true); + } } -void Settings::get_selected_word_fromX11(){ - qDebug()<<"Called"; - QProcess *xsel = new QProcess(this); - xsel->setObjectName("xclip"); - xsel->start("xclip",QStringList()<<"-o"<<"-sel"); - connect(xsel,SIGNAL(finished(int)),this,SLOT(set_x11_selection())); +void Settings::get_selected_word_fromX11() { + QProcess *xsel = new QProcess(this); + xsel->setObjectName("xclip"); + xsel->start("xclip", QStringList() << "-o" + << "-sel"); + connect(xsel, SIGNAL(finished(int)), this, SLOT(set_x11_selection())); } -void Settings::set_x11_selection(){ - QObject *xselection = this->findChild("xclip"); - x11_selected = ((QProcess*)(xselection))->readAllStandardOutput(); - if(!x11_selected.trimmed().isEmpty()) +void Settings::set_x11_selection() { + QObject *xselection = this->findChild("xclip"); + if (xselection) { + x11_selected = ((QProcess *)(xselection))->readAllStandardOutput(); + if (!x11_selected.trimmed().isEmpty()) show_requested_text(); - ((QProcess*)(xselection))->deleteLater(); + xselection->deleteLater(); + } } -void Settings::show_requested_text(){ - emit translationRequest(x11_selected); -} +void Settings::show_requested_text() { emit translationRequest(x11_selected); } -bool Settings::quickResultCheckBoxChecked(){ - return ui->quickResultCheckBox->isChecked(); +bool Settings::quickResultCheckBoxChecked() { + return ui->quickResultCheckBox->isChecked(); } -QKeySequence Settings::keySequenceEditKeySequence(){ - return ui->keySequenceEdit->keySequence(); +QKeySequence Settings::keySequenceEditKeySequence() { + return ui->keySequenceEdit->keySequence(); } - -void Settings::on_github_clicked() -{ - QDesktopServices::openUrl(QUrl("https://github.com/keshavbhatt/glate")); +void Settings::on_github_clicked() { + QDesktopServices::openUrl(QUrl("https://github.com/keshavbhatt/glate")); } -void Settings::on_rate_clicked() -{ - QDesktopServices::openUrl(QUrl("snap://glate")); +void Settings::on_rate_clicked() { + QDesktopServices::openUrl(QUrl("snap://glate")); } -void Settings::on_donate_clicked() -{ - QDesktopServices::openUrl(QUrl("https://paypal.me/keshavnrj/5")); +void Settings::on_donate_clicked() { + QDesktopServices::openUrl(QUrl("https://paypal.me/keshavnrj/5")); } -void Settings::on_dark_toggled(bool checked) -{ - settings.setValue("theme",checked ? "dark": "light"); - emit themeToggled(); +void Settings::on_dark_toggled(bool checked) { + settings.setValue("theme", checked ? "dark" : "light"); + emit themeToggled(); } -void Settings::on_light_toggled(bool checked) -{ - settings.setValue("theme",checked ? "light": "dark"); - emit themeToggled(); +void Settings::on_light_toggled(bool checked) { + settings.setValue("theme", checked ? "light" : "dark"); + emit themeToggled(); } diff --git a/src/settings.h b/src/settings.h index 3a5ac3a..5a5be29 100644 --- a/src/settings.h +++ b/src/settings.h @@ -1,51 +1,50 @@ #ifndef SETTINGS_H #define SETTINGS_H -#include -#include +#include #include #include - +#include +#include namespace Ui { class Settings; } -class Settings : public QWidget -{ - Q_OBJECT +class Settings : public QWidget { + Q_OBJECT public: - explicit Settings(QWidget *parent = nullptr, QHotkey *hotKey = nullptr); - ~Settings(); + explicit Settings(QWidget *parent = nullptr, QHotkey *hotKey = nullptr); + ~Settings(); signals: - void translationRequest(QString selected); - void themeToggled(); + void translationRequest(QString selected); + void themeToggled(); public slots: - QKeySequence keySequenceEditKeySequence(); - bool quickResultCheckBoxChecked(); + QKeySequence keySequenceEditKeySequence(); + bool quickResultCheckBoxChecked(); private slots: - void get_selected_word_fromX11(); - void set_x11_selection(); - void show_requested_text(); - void setShortcut(const QKeySequence &sequence); + void get_selected_word_fromX11(); + void set_x11_selection(); + void show_requested_text(); + void setShortcut(const QKeySequence &sequence); - void readSettings(); - void on_github_clicked(); + void readSettings(); + void on_github_clicked(); - void on_rate_clicked(); + void on_rate_clicked(); - void on_donate_clicked(); + void on_donate_clicked(); - void on_dark_toggled(bool checked); + void on_dark_toggled(bool checked); - void on_light_toggled(bool checked); + void on_light_toggled(bool checked); private: - Ui::Settings *ui; - QSettings settings; - QHotkey *nativeHotkey = nullptr; - QString x11_selected; + Ui::Settings *ui; + QSettings settings; + QHotkey *nativeHotkey = nullptr; + QString x11_selected; }; #endif // SETTINGS_H diff --git a/src/settings.ui b/src/settings.ui index b557424..bf9030a 100644 --- a/src/settings.ui +++ b/src/settings.ui @@ -6,8 +6,8 @@ 0 0 - 357 - 430 + 523 + 457
@@ -92,18 +92,13 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +<html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;"> -<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/icons/app/icon-64.png" /></p> -<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Designed and Developed</p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">by <span style=" font-weight:600;">Keshav Bhatt</span> &lt;keshavnrj@gmail.com&gt;</p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Website: https://ktechpit.com</p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Runtime: Qt 5.13.0</p> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Version: 2.0</p> -<p align="center" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> +hr { height: 1px; border-width: 0; } +li.unchecked::marker { content: "\2610"; } +li.checked::marker { content: "\2612"; } +</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> @@ -115,7 +110,7 @@ p, li { white-space: pre-wrap; } - Buy me a coffee + Donate via Paypal Donate @@ -155,7 +150,7 @@ p, li { white-space: pre-wrap; } - Give Ratings in Software App + Rate this app in Software App Rate diff --git a/src/share.cpp b/src/share.cpp index ea87ff2..8e5474a 100644 --- a/src/share.cpp +++ b/src/share.cpp @@ -1,294 +1,311 @@ #include "share.h" #include "ui_share.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "utils.h" -Share::Share(QWidget *parent) : - QWidget(parent), - ui(new Ui::Share) -{ - ui->setupUi(this); - ffmpeg=new QProcess(this); - pastebin_it=new QProcess(this); - pastebin_it_facebook=new QProcess(this); - connect(this->pastebin_it,SIGNAL(finished(int)),this,SLOT(pastebin_it_finished(int))); - connect(this->pastebin_it_facebook,SIGNAL(finished(int)),this,SLOT(pastebin_it_facebook_finished(int))); - connect(this->ffmpeg,SIGNAL(finished(int)),this,SLOT(ffmpeg_finished(int))); +Share::Share(QWidget *parent) : QWidget(parent), ui(new Ui::Share) { + ui->setupUi(this); + ffmpeg = new QProcess(this); + pastebin_it = new QProcess(this); + pastebin_it_facebook = new QProcess(this); + connect(this->pastebin_it, SIGNAL(finished(int)), this, + SLOT(pastebin_it_finished(int))); + connect(this->pastebin_it_facebook, SIGNAL(finished(int)), this, + SLOT(pastebin_it_facebook_finished(int))); + connect(this->ffmpeg, SIGNAL(finished(int)), this, + SLOT(ffmpeg_finished(int))); } -void Share::setTranslation(QString translation,QString uuid){ - ui->translation->setPlainText(translation); - translationUUID = uuid; +void Share::setTranslation(QString translation, QString uuid) { + ui->translation->setPlainText(translation); + translationUUID = uuid; } -Share::~Share() -{ - delete ui; -} +Share::~Share() { delete ui; } -void Share::on_twitter_clicked() -{ - showStatus("Share: opening web-browser..."); - bool opened = QDesktopServices::openUrl(QUrl(QUrl("https://twitter.com/intent/tweet?text="+ui->translation->toPlainText())).toString(QUrl::FullyEncoded)); - if(!opened){ - showStatus("Share: unable to open a web-browser..."); - } +void Share::on_twitter_clicked() { + showStatus("Share: opening web-browser..."); + bool opened = QDesktopServices::openUrl( + QUrl(QUrl("https://twitter.com/intent/tweet?text=" + + ui->translation->toPlainText())) + .toString(QUrl::FullyEncoded)); + if (!opened) { + showStatus("Share: unable to open a " + "web-browser..."); + } } -void Share::on_facebook_clicked() -{ - QString encoded = QUrl(ui->translation->toPlainText()).toString(QUrl::FullyEncoded); - QString o = "wget -O - --post-data=\"""sprunge="+encoded+"\" http://sprunge.us"; - pastebin_it_facebook->start("bash", QStringList()<<"-c"<< o); - ui->facebook->setDisabled(true); - if(pastebin_it_facebook->waitForStarted(1000)){ - showStatus("Share: Prepearing facebook share please wait..."); - }else{ - showStatus("Share: Failure.
"); - } +void Share::on_facebook_clicked() { + QString encoded = + QUrl(ui->translation->toPlainText()).toString(QUrl::FullyEncoded); + QString o = "wget -O - --post-data=\"" + "sprunge=" + + encoded + "\" http://sprunge.us"; + pastebin_it_facebook->start("bash", QStringList() << "-c" << o); + ui->facebook->setDisabled(true); + if (pastebin_it_facebook->waitForStarted(1000)) { + showStatus("Share: Prepearing facebook " + "share please wait..."); + } else { + showStatus("Share: Failure.
"); + } } -QString Share::getFileNameFromString(QString string){ - QString filename ; - if(string.trimmed().length()>10){ - filename = string.trimmed().left(10).trimmed(); - }else{ - filename = utils::generateRandomId(10); - } +QString Share::getFileNameFromString(QString string) { + QString filename; + if (string.trimmed().length() > 10) { + filename = string.trimmed().left(10).trimmed(); + } else { + filename = utils::generateRandomId(10); + } - return filename.remove("/").remove("."); + return filename.remove("/").remove("."); } -void Share::on_text_clicked() -{ - QString translation = ui->translation->toPlainText(); - QString path = settings.value("sharePath",QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).toString(); - QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path+"/"+getFileNameFromString(translation)+".txt", tr("Text Files (*.txt)")); - if (!fileName.isEmpty()) - { - QFile file(QFileInfo(fileName).absoluteFilePath()); - if (!file.open(QIODevice::WriteOnly)) - { - showStatus("Share: error failed to save file."); - return; //aborted - } - //save data - QString text = translation; - QTextStream out(&file); - out << text; - //save last used location - settings.setValue("sharePath",QFileInfo(file).path()); - file.close(); - //inform user - showStatus("Share: file saved successfully."); - }else { - showStatus("Share: file save operation cancelled."); +void Share::on_text_clicked() { + QString translation = ui->translation->toPlainText(); + QString path = settings + .value("sharePath", QStandardPaths::writableLocation( + QStandardPaths::DocumentsLocation)) + .toString(); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Save Text File"), + path + "/" + getFileNameFromString(translation) + ".txt", + tr("Text Files (*.txt)")); + if (!fileName.isEmpty()) { + QFile file(QFileInfo(fileName).absoluteFilePath()); + if (!file.open(QIODevice::WriteOnly)) { + showStatus( + "Share: error failed to save file."); + return; // aborted } + // save data + QString text = translation; + QTextStream out(&file); + out << text; + // save last used location + settings.setValue("sharePath", QFileInfo(file).path()); + file.close(); + // inform user + showStatus( + "Share: file saved successfully."); + } else { + showStatus( + "Share: file save operation cancelled."); + } } -void Share::on_email_clicked() -{ - showStatus("Share: opening mail client..."); - bool opened = QDesktopServices::openUrl(QUrl("mailto:?body="+ui->translation->toPlainText())); - if(!opened){ - showStatus("Share: unable to open a mail client..."); - } +void Share::on_email_clicked() { + showStatus("Share: opening mail client..."); + bool opened = QDesktopServices::openUrl( + QUrl("mailto:?body=" + ui->translation->toPlainText())); + if (!opened) { + showStatus("Share: unable to open a mail " + "client..."); + } } -void Share::on_pastebin_clicked() -{ - QString encoded = QUrl(ui->translation->toPlainText()).toString(QUrl::FullyEncoded); - QString o = "wget -O - --post-data=\"""sprunge="+ui->translation->toPlainText().toHtmlEscaped()+"\" http://sprunge.us"; - pastebin_it->start("bash", QStringList()<<"-c"<< o); - showStatus("Share: Prepearing facebook share please wait..."); - ui->pastebin->setDisabled(true); - if(pastebin_it->waitForStarted(1000)){ - showStatus("Share: Uploading paste please wait...
"); - }else{ - showStatus("Share: Failure.
"); - } +void Share::on_pastebin_clicked() { + // QString encoded = + // QUrl(ui->translation->toPlainText()).toString(QUrl::FullyEncoded); + QString o = "wget -O - --post-data=\"" + "sprunge=" + + ui->translation->toPlainText().toHtmlEscaped() + + "\" http://sprunge.us"; + pastebin_it->start("bash", QStringList() << "-c" << o); + showStatus("Share: Prepearing facebook share " + "please wait..."); + ui->pastebin->setDisabled(true); + if (pastebin_it->waitForStarted(1000)) { + showStatus("Share: Uploading paste please " + "wait...
"); + } else { + showStatus("Share: Failure.
"); + } } -//not being used as we are not saving file now to share. -bool Share::saveFile(QString filename) -{ - QString path = QStandardPaths::writableLocation(QStandardPaths::TempLocation); - QFile file(path+"/"+filename); - if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("Application"), - tr("Cannot write file %1:\n%2.") +// not being used as we are not saving file now to share. +bool Share::saveFile(QString filename) { + QString path = QStandardPaths::writableLocation(QStandardPaths::TempLocation); + QFile file(path + "/" + filename); + if (!file.open(QFile::WriteOnly | QFile::Text)) { + QMessageBox::warning(this, tr("Application"), + tr("Cannot write file %1:\n%2.") .arg(QDir::toNativeSeparators(file.fileName()), file.errorString())); - return false; - } - QTextStream out(&file); + return false; + } + QTextStream out(&file); #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); #endif - out << ui->translation->toPlainText(); + out << ui->translation->toPlainText(); #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); #endif - file.close(); - return true; + file.close(); + return true; } -void Share::pastebin_it_finished(int k) -{ - if(k==0){ - QString url = pastebin_it->readAll().trimmed().simplified(); - showStatus("Share: Pastebin link - "+url+""); - ui->pastebin->setDisabled(false); - } - else{ - showStatus(""+pastebin_it->readAllStandardError()+"
"); - ui->pastebin->setDisabled(false); - } +void Share::pastebin_it_finished(int k) { + if (k == 0) { + QString url = pastebin_it->readAll().trimmed().simplified(); + showStatus("Share: Pastebin link - " + url + ""); + ui->pastebin->setDisabled(false); + } else { + showStatus("" + + pastebin_it->readAllStandardError() + "
"); + ui->pastebin->setDisabled(false); + } } -void Share::pastebin_it_facebook_finished(int k) -{ - if(k==0){ - QString url = pastebin_it_facebook->readAll(); - showStatus("Share: opening web-browser with url - https://www.facebook.com/sharer/sharer.php?u="+url); - ui->facebook->setDisabled(false); - bool opened = QDesktopServices::openUrl(QUrl("https://www.facebook.com/sharer/sharer.php?u="+url)); - if(!opened){ - showStatus("Share: unable to open a web-browser..."); - } - } - else { - showStatus(""+pastebin_it_facebook->readAllStandardError()+"
"); - ui->facebook->setDisabled(false); +void Share::pastebin_it_facebook_finished(int k) { + if (k == 0) { + QString url = pastebin_it_facebook->readAll(); + showStatus("Share: opening web-browser " + "with url - https://www.facebook.com/sharer/sharer.php?u=" + + url); + ui->facebook->setDisabled(false); + bool opened = QDesktopServices::openUrl( + QUrl("https://www.facebook.com/sharer/sharer.php?u=" + url)); + if (!opened) { + showStatus("Share: unable to open a " + "web-browser..."); } + } else { + showStatus("" + + pastebin_it_facebook->readAllStandardError() + "
"); + ui->facebook->setDisabled(false); + } } -void Share::showStatus(QString message) -{ - QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); - ui->status->setGraphicsEffect(eff); - QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity"); - a->setDuration(500); - a->setStartValue(0); - a->setEndValue(1); - a->setEasingCurve(QEasingCurve::InCurve); - a->start(QPropertyAnimation::DeleteWhenStopped); - ui->status->setText(message); - ui->status->show(); +void Share::showStatus(QString message) { + QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); + ui->status->setGraphicsEffect(eff); + QPropertyAnimation *a = new QPropertyAnimation(eff, "opacity"); + a->setDuration(500); + a->setStartValue(0); + a->setEndValue(1); + a->setEasingCurve(QEasingCurve::InCurve); + a->start(QPropertyAnimation::DeleteWhenStopped); + ui->status->setText(message); + ui->status->show(); } +void Share::on_download_clicked() { -void Share::on_download_clicked() -{ - - //create a dir with uuid to track process, - //start donwload manager with tasks, - //wait for tasks to finish, - //concat downloaded results, - //ask user to save file, - //destroy uuid and file on close. + // create a dir with uuid to track process, + // start donwload manager with tasks, + // wait for tasks to finish, + // concat downloaded results, + // ask user to save file, + // destroy uuid and file on close. - QString text = ui->translation->toPlainText(); - QStringList src1Parts; - QList urls; - if(utils::splitString(text,1400,src1Parts)){ - qDebug()<translation->toPlainText(); + QStringList src1Parts; + QList urls; + if (utils::splitString(text, 1400, src1Parts)) { + qDebug() << src1Parts; + for (int i = 0; i < src1Parts.count(); i++) { + QUrl url("https://www.google.com/speech-api/v1/synthesize"); + QUrlQuery params; + params.addQueryItem("ie", "UTF-8"); + params.addQueryItem("lang", "hi"); + params.addQueryItem("text", + QUrl::toPercentEncoding(src1Parts.at(i).toUtf8())); + url.setQuery(params); + urls.append(url); } + } - if(td!=nullptr){ - td->disconnect(); - td->deleteLater(); - td = nullptr; - }else{ - td = new TranslationDownloader(this,urls,translationUUID); - ui->download->setEnabled(false); - connect(td,&TranslationDownloader::downloadComplete,[=](){ - qDebug()<<"DOWNLOAD FINISHED"; - showStatus("Voice download finished..."); - showStatus("Prepearing output file..."); - concat(td->currentDownloadDir); - td->deleteLater(); - td = nullptr; - }); - connect(td,&TranslationDownloader::downloadStarted,[=](QString status){ - showStatus(status); - }); - connect(td,&TranslationDownloader::downloadError,[=](QString status){ - showStatus(status); - ui->download->setEnabled(true); - }); - connect(td,&TranslationDownloader::downloadFinished,[=](QString status){ - showStatus(status); - }); - td->start(); - } + if (td != nullptr) { + td->disconnect(); + td->deleteLater(); + td = nullptr; + } else { + td = new TranslationDownloader(this, urls, translationUUID); + ui->download->setEnabled(false); + connect(td, &TranslationDownloader::downloadComplete, this, [=]() { + qDebug() << "DOWNLOAD FINISHED"; + showStatus("Voice download finished..."); + showStatus("Prepearing output file..."); + concat(td->currentDownloadDir); + td->deleteLater(); + td = nullptr; + }); + connect(td, &TranslationDownloader::downloadStarted, this, + [=](QString status) { showStatus(status); }); + connect(td, &TranslationDownloader::downloadError, this, + [=](QString status) { + showStatus(status); + ui->download->setEnabled(true); + }); + connect(td, &TranslationDownloader::downloadFinished, this, + [=](QString status) { showStatus(status); }); + td->start(); + } } -void Share::concat(QString currentDownloadDir){ - //get path - QString translation = ui->translation->toPlainText(); - QString path = settings.value("sharePathAudio",QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).toString(); - QString fileName = QFileDialog::getSaveFileName(this, tr("Save Audio File"), path+"/"+getFileNameFromString(translation)+".mp3", tr("Audio Files (*.mp3)")); - if (!fileName.isEmpty()) - { - - QStringList args; - QString complex; - args<<"-v"<<"quiet"<<"-stats"; - QDir transDir(currentDownloadDir); - cacheDirToDelete = currentDownloadDir; //save audio cahce dir for deletion after concat - transDir.setFilter(QDir::Files); - transDir.setSorting(QDir::Name); - QFileInfoList infoList = transDir.entryInfoList(); - for (int i= 0;istart("ffmpeg", args); +void Share::concat(QString currentDownloadDir) { + // get path + QString translation = ui->translation->toPlainText(); + QString path = + settings + .value("sharePathAudio", QStandardPaths::writableLocation( + QStandardPaths::DocumentsLocation)) + .toString(); + QString fileName = QFileDialog::getSaveFileName( + this, tr("Save Audio File"), + path + "/" + getFileNameFromString(translation) + ".mp3", + tr("Audio Files (*.mp3)")); + if (!fileName.isEmpty()) { - ui->download->setEnabled(!ffmpeg->waitForStarted()); - //save last used location - showStatus("Share: concating parts..."); - settings.setValue("sharePathAudio",QFileInfo(fileName).path()); - }else { - showStatus("Share: file save operation cancelled."); - ui->download->setEnabled(true); + QStringList args; + QString complex; + args << "-v" + << "quiet" + << "-stats"; + QDir transDir(currentDownloadDir); + cacheDirToDelete = + currentDownloadDir; // save audio cahce dir for deletion after concat + transDir.setFilter(QDir::Files); + transDir.setSorting(QDir::Name); + QFileInfoList infoList = transDir.entryInfoList(); + for (int i = 0; i < infoList.count(); i++) { + args << "-i" << infoList.at(i).filePath(); + complex += "[" + QString::number(i) + ":0]"; } + complex += + "concat=n=" + QString::number(infoList.count()) + ":v=0:a=1[out]"; + args << "-filter_complex" << complex << "-map" + << "[out]" << fileName << "-y"; + // ffmpeg -v quiet -stats inputs -filter_complex + // '[0:0][1:0]concat=n=2:v=0:a=1[out]' -map '[out]' /tmp/output.mp3 + ffmpeg->start("ffmpeg", args); + + ui->download->setEnabled(!ffmpeg->waitForStarted()); + // save last used location + showStatus("Share: concating parts..."); + settings.setValue("sharePathAudio", QFileInfo(fileName).path()); + } else { + showStatus( + "Share: file save operation cancelled."); + ui->download->setEnabled(true); + } } -void Share::ffmpeg_finished(int k) -{ - if(k==0){ - QString output = ffmpeg->readAll(); - showStatus("Share: export finished.\n"+output); - QDir d(cacheDirToDelete); - d.removeRecursively(); - } - else { - showStatus(""+ffmpeg->readAllStandardError()+"
"); - } - ui->download->setDisabled(false); +void Share::ffmpeg_finished(int k) { + if (k == 0) { + QString output = ffmpeg->readAll(); + showStatus("Share: export finished.\n" + + output); + QDir d(cacheDirToDelete); + d.removeRecursively(); + } else { + showStatus("" + ffmpeg->readAllStandardError() + + "
"); + } + ui->download->setDisabled(false); } diff --git a/src/share.h b/src/share.h index a208056..fd52eb0 100644 --- a/src/share.h +++ b/src/share.h @@ -1,53 +1,64 @@ #ifndef SHARE_H #define SHARE_H -#include -#include -#include #include "translationdownloader.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + namespace Ui { class Share; } -class Share : public QWidget -{ - Q_OBJECT +class Share : public QWidget { + Q_OBJECT public: - explicit Share(QWidget *parent = nullptr); - ~Share(); + explicit Share(QWidget *parent = nullptr); + ~Share(); public slots: - void setTranslation(QString translation, QString uuid); + void setTranslation(QString translation, QString uuid); private slots: - void on_twitter_clicked(); + void on_twitter_clicked(); - void on_facebook_clicked(); - void on_text_clicked(); - void on_email_clicked(); + void on_facebook_clicked(); + void on_text_clicked(); + void on_email_clicked(); - QString getFileNameFromString(QString string); + QString getFileNameFromString(QString string); - void showStatus(QString message); - void pastebin_it_finished(int k); - void on_pastebin_clicked(); - bool saveFile(QString filename); - void pastebin_it_facebook_finished(int k); - void on_download_clicked(); + void showStatus(QString message); + void pastebin_it_finished(int k); + void on_pastebin_clicked(); + bool saveFile(QString filename); + void pastebin_it_facebook_finished(int k); + void on_download_clicked(); - void ffmpeg_finished(int k); - void concat(QString currentDownloadDir); + void ffmpeg_finished(int k); + void concat(QString currentDownloadDir); private: - Ui::Share *ui; - QSettings settings; - QProcess * ffmpeg = nullptr; - QProcess * pastebin_it = nullptr; - QProcess * pastebin_it_facebook = nullptr; - QString translationUUID; - TranslationDownloader * td = nullptr; - QString cacheDirToDelete; + Ui::Share *ui; + QSettings settings; + QProcess *ffmpeg = nullptr; + QProcess *pastebin_it = nullptr; + QProcess *pastebin_it_facebook = nullptr; + QString translationUUID; + TranslationDownloader *td = nullptr; + QString cacheDirToDelete; }; #endif // SHARE_H diff --git a/src/slider.cpp b/src/slider.cpp index e49a82b..0036434 100644 --- a/src/slider.cpp +++ b/src/slider.cpp @@ -2,200 +2,182 @@ #include "ui_slider.h" #include -Slider::Slider(QWidget *parent) : - QWidget(parent), - ui(new Ui::Slider) -{ - ui->setupUi(this); - /* Set Global variables here - * total = total numbers of slides in resource. - * currentIndex = index where the slider will start, this updates with time set in timeout - * progeressbar = show slide timer based progressbar on top. - * duration = duration of slide while auto playback - */ - total = 8; - currentIndex = 0; - duration = 10000; - progressbar = false; - - ui->progressBar->setMinimum(0); - ui->progressBar->setMaximum(100); - - if(progressbar== false){ - ui->progressBar->hide(); - } - - connect(ui->next,SIGNAL(clicked()),this,SLOT(next())); - connect(ui->prev,SIGNAL(clicked()),this,SLOT(prev())); - connect(ui->skip,SIGNAL(clicked(bool)),this,SLOT(close())); - - timer = new QTimer (this); - timer->setInterval(duration); - connect(timer,SIGNAL(timeout()),this,SLOT(next())); - - loadSlides(); +Slider::Slider(QWidget *parent) : QWidget(parent), ui(new Ui::Slider) { + ui->setupUi(this); + /* Set Global variables here + * total = total numbers of slides in resource. + * currentIndex = index where the slider will start, this updates with time + * set in timeout progeressbar = show slide timer based progressbar on top. + * duration = duration of slide while auto playback + */ + total = 8; + currentIndex = 0; + duration = 10000; + progressbar = false; + + ui->progressBar->setMinimum(0); + ui->progressBar->setMaximum(100); + + if (progressbar == false) { + ui->progressBar->hide(); + } + + connect(ui->next, &QAbstractButton::clicked, this, &Slider::next); + connect(ui->prev, &QAbstractButton::clicked, this, &Slider::prev); + connect(ui->skip, &QAbstractButton::clicked, this, &QWidget::close); + + timer = new QTimer(this); + timer->setInterval(duration); + connect(timer, &QTimer::timeout, this, &Slider::next); + + loadSlides(); } +Slider::~Slider() { delete ui; } +void Slider::closeEvent(QCloseEvent *event) { + reset(); + QWidget::closeEvent(event); +} -Slider::~Slider() -{ - delete ui; +void Slider::start() { + changeSlide(0); + timer->start(); } -void Slider::closeEvent(QCloseEvent *event) -{ - reset(); - QWidget::closeEvent(event); +void Slider::loadSlides() { + for (int i = 0; i < total; i++) { + QFile file(":/slides/" + QString::number(i) + ".html"); + file.open(QIODevice::ReadOnly); + createSlide(file.readAll(), i); + file.close(); + } } -void Slider::start() -{ - changeSlide(0); - timer->start(); +void Slider::progressBarUpdate() { + if (progressbar) { + animation = new QPropertyAnimation(ui->progressBar, "value"); + animation->setDuration(duration); + animation->setStartValue(ui->progressBar->minimum()); + animation->setEndValue(ui->progressBar->maximum()); + animation->start(QPropertyAnimation::DeleteWhenStopped); + } } -void Slider::loadSlides() -{ - for (int i = 0; i < total; i++) - { - QFile file(":/slides/"+QString::number(i)+".html"); - file.open(QIODevice::ReadOnly); - createSlide(file.readAll(),i); - file.close(); - } +void Slider::stop() { + timer->stop(); + updateStopButton(); + progressBarUpdate(); + if (animation != nullptr) { + animation->stop(); + } } -void Slider::progressBarUpdate() -{ - if(progressbar){ - animation = new QPropertyAnimation(ui->progressBar, "value"); - animation->setDuration(duration); - animation->setStartValue(ui->progressBar->minimum()); - animation->setEndValue(ui->progressBar->maximum()); - animation->start(QPropertyAnimation::DeleteWhenStopped); - } +void Slider::reset() { + currentIndex = 0; + changeSlide(currentIndex); + stop(); } -void Slider::stop() -{ - timer->stop(); - updateStopButton(); - progressBarUpdate(); - if(animation!=nullptr){ - animation->stop(); - } +void Slider::updateStopButton() { + if (timer->isActive()) { + ui->stop->setToolTip("Stop"); + ui->stop->setIcon(QIcon(":/icons/stop-line.png")); + } + if (timer->isActive() == false) { + ui->stop->setToolTip("Play"); + ui->stop->setIcon(QIcon(":/icons/play-line.png")); + } } -void Slider::reset() -{ - currentIndex = 0; - changeSlide(currentIndex); +void Slider::next() { + timer->stop(); + if (currentIndex >= total - 1) { stop(); + } else { + changeSlide(++currentIndex); + timer->start(); + } + updateStopButton(); } -void Slider::updateStopButton() -{ - if(timer->isActive()){ - ui->stop->setToolTip("Stop"); - ui->stop->setIcon(QIcon(":/icons/stop-line.png")); - } - if(timer->isActive()==false){ - ui->stop->setToolTip("Play"); - ui->stop->setIcon(QIcon(":/icons/play-line.png")); - } +void Slider::prev() { + timer->stop(); + if (currentIndex == 0) { + currentIndex = total - 1; + changeSlide(currentIndex); + } else { + changeSlide(--currentIndex); + timer->start(); + } + updateStopButton(); } -void Slider::next() -{ - timer->stop(); - if(currentIndex>=total-1){ - stop(); - }else{ - changeSlide(++currentIndex); - timer->start(); - } - updateStopButton(); -} +void Slider::changeSlide(int index) { -void Slider::prev() -{ - timer->stop(); - if(currentIndex==0){ - currentIndex = total-1; - changeSlide(currentIndex); - }else{ - changeSlide(--currentIndex); - timer->start(); + // hide all in view + for (int i = 0; i < ui->view->count(); ++i) { + QWidget *widget = ui->view->itemAt(i)->widget(); + if (widget != NULL) { + widget->setVisible(false); } - updateStopButton(); + } + // show requested slide + Slide *slide = this->findChild("slide_" + QString::number(index)); + ui->view->addWidget(slide); + slide->show(); + uncheckAllNavBtn(); + QPushButton *navBtn = + this->findChild("navBtn_" + QString::number(index)); + navBtn->setChecked(true); + progressBarUpdate(); } -void Slider::changeSlide(int index) -{ - - //hide all in view - for (int i = 0; i < ui->view->count(); ++i){ - QWidget *widget = ui->view->itemAt(i)->widget(); - if (widget != NULL){ - widget->setVisible(false); - } +void Slider::createSlide(QString html, int index) { + Slide *slide = new Slide(this); + slide->setObjectName("slide_" + QString::number(index)); + slide->hide(); + slide->setText(html); + connect(slide, &Slide::linkActivated, this, [=](QString link) { + if (link == "start") { + this->close(); + } else { + QDesktopServices::openUrl(QUrl(link)); } - //show requested slide - Slide *slide = this->findChild("slide_"+QString::number(index)); - ui->view->addWidget(slide); - slide->show(); + }); + // make button without name + QPushButton *navBtn = new QPushButton("", this); + navBtn->setCheckable(true); + navBtn->setFixedSize(12, 12); + // uncomment to make buttons circular + navBtn->setStyleSheet("border-radius:" + + QString::number(navBtn->width() / 2)); + navBtn->setObjectName("navBtn_" + QString::number(index)); + connect(navBtn, &QPushButton::clicked, this, [=]() { uncheckAllNavBtn(); - QPushButton *navBtn = this->findChild("navBtn_"+QString::number(index)); navBtn->setChecked(true); - progressBarUpdate(); -} - -void Slider::createSlide(QString html,int index){ - Slide *slide = new Slide(this); - slide->setObjectName("slide_"+QString::number(index)); - slide->hide(); - slide->setText(html); - connect(slide,&Slide::linkActivated,[=](QString link){ - if(link=="start"){ - this->close(); - }else{ - QDesktopServices::openUrl(QUrl(link)); - } - }); - //make button without name - QPushButton *navBtn = new QPushButton("",this); - navBtn->setCheckable(true); - navBtn->setFixedSize(12,12); - //uncomment to make buttons circular - navBtn->setStyleSheet("border-radius:"+QString::number(navBtn->width()/2)); - navBtn->setObjectName("navBtn_"+QString::number(index)); - connect(navBtn,&QPushButton::clicked,[=](){ - uncheckAllNavBtn(); - navBtn->setChecked(true); - changeSlide(index); - currentIndex = index; - stop();// stop auto slider if user clicks button to navigate - }); - ui->navDots->addWidget(navBtn); + changeSlide(index); + currentIndex = index; + stop(); // stop auto slider if user clicks button to navigate + }); + ui->navDots->addWidget(navBtn); } -void Slider::uncheckAllNavBtn(){ - foreach (QPushButton*btn, this->findChildren()) { - btn->setChecked(false); - } +void Slider::uncheckAllNavBtn() { + foreach (QPushButton *btn, this->findChildren()) { + btn->setChecked(false); + } } -void Slider::on_stop_clicked() -{ - if(timer->isActive()){ - if(animation !=nullptr){ - animation->stop(); - } - timer->stop(); - }else if(timer->isActive()==false){ - progressBarUpdate(); - timer->start(); +void Slider::on_stop_clicked() { + if (timer->isActive()) { + if (animation != nullptr) { + animation->stop(); } - updateStopButton(); + timer->stop(); + } else if (timer->isActive() == false) { + progressBarUpdate(); + timer->start(); + } + updateStopButton(); } diff --git a/src/slider.h b/src/slider.h index 0a081e1..ef2289d 100644 --- a/src/slider.h +++ b/src/slider.h @@ -1,63 +1,60 @@ #ifndef SLIDER_H #define SLIDER_H -#include #include -#include +#include +#include #include #include -#include #include -#include +#include +#include namespace Ui { class Slider; } -class Slider : public QWidget -{ - Q_OBJECT +class Slider : public QWidget { + Q_OBJECT public: - explicit Slider(QWidget *parent = nullptr); - ~Slider(); + explicit Slider(QWidget *parent = nullptr); + ~Slider(); public slots: - void start(); - void stop(); - void reset(); + void start(); + void stop(); + void reset(); protected slots: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private slots: - void createSlide(QString html, int index); - void loadSlides(); - void next(); - void prev(); - void changeSlide(int index); - void uncheckAllNavBtn(); - void on_stop_clicked(); - void progressBarUpdate(); - void updateStopButton(); + void createSlide(QString html, int index); + void loadSlides(); + void next(); + void prev(); + void changeSlide(int index); + void uncheckAllNavBtn(); + void on_stop_clicked(); + void progressBarUpdate(); + void updateStopButton(); private: - Ui::Slider *ui; - QTimer *timer = nullptr; - QStringList slideData; - int currentIndex; - int total; - int duration; - QPropertyAnimation *animation = nullptr; - bool progressbar; + Ui::Slider *ui; + QTimer *timer = nullptr; + QStringList slideData; + int currentIndex; + int total; + int duration; + QPropertyAnimation *animation = nullptr; + bool progressbar; }; -class Slide : public QLabel -{ - Q_OBJECT +class Slide : public QLabel { + Q_OBJECT public: - Slide(QWidget *parent = nullptr) : QLabel(parent) - { - this->setTextInteractionFlags(Qt::LinksAccessibleByMouse); - this->setAlignment(Qt::AlignCenter); - } + Slide(QWidget *parent = nullptr) : QLabel(parent) { + this->setTextInteractionFlags(Qt::LinksAccessibleByMouse); + this->setAlignment(Qt::AlignCenter); + } }; #endif // SLIDER_H diff --git a/src/slider.ui b/src/slider.ui index 69e5c5e..9019ea5 100644 --- a/src/slider.ui +++ b/src/slider.ui @@ -158,8 +158,8 @@ p, li { white-space: pre-wrap; } <p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14pt; font-weight:600;">Welcome to Glate</span></p> <p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14pt;">Designed and Developed by</span></p> <p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14pt; font-weight:600;">Keshav Bhatt</span></p> -<p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="mailto:keshavnrj@gmail.com"><span style=" font-size:14pt; text-decoration: underline; color:#0000ff;">keshavnrj@gmail.com</span></a></p> -<p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://paypal.me/keshavnrj/5"><span style=" font-size:14pt; text-decoration: underline; color:#0000ff;">Donate</span></a></p> +<p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="mailto:keshavnrj@gmail.com"><span style=" font-size:14pt; text-decoration: underline;">keshavnrj@gmail.com</span></a></p> +<p align="center" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://paypal.me/keshavnrj/5"><span style=" font-size:14pt; text-decoration: underline;">Donate</span></a></p> <h1 align="center" style="-qt-paragraph-type:empty; margin-top:18px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:14pt; font-weight:600;"><br /></h1></body></html>
diff --git a/src/slides/0.html b/src/slides/0.html index b09ad93..6a5df68 100644 --- a/src/slides/0.html +++ b/src/slides/0.html @@ -6,9 +6,9 @@

Welcome to Glate

Designed and Developed by

Keshav Bhatt

-

keshavnrj@gmail.com

-

Donate

-

Rate in Store

-

Other Applications

+

keshavnrj@gmail.com

+

Donate

+

Rate in Store

+

Other Applications


diff --git a/src/translationdownloader.cpp b/src/translationdownloader.cpp index 1b52769..49e895b 100644 --- a/src/translationdownloader.cpp +++ b/src/translationdownloader.cpp @@ -1,56 +1,63 @@ -#include #include "translationdownloader.h" #include "utils.h" +#include /* Class used to download audio translation of given text */ -TranslationDownloader::TranslationDownloader(QObject *parent, QList urls, QString translationUUID) : QObject(parent) -{ - //init download dir - currentDownloadDir = utils::returnPath("audioCache/"+translationUUID); - _cache_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); - this->urls = urls; - total = urls.count(); - current = -1 ; +TranslationDownloader::TranslationDownloader(QObject *parent, QList urls, + QString translationUUID) + : QObject(parent) { + // init download dir + currentDownloadDir = utils::returnPath("audioCache/" + translationUUID); + _cache_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); + this->urls = urls; + total = urls.count(); + current = -1; } -//entry function after class init -void TranslationDownloader::start(){ - if(current < total-1) - { - current = current+1; - }else if(current == total - 1){ - emit downloadComplete(); - return; - } - startDownload(urls.at(current)); - emit downloadStarted("Share: downloading part: "+QString::number(current+1)+" of "+QString::number(total)); +// entry function after class init +void TranslationDownloader::start() { + if (current < total - 1) { + current = current + 1; + } else if (current == total - 1) { + emit downloadComplete(); + return; + } + startDownload(urls.at(current)); + emit downloadStarted( + "Share: downloading part: " + + QString::number(current + 1) + " of " + QString::number(total)); } -void TranslationDownloader::startDownload(QUrl url){ - QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this); - QNetworkDiskCache* diskCache = new QNetworkDiskCache(this); - diskCache->setCacheDirectory(_cache_path); - m_netwManager->setCache(diskCache); - connect(m_netwManager,&QNetworkAccessManager::finished,[=](QNetworkReply* rep){ - if(rep->error() == QNetworkReply::NoError){ - emit downloadFinished("Downloaded part: "+QString::number(current+1)+" of "+QString::number(total)); - //save to file - QFile file(currentDownloadDir+"/"+QString::number(current)); - file.open(QIODevice::WriteOnly); - file.write(rep->readAll()); - file.close(); - start(); - }else{ - emit downloadError("Share: downloaded error on part: "+QString::number(current+1)+" "+rep->errorString()+" of "+QString::number(total)); - } - rep->deleteLater(); - m_netwManager->deleteLater(); - }); - QNetworkRequest request(url); - m_netwManager->get(request); +void TranslationDownloader::startDownload(QUrl url) { + QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this); + QNetworkDiskCache *diskCache = new QNetworkDiskCache(this); + diskCache->setCacheDirectory(_cache_path); + m_netwManager->setCache(diskCache); + connect(m_netwManager, &QNetworkAccessManager::finished, + [=](QNetworkReply *rep) { + if (rep->error() == QNetworkReply::NoError) { + emit downloadFinished( + "Downloaded part: " + QString::number(current + 1) + " of " + + QString::number(total)); + // save to file + QFile file(currentDownloadDir + "/" + QString::number(current)); + file.open(QIODevice::WriteOnly); + file.write(rep->readAll()); + file.close(); + start(); + } else { + emit downloadError("Share: " + "downloaded error on part: " + + QString::number(current + 1) + " " + + rep->errorString() + " of " + + QString::number(total)); + } + rep->deleteLater(); + m_netwManager->deleteLater(); + }); + QNetworkRequest request(url); + m_netwManager->get(request); } - - diff --git a/src/translationdownloader.h b/src/translationdownloader.h index c4dde04..cd86b79 100644 --- a/src/translationdownloader.h +++ b/src/translationdownloader.h @@ -4,27 +4,29 @@ #include #include -class TranslationDownloader : public QObject -{ - Q_OBJECT +class TranslationDownloader : public QObject { + Q_OBJECT public: - explicit TranslationDownloader(QObject *parent = nullptr, QList urls = {}, QString translationUUID = ""); - QString currentDownloadDir; + explicit TranslationDownloader(QObject *parent = nullptr, + QList urls = {}, + QString translationUUID = ""); + QString currentDownloadDir; signals: - void downloadStarted(QString status); - void downloadFinished(QString status); - void downloadError(QString status); - void downloadComplete(); + void downloadStarted(QString status); + void downloadFinished(QString status); + void downloadError(QString status); + void downloadComplete(); public slots: - void start(); + void start(); private slots: - void startDownload(QUrl url); + void startDownload(QUrl url); + private: - QString _cache_path; - int total= 0; - int current = 0 ; - QList urls; + QString _cache_path; + int total = 0; + int current = 0; + QList urls; }; #endif // TRANSLATIONDOWNLOADER_H diff --git a/src/utils.cpp b/src/utils.cpp index 549cb09..07cef9c 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -1,180 +1,144 @@ #include "utils.h" #include -utils::utils(QObject *parent) : QObject(parent) -{ - setParent(parent); -} - -utils::~utils() -{ - this->deleteLater(); -} - -//calculate dir size -quint64 utils::dir_size(const QString & directory) -{ - quint64 sizex = 0; - QFileInfo str_info(directory); - if (str_info.isDir()) - { - QDir dir(directory); - QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); - for (int i = 0; i < list.size(); ++i) - { - QFileInfo fileInfo = list.at(i); - if(fileInfo.isDir()) - { - sizex += dir_size(fileInfo.absoluteFilePath()); - } - else{ - sizex += fileInfo.size(); - } - } +utils::utils(QObject *parent) : QObject(parent) {} + +utils::~utils() {} + +// calculate dir size +quint64 utils::dir_size(const QString &directory) { + quint64 sizex = 0; + QFileInfo str_info(directory); + if (str_info.isDir()) { + QDir dir(directory); + QFileInfoList list = + dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::Hidden | + QDir::NoSymLinks | QDir::NoDotAndDotDot); + for (int i = 0; i < list.size(); ++i) { + QFileInfo fileInfo = list.at(i); + if (fileInfo.isDir()) { + sizex += dir_size(fileInfo.absoluteFilePath()); + } else { + sizex += fileInfo.size(); + } } - return sizex; + } + return sizex; } -//get the size of cache folder in human readble format -QString utils::refreshCacheSize(const QString cache_dir) -{ - qint64 cache_size = dir_size(cache_dir); - QString cache_unit; - if(cache_size > 1024*1024*1024) - { - cache_size = cache_size/(1024*1024*1024); - cache_unit = " GB"; - } - if(cache_size > 1024*1024) - { - cache_size = cache_size/(1024*1024); - cache_unit = " MB"; - } - else if(cache_size > 1024) - { - cache_size = cache_size/(1024); - cache_unit = " kB"; - } - else - { - cache_unit = " B"; - } - return QString::number(cache_size) + cache_unit; +// get the size of cache folder in human readble format +QString utils::refreshCacheSize(const QString cache_dir) { + qint64 cache_size = dir_size(cache_dir); + QString cache_unit; + if (cache_size > 1024 * 1024 * 1024) { + cache_size = cache_size / (1024 * 1024 * 1024); + cache_unit = " GB"; + } + if (cache_size > 1024 * 1024) { + cache_size = cache_size / (1024 * 1024); + cache_unit = " MB"; + } else if (cache_size > 1024) { + cache_size = cache_size / (1024); + cache_unit = " kB"; + } else { + cache_unit = " B"; + } + return QString::number(cache_size) + cache_unit; } -bool utils::delete_cache(const QString cache_dir){ - bool deleted = QDir(cache_dir).removeRecursively(); - QDir(cache_dir).mkpath(cache_dir); - return deleted; +bool utils::delete_cache(const QString cache_dir) { + bool deleted = QDir(cache_dir).removeRecursively(); + QDir(cache_dir).mkpath(cache_dir); + return deleted; } -//returns string with first letter capitalized -QString utils::toCamelCase(const QString& s) -{ - QStringList parts = s.split(' ', QString::SkipEmptyParts); - for (int i = 0; i < parts.size(); ++i) - parts[i].replace(0, 1, parts[i][0].toUpper()); - return parts.join(" "); +// returns string with first letter capitalized +QString utils::toCamelCase(const QString &s) { + QStringList parts = s.split(' ', QString::SkipEmptyParts); + for (int i = 0; i < parts.size(); ++i) + parts[i].replace(0, 1, parts[i][0].toUpper()); + return parts.join(" "); } -QString utils::generateRandomId(int length){ - - QDateTime cd = QDateTime::currentDateTime(); - const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+QString::number(cd.currentMSecsSinceEpoch()).remove(QRegExp("[^a-zA-Z\\d\\s]"))); - const int randomStringLength = length; - QString randomString; - qsrand(cd.toTime_t()); - for(int i=0; i") - .replace("<","<") - .replace("'","'"); +QString utils::htmlToPlainText(QString str) { + QString out; + QTextDocument text; + text.setHtml(str); + out = text.toPlainText(); + text.deleteLater(); + return out.replace("\\\"", "'") + .replace("&", "&") + .replace(">", ">") + .replace("<", "<") + .replace("'", "'"); } -//bool utils::splitString(const QString &str, int n, QStringList &list) -//{ -// if (n < 1) -// return false; -// QString tmp(str); -// list.clear(); -// while (!tmp.isEmpty()) { -// int m = get_n(tmp,n); -//// list.append(tmp.left(n)); -//// tmp.remove(0, n); -// list.append(tmp.left(m)); -// tmp.remove(0, m); -// } -// return true; -//} - -bool utils::splitString(const QString &str, int m, QStringList &list){ - if (m < 1) - return false; - QStringList words = str.split(" "); - while(words.isEmpty()==false){ - QString strPart; - if(QString(words.join(" ")).length()>m){ - for (int i = 0; i < words.count(); i++) { - if(strPart.count() m) { + for (int i = 0; i < words.count(); i++) { + if (strPart.count() < m) { + strPart.append(words.at(i) + " "); + words.removeAt(i); + --i; } - list.append(strPart); - } - return true; + } + } else if (QString(words.join(" ")).length() < m) { + strPart.append(words.join(" ")); + words.clear(); + } + list.append(strPart); + } + return true; } - - diff --git a/src/utils.h b/src/utils.h index 3f1ab76..1974325 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,82 +1,83 @@ #ifndef UTILS_H #define UTILS_H -#include #include +#include #include +#include #include -#include #include -class utils : public QObject -{ - Q_OBJECT +class utils : public QObject { + Q_OBJECT public: - utils(QObject* parent=0); - virtual ~utils(); + utils(QObject *parent = 0); + virtual ~utils(); public slots: - static bool splitString(const QString &str, int m, QStringList &list); - static QString refreshCacheSize(const QString cache_dir); - bool delete_cache(const QString cache_dir); - QString toCamelCase(const QString &s); - static QString generateRandomId(int length); - static QString convertSectoDay(qint64 secs); - static QString returnPath(QString pathname); - - static QString EncodeXML ( const QString& encodeMe ){ - - QString temp; - int length = encodeMe.size(); - for (int index = 0; index < length; index++) - { - QChar character(encodeMe.at(index)); - - switch (character.unicode()) - { - case '&': - temp += "&"; break; - - case '\'': - temp += "'"; break; - - case '"': - temp += """; break; - - case '<': - temp += "<"; break; - - case '>': - temp += ">"; break; - - default: - temp += character; - break; - } - } - - return temp; + static bool splitString(const QString &str, int m, QStringList &list); + static QString refreshCacheSize(const QString cache_dir); + bool delete_cache(const QString cache_dir); + QString toCamelCase(const QString &s); + static QString generateRandomId(int length); + static QString convertSectoDay(qint64 secs); + static QString returnPath(QString pathname); + + static QString EncodeXML(const QString &encodeMe) { + + QString temp; + int length = encodeMe.size(); + for (int index = 0; index < length; index++) { + QChar character(encodeMe.at(index)); + + switch (character.unicode()) { + case '&': + temp += "&"; + break; + + case '\'': + temp += "'"; + break; + + case '"': + temp += """; + break; + + case '<': + temp += "<"; + break; + + case '>': + temp += ">"; + break; + + default: + temp += character; + break; + } } - static QString DecodeXML ( const QString& decodeMe ) { + return temp; + } - QString temp(decodeMe); + static QString DecodeXML(const QString &decodeMe) { - temp.replace("&", "&"); - temp.replace("'", "'"); - temp.replace(""", "\""); - temp.replace("<", "<"); - temp.replace(">", ">"); + QString temp(decodeMe); - return temp; - } + temp.replace("&", "&"); + temp.replace("'", "'"); + temp.replace(""", "\""); + temp.replace("<", "<"); + temp.replace(">", ">"); - static QString htmlToPlainText(QString str); + return temp; + } -private slots: - //use refreshCacheSize - static quint64 dir_size(const QString &directory); + static QString htmlToPlainText(QString str); +private slots: + // use refreshCacheSize + static quint64 dir_size(const QString &directory); }; #endif // UTILS_H diff --git a/src/waitingspinnerwidget.cpp b/src/waitingspinnerwidget.cpp index dff67c9..bcd7ad6 100644 --- a/src/waitingspinnerwidget.cpp +++ b/src/waitingspinnerwidget.cpp @@ -24,255 +24,234 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "waitingspinnerwidget.h" // Standard includes -#include #include +#include // Qt includes #include #include - -WaitingSpinnerWidget::WaitingSpinnerWidget(QWidget *parent, - bool centerOnParent, +WaitingSpinnerWidget::WaitingSpinnerWidget(QWidget *parent, bool centerOnParent, bool disableParentWhenSpinning) - : QWidget(parent), - _centerOnParent(centerOnParent), + : QWidget(parent), _centerOnParent(centerOnParent), _disableParentWhenSpinning(disableParentWhenSpinning) { - initialize(); + initialize(); } WaitingSpinnerWidget::WaitingSpinnerWidget(Qt::WindowModality modality, - QWidget *parent, - bool centerOnParent, + QWidget *parent, bool centerOnParent, bool disableParentWhenSpinning) : QWidget(parent, Qt::Dialog | Qt::FramelessWindowHint), _centerOnParent(centerOnParent), - _disableParentWhenSpinning(disableParentWhenSpinning){ - initialize(); - - // We need to set the window modality AFTER we've hidden the - // widget for the first time since changing this property while - // the widget is visible has no effect. - setWindowModality(modality); - setAttribute(Qt::WA_TranslucentBackground); + _disableParentWhenSpinning(disableParentWhenSpinning) { + initialize(); + + // We need to set the window modality AFTER we've hidden the + // widget for the first time since changing this property while + // the widget is visible has no effect. + setWindowModality(modality); + setAttribute(Qt::WA_TranslucentBackground); } void WaitingSpinnerWidget::initialize() { - _color = Qt::black; - _roundness = 100.0; - _minimumTrailOpacity = 3.14159265358979323846; - _trailFadePercentage = 80.0; - _revolutionsPerSecond = 1.57079632679489661923; - _numberOfLines = 20; - _lineLength = 10; - _lineWidth = 2; - _innerRadius = 10; - _currentCounter = 0; - _isSpinning = false; - - _timer = new QTimer(this); - connect(_timer, SIGNAL(timeout()), this, SLOT(rotate())); - updateSize(); - updateTimer(); - hide(); + _color = Qt::black; + _roundness = 100.0; + _minimumTrailOpacity = 3.14159265358979323846; + _trailFadePercentage = 80.0; + _revolutionsPerSecond = 1.57079632679489661923; + _numberOfLines = 20; + _lineLength = 10; + _lineWidth = 2; + _innerRadius = 10; + _currentCounter = 0; + _isSpinning = false; + + _timer = new QTimer(this); + connect(_timer, &QTimer::timeout, this, &WaitingSpinnerWidget::rotate); + updateSize(); + updateTimer(); + hide(); } void WaitingSpinnerWidget::paintEvent(QPaintEvent *) { - updatePosition(); - QPainter painter(this); - painter.fillRect(this->rect(), Qt::transparent); - painter.setRenderHint(QPainter::Antialiasing, true); - - if (_currentCounter >= _numberOfLines) { - _currentCounter = 0; - } - - painter.setPen(Qt::NoPen); - for (int i = 0; i < _numberOfLines; ++i) { - painter.save(); - painter.translate(_innerRadius + _lineLength, - _innerRadius + _lineLength); - qreal rotateAngle = - static_cast(360 * i) / static_cast(_numberOfLines); - painter.rotate(rotateAngle); - painter.translate(_innerRadius, 0); - int distance = - lineCountDistanceFromPrimary(i, _currentCounter, _numberOfLines); - QColor color = - currentLineColor(distance, _numberOfLines, _trailFadePercentage, - _minimumTrailOpacity, _color); - painter.setBrush(color); - // TODO improve the way rounded rect is painted - painter.drawRoundedRect( - QRect(0, -_lineWidth / 2, _lineLength, _lineWidth), _roundness, - _roundness, Qt::RelativeSize); - painter.restore(); - } + updatePosition(); + QPainter painter(this); + painter.fillRect(this->rect(), Qt::transparent); + painter.setRenderHint(QPainter::Antialiasing, true); + + if (_currentCounter >= _numberOfLines) { + _currentCounter = 0; + } + + painter.setPen(Qt::NoPen); + for (int i = 0; i < _numberOfLines; ++i) { + painter.save(); + painter.translate(_innerRadius + _lineLength, _innerRadius + _lineLength); + qreal rotateAngle = + static_cast(360 * i) / static_cast(_numberOfLines); + painter.rotate(rotateAngle); + painter.translate(_innerRadius, 0); + int distance = + lineCountDistanceFromPrimary(i, _currentCounter, _numberOfLines); + QColor color = + currentLineColor(distance, _numberOfLines, _trailFadePercentage, + _minimumTrailOpacity, _color); + painter.setBrush(color); + // TODO improve the way rounded rect is painted + painter.drawRoundedRect(QRect(0, -_lineWidth / 2, _lineLength, _lineWidth), + _roundness, _roundness, Qt::RelativeSize); + painter.restore(); + } } void WaitingSpinnerWidget::start() { - updatePosition(); - _isSpinning = true; - show(); - - if(parentWidget() && _disableParentWhenSpinning) { - parentWidget()->setEnabled(false); - } - - if (!_timer->isActive()) { - _timer->start(); - _currentCounter = 0; - } + updatePosition(); + _isSpinning = true; + show(); + + if (parentWidget() && _disableParentWhenSpinning) { + parentWidget()->setEnabled(false); + } + + if (!_timer->isActive()) { + _timer->start(); + _currentCounter = 0; + } } void WaitingSpinnerWidget::stop() { - _isSpinning = false; - hide(); + _isSpinning = false; + hide(); - if(parentWidget() && _disableParentWhenSpinning) { - parentWidget()->setEnabled(true); - } + if (parentWidget() && _disableParentWhenSpinning) { + parentWidget()->setEnabled(true); + } - if (_timer->isActive()) { - _timer->stop(); - _currentCounter = 0; - } + if (_timer->isActive()) { + _timer->stop(); + _currentCounter = 0; + } } void WaitingSpinnerWidget::setNumberOfLines(int lines) { - _numberOfLines = lines; - _currentCounter = 0; - updateTimer(); + _numberOfLines = lines; + _currentCounter = 0; + updateTimer(); } void WaitingSpinnerWidget::setLineLength(int length) { - _lineLength = length; - updateSize(); + _lineLength = length; + updateSize(); } void WaitingSpinnerWidget::setLineWidth(int width) { - _lineWidth = width; - updateSize(); + _lineWidth = width; + updateSize(); } void WaitingSpinnerWidget::setInnerRadius(int radius) { - _innerRadius = radius; - updateSize(); + _innerRadius = radius; + updateSize(); } -QColor WaitingSpinnerWidget::color() { - return _color; -} +QColor WaitingSpinnerWidget::color() { return _color; } -qreal WaitingSpinnerWidget::roundness() { - return _roundness; -} +qreal WaitingSpinnerWidget::roundness() { return _roundness; } qreal WaitingSpinnerWidget::minimumTrailOpacity() { - return _minimumTrailOpacity; + return _minimumTrailOpacity; } qreal WaitingSpinnerWidget::trailFadePercentage() { - return _trailFadePercentage; + return _trailFadePercentage; } qreal WaitingSpinnerWidget::revolutionsPersSecond() { - return _revolutionsPerSecond; + return _revolutionsPerSecond; } -int WaitingSpinnerWidget::numberOfLines() { - return _numberOfLines; -} +int WaitingSpinnerWidget::numberOfLines() { return _numberOfLines; } -int WaitingSpinnerWidget::lineLength() { - return _lineLength; -} +int WaitingSpinnerWidget::lineLength() { return _lineLength; } -int WaitingSpinnerWidget::lineWidth() { - return _lineWidth; -} +int WaitingSpinnerWidget::lineWidth() { return _lineWidth; } -int WaitingSpinnerWidget::innerRadius() { - return _innerRadius; -} +int WaitingSpinnerWidget::innerRadius() { return _innerRadius; } -bool WaitingSpinnerWidget::isSpinning() const { - return _isSpinning; -} +bool WaitingSpinnerWidget::isSpinning() const { return _isSpinning; } void WaitingSpinnerWidget::setRoundness(qreal roundness) { - _roundness = std::max(0.0, std::min(100.0, roundness)); + _roundness = std::max(0.0, std::min(100.0, roundness)); } -void WaitingSpinnerWidget::setColor(QColor color) { - _color = color; -} +void WaitingSpinnerWidget::setColor(QColor color) { _color = color; } void WaitingSpinnerWidget::setRevolutionsPerSecond(qreal revolutionsPerSecond) { - _revolutionsPerSecond = revolutionsPerSecond; - updateTimer(); + _revolutionsPerSecond = revolutionsPerSecond; + updateTimer(); } void WaitingSpinnerWidget::setTrailFadePercentage(qreal trail) { - _trailFadePercentage = trail; + _trailFadePercentage = trail; } void WaitingSpinnerWidget::setMinimumTrailOpacity(qreal minimumTrailOpacity) { - _minimumTrailOpacity = minimumTrailOpacity; + _minimumTrailOpacity = minimumTrailOpacity; } void WaitingSpinnerWidget::rotate() { - ++_currentCounter; - if (_currentCounter >= _numberOfLines) { - _currentCounter = 0; - } - update(); + ++_currentCounter; + if (_currentCounter >= _numberOfLines) { + _currentCounter = 0; + } + update(); } void WaitingSpinnerWidget::updateSize() { - int size = (_innerRadius + _lineLength) * 2; - setFixedSize(size, size); + int size = (_innerRadius + _lineLength) * 2; + setFixedSize(size, size); } void WaitingSpinnerWidget::updateTimer() { - _timer->setInterval(1000 / (_numberOfLines * _revolutionsPerSecond)); + _timer->setInterval(1000 / (_numberOfLines * _revolutionsPerSecond)); } void WaitingSpinnerWidget::updatePosition() { - if (parentWidget() && _centerOnParent) { - move(parentWidget()->width() / 2 - width() / 2, - parentWidget()->height() / 2 - height() / 2); - } + if (parentWidget() && _centerOnParent) { + move(parentWidget()->width() / 2 - width() / 2, + parentWidget()->height() / 2 - height() / 2); + } } int WaitingSpinnerWidget::lineCountDistanceFromPrimary(int current, int primary, int totalNrOfLines) { - int distance = primary - current; - if (distance < 0) { - distance += totalNrOfLines; - } - return distance; + int distance = primary - current; + if (distance < 0) { + distance += totalNrOfLines; + } + return distance; } -QColor WaitingSpinnerWidget::currentLineColor(int countDistance, int totalNrOfLines, - qreal trailFadePerc, qreal minOpacity, - QColor color) { - if (countDistance == 0) { - return color; - } - const qreal minAlphaF = minOpacity / 100.0; - int distanceThreshold = - static_cast(ceil((totalNrOfLines - 1) * trailFadePerc / 100.0)); - if (countDistance > distanceThreshold) { - color.setAlphaF(minAlphaF); - } else { - qreal alphaDiff = color.alphaF() - minAlphaF; - qreal gradient = alphaDiff / static_cast(distanceThreshold + 1); - qreal resultAlpha = color.alphaF() - gradient * countDistance; - - // If alpha is out of bounds, clip it. - resultAlpha = std::min(1.0, std::max(0.0, resultAlpha)); - color.setAlphaF(resultAlpha); - } +QColor WaitingSpinnerWidget::currentLineColor(int countDistance, + int totalNrOfLines, + qreal trailFadePerc, + qreal minOpacity, QColor color) { + if (countDistance == 0) { return color; + } + const qreal minAlphaF = minOpacity / 100.0; + int distanceThreshold = + static_cast(ceil((totalNrOfLines - 1) * trailFadePerc / 100.0)); + if (countDistance > distanceThreshold) { + color.setAlphaF(minAlphaF); + } else { + qreal alphaDiff = color.alphaF() - minAlphaF; + qreal gradient = alphaDiff / static_cast(distanceThreshold + 1); + qreal resultAlpha = color.alphaF() - gradient * countDistance; + + // If alpha is out of bounds, clip it. + resultAlpha = std::min(1.0, std::max(0.0, resultAlpha)); + color.setAlphaF(resultAlpha); + } + return color; } diff --git a/src/waitingspinnerwidget.h b/src/waitingspinnerwidget.h index 1c1f28e..ce2ce8c 100644 --- a/src/waitingspinnerwidget.h +++ b/src/waitingspinnerwidget.h @@ -22,94 +22,91 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #pragma once // Qt includes -#include -#include #include +#include +#include class WaitingSpinnerWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - /*! Constructor for "standard" widget behaviour - use this + /*! Constructor for "standard" widget behaviour - use this * constructor if you wish to, e.g. embed your widget in another. */ - WaitingSpinnerWidget(QWidget *parent = 0, - bool centerOnParent = false, - bool disableParentWhenSpinning = false); + WaitingSpinnerWidget(QWidget *parent = 0, bool centerOnParent = false, + bool disableParentWhenSpinning = false); - /*! Constructor - use this constructor to automatically create a modal + /*! Constructor - use this constructor to automatically create a modal * ("blocking") spinner on top of the calling widget/window. If a valid * parent widget is provided, "centreOnParent" will ensure that * QtWaitingSpinner automatically centres itself on it, if not, * "centreOnParent" is ignored. */ - WaitingSpinnerWidget(Qt::WindowModality modality, - QWidget *parent = 0, - bool centerOnParent = true, - bool disableParentWhenSpinning = true); + WaitingSpinnerWidget(Qt::WindowModality modality, QWidget *parent = 0, + bool centerOnParent = true, + bool disableParentWhenSpinning = true); public slots: - void start(); - void stop(); + void start(); + void stop(); public: - void setColor(QColor color); - void setRoundness(qreal roundness); - void setMinimumTrailOpacity(qreal minimumTrailOpacity); - void setTrailFadePercentage(qreal trail); - void setRevolutionsPerSecond(qreal revolutionsPerSecond); - void setNumberOfLines(int lines); - void setLineLength(int length); - void setLineWidth(int width); - void setInnerRadius(int radius); - void setText(QString text); - - QColor color(); - qreal roundness(); - qreal minimumTrailOpacity(); - qreal trailFadePercentage(); - qreal revolutionsPersSecond(); - int numberOfLines(); - int lineLength(); - int lineWidth(); - int innerRadius(); - - bool isSpinning() const; + void setColor(QColor color); + void setRoundness(qreal roundness); + void setMinimumTrailOpacity(qreal minimumTrailOpacity); + void setTrailFadePercentage(qreal trail); + void setRevolutionsPerSecond(qreal revolutionsPerSecond); + void setNumberOfLines(int lines); + void setLineLength(int length); + void setLineWidth(int width); + void setInnerRadius(int radius); + void setText(QString text); + + QColor color(); + qreal roundness(); + qreal minimumTrailOpacity(); + qreal trailFadePercentage(); + qreal revolutionsPersSecond(); + int numberOfLines(); + int lineLength(); + int lineWidth(); + int innerRadius(); + + bool isSpinning() const; private slots: - void rotate(); + void rotate(); protected: - void paintEvent(QPaintEvent *paintEvent); - + void paintEvent(QPaintEvent *paintEvent); private: - static int lineCountDistanceFromPrimary(int current, int primary, - int totalNrOfLines); - static QColor currentLineColor(int distance, int totalNrOfLines, - qreal trailFadePerc, qreal minOpacity, - QColor color); + static int lineCountDistanceFromPrimary(int current, int primary, + int totalNrOfLines); + static QColor currentLineColor(int distance, int totalNrOfLines, + qreal trailFadePerc, qreal minOpacity, + QColor color); - void initialize(); - void updateSize(); - void updateTimer(); - void updatePosition(); + void initialize(); + void updateSize(); + void updateTimer(); + void updatePosition(); private: - QColor _color; - qreal _roundness; // 0..100 - qreal _minimumTrailOpacity; - qreal _trailFadePercentage; - qreal _revolutionsPerSecond; - int _numberOfLines; - int _lineLength; - int _lineWidth; - int _innerRadius; + QColor _color; + qreal _roundness; // 0..100 + qreal _minimumTrailOpacity; + qreal _trailFadePercentage; + qreal _revolutionsPerSecond; + int _numberOfLines; + int _lineLength; + int _lineWidth; + int _innerRadius; private: - WaitingSpinnerWidget(const WaitingSpinnerWidget&); - WaitingSpinnerWidget& operator=(const WaitingSpinnerWidget&); - - QTimer *_timer; - bool _centerOnParent; - bool _disableParentWhenSpinning; - int _currentCounter; - bool _isSpinning; + WaitingSpinnerWidget(const WaitingSpinnerWidget &); + WaitingSpinnerWidget &operator=(const WaitingSpinnerWidget &); + + QTimer *_timer; + bool _centerOnParent; + bool _disableParentWhenSpinning; + int _currentCounter; + bool _isSpinning; };