Code formatting with uncrustify.

This commit is contained in:
Gres 2015-09-22 21:41:08 +03:00
parent f97082d1ed
commit 9007379242
27 changed files with 2114 additions and 669 deletions

View File

@ -8,13 +8,11 @@
QHash<QPair<quint32, quint32>, QAction *> GlobalActionHelper::actions_; QHash<QPair<quint32, quint32>, QAction *> GlobalActionHelper::actions_;
bool GlobalActionHelper::nativeEventFilter (const QByteArray &eventType, bool GlobalActionHelper::nativeEventFilter (const QByteArray &eventType,
void* message, long* result) void *message, long *result) {
{
Q_UNUSED (eventType); Q_UNUSED (eventType);
Q_UNUSED (result); Q_UNUSED (result);
MSG *msg = static_cast<MSG *>(message); MSG *msg = static_cast<MSG *>(message);
if (msg->message == WM_HOTKEY) if (msg->message == WM_HOTKEY) {
{
const quint32 keycode = HIWORD (msg->lParam); const quint32 keycode = HIWORD (msg->lParam);
const quint32 modifiers = LOWORD (msg->lParam); const quint32 modifiers = LOWORD (msg->lParam);
QAction *action = actions_.value (qMakePair (keycode, modifiers)); QAction *action = actions_.value (qMakePair (keycode, modifiers));
@ -24,16 +22,13 @@ bool GlobalActionHelper::nativeEventFilter(const QByteArray& eventType,
return false; return false;
} }
void GlobalActionHelper::init() void GlobalActionHelper::init () {
{
qApp->installNativeEventFilter (new GlobalActionHelper); qApp->installNativeEventFilter (new GlobalActionHelper);
} }
bool GlobalActionHelper::makeGlobal(QAction* action) bool GlobalActionHelper::makeGlobal (QAction *action) {
{
QKeySequence hotKey = action->shortcut (); QKeySequence hotKey = action->shortcut ();
if (hotKey.isEmpty ()) if (hotKey.isEmpty ()) {
{
return true; return true;
} }
Qt::KeyboardModifiers allMods = Qt::ShiftModifier | Qt::ControlModifier | Qt::KeyboardModifiers allMods = Qt::ShiftModifier | Qt::ControlModifier |
@ -47,18 +42,18 @@ bool GlobalActionHelper::makeGlobal(QAction* action)
const quint32 nativeKey = nativeKeycode (key); const quint32 nativeKey = nativeKeycode (key);
const quint32 nativeMods = nativeModifiers (mods); const quint32 nativeMods = nativeModifiers (mods);
const bool res = registerHotKey (nativeKey, nativeMods); const bool res = registerHotKey (nativeKey, nativeMods);
if (res) if (res) {
actions_.insert (qMakePair (nativeKey, nativeMods), action); actions_.insert (qMakePair (nativeKey, nativeMods), action);
else }
else {
qWarning () << "Failed to register global hotkey:" << hotKey.toString (); qWarning () << "Failed to register global hotkey:" << hotKey.toString ();
}
return res; return res;
} }
bool GlobalActionHelper::removeGlobal(QAction *action) bool GlobalActionHelper::removeGlobal (QAction *action) {
{
QKeySequence hotKey = action->shortcut (); QKeySequence hotKey = action->shortcut ();
if (hotKey.isEmpty ()) if (hotKey.isEmpty ()) {
{
return true; return true;
} }
Qt::KeyboardModifiers allMods = Qt::ShiftModifier | Qt::ControlModifier | Qt::KeyboardModifiers allMods = Qt::ShiftModifier | Qt::ControlModifier |
@ -71,22 +66,21 @@ bool GlobalActionHelper::removeGlobal(QAction *action)
Qt::KeyboardModifiers (hotKey[0] & allMods); Qt::KeyboardModifiers (hotKey[0] & allMods);
const quint32 nativeKey = nativeKeycode (key); const quint32 nativeKey = nativeKeycode (key);
const quint32 nativeMods = nativeModifiers (mods); const quint32 nativeMods = nativeModifiers (mods);
if (!actions_.contains (qMakePair(nativeKey, nativeMods))) if (!actions_.contains (qMakePair (nativeKey, nativeMods))) {
{
return true; return true;
} }
const bool res = unregisterHotKey (nativeKey, nativeMods); const bool res = unregisterHotKey (nativeKey, nativeMods);
if (res) if (res) {
actions_.remove (qMakePair (nativeKey, nativeMods)); actions_.remove (qMakePair (nativeKey, nativeMods));
else }
else {
qWarning () << "Failed to unregister global hotkey:" << hotKey.toString (); qWarning () << "Failed to unregister global hotkey:" << hotKey.toString ();
}
return res; return res;
} }
quint32 GlobalActionHelper::nativeKeycode(Qt::Key key) quint32 GlobalActionHelper::nativeKeycode (Qt::Key key) {
{ switch (key) {
switch (key)
{
case Qt::Key_Escape: case Qt::Key_Escape:
return VK_ESCAPE; return VK_ESCAPE;
case Qt::Key_Tab: case Qt::Key_Tab:
@ -248,29 +242,30 @@ quint32 GlobalActionHelper::nativeKeycode(Qt::Key key)
} }
} }
quint32 GlobalActionHelper::nativeModifiers(Qt::KeyboardModifiers modifiers) quint32 GlobalActionHelper::nativeModifiers (Qt::KeyboardModifiers modifiers) {
{
// MOD_ALT, MOD_CONTROL, (MOD_KEYUP), MOD_SHIFT, MOD_WIN // MOD_ALT, MOD_CONTROL, (MOD_KEYUP), MOD_SHIFT, MOD_WIN
quint32 native = 0; quint32 native = 0;
if (modifiers & Qt::ShiftModifier) if (modifiers & Qt::ShiftModifier) {
native |= MOD_SHIFT; native |= MOD_SHIFT;
if (modifiers & Qt::ControlModifier) }
if (modifiers & Qt::ControlModifier) {
native |= MOD_CONTROL; native |= MOD_CONTROL;
if (modifiers & Qt::AltModifier) }
if (modifiers & Qt::AltModifier) {
native |= MOD_ALT; native |= MOD_ALT;
if (modifiers & Qt::MetaModifier) }
if (modifiers & Qt::MetaModifier) {
native |= MOD_WIN; native |= MOD_WIN;
}
//if (modifiers & Qt::KeypadModifier) //if (modifiers & Qt::KeypadModifier)
//if (modifiers & Qt::GroupSwitchModifier) //if (modifiers & Qt::GroupSwitchModifier)
return native; return native;
} }
bool GlobalActionHelper::registerHotKey(quint32 nativeKey, quint32 nativeMods) bool GlobalActionHelper::registerHotKey (quint32 nativeKey, quint32 nativeMods) {
{
return RegisterHotKey (0, nativeMods ^ nativeKey, nativeMods, nativeKey); return RegisterHotKey (0, nativeMods ^ nativeKey, nativeMods, nativeKey);
} }
bool GlobalActionHelper::unregisterHotKey(quint32 nativeKey, quint32 nativeMods) bool GlobalActionHelper::unregisterHotKey (quint32 nativeKey, quint32 nativeMods) {
{
return UnregisterHotKey (0, nativeMods ^ nativeKey); return UnregisterHotKey (0, nativeMods ^ nativeKey);
} }

View File

@ -6,8 +6,7 @@
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
#include <QAction> #include <QAction>
class GlobalActionHelper : public QAbstractNativeEventFilter class GlobalActionHelper : public QAbstractNativeEventFilter {
{
public: public:
bool nativeEventFilter (const QByteArray &eventType, void *message, bool nativeEventFilter (const QByteArray &eventType, void *message,
long *result); long *result);

View File

@ -72,8 +72,7 @@ void GoogleWebTranslator::loadFinished(bool ok) {
} }
} }
void GoogleWebTranslator::replyFinished(QNetworkReply *reply) void GoogleWebTranslator::replyFinished (QNetworkReply *reply) {
{
if (reply->url ().toString ().contains ("/translate_a/single")) { if (reply->url ().toString ().contains ("/translate_a/single")) {
isTranslationFinished_ = true; isTranslationFinished_ = true;
if (isLoadFinished_) { if (isLoadFinished_) {

View File

@ -9,9 +9,9 @@ class QWebView;
class QUrl; class QUrl;
class QNetworkReply; class QNetworkReply;
class GoogleWebTranslator : public QObject class GoogleWebTranslator : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
GoogleWebTranslator (); GoogleWebTranslator ();
~GoogleWebTranslator (); ~GoogleWebTranslator ();

View File

@ -9,20 +9,17 @@
#ifdef WIN32 #ifdef WIN32
# include <windows.h> # include <windows.h>
qint64 getFreeMemory () qint64 getFreeMemory () {
{
MEMORYSTATUSEX statex; MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex); statex.dwLength = sizeof (statex);
if (GlobalMemoryStatusEx (&statex)) if (GlobalMemoryStatusEx (&statex)) {
{
return statex.ullAvailPhys; return statex.ullAvailPhys;
} }
return -1; return -1;
} }
#endif #endif
Pix *convertImage(const QImage& image) Pix * convertImage (const QImage &image) {
{
PIX *pix; PIX *pix;
QImage swapped = image.rgbSwapped (); QImage swapped = image.rgbSwapped ();
@ -36,12 +33,10 @@ Pix *convertImage(const QImage& image)
pixSetColormap (pix, NULL); pixSetColormap (pix, NULL);
l_uint32 *outData = pix->data; l_uint32 *outData = pix->data;
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++) {
{
l_uint32 *lines = outData + y * wpl; l_uint32 *lines = outData + y * wpl;
QByteArray a ((const char *)swapped.scanLine (y), swapped.bytesPerLine ()); QByteArray a ((const char *)swapped.scanLine (y), swapped.bytesPerLine ());
for (int j = 0; j < a.size(); j++) for (int j = 0; j < a.size (); j++) {
{
*((l_uint8 *)lines + j) = a[j]; *((l_uint8 *)lines + j) = a[j];
} }
} }
@ -50,15 +45,18 @@ Pix *convertImage(const QImage& image)
int resolutionX = swapped.dotsPerMeterX () / toDPM; int resolutionX = swapped.dotsPerMeterX () / toDPM;
int resolutionY = swapped.dotsPerMeterY () / toDPM; int resolutionY = swapped.dotsPerMeterY () / toDPM;
if (resolutionX < 300) resolutionX = 300; if (resolutionX < 300) {
if (resolutionY < 300) resolutionY = 300; resolutionX = 300;
}
if (resolutionY < 300) {
resolutionY = 300;
}
pixSetResolution (pix, resolutionX, resolutionY); pixSetResolution (pix, resolutionX, resolutionY);
return pixEndianByteSwapNew (pix); return pixEndianByteSwapNew (pix);
} }
QImage convertImage(Pix &image) QImage convertImage (Pix &image) {
{
int width = pixGetWidth (&image); int width = pixGetWidth (&image);
int height = pixGetHeight (&image); int height = pixGetHeight (&image);
int depth = pixGetDepth (&image); int depth = pixGetDepth (&image);
@ -66,12 +64,15 @@ QImage convertImage(Pix &image)
l_uint32 *datas = pixGetData (pixEndianByteSwapNew (&image)); l_uint32 *datas = pixGetData (pixEndianByteSwapNew (&image));
QImage::Format format; QImage::Format format;
if (depth == 1) if (depth == 1) {
format = QImage::Format_Mono; format = QImage::Format_Mono;
else if (depth == 8) }
else if (depth == 8) {
format = QImage::Format_Indexed8; format = QImage::Format_Indexed8;
else }
else {
format = QImage::Format_RGB32; format = QImage::Format_RGB32;
}
QImage result ((uchar *)datas, width, height, bytesPerLine, format); QImage result ((uchar *)datas, width, height, bytesPerLine, format);
@ -111,8 +112,7 @@ QImage convertImage(Pix &image)
return result.rgbSwapped (); return result.rgbSwapped ();
} }
Pix *prepareImage(const QImage &image, int preferredScale) Pix * prepareImage (const QImage &image, int preferredScale) {
{
Pix *pix = convertImage (image); Pix *pix = convertImage (image);
ST_ASSERT (pix != NULL); ST_ASSERT (pix != NULL);
@ -121,8 +121,7 @@ Pix *prepareImage(const QImage &image, int preferredScale)
pixDestroy (&pix); pixDestroy (&pix);
Pix *scaled = gray; Pix *scaled = gray;
if (preferredScale > 0) if (preferredScale > 0) {
{
float maxScaleX = MAX_INT16 / double (gray->w); float maxScaleX = MAX_INT16 / double (gray->w);
float scaleX = std::min (float (preferredScale), maxScaleX); float scaleX = std::min (float (preferredScale), maxScaleX);
float maxScaleY = MAX_INT16 / double (gray->h); float maxScaleY = MAX_INT16 / double (gray->h);
@ -139,14 +138,12 @@ Pix *prepareImage(const QImage &image, int preferredScale)
scaled = pixScale (gray, scale, scale); scaled = pixScale (gray, scale, scale);
} }
ST_ASSERT (scaled != NULL); ST_ASSERT (scaled != NULL);
if (scaled != gray) if (scaled != gray) {
{
pixDestroy (&gray); pixDestroy (&gray);
} }
return scaled; return scaled;
} }
void cleanupImage(Pix **image) void cleanupImage (Pix **image) {
{
pixDestroy (image); pixDestroy (image);
} }

View File

@ -4,108 +4,89 @@
#include "LanguageHelper.h" #include "LanguageHelper.h"
#include "Settings.h" #include "Settings.h"
LanguageHelper::LanguageHelper() LanguageHelper::LanguageHelper () {
{
init (); init ();
} }
QStringList LanguageHelper::availableOcrLanguagesUi() const QStringList LanguageHelper::availableOcrLanguagesUi () const {
{
QStringList uiItems; QStringList uiItems;
foreach (const QString& item, availableOcrLanguages_) foreach (const QString &item, availableOcrLanguages_) {
{
uiItems << ocrCodeToUi (item); uiItems << ocrCodeToUi (item);
} }
uiItems.sort (); uiItems.sort ();
return uiItems; return uiItems;
} }
const QStringList &LanguageHelper::availableOcrLanguages() const const QStringList &LanguageHelper::availableOcrLanguages () const {
{
return availableOcrLanguages_; return availableOcrLanguages_;
} }
QStringList LanguageHelper::availableOcrLanguages(const QString &path) const QStringList LanguageHelper::availableOcrLanguages (const QString &path) const {
{
QDir dir (path + "/tessdata/"); QDir dir (path + "/tessdata/");
if (!dir.exists ()) if (!dir.exists ()) {
{
return QStringList (); return QStringList ();
} }
QStringList items; QStringList items;
QStringList files = dir.entryList (QStringList () << "*.traineddata", QDir::Files); QStringList files = dir.entryList (QStringList () << "*.traineddata", QDir::Files);
foreach (const QString& file, files) foreach (const QString &file, files) {
{
QString lang = file.left (file.indexOf (".")); QString lang = file.left (file.indexOf ("."));
items << lang; items << lang;
} }
return items; return items;
} }
QStringList LanguageHelper::availableOcrLanguagesUi(const QString &path) const QStringList LanguageHelper::availableOcrLanguagesUi (const QString &path) const {
{
QStringList uiItems, items; QStringList uiItems, items;
items = availableOcrLanguages (path); items = availableOcrLanguages (path);
foreach (const QString& item, items) foreach (const QString &item, items) {
{
uiItems << ocrCodeToUi (item); uiItems << ocrCodeToUi (item);
} }
uiItems.sort (); uiItems.sort ();
return uiItems; return uiItems;
} }
QStringList LanguageHelper::translateLanguagesUi() const QStringList LanguageHelper::translateLanguagesUi () const {
{
QStringList uiItems = translateLanguages_.keys (); QStringList uiItems = translateLanguages_.keys ();
uiItems.sort (); uiItems.sort ();
return uiItems; return uiItems;
} }
QStringList LanguageHelper::translateLanguages() const QStringList LanguageHelper::translateLanguages () const {
{
return translateLanguages_.values (); return translateLanguages_.values ();
} }
QString LanguageHelper::translateCodeToUi(const QString &text) const QString LanguageHelper::translateCodeToUi (const QString &text) const {
{
return translateLanguages_.key (text, text); return translateLanguages_.key (text, text);
} }
QString LanguageHelper::translateUiToCode(const QString &text) const QString LanguageHelper::translateUiToCode (const QString &text) const {
{
return translateLanguages_.value (text, text); return translateLanguages_.value (text, text);
} }
QString LanguageHelper::ocrCodeToUi(const QString &text) const QString LanguageHelper::ocrCodeToUi (const QString &text) const {
{
return ocrLanguages_.key (text, text); return ocrLanguages_.key (text, text);
} }
QString LanguageHelper::ocrUiToCode(const QString &text) const QString LanguageHelper::ocrUiToCode (const QString &text) const {
{
return ocrLanguages_.value (text, text); return ocrLanguages_.value (text, text);
} }
QString LanguageHelper::translateForOcrCode(const QString &text) const QString LanguageHelper::translateForOcrCode (const QString &text) const {
{
QString ocrUi = ocrUiToCode (text); QString ocrUi = ocrUiToCode (text);
QString translate = translateCodeToUi (ocrUi); QString translate = translateCodeToUi (ocrUi);
if (translate == ocrUi) if (translate == ocrUi) {
{
translate = "auto"; translate = "auto";
} }
return translate; return translate;
} }
void LanguageHelper::init() void LanguageHelper::init () {
{
initOcrLanguages (); initOcrLanguages ();
initTranslateLanguages (); initTranslateLanguages ();
updateAvailableOcrLanguages (); updateAvailableOcrLanguages ();
} }
void LanguageHelper::updateAvailableOcrLanguages() void LanguageHelper::updateAvailableOcrLanguages () {
{
availableOcrLanguages_.clear (); availableOcrLanguages_.clear ();
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::recogntionGroup); settings.beginGroup (settings_names::recogntionGroup);
@ -114,8 +95,7 @@ void LanguageHelper::updateAvailableOcrLanguages()
availableOcrLanguages_ = availableOcrLanguages (tessDataPlace); availableOcrLanguages_ = availableOcrLanguages (tessDataPlace);
} }
void LanguageHelper::initTranslateLanguages() void LanguageHelper::initTranslateLanguages () {
{
translateLanguages_.insert (QObject::tr ("Afrikaans"),"af"); translateLanguages_.insert (QObject::tr ("Afrikaans"),"af");
translateLanguages_.insert (QObject::tr ("Albanian"),"sq"); translateLanguages_.insert (QObject::tr ("Albanian"),"sq");
translateLanguages_.insert (QObject::tr ("Arabic"),"ar"); translateLanguages_.insert (QObject::tr ("Arabic"),"ar");
@ -176,8 +156,7 @@ void LanguageHelper::initTranslateLanguages()
translateLanguages_.insert (QObject::tr ("Yiddish"),"yi"); translateLanguages_.insert (QObject::tr ("Yiddish"),"yi");
} }
void LanguageHelper::initOcrLanguages() void LanguageHelper::initOcrLanguages () {
{
ocrLanguages_.insert (QObject::tr ("Ancient Greek"),"grc"); ocrLanguages_.insert (QObject::tr ("Ancient Greek"),"grc");
ocrLanguages_.insert (QObject::tr ("Esperanto alternative"),"epo_alt"); ocrLanguages_.insert (QObject::tr ("Esperanto alternative"),"epo_alt");
ocrLanguages_.insert (QObject::tr ("English"),"eng"); ocrLanguages_.insert (QObject::tr ("English"),"eng");

View File

@ -4,8 +4,7 @@
#include <QMap> #include <QMap>
#include <QStringList> #include <QStringList>
class LanguageHelper class LanguageHelper {
{
public: public:
LanguageHelper (); LanguageHelper ();

View File

@ -27,8 +27,7 @@ Manager::Manager(QObject *parent) :
selection_ (new SelectionDialog (*dictionary_)), selection_ (new SelectionDialog (*dictionary_)),
resultDialog_ (new ResultDialog), resultDialog_ (new ResultDialog),
captureAction_ (NULL), repeatAction_ (NULL), clipboardAction_ (NULL), captureAction_ (NULL), repeatAction_ (NULL), clipboardAction_ (NULL),
useResultDialog_ (true) useResultDialog_ (true) {
{
GlobalActionHelper::init (); GlobalActionHelper::init ();
qRegisterMetaType<ProcessingItem>(); qRegisterMetaType<ProcessingItem>();
@ -80,8 +79,7 @@ Manager::Manager(QObject *parent) :
applySettings (); applySettings ();
} }
QMenu*Manager::trayContextMenu() QMenu * Manager::trayContextMenu () {
{
QMenu *menu = new QMenu (); QMenu *menu = new QMenu ();
captureAction_ = menu->addAction (tr ("Захват"), this, SLOT (capture ())); captureAction_ = menu->addAction (tr ("Захват"), this, SLOT (capture ()));
QMenu *translateMenu = menu->addMenu (tr ("Перевод")); QMenu *translateMenu = menu->addMenu (tr ("Перевод"));
@ -95,8 +93,7 @@ QMenu*Manager::trayContextMenu()
return menu; return menu;
} }
void Manager::applySettings() void Manager::applySettings () {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::guiGroup); settings.beginGroup (settings_names::guiGroup);
QString captureHotkey = settings.value (settings_names::captureHotkey, QString captureHotkey = settings.value (settings_names::captureHotkey,
@ -128,12 +125,10 @@ void Manager::applySettings()
dictionary_->updateAvailableOcrLanguages (); dictionary_->updateAvailableOcrLanguages ();
} }
Manager::~Manager() Manager::~Manager () {
{
} }
void Manager::capture() void Manager::capture () {
{
QList<QScreen *> screens = QApplication::screens (); QList<QScreen *> screens = QApplication::screens ();
ST_ASSERT (!screens.isEmpty ()); ST_ASSERT (!screens.isEmpty ());
QScreen *screen = screens.first (); QScreen *screen = screens.first ();
@ -144,21 +139,18 @@ void Manager::capture()
emit showPixmap (pixmap); emit showPixmap (pixmap);
} }
void Manager::settings() void Manager::settings () {
{
SettingsEditor editor (*dictionary_); SettingsEditor editor (*dictionary_);
editor.setWindowIcon (trayIcon_->icon ()); editor.setWindowIcon (trayIcon_->icon ());
connect (&editor, SIGNAL (settingsEdited ()), SIGNAL (settingsEdited ())); connect (&editor, SIGNAL (settingsEdited ()), SIGNAL (settingsEdited ()));
editor.exec (); editor.exec ();
} }
void Manager::close() void Manager::close () {
{
QApplication::quit (); QApplication::quit ();
} }
void Manager::about() void Manager::about () {
{
QString version = "1.2.3"; QString version = "1.2.3";
QString text = tr ("Программа для распознавания текста на экране.\n" \ QString text = tr ("Программа для распознавания текста на экране.\n" \
"Создана с использованием Qt, tesseract-ocr, Google Translate.\n" "Создана с использованием Qt, tesseract-ocr, Google Translate.\n"
@ -172,30 +164,23 @@ void Manager::about()
message.exec (); message.exec ();
} }
void Manager::processTrayAction(QSystemTrayIcon::ActivationReason reason) void Manager::processTrayAction (QSystemTrayIcon::ActivationReason reason) {
{ if (reason == QSystemTrayIcon::Trigger) {
if (reason == QSystemTrayIcon::Trigger)
{
showLast (); showLast ();
} }
else if (reason == QSystemTrayIcon::MiddleClick) else if (reason == QSystemTrayIcon::MiddleClick) {
{
copyLastToClipboard (); copyLastToClipboard ();
} }
} }
void Manager::showLast() void Manager::showLast () {
{ if (lastItem_.isValid ()) {
if (lastItem_.isValid ())
{
showResult (lastItem_); showResult (lastItem_);
} }
} }
void Manager::copyLastToClipboard() void Manager::copyLastToClipboard () {
{ if (lastItem_.isValid ()) {
if (lastItem_.isValid ())
{
QClipboard *clipboard = QApplication::clipboard (); QClipboard *clipboard = QApplication::clipboard ();
QString message = lastItem_.recognized + " - " + lastItem_.translated; QString message = lastItem_.recognized + " - " + lastItem_.translated;
clipboard->setText (message); clipboard->setText (message);
@ -205,23 +190,19 @@ void Manager::copyLastToClipboard()
} }
} }
void Manager::showResult(ProcessingItem item) void Manager::showResult (ProcessingItem item) {
{
ST_ASSERT (item.isValid ()); ST_ASSERT (item.isValid ());
lastItem_ = item; lastItem_ = item;
if (useResultDialog_) if (useResultDialog_) {
{
resultDialog_->showResult (item); resultDialog_->showResult (item);
} }
else else {
{
QString message = item.recognized + " - " + item.translated; QString message = item.recognized + " - " + item.translated;
trayIcon_->showMessage (tr ("Перевод"), message, QSystemTrayIcon::Information); trayIcon_->showMessage (tr ("Перевод"), message, QSystemTrayIcon::Information);
} }
} }
void Manager::showError(QString text) void Manager::showError (QString text) {
{
qCritical () << text; qCritical () << text;
trayIcon_->showMessage (tr ("Ошибка"), text, QSystemTrayIcon::Critical); trayIcon_->showMessage (tr ("Ошибка"), text, QSystemTrayIcon::Critical);
} }

View File

@ -13,9 +13,9 @@ class SelectionDialog;
class ResultDialog; class ResultDialog;
class LanguageHelper; class LanguageHelper;
class Manager : public QObject class Manager : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit Manager (QObject *parent = 0); explicit Manager (QObject *parent = 0);
~Manager (); ~Manager ();

View File

@ -1,7 +1,6 @@
#include "ProcessingItem.h" #include "ProcessingItem.h"
bool ProcessingItem::isValid() const bool ProcessingItem::isValid () const {
{
bool valid = true; bool valid = true;
valid &= (!screenPos.isNull ()); valid &= (!screenPos.isNull ());
valid &= (!source.isNull ()); valid &= (!source.isNull ());

View File

@ -3,8 +3,7 @@
#include <QPixmap> #include <QPixmap>
struct ProcessingItem struct ProcessingItem {
{
QPoint screenPos; QPoint screenPos;
QPixmap source; QPixmap source;
QString recognized; QString recognized;

View File

@ -11,20 +11,17 @@
Recognizer::Recognizer (QObject *parent) : Recognizer::Recognizer (QObject *parent) :
QObject (parent), QObject (parent),
engine_ (NULL), imageScale_ (0) engine_ (NULL), imageScale_ (0) {
{
applySettings (); applySettings ();
} }
void Recognizer::applySettings() void Recognizer::applySettings () {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::recogntionGroup); settings.beginGroup (settings_names::recogntionGroup);
tessDataDir_ = settings.value (settings_names::tessDataPlace, tessDataDir_ = settings.value (settings_names::tessDataPlace,
settings_values::tessDataPlace).toString (); settings_values::tessDataPlace).toString ();
if (tessDataDir_.right (1) != "/") if (tessDataDir_.right (1) != "/") {
{
tessDataDir_ += "/"; tessDataDir_ += "/";
} }
ocrLanguage_ = settings.value (settings_names::ocrLanguage, ocrLanguage_ = settings.value (settings_names::ocrLanguage,
@ -35,22 +32,18 @@ void Recognizer::applySettings()
initEngine (engine_, ocrLanguage_); initEngine (engine_, ocrLanguage_);
} }
bool Recognizer::initEngine(tesseract::TessBaseAPI *&engine, const QString& language) bool Recognizer::initEngine (tesseract::TessBaseAPI * &engine, const QString &language) {
{ if (tessDataDir_.isEmpty () || language.isEmpty ()) {
if (tessDataDir_.isEmpty () || language.isEmpty ())
{
emit error (tr ("Неверные параметры для OCR")); emit error (tr ("Неверные параметры для OCR"));
return false; return false;
} }
if (engine != NULL) if (engine != NULL) {
{
delete engine; delete engine;
} }
engine = new tesseract::TessBaseAPI (); engine = new tesseract::TessBaseAPI ();
int result = engine->Init (qPrintable (tessDataDir_), qPrintable (language), int result = engine->Init (qPrintable (tessDataDir_), qPrintable (language),
tesseract::OEM_DEFAULT); tesseract::OEM_DEFAULT);
if (result != 0) if (result != 0) {
{
emit error (tr ("Ошибка инициализации OCR: %1").arg (result)); emit error (tr ("Ошибка инициализации OCR: %1").arg (result));
delete engine; delete engine;
engine = NULL; engine = NULL;
@ -59,17 +52,14 @@ bool Recognizer::initEngine(tesseract::TessBaseAPI *&engine, const QString& lang
return true; return true;
} }
void Recognizer::recognize(ProcessingItem item) void Recognizer::recognize (ProcessingItem item) {
{
ST_ASSERT (!item.source.isNull ()); ST_ASSERT (!item.source.isNull ());
bool isCustomLanguage = (!item.ocrLanguage.isEmpty () && bool isCustomLanguage = (!item.ocrLanguage.isEmpty () &&
item.ocrLanguage != ocrLanguage_); item.ocrLanguage != ocrLanguage_);
tesseract::TessBaseAPI *engine = (isCustomLanguage) ? NULL : engine_; tesseract::TessBaseAPI *engine = (isCustomLanguage) ? NULL : engine_;
if (engine == NULL) if (engine == NULL) {
{
QString language = (isCustomLanguage) ? item.ocrLanguage : ocrLanguage_; QString language = (isCustomLanguage) ? item.ocrLanguage : ocrLanguage_;
if (!initEngine (engine, language)) if (!initEngine (engine, language)) {
{
return; return;
} }
} }
@ -83,18 +73,15 @@ void Recognizer::recognize(ProcessingItem item)
QString result = QString (outText).trimmed (); QString result = QString (outText).trimmed ();
delete [] outText; delete [] outText;
if (isCustomLanguage) if (isCustomLanguage) {
{
delete engine; delete engine;
} }
if (!result.isEmpty ()) if (!result.isEmpty ()) {
{
item.recognized = result; item.recognized = result;
emit recognized (item); emit recognized (item);
} }
else else {
{
emit error (tr ("Текст не распознан.")); emit error (tr ("Текст не распознан."));
} }
} }

View File

@ -6,14 +6,13 @@
#include "ProcessingItem.h" #include "ProcessingItem.h"
namespace tesseract namespace tesseract {
{
class TessBaseAPI; class TessBaseAPI;
} }
class Recognizer : public QObject class Recognizer : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit Recognizer (QObject *parent = 0); explicit Recognizer (QObject *parent = 0);

View File

@ -7,8 +7,7 @@
ResultDialog::ResultDialog (QWidget *parent) : ResultDialog::ResultDialog (QWidget *parent) :
QDialog (parent), QDialog (parent),
ui (new Ui::ResultDialog), ui (new Ui::ResultDialog),
isShowAtCapturePos_ (true) isShowAtCapturePos_ (true) {
{
ui->setupUi (this); ui->setupUi (this);
setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint |
Qt::WindowStaysOnTopHint); Qt::WindowStaysOnTopHint);
@ -16,23 +15,19 @@ ResultDialog::ResultDialog(QWidget *parent) :
installEventFilter (this); installEventFilter (this);
} }
ResultDialog::~ResultDialog() ResultDialog::~ResultDialog () {
{
delete ui; delete ui;
} }
bool ResultDialog::eventFilter(QObject* object, QEvent* event) bool ResultDialog::eventFilter (QObject *object, QEvent *event) {
{
Q_UNUSED (object); Q_UNUSED (object);
if (event->type () == QEvent::MouseButtonRelease) if (event->type () == QEvent::MouseButtonRelease) {
{
hide (); hide ();
} }
return QDialog::eventFilter (object, event); return QDialog::eventFilter (object, event);
} }
void ResultDialog::showResult(ProcessingItem item) void ResultDialog::showResult (ProcessingItem item) {
{
ST_ASSERT (!item.source.isNull ()); ST_ASSERT (!item.source.isNull ());
ST_ASSERT (!item.recognized.isEmpty ()); ST_ASSERT (!item.recognized.isEmpty ());
ST_ASSERT (!item.translated.isEmpty ()); ST_ASSERT (!item.translated.isEmpty ());
@ -47,19 +42,16 @@ void ResultDialog::showResult(ProcessingItem item)
QDesktopWidget *desktop = QApplication::desktop (); QDesktopWidget *desktop = QApplication::desktop ();
Q_CHECK_PTR (desktop); Q_CHECK_PTR (desktop);
if (isShowAtCapturePos_) if (isShowAtCapturePos_) {
{
QPoint correction = QPoint (ui->frame->lineWidth (), ui->frame->lineWidth ()); QPoint correction = QPoint (ui->frame->lineWidth (), ui->frame->lineWidth ());
move (item.screenPos - correction); move (item.screenPos - correction);
QRect screenRect = desktop->screenGeometry (this); QRect screenRect = desktop->screenGeometry (this);
int minY = screenRect.bottom () - height (); int minY = screenRect.bottom () - height ();
if (y () > minY) if (y () > minY) {
{
move (x (), minY); move (x (), minY);
} }
} }
else else {
{
QRect screenRect = desktop->availableGeometry (this); QRect screenRect = desktop->availableGeometry (this);
ST_ASSERT (screenRect.isValid ()); ST_ASSERT (screenRect.isValid ());

View File

@ -9,8 +9,7 @@ namespace Ui {
class ResultDialog; class ResultDialog;
} }
class ResultDialog : public QDialog class ResultDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View File

@ -63,4 +63,5 @@ RC_FILE = app.rc
OTHER_FILES += \ OTHER_FILES += \
app.rc \ app.rc \
images/icon.ico \ images/icon.ico \
README.md README.md \
uncrustify.cfg

View File

@ -11,8 +11,7 @@
SelectionDialog::SelectionDialog (const LanguageHelper &dictionary, QWidget *parent) : SelectionDialog::SelectionDialog (const LanguageHelper &dictionary, QWidget *parent) :
QDialog (parent), QDialog (parent),
ui (new Ui::SelectionDialog), dictionary_ (dictionary), ui (new Ui::SelectionDialog), dictionary_ (dictionary),
languageMenu_ (new QMenu) languageMenu_ (new QMenu) {
{
ui->setupUi (this); ui->setupUi (this);
setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint |
Qt::WindowStaysOnTopHint); Qt::WindowStaysOnTopHint);
@ -23,42 +22,33 @@ SelectionDialog::SelectionDialog(const LanguageHelper &dictionary, QWidget *pare
updateMenu (); updateMenu ();
} }
SelectionDialog::~SelectionDialog() SelectionDialog::~SelectionDialog () {
{
delete ui; delete ui;
} }
void SelectionDialog::updateMenu() void SelectionDialog::updateMenu () {
{
Q_CHECK_PTR (languageMenu_); Q_CHECK_PTR (languageMenu_);
languageMenu_->clear (); languageMenu_->clear ();
QStringList languages = dictionary_.availableOcrLanguagesUi (); QStringList languages = dictionary_.availableOcrLanguagesUi ();
if (languages.isEmpty ()) if (languages.isEmpty ()) {
{
return; return;
} }
const int max = 10; const int max = 10;
if (languages.size () <= max) if (languages.size () <= max) {
{ foreach (const QString &language, languages) {
foreach (const QString& language, languages)
{
languageMenu_->addAction (language); languageMenu_->addAction (language);
} }
} }
else else {
{
int subIndex = max; int subIndex = max;
QMenu *subMenu = NULL; QMenu *subMenu = NULL;
QString prevLetter; QString prevLetter;
foreach (const QString& language, languages) foreach (const QString &language, languages) {
{
QString curLetter = language.left (1); QString curLetter = language.left (1);
if (++subIndex >= max && prevLetter != curLetter) if (++subIndex >= max && prevLetter != curLetter) {
{ if (subMenu != NULL) {
if (subMenu != NULL)
{
subMenu->setTitle (subMenu->title () + " - " + prevLetter); subMenu->setTitle (subMenu->title () + " - " + prevLetter);
} }
subMenu = languageMenu_->addMenu (curLetter); subMenu = languageMenu_->addMenu (curLetter);
@ -71,71 +61,56 @@ void SelectionDialog::updateMenu()
} }
} }
bool SelectionDialog::eventFilter(QObject* object, QEvent* event) bool SelectionDialog::eventFilter (QObject *object, QEvent *event) {
{ if (object != ui->label) {
if (object != ui->label)
{
return QDialog::eventFilter (object, event); return QDialog::eventFilter (object, event);
} }
if (event->type () == QEvent::Show) if (event->type () == QEvent::Show) {
{
startSelectPos_ = currentSelectPos_ = QPoint (); startSelectPos_ = currentSelectPos_ = QPoint ();
} }
else if (event->type () == QEvent::MouseButtonPress) else if (event->type () == QEvent::MouseButtonPress) {
{
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if ((mouseEvent->button () == Qt::LeftButton || if ((mouseEvent->button () == Qt::LeftButton ||
mouseEvent->button () == Qt::RightButton) && startSelectPos_.isNull ()) mouseEvent->button () == Qt::RightButton) && startSelectPos_.isNull ()) {
{
startSelectPos_ = mouseEvent->pos (); startSelectPos_ = mouseEvent->pos ();
} }
} }
else if (event->type () == QEvent::MouseMove) else if (event->type () == QEvent::MouseMove) {
{
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if ((mouseEvent->buttons () & Qt::LeftButton || if ((mouseEvent->buttons () & Qt::LeftButton ||
mouseEvent->buttons () & Qt::RightButton) && !startSelectPos_.isNull ()) mouseEvent->buttons () & Qt::RightButton) && !startSelectPos_.isNull ()) {
{
currentSelectPos_ = mouseEvent->pos (); currentSelectPos_ = mouseEvent->pos ();
ui->label->repaint (); ui->label->repaint ();
} }
} }
else if (event->type () == QEvent::Paint) else if (event->type () == QEvent::Paint) {
{
QRect selection = QRect (startSelectPos_, currentSelectPos_).normalized (); QRect selection = QRect (startSelectPos_, currentSelectPos_).normalized ();
if (selection.isValid ()) if (selection.isValid ()) {
{
QPainter painter (ui->label); QPainter painter (ui->label);
painter.setPen (Qt::red); painter.setPen (Qt::red);
painter.drawRect (selection); painter.drawRect (selection);
} }
} }
else if (event->type () == QEvent::MouseButtonRelease) else if (event->type () == QEvent::MouseButtonRelease) {
{
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if (mouseEvent->button () == Qt::LeftButton || if (mouseEvent->button () == Qt::LeftButton ||
mouseEvent->button () == Qt::RightButton) mouseEvent->button () == Qt::RightButton) {
{ if (startSelectPos_.isNull () || currentPixmap_.isNull ()) {
if (startSelectPos_.isNull () || currentPixmap_.isNull ())
{
return QDialog::eventFilter (object, event); return QDialog::eventFilter (object, event);
} }
QPoint endPos = mouseEvent->pos (); QPoint endPos = mouseEvent->pos ();
QRect selection = QRect (startSelectPos_, endPos).normalized (); QRect selection = QRect (startSelectPos_, endPos).normalized ();
QPixmap selectedPixmap = currentPixmap_.copy (selection); QPixmap selectedPixmap = currentPixmap_.copy (selection);
if (!selectedPixmap.isNull ()) if (!selectedPixmap.isNull ()) {
{
ProcessingItem item; ProcessingItem item;
item.source = selectedPixmap; item.source = selectedPixmap;
item.screenPos = selection.topLeft (); item.screenPos = selection.topLeft ();
if (mouseEvent->button () == Qt::RightButton && if (mouseEvent->button () == Qt::RightButton &&
!languageMenu_->children ().isEmpty ()) !languageMenu_->children ().isEmpty ()) {
{
QAction *action = languageMenu_->exec (QCursor::pos ()); QAction *action = languageMenu_->exec (QCursor::pos ());
if (action == NULL) if (action == NULL) {
{
reject (); reject ();
return QDialog::eventFilter (object, event); return QDialog::eventFilter (object, event);
} }
@ -152,8 +127,7 @@ bool SelectionDialog::eventFilter(QObject* object, QEvent* event)
return QDialog::eventFilter (object, event); return QDialog::eventFilter (object, event);
} }
void SelectionDialog::setPixmap(QPixmap pixmap) void SelectionDialog::setPixmap (QPixmap pixmap) {
{
ST_ASSERT (!pixmap.isNull ()); ST_ASSERT (!pixmap.isNull ());
currentPixmap_ = pixmap; currentPixmap_ = pixmap;
QPalette palette = this->palette (); QPalette palette = this->palette ();

View File

@ -12,8 +12,7 @@ namespace Ui {
} }
class LanguageHelper; class LanguageHelper;
class SelectionDialog : public QDialog class SelectionDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View File

@ -3,8 +3,7 @@
#include <QString> #include <QString>
namespace settings_names namespace settings_names {
{
//! UI //! UI
const QString guiGroup = "GUI"; const QString guiGroup = "GUI";
const QString geometry = "geometry"; const QString geometry = "geometry";
@ -26,8 +25,7 @@ namespace settings_names
} }
namespace settings_values namespace settings_values {
{
const QString appName = "ScreenTranslator"; const QString appName = "ScreenTranslator";
const QString companyName = "Gres"; const QString companyName = "Gres";

View File

@ -10,8 +10,7 @@
SettingsEditor::SettingsEditor (const LanguageHelper &dictionary, QWidget *parent) : SettingsEditor::SettingsEditor (const LanguageHelper &dictionary, QWidget *parent) :
QDialog (parent), QDialog (parent),
ui (new Ui::SettingsEditor), dictionary_ (dictionary), ui (new Ui::SettingsEditor), dictionary_ (dictionary),
buttonGroup_ (new QButtonGroup (this)) buttonGroup_ (new QButtonGroup (this)) {
{
ui->setupUi (this); ui->setupUi (this);
buttonGroup_->addButton (ui->trayRadio, 0); buttonGroup_->addButton (ui->trayRadio, 0);
@ -26,24 +25,20 @@ SettingsEditor::SettingsEditor(const LanguageHelper &dictionary, QWidget *parent
loadState (); loadState ();
} }
SettingsEditor::~SettingsEditor() SettingsEditor::~SettingsEditor () {
{
saveState (); saveState ();
delete ui; delete ui;
} }
void SettingsEditor::done(int result) void SettingsEditor::done (int result) {
{ if (result == QDialog::Accepted) {
if (result == QDialog::Accepted)
{
saveSettings (); saveSettings ();
emit settingsEdited (); emit settingsEdited ();
} }
QDialog::done (result); QDialog::done (result);
} }
void SettingsEditor::saveSettings() const void SettingsEditor::saveSettings () const {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::guiGroup); settings.beginGroup (settings_names::guiGroup);
settings.setValue (settings_names::captureHotkey, ui->captureEdit->text ()); settings.setValue (settings_names::captureHotkey, ui->captureEdit->text ());
@ -69,23 +64,19 @@ void SettingsEditor::saveSettings() const
settings.endGroup (); settings.endGroup ();
} }
void SettingsEditor::openTessdataDialog() void SettingsEditor::openTessdataDialog () {
{
QString path = QFileDialog::getExistingDirectory (this, tr ("Путь к tessdata")); QString path = QFileDialog::getExistingDirectory (this, tr ("Путь к tessdata"));
if (path.isEmpty ()) if (path.isEmpty ()) {
{
return; return;
} }
QDir dir (path); QDir dir (path);
if (dir.dirName () == QString ("tessdata")) if (dir.dirName () == QString ("tessdata")) {
{
dir.cdUp (); dir.cdUp ();
} }
ui->tessdataEdit->setText (dir.path ()); ui->tessdataEdit->setText (dir.path ());
} }
void SettingsEditor::loadSettings() void SettingsEditor::loadSettings () {
{
#define GET(FIELD) settings.value (settings_names::FIELD, settings_values::FIELD) #define GET(FIELD) settings.value (settings_names::FIELD, settings_values::FIELD)
QSettings settings; QSettings settings;
@ -112,22 +103,19 @@ void SettingsEditor::loadSettings()
#undef GET #undef GET
} }
void SettingsEditor::saveState() const void SettingsEditor::saveState () const {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::guiGroup); settings.beginGroup (settings_names::guiGroup);
settings.setValue (objectName () + "_" + settings_names::geometry, saveGeometry ()); settings.setValue (objectName () + "_" + settings_names::geometry, saveGeometry ());
} }
void SettingsEditor::loadState() void SettingsEditor::loadState () {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::guiGroup); settings.beginGroup (settings_names::guiGroup);
restoreGeometry (settings.value (objectName () + "_" + settings_names::geometry).toByteArray ()); restoreGeometry (settings.value (objectName () + "_" + settings_names::geometry).toByteArray ());
} }
void SettingsEditor::initOcrLangCombo(const QString &path) void SettingsEditor::initOcrLangCombo (const QString &path) {
{
ui->ocrLangCombo->clear (); ui->ocrLangCombo->clear ();
ui->ocrLangCombo->addItems (dictionary_.availableOcrLanguagesUi (path)); ui->ocrLangCombo->addItems (dictionary_.availableOcrLanguagesUi (path));
} }

View File

@ -10,8 +10,7 @@ namespace Ui {
} }
class LanguageHelper; class LanguageHelper;
class SettingsEditor : public QDialog class SettingsEditor : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View File

@ -12,8 +12,7 @@
#include "GoogleWebTranslator.h" #include "GoogleWebTranslator.h"
#include "StAssert.h" #include "StAssert.h"
namespace namespace {
{
const QString translateBaseUrl = "http://translate.google.com/translate_a/" const QString translateBaseUrl = "http://translate.google.com/translate_a/"
"t?client=t&text=%1&sl=%2&tl=%3"; "t?client=t&text=%1&sl=%2&tl=%3";
} }
@ -21,8 +20,7 @@ namespace
Translator::Translator (QObject *parent) : Translator::Translator (QObject *parent) :
QObject (parent), QObject (parent),
network_ (this), network_ (this),
useAlternativeTranslation_ (false) useAlternativeTranslation_ (false) {
{
connect (&network_, SIGNAL (finished (QNetworkReply *)), connect (&network_, SIGNAL (finished (QNetworkReply *)),
SLOT (replyFinished (QNetworkReply *))); SLOT (replyFinished (QNetworkReply *)));
@ -36,8 +34,7 @@ Translator::Translator(QObject *parent) :
applySettings (); applySettings ();
} }
void Translator::applySettings() void Translator::applySettings () {
{
QSettings settings; QSettings settings;
settings.beginGroup (settings_names::translationGroup); settings.beginGroup (settings_names::translationGroup);
translationLanguage_ = settings.value (settings_names::translationLanguage, translationLanguage_ = settings.value (settings_names::translationLanguage,
@ -46,8 +43,7 @@ void Translator::applySettings()
settings_values::sourceLanguage).toString (); settings_values::sourceLanguage).toString ();
} }
void Translator::translate(ProcessingItem item) void Translator::translate (ProcessingItem item) {
{
if (useAlternativeTranslation_) { if (useAlternativeTranslation_) {
emit translateAlternative (item); emit translateAlternative (item);
return; return;
@ -55,8 +51,7 @@ void Translator::translate(ProcessingItem item)
ST_ASSERT (!item.recognized.isEmpty ()); ST_ASSERT (!item.recognized.isEmpty ());
QString sourceLanguage = item.sourceLanguage.isEmpty () ? sourceLanguage_ : QString sourceLanguage = item.sourceLanguage.isEmpty () ? sourceLanguage_ :
item.sourceLanguage; item.sourceLanguage;
if (translationLanguage_.isEmpty () || sourceLanguage.isEmpty ()) if (translationLanguage_.isEmpty () || sourceLanguage.isEmpty ()) {
{
emit error (tr ("Неверные парметры для перевода.")); emit error (tr ("Неверные парметры для перевода."));
return; return;
} }
@ -65,25 +60,20 @@ void Translator::translate(ProcessingItem item)
items_.insert (reply, item); items_.insert (reply, item);
} }
void Translator::translatedAlternative(ProcessingItem item, bool success) void Translator::translatedAlternative (ProcessingItem item, bool success) {
{ if (success) {
if (success)
{
emit translated (item); emit translated (item);
} }
else else {
{
emit error (tr ("Ошибка альтернативного перевода текста: %1").arg (item.recognized)); emit error (tr ("Ошибка альтернативного перевода текста: %1").arg (item.recognized));
} }
} }
void Translator::replyFinished(QNetworkReply* reply) void Translator::replyFinished (QNetworkReply *reply) {
{
ST_ASSERT (items_.contains (reply)); ST_ASSERT (items_.contains (reply));
ProcessingItem item = items_.take (reply); ProcessingItem item = items_.take (reply);
ST_ASSERT (reply->isFinished ()); ST_ASSERT (reply->isFinished ());
if (reply->error () != QNetworkReply::NoError) if (reply->error () != QNetworkReply::NoError) {
{
useAlternativeTranslation_ = true; useAlternativeTranslation_ = true;
emit translateAlternative (item); emit translateAlternative (item);
reply->deleteLater (); reply->deleteLater ();
@ -92,14 +82,12 @@ void Translator::replyFinished(QNetworkReply* reply)
QByteArray data = reply->readAll (); QByteArray data = reply->readAll ();
reply->deleteLater (); reply->deleteLater ();
while (data.indexOf (",,") != -1)//make json valid while (data.indexOf (",,") != -1) {//make json valid
{
data.replace (",,", ","); data.replace (",,", ",");
} }
QJsonParseError parseError; QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson (data, &parseError); QJsonDocument document = QJsonDocument::fromJson (data, &parseError);
if (document.isEmpty ()) if (document.isEmpty ()) {
{
useAlternativeTranslation_ = true; useAlternativeTranslation_ = true;
emit translateAlternative (item); emit translateAlternative (item);
return; return;
@ -107,11 +95,9 @@ void Translator::replyFinished(QNetworkReply* reply)
QJsonArray answerArray = document.array (); QJsonArray answerArray = document.array ();
QJsonArray fullTranslation = answerArray.first ().toArray (); QJsonArray fullTranslation = answerArray.first ().toArray ();
QString translation = ""; QString translation = "";
foreach (QJsonValue part, fullTranslation) foreach (QJsonValue part, fullTranslation) {
{
QJsonArray partTranslation = part.toArray (); QJsonArray partTranslation = part.toArray ();
if (partTranslation.isEmpty ()) if (partTranslation.isEmpty ()) {
{
continue; continue;
} }
translation += partTranslation.at (0).toString (); translation += partTranslation.at (0).toString ();

View File

@ -5,9 +5,9 @@
#include "ProcessingItem.h" #include "ProcessingItem.h"
class Translator : public QObject class Translator : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit Translator (QObject *parent = 0); explicit Translator (QObject *parent = 0);

View File

@ -4,8 +4,7 @@
#include <Manager.h> #include <Manager.h>
#include <Settings.h> #include <Settings.h>
int main(int argc, char *argv[]) int main (int argc, char *argv[]) {
{
QApplication a (argc, argv); QApplication a (argc, argv);
a.setQuitOnLastWindowClosed (false); a.setQuitOnLastWindowClosed (false);
a.setApplicationName (settings_values::appName); a.setApplicationName (settings_values::appName);
@ -14,8 +13,7 @@ int main(int argc, char *argv[])
QTranslator translator; QTranslator translator;
// Set default to english. // Set default to english.
if (translator.load (QLocale::system (), "translation", "_", ":/translations") || if (translator.load (QLocale::system (), "translation", "_", ":/translations") ||
translator.load (":/translations/translation_en")) translator.load (":/translations/translation_en")) {
{
a.installTranslator (&translator); a.installTranslator (&translator);
} }

1578
uncrustify.cfg Normal file

File diff suppressed because it is too large Load Diff