Add .gitattributes rules for text and binary handling

This commit is contained in:
Felix Kauselmann
2018-07-01 21:29:59 +02:00
parent 4f6618c096
commit d5a11fb16b
377 changed files with 54049 additions and 53970 deletions

79
.gitattributes vendored
View File

@ -6,3 +6,82 @@
/dependencies/create-dmg export-ignore /dependencies/create-dmg export-ignore
.gitignore export-ignore .gitignore export-ignore
.gitattributes export-ignore .gitattributes export-ignore
# Auto detect text files and perform LF normalization
# http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/
* text=auto
#
# The above will handle all files NOT found below
#
# Documents
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.md text
*.adoc text
*.textile text
*.mustache text
*.csv text
*.tab text
*.tsv text
*.sql text
# Graphics
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.tif binary
*.tiff binary
*.ico binary
# SVG treated as an asset (binary) by default. If you want to treat it as text,
# comment-out the following line and uncomment the line after.
*.svg binary
#*.svg text
*.eps binary
# Sources
*.c text
*.cc text
*.cxx text
*.cpp text
*.c++ text
*.hpp text
*.h text
*.h++ text
*.hh text
# Compiled Object files
*.slo binary
*.lo binary
*.o binary
*.obj binary
# Precompiled Headers
*.gch binary
*.pch binary
# Compiled Dynamic libraries
*.so binary
*.dylib binary
*.dll binary
# Compiled Static libraries
*.lai binary
*.la binary
*.a binary
*.lib binary
# Executables
*.exe binary
*.out binary
*.app binary

View File

@ -1,111 +1,111 @@
# Building YACReader from source # Building YACReader from source
YACReader and YACReaderLibrary are build using qmake. To build and install the YACReader and YACReaderLibrary are build using qmake. To build and install the
program, run: program, run:
> qmake-qt5 CONFIG+=[Options] > qmake-qt5 CONFIG+=[Options]
> make > make
> make install > make install
from the source dir. For separate builds of YACReader or YACReaderLibrary, from the source dir. For separate builds of YACReader or YACReaderLibrary,
enter their respective subfolders and run the commands from there. enter their respective subfolders and run the commands from there.
The headless version of YACReaderLibrary is located in the YACReaderLibraryServer The headless version of YACReaderLibrary is located in the YACReaderLibraryServer
folder. To build it, enter the folder and run the commands described above. folder. To build it, enter the folder and run the commands described above.
## Build dependencies: ## Build dependencies:
- Qt >= 5.6 with the following modules: - Qt >= 5.6 with the following modules:
- declarative - declarative
- quickcontrols - quickcontrols
- sql - sql
- script - script
- multimedia - multimedia
- imageformats - imageformats
- opengl - opengl
- sql-sqlite - sql-sqlite
- network - network
- A pdf rendering backend (optional, see below) - A pdf rendering backend (optional, see below)
- qrencode (optional) - qrencode (optional)
- glu - glu
- (lib)unarr (see below) - (lib)unarr (see below)
Not all dependencies are needed at build time. For example the qml components in Not all dependencies are needed at build time. For example the qml components in
YACReaderLibrary (GridView, InfoView) will only show a white page if the YACReaderLibrary (GridView, InfoView) will only show a white page if the
required qml modules (declarative, quickcontrols) are missing. required qml modules (declarative, quickcontrols) are missing.
This can also happen if these dependencies are too old (i.e Qt < 5.6 is used). This can also happen if these dependencies are too old (i.e Qt < 5.6 is used).
## Backends ## Backends
### Decompression ### Decompression
YACReader uses [(lib)unarr](https://github.com/selmf/unarr) for comic book archive YACReader uses [(lib)unarr](https://github.com/selmf/unarr) for comic book archive
decompression. Most Linux distributions don't ship this library yet, so you will decompression. Most Linux distributions don't ship this library yet, so you will
probably have to build it yourself. probably have to build it yourself.
We recommend using (lib)unarr as a shared library, but we also support static We recommend using (lib)unarr as a shared library, but we also support static
and embedded builds. Please consult the [README](compressed_archive/unarr/README.txt) and embedded builds. Please consult the [README](compressed_archive/unarr/README.txt)
for more information on this topic. for more information on this topic.
### PDF ### PDF
Starting with version 9.0.0 YACReader supports the following pdf render engines: Starting with version 9.0.0 YACReader supports the following pdf render engines:
- poppler (Linux/Unix default) - poppler (Linux/Unix default)
- pdfium (default for Windows and MacOS) - pdfium (default for Windows and MacOS)
- pdfkit (MacOS only) - pdfkit (MacOS only)
- no_pdf (disable pdf support) - no_pdf (disable pdf support)
To override the default for a given platform add CONFIG+=[pdfbackend] as an option To override the default for a given platform add CONFIG+=[pdfbackend] as an option
when running qmake. when running qmake.
While the Poppler backend is well tested and has been the standard for YACReader While the Poppler backend is well tested and has been the standard for YACReader
for a long time, it's performance is a bit lacking. The pdfium engine offers for a long time, it's performance is a bit lacking. The pdfium engine offers
much better performance (about 10x faster on some pdf files we tested). much better performance (about 10x faster on some pdf files we tested).
However, at the time of this writing, it is not a library that is available However, at the time of this writing, it is not a library that is available
prepackaged for Linux. prepackaged for Linux.
### Other build options: ### Other build options:
You can adjust the installation prefix as well als the path "make install" uses You can adjust the installation prefix as well als the path "make install" uses
to install the files. to install the files.
>qmake PREFIX=DIR >qmake PREFIX=DIR
sets the default prefix (for example "/", "/usr", "/usr/local"). sets the default prefix (for example "/", "/usr", "/usr/local").
>make install INSTALL_ROOT=DIR >make install INSTALL_ROOT=DIR
can be used to install to a different location, which is usefull for packaging. can be used to install to a different location, which is usefull for packaging.
Default values: Default values:
>PREFIX=/usr >PREFIX=/usr
>INSTALL_ROOT="" >INSTALL_ROOT=""
On embedded devices that don't support desktop OpenGL, it is recommended to use On embedded devices that don't support desktop OpenGL, it is recommended to use
the no_opengl config option: the no_opengl config option:
qmake-qt5 CONFIG+=no_opengl qmake-qt5 CONFIG+=no_opengl
This will remove any dependency on desktop OpenGL and hardlock YACReader's This will remove any dependency on desktop OpenGL and hardlock YACReader's
coverflow to software rendering. Please note that it does not actually remove coverflow to software rendering. Please note that it does not actually remove
OpenGL from the build, the Qt toolkit will still make use of it. OpenGL from the build, the Qt toolkit will still make use of it.
# Feedback and contribution # Feedback and contribution
If you're compiling YACReader because there is no package available for your If you're compiling YACReader because there is no package available for your
Linux distribution please consider creating and submitting a package or filing a Linux distribution please consider creating and submitting a package or filing a
package request. package request.
While we do provide packages for .deb and .rpm based distributions as well as an While we do provide packages for .deb and .rpm based distributions as well as an
AUR package for Archlinux and it's derivates, we are in need of downstream packagers AUR package for Archlinux and it's derivates, we are in need of downstream packagers
that are willing to make YACReader available as a standard package for their distro. that are willing to make YACReader available as a standard package for their distro.
If you are interested, please contact @selmf on the YACReader forums or write If you are interested, please contact @selmf on the YACReader forums or write
an email to info@yacreader.com an email to info@yacreader.com
If you have already created a package please let us know so we can add it to If you have already created a package please let us know so we can add it to
our downloads list ;) our downloads list ;)

View File

@ -1,249 +1,249 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#include "QsLog.h" #include "QsLog.h"
#include "QsLogDest.h" #include "QsLogDest.h"
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
#include <QThreadPool> #include <QThreadPool>
#include <QRunnable> #include <QRunnable>
#endif #endif
#include <QMutex> #include <QMutex>
#include <QVector> #include <QVector>
#include <QDateTime> #include <QDateTime>
#include <QtGlobal> #include <QtGlobal>
#include <cassert> #include <cassert>
#include <cstdlib> #include <cstdlib>
#include <stdexcept> #include <stdexcept>
namespace QsLogging namespace QsLogging
{ {
typedef QVector<DestinationPtr> DestinationList; typedef QVector<DestinationPtr> DestinationList;
static const char TraceString[] = "TRACE"; static const char TraceString[] = "TRACE";
static const char DebugString[] = "DEBUG"; static const char DebugString[] = "DEBUG";
static const char InfoString[] = "INFO "; static const char InfoString[] = "INFO ";
static const char WarnString[] = "WARN "; static const char WarnString[] = "WARN ";
static const char ErrorString[] = "ERROR"; static const char ErrorString[] = "ERROR";
static const char FatalString[] = "FATAL"; static const char FatalString[] = "FATAL";
// not using Qt::ISODate because we need the milliseconds too // not using Qt::ISODate because we need the milliseconds too
static const QString fmtDateTime("yyyy-MM-ddThh:mm:ss.zzz"); static const QString fmtDateTime("yyyy-MM-ddThh:mm:ss.zzz");
static Logger* sInstance = 0; static Logger* sInstance = 0;
static const char* LevelToText(Level theLevel) static const char* LevelToText(Level theLevel)
{ {
switch (theLevel) { switch (theLevel) {
case TraceLevel: case TraceLevel:
return TraceString; return TraceString;
case DebugLevel: case DebugLevel:
return DebugString; return DebugString;
case InfoLevel: case InfoLevel:
return InfoString; return InfoString;
case WarnLevel: case WarnLevel:
return WarnString; return WarnString;
case ErrorLevel: case ErrorLevel:
return ErrorString; return ErrorString;
case FatalLevel: case FatalLevel:
return FatalString; return FatalString;
case OffLevel: case OffLevel:
return ""; return "";
default: { default: {
assert(!"bad log level"); assert(!"bad log level");
return InfoString; return InfoString;
} }
} }
} }
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
class LogWriterRunnable : public QRunnable class LogWriterRunnable : public QRunnable
{ {
public: public:
LogWriterRunnable(QString message, Level level); LogWriterRunnable(QString message, Level level);
virtual void run(); virtual void run();
private: private:
QString mMessage; QString mMessage;
Level mLevel; Level mLevel;
}; };
#endif #endif
class LoggerImpl class LoggerImpl
{ {
public: public:
LoggerImpl(); LoggerImpl();
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
QThreadPool threadPool; QThreadPool threadPool;
#endif #endif
QMutex logMutex; QMutex logMutex;
Level level; Level level;
DestinationList destList; DestinationList destList;
}; };
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
LogWriterRunnable::LogWriterRunnable(QString message, Level level) LogWriterRunnable::LogWriterRunnable(QString message, Level level)
: QRunnable() : QRunnable()
, mMessage(message) , mMessage(message)
, mLevel(level) , mLevel(level)
{ {
} }
void LogWriterRunnable::run() void LogWriterRunnable::run()
{ {
Logger::instance().write(mMessage, mLevel); Logger::instance().write(mMessage, mLevel);
} }
#endif #endif
LoggerImpl::LoggerImpl() LoggerImpl::LoggerImpl()
: level(InfoLevel) : level(InfoLevel)
{ {
// assume at least file + console // assume at least file + console
destList.reserve(2); destList.reserve(2);
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
threadPool.setMaxThreadCount(1); threadPool.setMaxThreadCount(1);
threadPool.setExpiryTimeout(-1); threadPool.setExpiryTimeout(-1);
#endif #endif
} }
Logger::Logger() Logger::Logger()
: d(new LoggerImpl) : d(new LoggerImpl)
{ {
} }
Logger& Logger::instance() Logger& Logger::instance()
{ {
if (!sInstance) if (!sInstance)
sInstance = new Logger; sInstance = new Logger;
return *sInstance; return *sInstance;
} }
void Logger::destroyInstance() void Logger::destroyInstance()
{ {
delete sInstance; delete sInstance;
sInstance = 0; sInstance = 0;
} }
// tries to extract the level from a string log message. If available, conversionSucceeded will // tries to extract the level from a string log message. If available, conversionSucceeded will
// contain the conversion result. // contain the conversion result.
Level Logger::levelFromLogMessage(const QString& logMessage, bool* conversionSucceeded) Level Logger::levelFromLogMessage(const QString& logMessage, bool* conversionSucceeded)
{ {
if (conversionSucceeded) if (conversionSucceeded)
*conversionSucceeded = true; *conversionSucceeded = true;
if (logMessage.startsWith(QLatin1String(TraceString))) if (logMessage.startsWith(QLatin1String(TraceString)))
return TraceLevel; return TraceLevel;
if (logMessage.startsWith(QLatin1String(DebugString))) if (logMessage.startsWith(QLatin1String(DebugString)))
return DebugLevel; return DebugLevel;
if (logMessage.startsWith(QLatin1String(InfoString))) if (logMessage.startsWith(QLatin1String(InfoString)))
return InfoLevel; return InfoLevel;
if (logMessage.startsWith(QLatin1String(WarnString))) if (logMessage.startsWith(QLatin1String(WarnString)))
return WarnLevel; return WarnLevel;
if (logMessage.startsWith(QLatin1String(ErrorString))) if (logMessage.startsWith(QLatin1String(ErrorString)))
return ErrorLevel; return ErrorLevel;
if (logMessage.startsWith(QLatin1String(FatalString))) if (logMessage.startsWith(QLatin1String(FatalString)))
return FatalLevel; return FatalLevel;
if (conversionSucceeded) if (conversionSucceeded)
*conversionSucceeded = false; *conversionSucceeded = false;
return OffLevel; return OffLevel;
} }
Logger::~Logger() Logger::~Logger()
{ {
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
d->threadPool.waitForDone(); d->threadPool.waitForDone();
#endif #endif
delete d; delete d;
d = 0; d = 0;
} }
void Logger::addDestination(DestinationPtr destination) void Logger::addDestination(DestinationPtr destination)
{ {
assert(destination.data()); assert(destination.data());
d->destList.push_back(destination); d->destList.push_back(destination);
} }
void Logger::setLoggingLevel(Level newLevel) void Logger::setLoggingLevel(Level newLevel)
{ {
d->level = newLevel; d->level = newLevel;
} }
Level Logger::loggingLevel() const Level Logger::loggingLevel() const
{ {
return d->level; return d->level;
} }
//! creates the complete log message and passes it to the logger //! creates the complete log message and passes it to the logger
void Logger::Helper::writeToLog() void Logger::Helper::writeToLog()
{ {
const char* const levelName = LevelToText(level); const char* const levelName = LevelToText(level);
const QString completeMessage(QString("%1 %2 %3") const QString completeMessage(QString("%1 %2 %3")
.arg(levelName) .arg(levelName)
.arg(QDateTime::currentDateTime().toString(fmtDateTime)) .arg(QDateTime::currentDateTime().toString(fmtDateTime))
.arg(buffer) .arg(buffer)
); );
Logger::instance().enqueueWrite(completeMessage, level); Logger::instance().enqueueWrite(completeMessage, level);
} }
Logger::Helper::~Helper() Logger::Helper::~Helper()
{ {
try { try {
writeToLog(); writeToLog();
} }
catch(std::exception&) { catch(std::exception&) {
// you shouldn't throw exceptions from a sink // you shouldn't throw exceptions from a sink
assert(!"exception in logger helper destructor"); assert(!"exception in logger helper destructor");
//CHANGED throw; //CHANGED throw;
} }
} }
//! directs the message to the task queue or writes it directly //! directs the message to the task queue or writes it directly
void Logger::enqueueWrite(const QString& message, Level level) void Logger::enqueueWrite(const QString& message, Level level)
{ {
#ifdef QS_LOG_SEPARATE_THREAD #ifdef QS_LOG_SEPARATE_THREAD
LogWriterRunnable *r = new LogWriterRunnable(message, level); LogWriterRunnable *r = new LogWriterRunnable(message, level);
d->threadPool.start(r); d->threadPool.start(r);
#else #else
write(message, level); write(message, level);
#endif #endif
} }
//! Sends the message to all the destinations. The level for this message is passed in case //! Sends the message to all the destinations. The level for this message is passed in case
//! it's useful for processing in the destination. //! it's useful for processing in the destination.
void Logger::write(const QString& message, Level level) void Logger::write(const QString& message, Level level)
{ {
QMutexLocker lock(&d->logMutex); QMutexLocker lock(&d->logMutex);
for (DestinationList::iterator it = d->destList.begin(), for (DestinationList::iterator it = d->destList.begin(),
endIt = d->destList.end();it != endIt;++it) { endIt = d->destList.end();it != endIt;++it) {
(*it)->write(message, level); (*it)->write(message, level);
} }
} }
} // end namespace } // end namespace

View File

@ -1,137 +1,137 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef QSLOG_H #ifndef QSLOG_H
#define QSLOG_H #define QSLOG_H
#include "QsLogLevel.h" #include "QsLogLevel.h"
#include "QsLogDest.h" #include "QsLogDest.h"
#include <QDebug> #include <QDebug>
#include <QString> #include <QString>
#define QS_LOG_VERSION "2.0b3" #define QS_LOG_VERSION "2.0b3"
namespace QsLogging namespace QsLogging
{ {
class Destination; class Destination;
class LoggerImpl; // d pointer class LoggerImpl; // d pointer
class QSLOG_SHARED_OBJECT Logger class QSLOG_SHARED_OBJECT Logger
{ {
public: public:
static Logger& instance(); static Logger& instance();
static void destroyInstance(); static void destroyInstance();
static Level levelFromLogMessage(const QString& logMessage, bool* conversionSucceeded = 0); static Level levelFromLogMessage(const QString& logMessage, bool* conversionSucceeded = 0);
~Logger(); ~Logger();
//! Adds a log message destination. Don't add null destinations. //! Adds a log message destination. Don't add null destinations.
void addDestination(DestinationPtr destination); void addDestination(DestinationPtr destination);
//! Logging at a level < 'newLevel' will be ignored //! Logging at a level < 'newLevel' will be ignored
void setLoggingLevel(Level newLevel); void setLoggingLevel(Level newLevel);
//! The default level is INFO //! The default level is INFO
Level loggingLevel() const; Level loggingLevel() const;
//! The helper forwards the streaming to QDebug and builds the final //! The helper forwards the streaming to QDebug and builds the final
//! log message. //! log message.
class QSLOG_SHARED_OBJECT Helper class QSLOG_SHARED_OBJECT Helper
{ {
public: public:
explicit Helper(Level logLevel) : explicit Helper(Level logLevel) :
level(logLevel), level(logLevel),
qtDebug(&buffer) {} qtDebug(&buffer) {}
~Helper(); ~Helper();
QDebug& stream(){ return qtDebug; } QDebug& stream(){ return qtDebug; }
private: private:
void writeToLog(); void writeToLog();
Level level; Level level;
QString buffer; QString buffer;
QDebug qtDebug; QDebug qtDebug;
}; };
private: private:
Logger(); Logger();
Logger(const Logger&); // not available Logger(const Logger&); // not available
Logger& operator=(const Logger&); // not available Logger& operator=(const Logger&); // not available
void enqueueWrite(const QString& message, Level level); void enqueueWrite(const QString& message, Level level);
void write(const QString& message, Level level); void write(const QString& message, Level level);
LoggerImpl* d; LoggerImpl* d;
friend class LogWriterRunnable; friend class LogWriterRunnable;
}; };
} // end namespace } // end namespace
//! Logging macros: define QS_LOG_LINE_NUMBERS to get the file and line number //! Logging macros: define QS_LOG_LINE_NUMBERS to get the file and line number
//! in the log output. //! in the log output.
#ifndef QS_LOG_LINE_NUMBERS #ifndef QS_LOG_LINE_NUMBERS
#define QLOG_TRACE() \ #define QLOG_TRACE() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::TraceLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::TraceLevel) {} \
else QsLogging::Logger::Helper(QsLogging::TraceLevel).stream() else QsLogging::Logger::Helper(QsLogging::TraceLevel).stream()
#define QLOG_DEBUG() \ #define QLOG_DEBUG() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::DebugLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::DebugLevel) {} \
else QsLogging::Logger::Helper(QsLogging::DebugLevel).stream() else QsLogging::Logger::Helper(QsLogging::DebugLevel).stream()
#define QLOG_INFO() \ #define QLOG_INFO() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::InfoLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::InfoLevel) {} \
else QsLogging::Logger::Helper(QsLogging::InfoLevel).stream() else QsLogging::Logger::Helper(QsLogging::InfoLevel).stream()
#define QLOG_WARN() \ #define QLOG_WARN() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::WarnLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::WarnLevel) {} \
else QsLogging::Logger::Helper(QsLogging::WarnLevel).stream() else QsLogging::Logger::Helper(QsLogging::WarnLevel).stream()
#define QLOG_ERROR() \ #define QLOG_ERROR() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::ErrorLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::ErrorLevel) {} \
else QsLogging::Logger::Helper(QsLogging::ErrorLevel).stream() else QsLogging::Logger::Helper(QsLogging::ErrorLevel).stream()
#define QLOG_FATAL() \ #define QLOG_FATAL() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::FatalLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::FatalLevel) {} \
else QsLogging::Logger::Helper(QsLogging::FatalLevel).stream() else QsLogging::Logger::Helper(QsLogging::FatalLevel).stream()
#else #else
#define QLOG_TRACE() \ #define QLOG_TRACE() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::TraceLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::TraceLevel) {} \
else QsLogging::Logger::Helper(QsLogging::TraceLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::TraceLevel).stream() << __FILE__ << '@' << __LINE__
#define QLOG_DEBUG() \ #define QLOG_DEBUG() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::DebugLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::DebugLevel) {} \
else QsLogging::Logger::Helper(QsLogging::DebugLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::DebugLevel).stream() << __FILE__ << '@' << __LINE__
#define QLOG_INFO() \ #define QLOG_INFO() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::InfoLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::InfoLevel) {} \
else QsLogging::Logger::Helper(QsLogging::InfoLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::InfoLevel).stream() << __FILE__ << '@' << __LINE__
#define QLOG_WARN() \ #define QLOG_WARN() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::WarnLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::WarnLevel) {} \
else QsLogging::Logger::Helper(QsLogging::WarnLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::WarnLevel).stream() << __FILE__ << '@' << __LINE__
#define QLOG_ERROR() \ #define QLOG_ERROR() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::ErrorLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::ErrorLevel) {} \
else QsLogging::Logger::Helper(QsLogging::ErrorLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::ErrorLevel).stream() << __FILE__ << '@' << __LINE__
#define QLOG_FATAL() \ #define QLOG_FATAL() \
if (QsLogging::Logger::instance().loggingLevel() > QsLogging::FatalLevel) {} \ if (QsLogging::Logger::instance().loggingLevel() > QsLogging::FatalLevel) {} \
else QsLogging::Logger::Helper(QsLogging::FatalLevel).stream() << __FILE__ << '@' << __LINE__ else QsLogging::Logger::Helper(QsLogging::FatalLevel).stream() << __FILE__ << '@' << __LINE__
#endif #endif
#ifdef QS_LOG_DISABLE #ifdef QS_LOG_DISABLE
#include "QsLogDisableForThisFile.h" #include "QsLogDisableForThisFile.h"
#endif #endif
#endif // QSLOG_H #endif // QSLOG_H

View File

@ -1,70 +1,70 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#include "QsLogDest.h" #include "QsLogDest.h"
#include "QsLogDestConsole.h" #include "QsLogDestConsole.h"
#include "QsLogDestFile.h" #include "QsLogDestFile.h"
#include "QsLogDestFunctor.h" #include "QsLogDestFunctor.h"
#include <QString> #include <QString>
namespace QsLogging namespace QsLogging
{ {
Destination::~Destination() Destination::~Destination()
{ {
} }
//! destination factory //! destination factory
DestinationPtr DestinationFactory::MakeFileDestination(const QString& filePath, DestinationPtr DestinationFactory::MakeFileDestination(const QString& filePath,
LogRotationOption rotation, const MaxSizeBytes &sizeInBytesToRotateAfter, LogRotationOption rotation, const MaxSizeBytes &sizeInBytesToRotateAfter,
const MaxOldLogCount &oldLogsToKeep) const MaxOldLogCount &oldLogsToKeep)
{ {
if (EnableLogRotation == rotation) { if (EnableLogRotation == rotation) {
QScopedPointer<SizeRotationStrategy> logRotation(new SizeRotationStrategy); QScopedPointer<SizeRotationStrategy> logRotation(new SizeRotationStrategy);
logRotation->setMaximumSizeInBytes(sizeInBytesToRotateAfter.size); logRotation->setMaximumSizeInBytes(sizeInBytesToRotateAfter.size);
logRotation->setBackupCount(oldLogsToKeep.count); logRotation->setBackupCount(oldLogsToKeep.count);
return DestinationPtr(new FileDestination(filePath, RotationStrategyPtr(logRotation.take()))); return DestinationPtr(new FileDestination(filePath, RotationStrategyPtr(logRotation.take())));
} }
return DestinationPtr(new FileDestination(filePath, RotationStrategyPtr(new NullRotationStrategy))); return DestinationPtr(new FileDestination(filePath, RotationStrategyPtr(new NullRotationStrategy)));
} }
DestinationPtr DestinationFactory::MakeDebugOutputDestination() DestinationPtr DestinationFactory::MakeDebugOutputDestination()
{ {
return DestinationPtr(new DebugOutputDestination); return DestinationPtr(new DebugOutputDestination);
} }
DestinationPtr DestinationFactory::MakeFunctorDestination(QsLogging::Destination::LogFunction f) DestinationPtr DestinationFactory::MakeFunctorDestination(QsLogging::Destination::LogFunction f)
{ {
return DestinationPtr(new FunctorDestination(f)); return DestinationPtr(new FunctorDestination(f));
} }
DestinationPtr DestinationFactory::MakeFunctorDestination(QObject *receiver, const char *member) DestinationPtr DestinationFactory::MakeFunctorDestination(QObject *receiver, const char *member)
{ {
return DestinationPtr(new FunctorDestination(receiver, member)); return DestinationPtr(new FunctorDestination(receiver, member));
} }
} // end namespace } // end namespace

View File

@ -1,99 +1,99 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef QSLOGDEST_H #ifndef QSLOGDEST_H
#define QSLOGDEST_H #define QSLOGDEST_H
#include "QsLogLevel.h" #include "QsLogLevel.h"
#include <QSharedPointer> #include <QSharedPointer>
#include <QtGlobal> #include <QtGlobal>
class QString; class QString;
class QObject; class QObject;
#ifdef QSLOG_IS_SHARED_LIBRARY #ifdef QSLOG_IS_SHARED_LIBRARY
#define QSLOG_SHARED_OBJECT Q_DECL_EXPORT #define QSLOG_SHARED_OBJECT Q_DECL_EXPORT
#elif QSLOG_IS_SHARED_LIBRARY_IMPORT #elif QSLOG_IS_SHARED_LIBRARY_IMPORT
#define QSLOG_SHARED_OBJECT Q_DECL_IMPORT #define QSLOG_SHARED_OBJECT Q_DECL_IMPORT
#else #else
#define QSLOG_SHARED_OBJECT #define QSLOG_SHARED_OBJECT
#endif #endif
namespace QsLogging namespace QsLogging
{ {
class QSLOG_SHARED_OBJECT Destination class QSLOG_SHARED_OBJECT Destination
{ {
public: public:
typedef void (*LogFunction)(const QString &message, Level level); typedef void (*LogFunction)(const QString &message, Level level);
public: public:
virtual ~Destination(); virtual ~Destination();
virtual void write(const QString& message, Level level) = 0; virtual void write(const QString& message, Level level) = 0;
virtual bool isValid() = 0; // returns whether the destination was created correctly virtual bool isValid() = 0; // returns whether the destination was created correctly
}; };
typedef QSharedPointer<Destination> DestinationPtr; typedef QSharedPointer<Destination> DestinationPtr;
// a series of "named" paramaters, to make the file destination creation more readable // a series of "named" paramaters, to make the file destination creation more readable
enum LogRotationOption enum LogRotationOption
{ {
DisableLogRotation = 0, DisableLogRotation = 0,
EnableLogRotation = 1 EnableLogRotation = 1
}; };
struct QSLOG_SHARED_OBJECT MaxSizeBytes struct QSLOG_SHARED_OBJECT MaxSizeBytes
{ {
MaxSizeBytes() : size(0) {} MaxSizeBytes() : size(0) {}
explicit MaxSizeBytes(qint64 size_) : size(size_) {} explicit MaxSizeBytes(qint64 size_) : size(size_) {}
qint64 size; qint64 size;
}; };
struct QSLOG_SHARED_OBJECT MaxOldLogCount struct QSLOG_SHARED_OBJECT MaxOldLogCount
{ {
MaxOldLogCount() : count(0) {} MaxOldLogCount() : count(0) {}
explicit MaxOldLogCount(int count_) : count(count_) {} explicit MaxOldLogCount(int count_) : count(count_) {}
int count; int count;
}; };
//! Creates logging destinations/sinks. The caller shares ownership of the destinations with the logger. //! Creates logging destinations/sinks. The caller shares ownership of the destinations with the logger.
//! After being added to a logger, the caller can discard the pointers. //! After being added to a logger, the caller can discard the pointers.
class QSLOG_SHARED_OBJECT DestinationFactory class QSLOG_SHARED_OBJECT DestinationFactory
{ {
public: public:
static DestinationPtr MakeFileDestination(const QString& filePath, static DestinationPtr MakeFileDestination(const QString& filePath,
LogRotationOption rotation = DisableLogRotation, LogRotationOption rotation = DisableLogRotation,
const MaxSizeBytes &sizeInBytesToRotateAfter = MaxSizeBytes(), const MaxSizeBytes &sizeInBytesToRotateAfter = MaxSizeBytes(),
const MaxOldLogCount &oldLogsToKeep = MaxOldLogCount()); const MaxOldLogCount &oldLogsToKeep = MaxOldLogCount());
static DestinationPtr MakeDebugOutputDestination(); static DestinationPtr MakeDebugOutputDestination();
// takes a pointer to a function // takes a pointer to a function
static DestinationPtr MakeFunctorDestination(Destination::LogFunction f); static DestinationPtr MakeFunctorDestination(Destination::LogFunction f);
// takes a QObject + signal/slot // takes a QObject + signal/slot
static DestinationPtr MakeFunctorDestination(QObject *receiver, const char *member); static DestinationPtr MakeFunctorDestination(QObject *receiver, const char *member);
}; };
} // end namespace } // end namespace
#endif // QSLOGDEST_H #endif // QSLOGDEST_H

View File

@ -1,55 +1,55 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#include "QsLogDestConsole.h" #include "QsLogDestConsole.h"
#include <QString> #include <QString>
#include <QtGlobal> #include <QtGlobal>
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
void QsDebugOutput::output( const QString& message ) void QsDebugOutput::output( const QString& message )
{ {
OutputDebugStringW(reinterpret_cast<const WCHAR*>(message.utf16())); OutputDebugStringW(reinterpret_cast<const WCHAR*>(message.utf16()));
OutputDebugStringW(L"\n"); OutputDebugStringW(L"\n");
} }
#elif defined(Q_OS_UNIX) #elif defined(Q_OS_UNIX)
#include <cstdio> #include <cstdio>
void QsDebugOutput::output( const QString& message ) void QsDebugOutput::output( const QString& message )
{ {
fprintf(stderr, "%s\n", qPrintable(message)); fprintf(stderr, "%s\n", qPrintable(message));
fflush(stderr); fflush(stderr);
} }
#endif #endif
void QsLogging::DebugOutputDestination::write(const QString& message, Level) void QsLogging::DebugOutputDestination::write(const QString& message, Level)
{ {
QsDebugOutput::output(message); QsDebugOutput::output(message);
} }
bool QsLogging::DebugOutputDestination::isValid() bool QsLogging::DebugOutputDestination::isValid()
{ {
return true; return true;
} }

View File

@ -1,52 +1,52 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef QSLOGDESTCONSOLE_H #ifndef QSLOGDESTCONSOLE_H
#define QSLOGDESTCONSOLE_H #define QSLOGDESTCONSOLE_H
#include "QsLogDest.h" #include "QsLogDest.h"
class QString; class QString;
class QsDebugOutput class QsDebugOutput
{ {
public: public:
static void output(const QString& a_message); static void output(const QString& a_message);
}; };
namespace QsLogging namespace QsLogging
{ {
// debugger sink // debugger sink
class DebugOutputDestination : public Destination class DebugOutputDestination : public Destination
{ {
public: public:
virtual void write(const QString& message, Level level); virtual void write(const QString& message, Level level);
virtual bool isValid(); virtual bool isValid();
}; };
} }
#endif // QSLOGDESTCONSOLE_H #endif // QSLOGDESTCONSOLE_H

View File

@ -1,45 +1,45 @@
// Copyright (c) 2013, Razvan Petru // Copyright (c) 2013, Razvan Petru
// All rights reserved. // All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this // * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. // list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this // * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other // list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// * The name of the contributors may not be used to endorse or promote products // * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission. // derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE. // OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef QSLOGLEVEL_H #ifndef QSLOGLEVEL_H
#define QSLOGLEVEL_H #define QSLOGLEVEL_H
namespace QsLogging namespace QsLogging
{ {
enum Level enum Level
{ {
TraceLevel = 0, TraceLevel = 0,
DebugLevel, DebugLevel,
InfoLevel, InfoLevel,
WarnLevel, WarnLevel,
ErrorLevel, ErrorLevel,
FatalLevel, FatalLevel,
OffLevel OffLevel
}; };
} }
#endif // QSLOGLEVEL_H #endif // QSLOGLEVEL_H

View File

@ -1,197 +1,197 @@
#include "bookmarks_dialog.h" #include "bookmarks_dialog.h"
#include <QGridLayout> #include <QGridLayout>
#include <QLabel> #include <QLabel>
#include <QApplication> #include <QApplication>
#include <QDesktopWidget> #include <QDesktopWidget>
#include <QFrame> #include <QFrame>
#include <QImage> #include <QImage>
#include "bookmarks.h" #include "bookmarks.h"
BookmarksDialog::BookmarksDialog(QWidget * parent) BookmarksDialog::BookmarksDialog(QWidget * parent)
:QDialog(parent) :QDialog(parent)
{ {
setModal(true); setModal(true);
//animation = new QPropertyAnimation(this,"windowOpacity"); //animation = new QPropertyAnimation(this,"windowOpacity");
//animation->setDuration(150); //animation->setDuration(150);
QHBoxLayout * layout = new QHBoxLayout(); QHBoxLayout * layout = new QHBoxLayout();
//bookmarks //bookmarks
QGridLayout * bookmarksL = new QGridLayout(); QGridLayout * bookmarksL = new QGridLayout();
pages.push_back(new QLabel(tr("Lastest Page"))); pages.push_back(new QLabel(tr("Lastest Page")));
for(int i=0;i<3;i++) for(int i=0;i<3;i++)
pages.push_back(new QLabel("-")); pages.push_back(new QLabel("-"));
QString labelsStyle = "QLabel {color:white;}"; QString labelsStyle = "QLabel {color:white;}";
foreach(QLabel * label,pages) foreach(QLabel * label,pages)
{ {
label->setStyleSheet(labelsStyle); label->setStyleSheet(labelsStyle);
} }
int heightDesktopResolution = QApplication::desktop()->screenGeometry().height(); int heightDesktopResolution = QApplication::desktop()->screenGeometry().height();
int height,width; int height,width;
height = heightDesktopResolution*0.50; height = heightDesktopResolution*0.50;
width = height*0.65; width = height*0.65;
coverSize = QSize(width,height); coverSize = QSize(width,height);
for(int i=0;i<4;i++) for(int i=0;i<4;i++)
{ {
QLabel * l = new QLabel(); QLabel * l = new QLabel();
l->setFixedSize(coverSize); l->setFixedSize(coverSize);
l->setScaledContents(false); l->setScaledContents(false);
//l->setPixmap(QPixmap(":/images/notCover.png")); //l->setPixmap(QPixmap(":/images/notCover.png"));
l->installEventFilter(this); l->installEventFilter(this);
images.push_back(l); images.push_back(l);
} }
for(int i=0;i<3;i++) for(int i=0;i<3;i++)
bookmarksL->addWidget(pages.at(i+1),0,i,Qt::AlignCenter); bookmarksL->addWidget(pages.at(i+1),0,i,Qt::AlignCenter);
for(int i=0;i<3;i++) for(int i=0;i<3;i++)
bookmarksL->addWidget(images.at(i+1),1,i,Qt::AlignCenter); bookmarksL->addWidget(images.at(i+1),1,i,Qt::AlignCenter);
//last page //last page
QGridLayout * lp = new QGridLayout(); QGridLayout * lp = new QGridLayout();
lp->addWidget(pages.at(0),0,0,Qt::AlignCenter); lp->addWidget(pages.at(0),0,0,Qt::AlignCenter);
lp->addWidget(images.at(0),1,0,Qt::AlignCenter); lp->addWidget(images.at(0),1,0,Qt::AlignCenter);
layout->addLayout(bookmarksL); layout->addLayout(bookmarksL);
QFrame *f = new QFrame( this ); QFrame *f = new QFrame( this );
f->setFrameStyle( QFrame::VLine | QFrame::Sunken ); f->setFrameStyle( QFrame::VLine | QFrame::Sunken );
layout->addWidget(f); layout->addWidget(f);
layout->addLayout(lp); layout->addLayout(lp);
QHBoxLayout * buttons = new QHBoxLayout(); QHBoxLayout * buttons = new QHBoxLayout();
cancel = new QPushButton(tr("Close")); cancel = new QPushButton(tr("Close"));
cancel->setFlat(true); cancel->setFlat(true);
connect(cancel,SIGNAL(clicked()),this,SLOT(hide())); connect(cancel,SIGNAL(clicked()),this,SLOT(hide()));
buttons->addStretch(); buttons->addStretch();
buttons->addWidget(cancel); buttons->addWidget(cancel);
cancel->setStyleSheet("QPushButton {border: 1px solid #242424; background: #2e2e2e; color:white; padding: 5px 26px 5px 26px; font-size:12px;font-family:Arial; font-weight:bold;}"); cancel->setStyleSheet("QPushButton {border: 1px solid #242424; background: #2e2e2e; color:white; padding: 5px 26px 5px 26px; font-size:12px;font-family:Arial; font-weight:bold;}");
QVBoxLayout * l = new QVBoxLayout(); QVBoxLayout * l = new QVBoxLayout();
l->addWidget(new QLabel("<font color=\"#FFFFFF\">"+tr("Click on any image to go to the bookmark")+"</font>"),0,Qt::AlignCenter); l->addWidget(new QLabel("<font color=\"#FFFFFF\">"+tr("Click on any image to go to the bookmark")+"</font>"),0,Qt::AlignCenter);
l->addLayout(layout); l->addLayout(layout);
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
l->addLayout(buttons); l->addLayout(buttons);
#endif #endif
QPalette Pal(palette()); QPalette Pal(palette());
// set black background // set black background
Pal.setColor(QPalette::Background, QColor("#454545")); Pal.setColor(QPalette::Background, QColor("#454545"));
this->setAutoFillBackground(true); this->setAutoFillBackground(true);
this->setPalette(Pal); this->setPalette(Pal);
setLayout(l); setLayout(l);
} }
void BookmarksDialog::setBookmarks(const Bookmarks & bm) void BookmarksDialog::setBookmarks(const Bookmarks & bm)
{ {
lastPage = bm.getLastPage(); lastPage = bm.getLastPage();
if (lastPage > 0) if (lastPage > 0)
{ {
QPixmap p = QPixmap::fromImage(bm.getLastPagePixmap()); QPixmap p = QPixmap::fromImage(bm.getLastPagePixmap());
if(p.isNull()) if(p.isNull())
{ {
images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
images.at(0)->setText(tr("Loading...")); images.at(0)->setText(tr("Loading..."));
} }
else else
{ {
images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignBottom); images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignBottom);
images.at(0)->setPixmap(p.scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation)); images.at(0)->setPixmap(p.scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation));
} }
} }
else else
{ {
images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); images.at(0)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
images.at(0)->setPixmap(QPixmap(":/images/notCover.png").scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation)); images.at(0)->setPixmap(QPixmap(":/images/notCover.png").scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation));
} }
QList<int> l = bm.getBookmarkPages(); QList<int> l = bm.getBookmarkPages();
int s = l.count(); int s = l.count();
for(int i=0;i<s;i++) for(int i=0;i<s;i++)
{ {
pages.at(i+1)->setText(QString::number(l.at(i)+1)); pages.at(i+1)->setText(QString::number(l.at(i)+1));
QPixmap p = QPixmap::fromImage(bm.getBookmarkPixmap(l.at(i))); QPixmap p = QPixmap::fromImage(bm.getBookmarkPixmap(l.at(i)));
if(p.isNull()) if(p.isNull())
{ {
images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
images.at(i+1)->setText(tr("Loading...")); images.at(i+1)->setText(tr("Loading..."));
} }
else else
{ {
images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignBottom); images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignBottom);
images.at(i+1)->setPixmap(p.scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation)); images.at(i+1)->setPixmap(p.scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation));
} }
} }
for(int i=s;i<3;i++) for(int i=s;i<3;i++)
{ {
pages.at(i+1)->setText("-"); pages.at(i+1)->setText("-");
images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); images.at(i+1)->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
images.at(i+1)->setPixmap(QPixmap(":/images/notCover.png").scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation)); images.at(i+1)->setPixmap(QPixmap(":/images/notCover.png").scaled(coverSize,Qt::KeepAspectRatio,Qt::SmoothTransformation));
} }
} }
bool BookmarksDialog::eventFilter(QObject *obj, QEvent *event) bool BookmarksDialog::eventFilter(QObject *obj, QEvent *event)
{ {
if(event->type() == QEvent::MouseButtonPress) if(event->type() == QEvent::MouseButtonPress)
{ {
if (obj == images.at(0)) if (obj == images.at(0))
{ {
emit(goToPage(lastPage)); emit(goToPage(lastPage));
close(); close();
event->accept(); event->accept();
} }
for(int i=1;i<=3;i++) for(int i=1;i<=3;i++)
{ {
if(obj == images.at(i)) if(obj == images.at(i))
{ {
bool b; bool b;
int page = pages.at(i)->text().toInt(&b)-1; int page = pages.at(i)->text().toInt(&b)-1;
if(b) if(b)
{ {
emit(goToPage(page)); emit(goToPage(page));
close(); close();
} }
event->accept(); event->accept();
} }
} }
} }
// pass the event on to the parent class // pass the event on to the parent class
return QDialog::eventFilter(obj, event); return QDialog::eventFilter(obj, event);
} }
void BookmarksDialog::keyPressEvent(QKeyEvent * event) void BookmarksDialog::keyPressEvent(QKeyEvent * event)
{ {
if(event->key() == Qt::Key_M) if(event->key() == Qt::Key_M)
hide(); hide();
} }
/* /*
void BookmarksDialog::show() void BookmarksDialog::show()
{ {
QDialog::show(); QDialog::show();
disconnect(animation,SIGNAL(finished()),this,SLOT(close())); disconnect(animation,SIGNAL(finished()),this,SLOT(close()));
animation->setStartValue(0); animation->setStartValue(0);
animation->setEndValue(1); animation->setEndValue(1);
animation->start(); animation->start();
} }
void BookmarksDialog::hide() void BookmarksDialog::hide()
{ {
connect(animation,SIGNAL(finished()),this,SLOT(close())); connect(animation,SIGNAL(finished()),this,SLOT(close()));
animation->setStartValue(1); animation->setStartValue(1);
animation->setEndValue(0); animation->setEndValue(0);
animation->start(); animation->start();
}*/ }*/

View File

@ -1,45 +1,45 @@
#ifndef __BOOKMARKS_DIALOG_H #ifndef __BOOKMARKS_DIALOG_H
#define __BOOKMARKS_DIALOG_H #define __BOOKMARKS_DIALOG_H
#include <QWidget> #include <QWidget>
#include <QDialog> #include <QDialog>
#include <QLabel> #include <QLabel>
#include <QPushButton> #include <QPushButton>
#include <QEvent> #include <QEvent>
#include <QKeyEvent> #include <QKeyEvent>
#include <QPropertyAnimation> #include <QPropertyAnimation>
#include "bookmarks.h" #include "bookmarks.h"
class BookmarksDialog : public QDialog class BookmarksDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
protected: protected:
QList<QLabel *> pages; QList<QLabel *> pages;
QList<QLabel *> images; QList<QLabel *> images;
int lastPage; int lastPage;
QPushButton * accept; QPushButton * accept;
QPushButton * cancel; QPushButton * cancel;
QSize coverSize; QSize coverSize;
bool eventFilter(QObject *obj, QEvent *event); bool eventFilter(QObject *obj, QEvent *event);
void keyPressEvent(QKeyEvent * event); void keyPressEvent(QKeyEvent * event);
//QPropertyAnimation * animation; //QPropertyAnimation * animation;
public: public:
BookmarksDialog(QWidget * parent = 0); BookmarksDialog(QWidget * parent = 0);
public slots: public slots:
void setBookmarks(const Bookmarks & bookmarks); void setBookmarks(const Bookmarks & bookmarks);
//void show(); //void show();
//void hide(); //void hide();
signals: signals:
void goToPage(unsigned int page); void goToPage(unsigned int page);
}; };
#endif // BOOKMARKS_DIALOG_H #endif // BOOKMARKS_DIALOG_H

View File

@ -1,79 +1,79 @@
#include "configuration.h" #include "configuration.h"
#include <QFile> #include <QFile>
#include <QFile> #include <QFile>
#include <QTextStream> #include <QTextStream>
#include <QCoreApplication> #include <QCoreApplication>
#include <QStringList> #include <QStringList>
#include <QMessageBox> #include <QMessageBox>
#include "yacreader_global.h" #include "yacreader_global.h"
Configuration::Configuration() Configuration::Configuration()
{ {
//read configuration //read configuration
//load("/YACReader.conf"); //load("/YACReader.conf");
} }
QSettings *Configuration::getSettings() QSettings *Configuration::getSettings()
{ {
return settings; return settings;
} }
/*Configuration::Configuration(const Configuration & conf) /*Configuration::Configuration(const Configuration & conf)
{ {
//nothing //nothing
}*/ }*/
void Configuration::load(QSettings * settings) void Configuration::load(QSettings * settings)
{ {
this->settings = settings; this->settings = settings;
//TODO set defaults //TODO set defaults
if(!settings->contains(PATH)) if(!settings->contains(PATH))
settings->setValue(PATH,"."); settings->setValue(PATH,".");
if(!settings->contains(GO_TO_FLOW_SIZE)) if(!settings->contains(GO_TO_FLOW_SIZE))
settings->setValue(GO_TO_FLOW_SIZE,QSize(126,200)); settings->setValue(GO_TO_FLOW_SIZE,QSize(126,200));
if(!settings->contains(MAG_GLASS_SIZE)) if(!settings->contains(MAG_GLASS_SIZE))
settings->setValue(MAG_GLASS_SIZE,QSize(350,175)); settings->setValue(MAG_GLASS_SIZE,QSize(350,175));
if(!settings->contains(ZOOM_LEVEL)) if(!settings->contains(ZOOM_LEVEL))
settings->setValue(MAG_GLASS_SIZE,QSize(350,175)); settings->setValue(MAG_GLASS_SIZE,QSize(350,175));
if(!settings->contains(FLOW_TYPE)) if(!settings->contains(FLOW_TYPE))
settings->setValue(FLOW_TYPE,0); settings->setValue(FLOW_TYPE,0);
if(!settings->contains(FULLSCREEN)) if(!settings->contains(FULLSCREEN))
settings->setValue(FULLSCREEN,false); settings->setValue(FULLSCREEN,false);
if(!settings->contains(Y_WINDOW_SIZE)) if(!settings->contains(Y_WINDOW_SIZE))
settings->setValue(Y_WINDOW_SIZE,QSize(0,0)); settings->setValue(Y_WINDOW_SIZE,QSize(0,0));
if(!settings->contains(MAXIMIZED)) if(!settings->contains(MAXIMIZED))
settings->setValue(MAXIMIZED,false); settings->setValue(MAXIMIZED,false);
if(!settings->contains(DOUBLE_PAGE)) if(!settings->contains(DOUBLE_PAGE))
settings->setValue(DOUBLE_PAGE,false); settings->setValue(DOUBLE_PAGE,false);
if(!settings->contains(BACKGROUND_COLOR)) if(!settings->contains(BACKGROUND_COLOR))
settings->setValue(BACKGROUND_COLOR,QColor(40,40,40)); settings->setValue(BACKGROUND_COLOR,QColor(40,40,40));
if(!settings->contains(ALWAYS_ON_TOP)) if(!settings->contains(ALWAYS_ON_TOP))
settings->setValue(ALWAYS_ON_TOP,false); settings->setValue(ALWAYS_ON_TOP,false);
if(!settings->contains(SHOW_TOOLBARS)) if(!settings->contains(SHOW_TOOLBARS))
settings->setValue(SHOW_TOOLBARS, true); settings->setValue(SHOW_TOOLBARS, true);
if(!settings->contains(QUICK_NAVI_MODE)) if(!settings->contains(QUICK_NAVI_MODE))
settings->setValue(QUICK_NAVI_MODE, false); settings->setValue(QUICK_NAVI_MODE, false);
//old fit stuff //old fit stuff
/*if(!settings->contains(FIT)) /*if(!settings->contains(FIT))
settings->setValue(FIT,false); settings->setValue(FIT,false);
if(!settings->contains(FIT_TO_WIDTH_RATIO)) if(!settings->contains(FIT_TO_WIDTH_RATIO))
settings->setValue(FIT_TO_WIDTH_RATIO,1); settings->setValue(FIT_TO_WIDTH_RATIO,1);
if(!settings->contains(ADJUST_TO_FULL_SIZE)) if(!settings->contains(ADJUST_TO_FULL_SIZE))
settings->setValue(ADJUST_TO_FULL_SIZE,false); settings->setValue(ADJUST_TO_FULL_SIZE,false);
*/ */
} }
void Configuration::updateOpenRecentList (QString path) void Configuration::updateOpenRecentList (QString path)
{ {
QStringList list = openRecentList(); QStringList list = openRecentList();
list.removeAll(path); list.removeAll(path);
list.prepend(path); list.prepend(path);
//TODO: Make list lenght configurable //TODO: Make list lenght configurable
while (list.length() > getOpenRecentSize()) while (list.length() > getOpenRecentSize())
{ {
list.removeLast(); list.removeLast();
} }
settings->setValue("recentFiles", list); settings->setValue("recentFiles", list);
} }

View File

@ -1,117 +1,117 @@
#ifndef __CONFIGURATION_H #ifndef __CONFIGURATION_H
#define __CONFIGURATION_H #define __CONFIGURATION_H
#include <QString> #include <QString>
#include <QSize> #include <QSize>
#include <QObject> #include <QObject>
#include <QPoint> #include <QPoint>
#include <QColor> #include <QColor>
#include <QSettings> #include <QSettings>
#include <QDate> #include <QDate>
#include "yacreader_global_gui.h" #include "yacreader_global_gui.h"
#define CONF_FILE_PATH "." #define CONF_FILE_PATH "."
#define SLIDE_ASPECT_RATIO 1.585 #define SLIDE_ASPECT_RATIO 1.585
using namespace YACReader; using namespace YACReader;
class Configuration : public QObject class Configuration : public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
QSettings * settings; QSettings * settings;
QString defaultPath; QString defaultPath;
//configuration properties //configuration properties
QSize magnifyingGlassSize; QSize magnifyingGlassSize;
QSize gotoSlideSize; QSize gotoSlideSize;
float zoomLevel; float zoomLevel;
bool adjustToWidth; bool adjustToWidth;
bool fullScreen; bool fullScreen;
FlowType flowType; FlowType flowType;
float fitToWidthRatio; float fitToWidthRatio;
QPoint windowPos; QPoint windowPos;
QSize windowSize; QSize windowSize;
bool maximized; bool maximized;
bool doublePage; bool doublePage;
bool doubleMangaPage; bool doubleMangaPage;
bool alwaysOnTop; bool alwaysOnTop;
bool adjustToFullSize; bool adjustToFullSize;
QColor backgroundColor; QColor backgroundColor;
Configuration(); Configuration();
//Configuration(const Configuration & conf); //Configuration(const Configuration & conf);
void load(const QString & path = CONF_FILE_PATH); void load(const QString & path = CONF_FILE_PATH);
public: public:
static Configuration & getConfiguration() static Configuration & getConfiguration()
{ {
static Configuration configuration; static Configuration configuration;
return configuration; return configuration;
}; };
QSettings *getSettings(); QSettings *getSettings();
void load(QSettings * settings); void load(QSettings * settings);
QString getDefaultPath() { return settings->value(PATH).toString(); } QString getDefaultPath() { return settings->value(PATH).toString(); }
void setDefaultPath(QString defaultPath){settings->setValue(PATH,defaultPath);} void setDefaultPath(QString defaultPath){settings->setValue(PATH,defaultPath);}
QSize getMagnifyingGlassSize() { return settings->value(MAG_GLASS_SIZE).toSize();} QSize getMagnifyingGlassSize() { return settings->value(MAG_GLASS_SIZE).toSize();}
void setMagnifyingGlassSize(const QSize & mgs) { settings->setValue(MAG_GLASS_SIZE,mgs);} void setMagnifyingGlassSize(const QSize & mgs) { settings->setValue(MAG_GLASS_SIZE,mgs);}
QSize getGotoSlideSize() { return settings->value(GO_TO_FLOW_SIZE).toSize();} QSize getGotoSlideSize() { return settings->value(GO_TO_FLOW_SIZE).toSize();}
void setGotoSlideSize(const QSize & gss) { settings->setValue(GO_TO_FLOW_SIZE,gss);} void setGotoSlideSize(const QSize & gss) { settings->setValue(GO_TO_FLOW_SIZE,gss);}
float getZoomLevel() { return settings->value(ZOOM_LEVEL).toFloat();} float getZoomLevel() { return settings->value(ZOOM_LEVEL).toFloat();}
void setZoomLevel(float zl) { settings->setValue(ZOOM_LEVEL,zl);} void setZoomLevel(float zl) { settings->setValue(ZOOM_LEVEL,zl);}
//Unified enum based fitmode //Unified enum based fitmode
YACReader::FitMode getFitMode() { return static_cast<YACReader::FitMode>(settings->value(FITMODE, YACReader::FitMode::FullPage).toInt()); } YACReader::FitMode getFitMode() { return static_cast<YACReader::FitMode>(settings->value(FITMODE, YACReader::FitMode::FullPage).toInt()); }
void setFitMode ( YACReader::FitMode fitMode ){ settings->setValue(FITMODE, static_cast<int>(fitMode)); } void setFitMode ( YACReader::FitMode fitMode ){ settings->setValue(FITMODE, static_cast<int>(fitMode)); }
//openRecent //openRecent
int getOpenRecentSize() { return settings->value("recentSize", 25).toInt();} int getOpenRecentSize() { return settings->value("recentSize", 25).toInt();}
QStringList openRecentList() { return settings->value("recentFiles").toStringList(); } QStringList openRecentList() { return settings->value("recentFiles").toStringList(); }
void updateOpenRecentList (QString path); void updateOpenRecentList (QString path);
void clearOpenRecentList() { settings->remove("recentFiles"); } void clearOpenRecentList() { settings->remove("recentFiles"); }
//Old fitmodes //Old fitmodes
/* /*
bool getAdjustToWidth() {return settings->value(FIT).toBool();} bool getAdjustToWidth() {return settings->value(FIT).toBool();}
void setAdjustToWidth(bool atw=true) {settings->setValue(FIT,atw);} void setAdjustToWidth(bool atw=true) {settings->setValue(FIT,atw);}
float getFitToWidthRatio(){return settings->value(FIT_TO_WIDTH_RATIO).toFloat();} float getFitToWidthRatio(){return settings->value(FIT_TO_WIDTH_RATIO).toFloat();}
void setFitToWidthRatio(float r){settings->setValue(FIT_TO_WIDTH_RATIO,r);} void setFitToWidthRatio(float r){settings->setValue(FIT_TO_WIDTH_RATIO,r);}
bool getAdjustToFullSize(){return settings->value(ADJUST_TO_FULL_SIZE).toBool();} bool getAdjustToFullSize(){return settings->value(ADJUST_TO_FULL_SIZE).toBool();}
void setAdjustToFullSize(bool b){settings->setValue(ADJUST_TO_FULL_SIZE,b);} void setAdjustToFullSize(bool b){settings->setValue(ADJUST_TO_FULL_SIZE,b);}
*/ */
FlowType getFlowType(){return (FlowType)settings->value(FLOW_TYPE_SW).toInt();} FlowType getFlowType(){return (FlowType)settings->value(FLOW_TYPE_SW).toInt();}
void setFlowType(FlowType type){settings->setValue(FLOW_TYPE_SW,type);} void setFlowType(FlowType type){settings->setValue(FLOW_TYPE_SW,type);}
bool getFullScreen(){return settings->value(FULLSCREEN).toBool();} bool getFullScreen(){return settings->value(FULLSCREEN).toBool();}
void setFullScreen(bool f){settings->setValue(FULLSCREEN,f);} void setFullScreen(bool f){settings->setValue(FULLSCREEN,f);}
QPoint getPos(){return settings->value(Y_WINDOW_POS).toPoint();} QPoint getPos(){return settings->value(Y_WINDOW_POS).toPoint();}
void setPos(QPoint p){settings->setValue(Y_WINDOW_POS,p);} void setPos(QPoint p){settings->setValue(Y_WINDOW_POS,p);}
QSize getSize(){return settings->value(Y_WINDOW_SIZE).toSize();} QSize getSize(){return settings->value(Y_WINDOW_SIZE).toSize();}
void setSize(QSize s){settings->setValue(Y_WINDOW_SIZE,s);} void setSize(QSize s){settings->setValue(Y_WINDOW_SIZE,s);}
bool getMaximized(){return settings->value(MAXIMIZED).toBool();} bool getMaximized(){return settings->value(MAXIMIZED).toBool();}
void setMaximized(bool b){settings->setValue(MAXIMIZED,b);} void setMaximized(bool b){settings->setValue(MAXIMIZED,b);}
bool getDoublePage(){return settings->value(DOUBLE_PAGE).toBool();} bool getDoublePage(){return settings->value(DOUBLE_PAGE).toBool();}
void setDoublePage(bool b){settings->setValue(DOUBLE_PAGE,b);} void setDoublePage(bool b){settings->setValue(DOUBLE_PAGE,b);}
bool getDoubleMangaPage(){return settings->value(DOUBLE_MANGA_PAGE).toBool();} bool getDoubleMangaPage(){return settings->value(DOUBLE_MANGA_PAGE).toBool();}
void setDoubleMangaPage(bool b){settings->setValue(DOUBLE_MANGA_PAGE,b);} void setDoubleMangaPage(bool b){settings->setValue(DOUBLE_MANGA_PAGE,b);}
QColor getBackgroundColor(){return settings->value(BACKGROUND_COLOR).value<QColor>();} QColor getBackgroundColor(){return settings->value(BACKGROUND_COLOR).value<QColor>();}
void setBackgroundColor(const QColor& color){settings->value(BACKGROUND_COLOR,color);} void setBackgroundColor(const QColor& color){settings->value(BACKGROUND_COLOR,color);}
bool getAlwaysOnTop(){return settings->value(ALWAYS_ON_TOP).toBool();} bool getAlwaysOnTop(){return settings->value(ALWAYS_ON_TOP).toBool();}
void setAlwaysOnTop(bool b){ settings->setValue(ALWAYS_ON_TOP,b);} void setAlwaysOnTop(bool b){ settings->setValue(ALWAYS_ON_TOP,b);}
bool getShowToolbars(){return settings->value(SHOW_TOOLBARS).toBool();} bool getShowToolbars(){return settings->value(SHOW_TOOLBARS).toBool();}
void setShowToolbars(bool b){settings->setValue(SHOW_TOOLBARS,b);} void setShowToolbars(bool b){settings->setValue(SHOW_TOOLBARS,b);}
bool getShowInformation(){return settings->value(SHOW_INFO,false).toBool();} bool getShowInformation(){return settings->value(SHOW_INFO,false).toBool();}
void setShowInformation(bool b){settings->setValue(SHOW_INFO,b);} void setShowInformation(bool b){settings->setValue(SHOW_INFO,b);}
QDate getLastVersionCheck(){return settings->value(LAST_VERSION_CHECK).toDate();} QDate getLastVersionCheck(){return settings->value(LAST_VERSION_CHECK).toDate();}
void setLastVersionCheck(const QDate & date){ settings->setValue(LAST_VERSION_CHECK,date);} void setLastVersionCheck(const QDate & date){ settings->setValue(LAST_VERSION_CHECK,date);}
int getNumDaysBetweenVersionChecks() {return settings->value(NUM_DAYS_BETWEEN_VERSION_CHECKS,1).toInt();} int getNumDaysBetweenVersionChecks() {return settings->value(NUM_DAYS_BETWEEN_VERSION_CHECKS,1).toInt();}
void setNumDaysBetweenVersionChecks(int days) {return settings->setValue(NUM_DAYS_BETWEEN_VERSION_CHECKS,days);} void setNumDaysBetweenVersionChecks(int days) {return settings->setValue(NUM_DAYS_BETWEEN_VERSION_CHECKS,days);}
bool getQuickNaviMode(){return settings->value(QUICK_NAVI_MODE).toBool();} bool getQuickNaviMode(){return settings->value(QUICK_NAVI_MODE).toBool();}
bool getDisableShowOnMouseOver(){return settings->value(DISABLE_MOUSE_OVER_GOTO_FLOW).toBool();} bool getDisableShowOnMouseOver(){return settings->value(DISABLE_MOUSE_OVER_GOTO_FLOW).toBool();}
}; };
#endif #endif

View File

@ -1,84 +1,84 @@
#include "goto_dialog.h" #include "goto_dialog.h"
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QIntValidator> #include <QIntValidator>
GoToDialog::GoToDialog(QWidget * parent) GoToDialog::GoToDialog(QWidget * parent)
:QDialog(parent) :QDialog(parent)
{ {
setupUI(); setupUI();
} }
void GoToDialog::setupUI() void GoToDialog::setupUI()
{ {
textLabel = new QLabel(tr("Page : ")); textLabel = new QLabel(tr("Page : "));
pageNumber = new QLineEdit; pageNumber = new QLineEdit;
v = new QIntValidator(this); v = new QIntValidator(this);
v->setBottom(1); v->setBottom(1);
pageNumber->setValidator(v); pageNumber->setValidator(v);
textLabel->setBuddy(pageNumber); textLabel->setBuddy(pageNumber);
textLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter); textLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
accept = new QPushButton(tr("Go To")); accept = new QPushButton(tr("Go To"));
connect(accept,SIGNAL(clicked()),this,SLOT(goTo())); connect(accept,SIGNAL(clicked()),this,SLOT(goTo()));
cancel = new QPushButton(tr("Cancel")); cancel = new QPushButton(tr("Cancel"));
connect(cancel,SIGNAL(clicked()),this,SLOT(close())); connect(cancel,SIGNAL(clicked()),this,SLOT(close()));
QHBoxLayout *topLayout = new QHBoxLayout; QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addWidget(textLabel); topLayout->addWidget(textLabel);
topLayout->addWidget(pageNumber); topLayout->addWidget(pageNumber);
QHBoxLayout *bottomLayout = new QHBoxLayout; QHBoxLayout *bottomLayout = new QHBoxLayout;
bottomLayout->addStretch(); bottomLayout->addStretch();
bottomLayout->addWidget(accept); bottomLayout->addWidget(accept);
bottomLayout->addWidget(cancel); bottomLayout->addWidget(cancel);
QVBoxLayout *mainLayout = new QVBoxLayout; QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(numPagesLabel = new QLabel(tr("Total pages : "))); mainLayout->addWidget(numPagesLabel = new QLabel(tr("Total pages : ")));
mainLayout->addLayout(topLayout); mainLayout->addLayout(topLayout);
mainLayout->addStretch(); mainLayout->addStretch();
mainLayout->addLayout(bottomLayout); mainLayout->addLayout(bottomLayout);
QHBoxLayout *imgMainLayout = new QHBoxLayout; QHBoxLayout *imgMainLayout = new QHBoxLayout;
QLabel * imgLabel = new QLabel(); QLabel * imgLabel = new QLabel();
QPixmap p(":/images/goto.png"); QPixmap p(":/images/goto.png");
imgLabel->setPixmap(p); imgLabel->setPixmap(p);
imgMainLayout->addWidget(imgLabel); imgMainLayout->addWidget(imgLabel);
imgMainLayout->addLayout(mainLayout); imgMainLayout->addLayout(mainLayout);
setLayout(imgMainLayout); setLayout(imgMainLayout);
setWindowTitle(tr("Go to...")); setWindowTitle(tr("Go to..."));
setModal (true); setModal (true);
pageNumber->setFocusPolicy(Qt::StrongFocus); pageNumber->setFocusPolicy(Qt::StrongFocus);
pageNumber->setFocus(); pageNumber->setFocus();
} }
void GoToDialog::goTo() void GoToDialog::goTo()
{ {
unsigned int page = pageNumber->text().toInt(); unsigned int page = pageNumber->text().toInt();
pageNumber->clear(); pageNumber->clear();
if(page >= 1) if(page >= 1)
emit(goToPage(page-1)); emit(goToPage(page-1));
close(); close();
} }
void GoToDialog::setNumPages(unsigned int numPages) void GoToDialog::setNumPages(unsigned int numPages)
{ {
numPagesLabel->setText(tr("Total pages : ")+QString::number(numPages)); numPagesLabel->setText(tr("Total pages : ")+QString::number(numPages));
v->setTop(numPages); v->setTop(numPages);
} }
void GoToDialog::open() void GoToDialog::open()
{ {
pageNumber->setFocus(); pageNumber->setFocus();
QDialog::open(); QDialog::open();
} }

View File

@ -1,32 +1,32 @@
#ifndef __GOTODIALOG_H #ifndef __GOTODIALOG_H
#define __GOTODIALOG_H #define __GOTODIALOG_H
#include <QDialog> #include <QDialog>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QIntValidator> #include <QIntValidator>
class GoToDialog : public QDialog class GoToDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
GoToDialog(QWidget * parent = 0); GoToDialog(QWidget * parent = 0);
private: private:
QLabel * numPagesLabel; QLabel * numPagesLabel;
QLabel * textLabel; QLabel * textLabel;
QLineEdit * pageNumber; QLineEdit * pageNumber;
QIntValidator * v; QIntValidator * v;
QPushButton * accept; QPushButton * accept;
QPushButton * cancel; QPushButton * cancel;
void setupUI(); void setupUI();
public slots: public slots:
void goTo(); void goTo();
void setNumPages(unsigned int numPages); void setNumPages(unsigned int numPages);
void open(); void open();
signals: signals:
void goToPage(unsigned int page); void goToPage(unsigned int page);
}; };
#endif #endif

View File

@ -1,322 +1,322 @@
#include "goto_flow.h" #include "goto_flow.h"
#include "configuration.h" #include "configuration.h"
#include "comic.h" #include "comic.h"
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QSize> #include <QSize>
#include <QImage> #include <QImage>
#include <QLabel> #include <QLabel>
#include <QPushButton> #include <QPushButton>
#include <QMutex> #include <QMutex>
#include <QApplication> #include <QApplication>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QPixmap> #include <QPixmap>
#include <QThread> #include <QThread>
#include <QSize> #include <QSize>
#include <QIntValidator> #include <QIntValidator>
#include <QWaitCondition> #include <QWaitCondition>
#include <QObject> #include <QObject>
#include <QEvent> #include <QEvent>
#include <QLabel> #include <QLabel>
#include "yacreader_flow.h" #include "yacreader_flow.h"
#include "goto_flow_toolbar.h" #include "goto_flow_toolbar.h"
GoToFlow::GoToFlow(QWidget *parent,FlowType flowType) GoToFlow::GoToFlow(QWidget *parent,FlowType flowType)
:GoToFlowWidget(parent),ready(false) :GoToFlowWidget(parent),ready(false)
{ {
updateTimer = new QTimer; updateTimer = new QTimer;
connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateImageData())); connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateImageData()));
worker = new PageLoader(&mutexGoToFlow); worker = new PageLoader(&mutexGoToFlow);
flow = new YACReaderFlow(this,flowType); flow = new YACReaderFlow(this,flowType);
flow->setReflectionEffect(PictureFlow::PlainReflection); flow->setReflectionEffect(PictureFlow::PlainReflection);
imageSize = Configuration::getConfiguration().getGotoSlideSize(); imageSize = Configuration::getConfiguration().getGotoSlideSize();
flow->setSlideSize(imageSize); flow->setSlideSize(imageSize);
connect(flow,SIGNAL(centerIndexChanged(int)),this,SLOT(setPageNumber(int))); connect(flow,SIGNAL(centerIndexChanged(int)),this,SLOT(setPageNumber(int)));
connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(goToPage(unsigned int))); connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(goToPage(unsigned int)));
connect(toolBar,SIGNAL(goTo(unsigned int)),this,SIGNAL(goToPage(unsigned int))); connect(toolBar,SIGNAL(goTo(unsigned int)),this,SIGNAL(goToPage(unsigned int)));
connect(toolBar,SIGNAL(setCenter(unsigned int)),flow,SLOT(showSlide(unsigned int))); connect(toolBar,SIGNAL(setCenter(unsigned int)),flow,SLOT(showSlide(unsigned int)));
mainLayout->addWidget(flow); mainLayout->addWidget(flow);
toolBar->raise(); toolBar->raise();
resize(static_cast<int>(5*imageSize.width()),toolBar->height() + static_cast<int>(imageSize.height()*1.7)); resize(static_cast<int>(5*imageSize.width()),toolBar->height() + static_cast<int>(imageSize.height()*1.7));
this->setCursor(QCursor(Qt::ArrowCursor)); this->setCursor(QCursor(Qt::ArrowCursor));
} }
GoToFlow::~GoToFlow() GoToFlow::~GoToFlow()
{ {
delete flow; delete flow;
delete updateTimer; delete updateTimer;
worker->deleteLater(); worker->deleteLater();
} }
void GoToFlow::keyPressEvent(QKeyEvent *event) void GoToFlow::keyPressEvent(QKeyEvent *event)
{ {
switch (event->key()) switch (event->key())
{ {
case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up:
QApplication::sendEvent(flow,event); QApplication::sendEvent(flow,event);
return; return;
default: default:
break; break;
} }
GoToFlowWidget::keyPressEvent(event); GoToFlowWidget::keyPressEvent(event);
} }
void GoToFlow::resizeEvent(QResizeEvent *event) void GoToFlow::resizeEvent(QResizeEvent *event)
{ {
QWidget::resizeEvent(event); QWidget::resizeEvent(event);
toolBar->move(0, event->size().height() - toolBar->height()); toolBar->move(0, event->size().height() - toolBar->height());
toolBar->setFixedWidth(width()); toolBar->setFixedWidth(width());
} }
void GoToFlow::centerSlide(int slide) void GoToFlow::centerSlide(int slide)
{ {
if(flow->centerIndex()!=slide) if(flow->centerIndex()!=slide)
{ {
flow->setCenterIndex(slide); flow->setCenterIndex(slide);
if(ready)// load images if pages are loaded. if(ready)// load images if pages are loaded.
{ {
//worker->reset(); //BUG FIXED : image didn't load if worker was working //worker->reset(); //BUG FIXED : image didn't load if worker was working
preload(); preload();
} }
} }
} }
void GoToFlow::setNumSlides(unsigned int slides) void GoToFlow::setNumSlides(unsigned int slides)
{ {
// numPagesLabel->setText(tr("Total pages : ")+QString::number(slides)); // numPagesLabel->setText(tr("Total pages : ")+QString::number(slides));
// numPagesLabel->adjustSize(); // numPagesLabel->adjustSize();
imagesReady.clear(); imagesReady.clear();
imagesReady.fill(false,slides); imagesReady.fill(false,slides);
rawImages.clear(); rawImages.clear();
rawImages.resize(slides); rawImages.resize(slides);
toolBar->setTop(slides); toolBar->setTop(slides);
SlideInitializer * si = new SlideInitializer(&mutexGoToFlow,flow,slides); SlideInitializer * si = new SlideInitializer(&mutexGoToFlow,flow,slides);
imagesLoaded.clear(); imagesLoaded.clear();
imagesLoaded.fill(false,slides); imagesLoaded.fill(false,slides);
imagesSetted.clear(); imagesSetted.clear();
imagesSetted.fill(false,slides); imagesSetted.fill(false,slides);
numImagesLoaded = 0; numImagesLoaded = 0;
connect(flow, SIGNAL(centerIndexChanged(int)), this, SLOT(preload())); connect(flow, SIGNAL(centerIndexChanged(int)), this, SLOT(preload()));
connect(flow, SIGNAL(centerIndexChangedSilent(int)), this, SLOT(preload())); connect(flow, SIGNAL(centerIndexChangedSilent(int)), this, SLOT(preload()));
ready = true; ready = true;
worker->reset(); worker->reset();
si->start(); si->start();
} }
void GoToFlow::reset() void GoToFlow::reset()
{ {
updateTimer->stop(); updateTimer->stop();
/*imagesLoaded.clear(); /*imagesLoaded.clear();
numImagesLoaded = 0; numImagesLoaded = 0;
imagesReady.clear(); imagesReady.clear();
rawImages.clear();*/ rawImages.clear();*/
ready = false; ready = false;
} }
void GoToFlow::setImageReady(int index,const QByteArray & image) void GoToFlow::setImageReady(int index,const QByteArray & image)
{ {
rawImages[index]=image; rawImages[index]=image;
imagesReady[index]=true; imagesReady[index]=true;
preload(); preload();
} }
void GoToFlow::preload() void GoToFlow::preload()
{ {
if(numImagesLoaded < imagesLoaded.size()) if(numImagesLoaded < imagesLoaded.size())
updateTimer->start(30); //TODO comprobar rendimiento, antes era 70 updateTimer->start(30); //TODO comprobar rendimiento, antes era 70
} }
void GoToFlow::updateImageData() void GoToFlow::updateImageData()
{ {
// can't do anything, wait for the next possibility // can't do anything, wait for the next possibility
if(worker->busy()) if(worker->busy())
return; return;
// set image of last one // set image of last one
int idx = worker->index(); int idx = worker->index();
if( idx >= 0 && !worker->result().isNull()) if( idx >= 0 && !worker->result().isNull())
{ {
if(!imagesSetted[idx]) if(!imagesSetted[idx])
{ {
flow->setSlide(idx, worker->result()); flow->setSlide(idx, worker->result());
imagesSetted[idx] = true; imagesSetted[idx] = true;
numImagesLoaded++; numImagesLoaded++;
rawImages[idx].clear();; //release memory rawImages[idx].clear();; //release memory
imagesLoaded[idx]=true; imagesLoaded[idx]=true;
} }
} }
// try to load only few images on the left and right side // try to load only few images on the left and right side
// i.e. all visible ones plus some extra // i.e. all visible ones plus some extra
#define COUNT 8 #define COUNT 8
int indexes[2*COUNT+1]; int indexes[2*COUNT+1];
int center = flow->centerIndex(); int center = flow->centerIndex();
indexes[0] = center; indexes[0] = center;
for(int j = 0; j < COUNT; j++) for(int j = 0; j < COUNT; j++)
{ {
indexes[j*2+1] = center+j+1; indexes[j*2+1] = center+j+1;
indexes[j*2+2] = center-j-1; indexes[j*2+2] = center-j-1;
} }
for(int c = 0; c < 2*COUNT+1; c++) for(int c = 0; c < 2*COUNT+1; c++)
{ {
int i = indexes[c]; int i = indexes[c];
if((i >= 0) && (i < flow->slideCount())) if((i >= 0) && (i < flow->slideCount()))
if(!imagesLoaded[i]&&imagesReady[i])//slide(i).isNull()) if(!imagesLoaded[i]&&imagesReady[i])//slide(i).isNull())
{ {
// schedule thumbnail generation // schedule thumbnail generation
worker->generate(i, flow->slideSize(),rawImages[i]); worker->generate(i, flow->slideSize(),rawImages[i]);
return; return;
} }
} }
// no need to generate anything? stop polling... // no need to generate anything? stop polling...
updateTimer->stop(); updateTimer->stop();
} }
void GoToFlow::wheelEvent(QWheelEvent * event) void GoToFlow::wheelEvent(QWheelEvent * event)
{ {
if(event->delta()<0) if(event->delta()<0)
flow->showNext(); flow->showNext();
else else
flow->showPrevious(); flow->showPrevious();
event->accept(); event->accept();
} }
void GoToFlow::setFlowType(FlowType flowType) void GoToFlow::setFlowType(FlowType flowType)
{ {
flow->setFlowType(flowType); flow->setFlowType(flowType);
} }
void GoToFlow::updateConfig(QSettings * settings) void GoToFlow::updateConfig(QSettings * settings)
{ {
GoToFlowWidget::updateConfig(settings); GoToFlowWidget::updateConfig(settings);
imageSize = Configuration::getConfiguration().getGotoSlideSize(); imageSize = Configuration::getConfiguration().getGotoSlideSize();
flow->setFlowType(Configuration::getConfiguration().getFlowType()); flow->setFlowType(Configuration::getConfiguration().getFlowType());
resize(5*imageSize.width(), toolBar->height() + imageSize.height()*1.7); resize(5*imageSize.width(), toolBar->height() + imageSize.height()*1.7);
updateSize(); updateSize();
} }
void GoToFlow::setFlowRightToLeft(bool b) void GoToFlow::setFlowRightToLeft(bool b)
{ {
flow->setFlowRightToLeft(b); flow->setFlowRightToLeft(b);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//SlideInitializer //SlideInitializer
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
SlideInitializer::SlideInitializer(QMutex * m,PictureFlow * flow,int slides) SlideInitializer::SlideInitializer(QMutex * m,PictureFlow * flow,int slides)
:QThread(),mutex(m),_flow(flow),_slides(slides) :QThread(),mutex(m),_flow(flow),_slides(slides)
{ {
} }
void SlideInitializer::run() void SlideInitializer::run()
{ {
mutex->lock(); mutex->lock();
_flow->clear(); _flow->clear();
for(int i=0;i<_slides;i++) for(int i=0;i<_slides;i++)
_flow->addSlide(QImage()); _flow->addSlide(QImage());
_flow->setCenterIndex(0); _flow->setCenterIndex(0);
mutex->unlock(); mutex->unlock();
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//PageLoader //PageLoader
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
PageLoader::PageLoader(QMutex * m): PageLoader::PageLoader(QMutex * m):
QThread(),mutex(m), restart(false), working(false), idx(-1) QThread(),mutex(m), restart(false), working(false), idx(-1)
{ {
} }
PageLoader::~PageLoader() PageLoader::~PageLoader()
{ {
mutex->lock(); mutex->lock();
condition.wakeOne(); condition.wakeOne();
mutex->unlock(); mutex->unlock();
wait(); wait();
} }
bool PageLoader::busy() const bool PageLoader::busy() const
{ {
return isRunning() ? working : false; return isRunning() ? working : false;
} }
void PageLoader::generate(int index, QSize size,const QByteArray & rImage) void PageLoader::generate(int index, QSize size,const QByteArray & rImage)
{ {
mutex->lock(); mutex->lock();
this->idx = index; this->idx = index;
//this->img = QImage(); //this->img = QImage();
this->size = size; this->size = size;
this->rawImage = rImage; this->rawImage = rImage;
mutex->unlock(); mutex->unlock();
if (!isRunning()) if (!isRunning())
start(); start();
else else
{ {
// already running, wake up whenever ready // already running, wake up whenever ready
restart = true; restart = true;
condition.wakeOne(); condition.wakeOne();
} }
} }
void PageLoader::run() void PageLoader::run()
{ {
for(;;) for(;;)
{ {
// copy necessary data // copy necessary data
mutex->lock(); mutex->lock();
this->working = true; this->working = true;
//int idx = this->idx; //int idx = this->idx;
QImage image; QImage image;
image.loadFromData(this->rawImage); image.loadFromData(this->rawImage);
// let everyone knows it is ready // let everyone knows it is ready
image = image.scaled(this->size,Qt::KeepAspectRatio,Qt::SmoothTransformation); image = image.scaled(this->size,Qt::KeepAspectRatio,Qt::SmoothTransformation);
mutex->unlock(); mutex->unlock();
mutex->lock(); mutex->lock();
this->working = false; this->working = false;
this->img = image; this->img = image;
mutex->unlock(); mutex->unlock();
// put to sleep // put to sleep
mutex->lock(); mutex->lock();
if (!this->restart) if (!this->restart)
condition.wait(mutex); condition.wait(mutex);
restart = false; restart = false;
mutex->unlock(); mutex->unlock();
} }
} }

View File

@ -1,114 +1,114 @@
#ifndef __GOTO_FLOW_H #ifndef __GOTO_FLOW_H
#define __GOTO_FLOW_H #define __GOTO_FLOW_H
#include "goto_flow_widget.h" #include "goto_flow_widget.h"
#include "yacreader_global_gui.h" #include "yacreader_global_gui.h"
#include <QThread> #include <QThread>
#include <QWaitCondition> #include <QWaitCondition>
#include <QMutex> #include <QMutex>
class QLineEdit; class QLineEdit;
class QPushButton; class QPushButton;
class QPixmap; class QPixmap;
class QThread; class QThread;
class QSize; class QSize;
class QIntValidator; class QIntValidator;
class QWaitCondition; class QWaitCondition;
class QEvent; class QEvent;
class QLabel; class QLabel;
class Comic; class Comic;
class SlideInitializer; class SlideInitializer;
class PageLoader; class PageLoader;
class YACReaderFlow; class YACReaderFlow;
class PictureFlow; class PictureFlow;
class QKeyEvent; class QKeyEvent;
class GoToFlow : public GoToFlowWidget class GoToFlow : public GoToFlowWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
GoToFlow(QWidget* parent = 0,FlowType flowType = CoverFlowLike); GoToFlow(QWidget* parent = 0,FlowType flowType = CoverFlowLike);
~GoToFlow(); ~GoToFlow();
bool ready; //comic is ready for read. bool ready; //comic is ready for read.
private: private:
YACReaderFlow * flow; YACReaderFlow * flow;
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
//Comic * comic; //Comic * comic;
QSize imageSize; QSize imageSize;
QVector<bool> imagesLoaded; QVector<bool> imagesLoaded;
QVector<bool> imagesSetted; QVector<bool> imagesSetted;
int numImagesLoaded; int numImagesLoaded;
QVector<bool> imagesReady; QVector<bool> imagesReady;
QVector<QByteArray> rawImages; QVector<QByteArray> rawImages;
QTimer* updateTimer; QTimer* updateTimer;
PageLoader* worker; PageLoader* worker;
virtual void wheelEvent(QWheelEvent * event); virtual void wheelEvent(QWheelEvent * event);
QMutex mutexGoToFlow; QMutex mutexGoToFlow;
private slots: private slots:
void preload(); void preload();
void updateImageData(); void updateImageData();
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
public slots: public slots:
void centerSlide(int slide); void centerSlide(int slide);
void reset(); void reset();
void setNumSlides(unsigned int slides); void setNumSlides(unsigned int slides);
void setImageReady(int index,const QByteArray & image); void setImageReady(int index,const QByteArray & image);
void setFlowType(FlowType flowType); void setFlowType(FlowType flowType);
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void setFlowRightToLeft(bool b); void setFlowRightToLeft(bool b);
signals: signals:
void goToPage(unsigned int page); void goToPage(unsigned int page);
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//SlideInitializer //SlideInitializer
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
class SlideInitializer : public QThread class SlideInitializer : public QThread
{ {
public: public:
SlideInitializer(QMutex * m,PictureFlow * flow,int slides); SlideInitializer(QMutex * m,PictureFlow * flow,int slides);
private: private:
QMutex * mutex; QMutex * mutex;
PictureFlow * _flow; PictureFlow * _flow;
int _slides; int _slides;
void run(); void run();
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//PageLoader //PageLoader
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
class PageLoader : public QThread class PageLoader : public QThread
{ {
public: public:
PageLoader(QMutex * m); PageLoader(QMutex * m);
~PageLoader(); ~PageLoader();
// returns FALSE if worker is still busy and can't take the task // returns FALSE if worker is still busy and can't take the task
bool busy() const; bool busy() const;
void generate(int index, QSize size,const QByteArray & rImage); void generate(int index, QSize size,const QByteArray & rImage);
void reset(){idx = -1;}; void reset(){idx = -1;};
int index() const { return idx; } int index() const { return idx; }
QImage result() const { return img; } QImage result() const { return img; }
protected: protected:
void run(); void run();
private: private:
QMutex * mutex; QMutex * mutex;
QWaitCondition condition; QWaitCondition condition;
bool restart; bool restart;
bool working; bool working;
int idx; int idx;
QSize size; QSize size;
QImage img; QImage img;
QByteArray rawImage; QByteArray rawImage;
}; };
#endif #endif

View File

@ -1,167 +1,167 @@
#include "goto_flow_gl.h" #include "goto_flow_gl.h"
#include <QLineEdit> #include <QLineEdit>
#include <QIntValidator> #include <QIntValidator>
#include <QPushButton> #include <QPushButton>
#include <QPushButton> #include <QPushButton>
#include <QSize> #include <QSize>
#include <QApplication> #include <QApplication>
#include "configuration.h" #include "configuration.h"
#include "goto_flow_toolbar.h" #include "goto_flow_toolbar.h"
GoToFlowGL::GoToFlowGL(QWidget* parent, FlowType flowType) GoToFlowGL::GoToFlowGL(QWidget* parent, FlowType flowType)
:GoToFlowWidget(parent) :GoToFlowWidget(parent)
{ {
Q_UNUSED(flowType) Q_UNUSED(flowType)
flow = new YACReaderPageFlowGL(this); flow = new YACReaderPageFlowGL(this);
flow->setShowMarks(false); flow->setShowMarks(false);
imageSize = Configuration::getConfiguration().getGotoSlideSize(); imageSize = Configuration::getConfiguration().getGotoSlideSize();
flow->setSlideSize(imageSize); flow->setSlideSize(imageSize);
connect(flow,SIGNAL(centerIndexChanged(int)),this,SLOT(setPageNumber(int))); connect(flow,SIGNAL(centerIndexChanged(int)),this,SLOT(setPageNumber(int)));
connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(goToPage(unsigned int))); connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(goToPage(unsigned int)));
connect(toolBar,SIGNAL(goTo(unsigned int)),this,SIGNAL(goToPage(unsigned int))); connect(toolBar,SIGNAL(goTo(unsigned int)),this,SIGNAL(goToPage(unsigned int)));
connect(toolBar,SIGNAL(setCenter(unsigned int)),flow,SLOT(setCenterIndex(unsigned int))); connect(toolBar,SIGNAL(setCenter(unsigned int)),flow,SLOT(setCenterIndex(unsigned int)));
mainLayout->addWidget(flow); mainLayout->addWidget(flow);
toolBar->raise(); toolBar->raise();
resize(static_cast<int>(5*imageSize.width()),toolBar->height() + static_cast<int>(imageSize.height()*1.7)); resize(static_cast<int>(5*imageSize.width()),toolBar->height() + static_cast<int>(imageSize.height()*1.7));
this->setCursor(QCursor(Qt::ArrowCursor)); this->setCursor(QCursor(Qt::ArrowCursor));
} }
GoToFlowGL::~GoToFlowGL() GoToFlowGL::~GoToFlowGL()
{ {
delete flow; delete flow;
} }
void GoToFlowGL::reset() void GoToFlowGL::reset()
{ {
flow->reset(); flow->reset();
} }
void GoToFlowGL::centerSlide(int slide) void GoToFlowGL::centerSlide(int slide)
{ {
if(flow->centerIndex()!=slide) if(flow->centerIndex()!=slide)
{ {
flow->setCenterIndex(slide); flow->setCenterIndex(slide);
} }
} }
void GoToFlowGL::setFlowType(FlowType flowType) void GoToFlowGL::setFlowType(FlowType flowType)
{ {
if(flowType == CoverFlowLike) if(flowType == CoverFlowLike)
flow->setPreset(presetYACReaderFlowClassicConfig); flow->setPreset(presetYACReaderFlowClassicConfig);
else if(flowType == Strip) else if(flowType == Strip)
flow->setPreset(presetYACReaderFlowStripeConfig); flow->setPreset(presetYACReaderFlowStripeConfig);
else if(flowType == StripOverlapped) else if(flowType == StripOverlapped)
flow->setPreset(presetYACReaderFlowOverlappedStripeConfig); flow->setPreset(presetYACReaderFlowOverlappedStripeConfig);
else else
flow->setPreset(defaultYACReaderFlowConfig); flow->setPreset(defaultYACReaderFlowConfig);
} }
void GoToFlowGL::setNumSlides(unsigned int slides) void GoToFlowGL::setNumSlides(unsigned int slides)
{ {
flow->populate(slides); flow->populate(slides);
toolBar->setTop(slides); toolBar->setTop(slides);
} }
void GoToFlowGL::setImageReady(int index,const QByteArray & imageData) void GoToFlowGL::setImageReady(int index,const QByteArray & imageData)
{ {
flow->rawImages[index] = imageData; flow->rawImages[index] = imageData;
flow->imagesReady[index] = true; flow->imagesReady[index] = true;
} }
void GoToFlowGL::updateConfig(QSettings * settings) void GoToFlowGL::updateConfig(QSettings * settings)
{ {
GoToFlowWidget::updateConfig(settings); GoToFlowWidget::updateConfig(settings);
Performance performance = medium; Performance performance = medium;
switch (settings->value(PERFORMANCE).toInt()) switch (settings->value(PERFORMANCE).toInt())
{ {
case 0: case 0:
performance = low; performance = low;
break; break;
case 1: case 1:
performance = medium; performance = medium;
break; break;
case 2: case 2:
performance = high; performance = high;
break; break;
case 3: case 3:
performance = ultraHigh; performance = ultraHigh;
break; break;
} }
imageSize = Configuration::getConfiguration().getGotoSlideSize(); imageSize = Configuration::getConfiguration().getGotoSlideSize();
resize(5*imageSize.width(), toolBar->height() + imageSize.height()*1.7); resize(5*imageSize.width(), toolBar->height() + imageSize.height()*1.7);
updateSize(); updateSize();
flow->setPerformance(performance); flow->setPerformance(performance);
switch (settings->value(FLOW_TYPE_GL).toInt()) switch (settings->value(FLOW_TYPE_GL).toInt())
{ {
case FlowType::CoverFlowLike: case FlowType::CoverFlowLike:
flow->setPreset(presetYACReaderFlowClassicConfig); flow->setPreset(presetYACReaderFlowClassicConfig);
break; break;
case FlowType::Strip: case FlowType::Strip:
flow->setPreset(presetYACReaderFlowStripeConfig); flow->setPreset(presetYACReaderFlowStripeConfig);
break; break;
case FlowType::StripOverlapped: case FlowType::StripOverlapped:
flow->setPreset(presetYACReaderFlowOverlappedStripeConfig); flow->setPreset(presetYACReaderFlowOverlappedStripeConfig);
break; break;
case FlowType::Modern: case FlowType::Modern:
flow->setPreset(defaultYACReaderFlowConfig); flow->setPreset(defaultYACReaderFlowConfig);
break; break;
case FlowType::Roulette: case FlowType::Roulette:
flow->setPreset(pressetYACReaderFlowDownConfig); flow->setPreset(pressetYACReaderFlowDownConfig);
break; break;
case FlowType::Custom: case FlowType::Custom:
flow->setCF_RX(settings->value(X_ROTATION).toInt()); flow->setCF_RX(settings->value(X_ROTATION).toInt());
flow->setCF_Y(settings->value(Y_POSITION).toInt()); flow->setCF_Y(settings->value(Y_POSITION).toInt());
flow->setX_Distance(settings->value(COVER_DISTANCE).toInt()); flow->setX_Distance(settings->value(COVER_DISTANCE).toInt());
flow->setCenter_Distance(settings->value(CENTRAL_DISTANCE).toInt()); flow->setCenter_Distance(settings->value(CENTRAL_DISTANCE).toInt());
flow->setCF_Z(settings->value(ZOOM_LEVEL).toInt()); flow->setCF_Z(settings->value(ZOOM_LEVEL).toInt());
flow->setY_Distance(settings->value(Y_COVER_OFFSET).toInt()); flow->setY_Distance(settings->value(Y_COVER_OFFSET).toInt());
flow->setZ_Distance(settings->value(Z_COVER_OFFSET).toInt()); flow->setZ_Distance(settings->value(Z_COVER_OFFSET).toInt());
flow->setRotation(settings->value(COVER_ROTATION).toInt()); flow->setRotation(settings->value(COVER_ROTATION).toInt());
flow->setFadeOutDist(settings->value(FADE_OUT_DIST).toInt()); flow->setFadeOutDist(settings->value(FADE_OUT_DIST).toInt());
flow->setLightStrenght(settings->value(LIGHT_STRENGTH).toInt()); flow->setLightStrenght(settings->value(LIGHT_STRENGTH).toInt());
flow->setMaxAngle(settings->value(MAX_ANGLE).toInt()); flow->setMaxAngle(settings->value(MAX_ANGLE).toInt());
break; break;
} }
if (Configuration::getConfiguration().getQuickNaviMode()) if (Configuration::getConfiguration().getQuickNaviMode())
flow->setFadeOutDist(20); flow->setFadeOutDist(20);
} }
void GoToFlowGL::keyPressEvent(QKeyEvent* event) void GoToFlowGL::keyPressEvent(QKeyEvent* event)
{ {
switch (event->key()) switch (event->key())
{ {
case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up:
QApplication::sendEvent(flow,event); QApplication::sendEvent(flow,event);
return; return;
default: default:
break; break;
} }
GoToFlowWidget::keyPressEvent(event); GoToFlowWidget::keyPressEvent(event);
} }
void GoToFlowGL::resizeEvent(QResizeEvent *event) void GoToFlowGL::resizeEvent(QResizeEvent *event)
{ {
QWidget::resizeEvent(event); QWidget::resizeEvent(event);
toolBar->move(0, event->size().height() - toolBar->height()); toolBar->move(0, event->size().height() - toolBar->height());
toolBar->setFixedWidth(width()); toolBar->setFixedWidth(width());
} }
void GoToFlowGL::setFlowRightToLeft(bool b) void GoToFlowGL::setFlowRightToLeft(bool b)
{ {
flow->setFlowRightToLeft(b); flow->setFlowRightToLeft(b);
} }

View File

@ -1,40 +1,40 @@
#ifndef __GOTO_FLOW_GL_H #ifndef __GOTO_FLOW_GL_H
#define __GOTO_FLOW_GL_H #define __GOTO_FLOW_GL_H
#include "yacreader_global.h" #include "yacreader_global.h"
#include "goto_flow_widget.h" #include "goto_flow_widget.h"
#include "yacreader_flow_gl.h" #include "yacreader_flow_gl.h"
class QLineEdit; class QLineEdit;
class QIntValidator; class QIntValidator;
class QPushButton; class QPushButton;
class QPushButton; class QPushButton;
class QSize; class QSize;
class QKeyEvent; class QKeyEvent;
class GoToFlowGL : public GoToFlowWidget class GoToFlowGL : public GoToFlowWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
GoToFlowGL(QWidget* parent = 0,FlowType flowType = CoverFlowLike); GoToFlowGL(QWidget* parent = 0,FlowType flowType = CoverFlowLike);
~GoToFlowGL(); ~GoToFlowGL();
void reset(); void reset();
void centerSlide(int slide); void centerSlide(int slide);
void setFlowType(FlowType flowType); void setFlowType(FlowType flowType);
void setNumSlides(unsigned int slides); void setNumSlides(unsigned int slides);
void setImageReady(int index,const QByteArray & image); void setImageReady(int index,const QByteArray & image);
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void setFlowRightToLeft(bool b); void setFlowRightToLeft(bool b);
signals: signals:
void goToPage(unsigned int page); void goToPage(unsigned int page);
private: private:
YACReaderPageFlowGL * flow; YACReaderPageFlowGL * flow;
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
//Comic * comic; //Comic * comic;
QSize imageSize; QSize imageSize;
}; };
#endif #endif

View File

@ -1,132 +1,132 @@
#include "goto_flow_toolbar.h" #include "goto_flow_toolbar.h"
#include <QtWidgets> #include <QtWidgets>
#include "configuration.h" #include "configuration.h"
GoToFlowToolBar::GoToFlowToolBar(QWidget * parent) GoToFlowToolBar::GoToFlowToolBar(QWidget * parent)
:QStackedWidget(parent) :QStackedWidget(parent)
{ {
//elementos interactivos //elementos interactivos
QWidget * normal = new QWidget(this); // container widget QWidget * normal = new QWidget(this); // container widget
QWidget * quickNavi = new QWidget(this); // container widget QWidget * quickNavi = new QWidget(this); // container widget
addWidget(normal); addWidget(normal);
addWidget(quickNavi); addWidget(quickNavi);
QHBoxLayout * normalLayout = new QHBoxLayout(normal); QHBoxLayout * normalLayout = new QHBoxLayout(normal);
QHBoxLayout * naviLayout = new QHBoxLayout(quickNavi); QHBoxLayout * naviLayout = new QHBoxLayout(quickNavi);
normal->setLayout(normalLayout); normal->setLayout(normalLayout);
quickNavi->setLayout(naviLayout); quickNavi->setLayout(naviLayout);
slider = new QSlider(Qt::Horizontal,this); slider = new QSlider(Qt::Horizontal,this);
slider->setStyleSheet( slider->setStyleSheet(
"QSlider::groove:horizontal {" "QSlider::groove:horizontal {"
" border: 1px solid #22FFFFFF;" " border: 1px solid #22FFFFFF;"
" border-radius: 1px;" " border-radius: 1px;"
" background: #77000000;" " background: #77000000;"
" margin: 2px 0;" " margin: 2px 0;"
" padding: 1px;" " padding: 1px;"
"}" "}"
"QSlider::handle:horizontal {" "QSlider::handle:horizontal {"
" background: #55FFFFFF;" " background: #55FFFFFF;"
" width: 48px;" " width: 48px;"
" border-radius: 1px;" " border-radius: 1px;"
"}" "}"
); );
connect(slider, &QSlider::valueChanged, this, [&](int v) { emit(setCenter(v)); }); connect(slider, &QSlider::valueChanged, this, [&](int v) { emit(setCenter(v)); });
pageHint = new QLabel("<b>" + tr("Page : ") + "</b>",this); pageHint = new QLabel("<b>" + tr("Page : ") + "</b>",this);
v = new QIntValidator(this); v = new QIntValidator(this);
v->setBottom(1); v->setBottom(1);
edit = new QLineEdit(this); edit = new QLineEdit(this);
edit->setValidator(v); edit->setValidator(v);
edit->setAlignment(Qt::AlignRight|Qt::AlignVCenter); edit->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
edit->setStyleSheet("QLineEdit {border: 1px solid #77000000; background: #55000000; color: white; padding: 3px 5px 5px 5px; margin: 13px 5px 12px 5px; font-weight:bold}"); edit->setStyleSheet("QLineEdit {border: 1px solid #77000000; background: #55000000; color: white; padding: 3px 5px 5px 5px; margin: 13px 5px 12px 5px; font-weight:bold}");
QPixmap p(":/images/imgEdit.png"); QPixmap p(":/images/imgEdit.png");
edit->setFixedSize(54,50); edit->setFixedSize(54,50);
edit->setAttribute(Qt::WA_MacShowFocusRect,false); edit->setAttribute(Qt::WA_MacShowFocusRect,false);
//edit->setAttribute(Qt::WA_LayoutUsesWidgetRect,true); //edit->setAttribute(Qt::WA_LayoutUsesWidgetRect,true);
//edit->resize(QSize(54,50)); //edit->resize(QSize(54,50));
edit->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed)); edit->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
//edit->setAutoFillBackground(false); //edit->setAutoFillBackground(false);
connect(edit,SIGNAL(returnPressed()),this,SLOT(goTo())); connect(edit,SIGNAL(returnPressed()),this,SLOT(goTo()));
QString centerButtonCSS = "QPushButton {background-image: url(:/images/imgCenterSlide.png); width: 100%; height:100%; background-repeat: none; border: none;} " QString centerButtonCSS = "QPushButton {background-image: url(:/images/imgCenterSlide.png); width: 100%; height:100%; background-repeat: none; border: none;} "
"QPushButton:focus { border: none; outline: none;}" "QPushButton:focus { border: none; outline: none;}"
"QPushButton:pressed {background-image: url(:/images/imgCenterSlidePressed.png); width: 100%; height:100%; background-repeat: none; border: none;} "; "QPushButton:pressed {background-image: url(:/images/imgCenterSlidePressed.png); width: 100%; height:100%; background-repeat: none; border: none;} ";
centerButton = new QPushButton(this); centerButton = new QPushButton(this);
//centerButton->setIcon(QIcon(":/images/center.png")); //centerButton->setIcon(QIcon(":/images/center.png"));
centerButton->setStyleSheet(centerButtonCSS); centerButton->setStyleSheet(centerButtonCSS);
centerButton->setFixedSize(26,50); centerButton->setFixedSize(26,50);
centerButton->setAttribute(Qt::WA_LayoutUsesWidgetRect,true); centerButton->setAttribute(Qt::WA_LayoutUsesWidgetRect,true);
connect(centerButton,SIGNAL(clicked()),this,SLOT(centerSlide())); connect(centerButton,SIGNAL(clicked()),this,SLOT(centerSlide()));
QString goToButtonCSS = "QPushButton {background-image: url(:/images/imgGoToSlide.png); width: 100%; height:100%; background-repeat: none; border: none;} " QString goToButtonCSS = "QPushButton {background-image: url(:/images/imgGoToSlide.png); width: 100%; height:100%; background-repeat: none; border: none;} "
"QPushButton:focus { border: none; outline: none;}" "QPushButton:focus { border: none; outline: none;}"
"QPushButton:pressed {background-image: url(:/images/imgGoToSlidePressed.png); width: 100%; height:100%; background-repeat: none; border: none;} "; "QPushButton:pressed {background-image: url(:/images/imgGoToSlidePressed.png); width: 100%; height:100%; background-repeat: none; border: none;} ";
goToButton = new QPushButton(this); goToButton = new QPushButton(this);
//goToButton->setIcon(QIcon(":/images/goto.png")); //goToButton->setIcon(QIcon(":/images/goto.png"));
goToButton->setStyleSheet(goToButtonCSS); goToButton->setStyleSheet(goToButtonCSS);
goToButton->setFixedSize(32,50); goToButton->setFixedSize(32,50);
goToButton->setAttribute(Qt::WA_LayoutUsesWidgetRect,true); goToButton->setAttribute(Qt::WA_LayoutUsesWidgetRect,true);
connect(goToButton,SIGNAL(clicked()),this,SLOT(goTo())); connect(goToButton,SIGNAL(clicked()),this,SLOT(goTo()));
normalLayout->setMargin(0); normalLayout->setMargin(0);
normalLayout->setSpacing(0); normalLayout->setSpacing(0);
normalLayout->addStretch(); normalLayout->addStretch();
normalLayout->addWidget(pageHint); normalLayout->addWidget(pageHint);
normalLayout->addWidget(edit); normalLayout->addWidget(edit);
normalLayout->addWidget(centerButton); normalLayout->addWidget(centerButton);
normalLayout->addWidget(goToButton); normalLayout->addWidget(goToButton);
normalLayout->addStretch(); normalLayout->addStretch();
naviLayout->setContentsMargins(5, 0, 0, 0); naviLayout->setContentsMargins(5, 0, 0, 0);
naviLayout->setSpacing(2); naviLayout->setSpacing(2);
naviLayout->addWidget(slider); naviLayout->addWidget(slider);
naviLayout->addWidget(goToButton); naviLayout->addWidget(goToButton);
updateOptions(); updateOptions();
setFixedHeight(50); setFixedHeight(50);
} }
void GoToFlowToolBar::paintEvent(QPaintEvent *) void GoToFlowToolBar::paintEvent(QPaintEvent *)
{ {
QPainter painter(this); QPainter painter(this);
painter.fillRect(0,0,width(),height(),QColor("#99000000")); painter.fillRect(0,0,width(),height(),QColor("#99000000"));
} }
void GoToFlowToolBar::setPage(int pageNumber) void GoToFlowToolBar::setPage(int pageNumber)
{ {
edit->setText(QString::number(pageNumber+1)); edit->setText(QString::number(pageNumber+1));
slider->setValue(pageNumber); slider->setValue(pageNumber);
} }
void GoToFlowToolBar::setTop(int numPages) void GoToFlowToolBar::setTop(int numPages)
{ {
v->setTop(numPages); v->setTop(numPages);
slider->setMaximum(numPages-1); // min is 0 slider->setMaximum(numPages-1); // min is 0
} }
void GoToFlowToolBar::goTo() void GoToFlowToolBar::goTo()
{ {
if(edit->text().toInt()!=0) if(edit->text().toInt()!=0)
emit(goTo(edit->text().toInt()-1)); emit(goTo(edit->text().toInt()-1));
} }
void GoToFlowToolBar::centerSlide() void GoToFlowToolBar::centerSlide()
{ {
if(edit->text().toInt()!=0) if(edit->text().toInt()!=0)
emit(setCenter(edit->text().toInt()-1)); emit(setCenter(edit->text().toInt()-1));
} }
void GoToFlowToolBar::updateOptions() void GoToFlowToolBar::updateOptions()
{ {
if (Configuration::getConfiguration().getQuickNaviMode()) if (Configuration::getConfiguration().getQuickNaviMode())
setCurrentIndex(1); setCurrentIndex(1);
else else
setCurrentIndex(0); setCurrentIndex(0);
slider->setInvertedAppearance(Configuration::getConfiguration().getDoubleMangaPage()); slider->setInvertedAppearance(Configuration::getConfiguration().getDoubleMangaPage());
} }

View File

@ -1,40 +1,40 @@
#ifndef GOTO_FLOW_TOOLBAR_H #ifndef GOTO_FLOW_TOOLBAR_H
#define GOTO_FLOW_TOOLBAR_H #define GOTO_FLOW_TOOLBAR_H
#include <QWidget> #include <QWidget>
#include <QStackedWidget> #include <QStackedWidget>
class QLineEdit; class QLineEdit;
class QIntValidator; class QIntValidator;
class QPushButton; class QPushButton;
class QSlider; class QSlider;
class QLabel; class QLabel;
class GoToFlowToolBar : public QStackedWidget class GoToFlowToolBar : public QStackedWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
QLineEdit * edit; QLineEdit * edit;
QSlider * slider; QSlider * slider;
QIntValidator * v; QIntValidator * v;
QPushButton * centerButton; QPushButton * centerButton;
QPushButton * goToButton; QPushButton * goToButton;
QLabel * pageHint; QLabel * pageHint;
QWidget * bar; QWidget * bar;
void paintEvent(QPaintEvent *); void paintEvent(QPaintEvent *);
public: public:
GoToFlowToolBar(QWidget * parent = 0); GoToFlowToolBar(QWidget * parent = 0);
public slots: public slots:
void setPage(int pageNumber); void setPage(int pageNumber);
void setTop(int numPages); void setTop(int numPages);
void goTo(); void goTo();
void centerSlide(); void centerSlide();
void updateOptions(); void updateOptions();
signals: signals:
void setCenter(unsigned int); void setCenter(unsigned int);
void goTo(unsigned int); void goTo(unsigned int);
}; };
#endif #endif

View File

@ -1,81 +1,81 @@
#include "goto_flow_widget.h" #include "goto_flow_widget.h"
#include <QSettings> #include <QSettings>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QKeyEvent> #include <QKeyEvent>
#include <QCoreApplication> #include <QCoreApplication>
#include "goto_flow_toolbar.h" #include "goto_flow_toolbar.h"
#include "configuration.h" #include "configuration.h"
GoToFlowWidget::GoToFlowWidget(QWidget * parent) GoToFlowWidget::GoToFlowWidget(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
mainLayout = new QVBoxLayout; mainLayout = new QVBoxLayout;
mainLayout->setMargin(0); mainLayout->setMargin(0);
mainLayout->setSpacing(0); mainLayout->setSpacing(0);
toolBar = new GoToFlowToolBar(this); toolBar = new GoToFlowToolBar(this);
setLayout(mainLayout); setLayout(mainLayout);
//toolBar->installEventFilter(this); //toolBar->installEventFilter(this);
} }
GoToFlowWidget::~GoToFlowWidget() { GoToFlowWidget::~GoToFlowWidget() {
delete toolBar; delete toolBar;
delete mainLayout; delete mainLayout;
} }
void GoToFlowWidget::setPageNumber(int page) void GoToFlowWidget::setPageNumber(int page)
{ {
toolBar->setPage(page); toolBar->setPage(page);
} }
void GoToFlowWidget::keyPressEvent(QKeyEvent* event) void GoToFlowWidget::keyPressEvent(QKeyEvent* event)
{ {
switch (event->key()) switch (event->key())
{ {
case Qt::Key_Return: case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Enter:
toolBar->goTo(); toolBar->goTo();
toolBar->centerSlide(); toolBar->centerSlide();
break; break;
case Qt::Key_Space: case Qt::Key_Space:
toolBar->centerSlide(); toolBar->centerSlide();
break; break;
case Qt::Key_S: case Qt::Key_S:
QCoreApplication::sendEvent(this->parent(),event); QCoreApplication::sendEvent(this->parent(),event);
break; break;
} }
event->accept(); event->accept();
} }
void GoToFlowWidget::updateConfig(QSettings * settings) void GoToFlowWidget::updateConfig(QSettings * settings)
{ {
Q_UNUSED(settings) Q_UNUSED(settings)
toolBar->updateOptions(); toolBar->updateOptions();
} }
void GoToFlowWidget::updateSize() void GoToFlowWidget::updateSize()
{ {
// called by parent in resizeEvent // called by parent in resizeEvent
// no need to update width when QuickNaviMode disabled // no need to update width when QuickNaviMode disabled
// height is set in updateConfig // height is set in updateConfig
if (Configuration::getConfiguration().getQuickNaviMode() && parentWidget() != nullptr) if (Configuration::getConfiguration().getQuickNaviMode() && parentWidget() != nullptr)
resize(parentWidget()->width(),height()); resize(parentWidget()->width(),height());
} }
/*bool GoToFlowWidget::eventFilter(QObject * target, QEvent * event) /*bool GoToFlowWidget::eventFilter(QObject * target, QEvent * event)
{ {
if(event->type() == QEvent::KeyPress) if(event->type() == QEvent::KeyPress)
{ {
QKeyEvent * e = static_cast<QKeyEvent *>(event); QKeyEvent * e = static_cast<QKeyEvent *>(event);
if(e->key()==Qt::Key_S || e->key() == Qt::Key_Space) if(e->key()==Qt::Key_S || e->key() == Qt::Key_Space)
{ {
this->keyPressEvent(e); this->keyPressEvent(e);
return true; return true;
} }
} }
return QWidget::eventFilter(target,event); return QWidget::eventFilter(target,event);
}*/ }*/

View File

@ -1,40 +1,40 @@
#ifndef __GOTO_FLOW_WIDGET_H #ifndef __GOTO_FLOW_WIDGET_H
#define __GOTO_FLOW_WIDGET_H #define __GOTO_FLOW_WIDGET_H
#include <QWidget> #include <QWidget>
#include <QSettings> #include <QSettings>
#include "yacreader_global_gui.h" #include "yacreader_global_gui.h"
using namespace YACReader; using namespace YACReader;
class QSettings; class QSettings;
class GoToFlowToolBar; class GoToFlowToolBar;
class QVBoxLayout; class QVBoxLayout;
class GoToFlowWidget : public QWidget class GoToFlowWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
protected: protected:
QVBoxLayout * mainLayout; QVBoxLayout * mainLayout;
GoToFlowToolBar * toolBar; GoToFlowToolBar * toolBar;
public: public:
GoToFlowWidget(QWidget * paret = 0); GoToFlowWidget(QWidget * paret = 0);
virtual ~GoToFlowWidget() = 0; virtual ~GoToFlowWidget() = 0;
public slots: public slots:
virtual void reset() = 0; virtual void reset() = 0;
virtual void centerSlide(int slide) = 0; virtual void centerSlide(int slide) = 0;
virtual void setPageNumber(int page); virtual void setPageNumber(int page);
virtual void setFlowType(FlowType flowType) = 0; virtual void setFlowType(FlowType flowType) = 0;
virtual void setNumSlides(unsigned int slides) = 0; virtual void setNumSlides(unsigned int slides) = 0;
virtual void setImageReady(int index,const QByteArray & image) = 0; virtual void setImageReady(int index,const QByteArray & image) = 0;
virtual void updateSize(); virtual void updateSize();
virtual void updateConfig(QSettings * settings); virtual void updateConfig(QSettings * settings);
virtual void setFlowRightToLeft(bool b) = 0; virtual void setFlowRightToLeft(bool b) = 0;
protected: protected:
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
//bool eventFilter(QObject *, QEvent *); //bool eventFilter(QObject *, QEvent *);
}; };
#endif #endif

View File

@ -1,292 +1,292 @@
#include "magnifying_glass.h" #include "magnifying_glass.h"
#include "viewer.h" #include "viewer.h"
#include "configuration.h" #include "configuration.h"
#include "shortcuts_manager.h" #include "shortcuts_manager.h"
#include <QScrollBar> #include <QScrollBar>
MagnifyingGlass::MagnifyingGlass(int w, int h, QWidget * parent) MagnifyingGlass::MagnifyingGlass(int w, int h, QWidget * parent)
:QLabel(parent),zoomLevel(0.5) :QLabel(parent),zoomLevel(0.5)
{ {
setup(QSize(w,h)); setup(QSize(w,h));
} }
MagnifyingGlass::MagnifyingGlass(const QSize & size, QWidget * parent) MagnifyingGlass::MagnifyingGlass(const QSize & size, QWidget * parent)
:QLabel(parent),zoomLevel(0.5) :QLabel(parent),zoomLevel(0.5)
{ {
setup(size); setup(size);
} }
void MagnifyingGlass::setup(const QSize & size) void MagnifyingGlass::setup(const QSize & size)
{ {
resize(size); resize(size);
setScaledContents(true); setScaledContents(true);
setMouseTracking(true); setMouseTracking(true);
setCursor(QCursor(QBitmap(1,1),QBitmap(1,1))); setCursor(QCursor(QBitmap(1,1),QBitmap(1,1)));
} }
void MagnifyingGlass::mouseMoveEvent(QMouseEvent * event) void MagnifyingGlass::mouseMoveEvent(QMouseEvent * event)
{ {
updateImage(); updateImage();
event->accept(); event->accept();
} }
void MagnifyingGlass::updateImage(int x, int y) void MagnifyingGlass::updateImage(int x, int y)
{ {
//image section augmented //image section augmented
int zoomWidth = static_cast<int>(width() * zoomLevel); int zoomWidth = static_cast<int>(width() * zoomLevel);
int zoomHeight = static_cast<int>(height() * zoomLevel); int zoomHeight = static_cast<int>(height() * zoomLevel);
Viewer * p = (Viewer *)parent(); Viewer * p = (Viewer *)parent();
int currentPos = p->verticalScrollBar()->sliderPosition(); int currentPos = p->verticalScrollBar()->sliderPosition();
const QPixmap * image = p->pixmap(); const QPixmap * image = p->pixmap();
int iWidth = image->width(); int iWidth = image->width();
int iHeight = image->height(); int iHeight = image->height();
float wFactor = static_cast<float>(iWidth) / p->widget()->width(); float wFactor = static_cast<float>(iWidth) / p->widget()->width();
float hFactor = static_cast<float>(iHeight) / p->widget()->height(); float hFactor = static_cast<float>(iHeight) / p->widget()->height();
zoomWidth *= wFactor; zoomWidth *= wFactor;
zoomHeight *= hFactor; zoomHeight *= hFactor;
if(p->verticalScrollBar()->minimum()==p->verticalScrollBar()->maximum()) if(p->verticalScrollBar()->minimum()==p->verticalScrollBar()->maximum())
{ {
int xp = static_cast<int>(((x-p->widget()->pos().x())*wFactor)-zoomWidth/2); int xp = static_cast<int>(((x-p->widget()->pos().x())*wFactor)-zoomWidth/2);
int yp = static_cast<int>((y-p->widget()->pos().y()+currentPos)*hFactor-zoomHeight/2); int yp = static_cast<int>((y-p->widget()->pos().y()+currentPos)*hFactor-zoomHeight/2);
int xOffset=0; int xOffset=0;
int yOffset=0; int yOffset=0;
int zw=zoomWidth; int zw=zoomWidth;
int zh=zoomHeight; int zh=zoomHeight;
//int wOffset,hOffset=0; //int wOffset,hOffset=0;
bool outImage = false; bool outImage = false;
if(xp<0) if(xp<0)
{ {
xOffset = -xp; xOffset = -xp;
xp=0; xp=0;
zw = zw - xOffset; zw = zw - xOffset;
outImage = true; outImage = true;
} }
if(yp<0) if(yp<0)
{ {
yOffset = -yp; yOffset = -yp;
yp=0; yp=0;
zh = zh - yOffset; zh = zh - yOffset;
outImage = true; outImage = true;
} }
if(xp+zoomWidth >= image->width()) if(xp+zoomWidth >= image->width())
{ {
zw -= xp+zw - image->width(); zw -= xp+zw - image->width();
outImage = true; outImage = true;
} }
if(yp+zoomHeight >= image->height()) if(yp+zoomHeight >= image->height())
{ {
zh -= yp+zh - image->height(); zh -= yp+zh - image->height();
outImage = true; outImage = true;
} }
if(outImage) if(outImage)
{ {
QImage img(zoomWidth,zoomHeight,QImage::Format_RGB32); QImage img(zoomWidth,zoomHeight,QImage::Format_RGB32);
img.fill(Configuration::getConfiguration().getBackgroundColor()); img.fill(Configuration::getConfiguration().getBackgroundColor());
if(zw>0&&zh>0) if(zw>0&&zh>0)
{ {
QPainter painter(&img); QPainter painter(&img);
painter.drawPixmap(xOffset,yOffset,p->pixmap()->copy(xp,yp,zw,zh)); painter.drawPixmap(xOffset,yOffset,p->pixmap()->copy(xp,yp,zw,zh));
} }
setPixmap(QPixmap().fromImage(img)); setPixmap(QPixmap().fromImage(img));
} }
else else
setPixmap(p->pixmap()->copy(xp,yp,zoomWidth,zoomHeight)); setPixmap(p->pixmap()->copy(xp,yp,zoomWidth,zoomHeight));
} }
else else
{ {
int xp = static_cast<int>(((x-p->widget()->pos().x())*wFactor)-zoomWidth/2); int xp = static_cast<int>(((x-p->widget()->pos().x())*wFactor)-zoomWidth/2);
int yp = static_cast<int>((y+currentPos)*hFactor-zoomHeight/2); int yp = static_cast<int>((y+currentPos)*hFactor-zoomHeight/2);
int xOffset=0; int xOffset=0;
int yOffset=0; int yOffset=0;
int zw=zoomWidth; int zw=zoomWidth;
int zh=zoomHeight; int zh=zoomHeight;
//int wOffset,hOffset=0; //int wOffset,hOffset=0;
bool outImage = false; bool outImage = false;
if(xp<0) if(xp<0)
{ {
xOffset = -xp; xOffset = -xp;
xp=0; xp=0;
zw = zw - xOffset; zw = zw - xOffset;
outImage = true; outImage = true;
} }
if(yp<0) if(yp<0)
{ {
yOffset = -yp; yOffset = -yp;
yp=0; yp=0;
zh = zh - yOffset; zh = zh - yOffset;
outImage = true; outImage = true;
} }
if(xp+zoomWidth >= image->width()) if(xp+zoomWidth >= image->width())
{ {
zw -= xp+zw - image->width(); zw -= xp+zw - image->width();
outImage = true; outImage = true;
} }
if(yp+zoomHeight >= image->height()) if(yp+zoomHeight >= image->height())
{ {
zh -= yp+zh - image->height(); zh -= yp+zh - image->height();
outImage = true; outImage = true;
} }
if(outImage) if(outImage)
{ {
QImage img(zoomWidth,zoomHeight,QImage::Format_RGB32); QImage img(zoomWidth,zoomHeight,QImage::Format_RGB32);
img.fill(Configuration::getConfiguration().getBackgroundColor()); img.fill(Configuration::getConfiguration().getBackgroundColor());
if(zw>0&&zh>0) if(zw>0&&zh>0)
{ {
QPainter painter(&img); QPainter painter(&img);
painter.drawPixmap(xOffset,yOffset,p->pixmap()->copy(xp,yp,zw,zh)); painter.drawPixmap(xOffset,yOffset,p->pixmap()->copy(xp,yp,zw,zh));
} }
setPixmap(QPixmap().fromImage(img)); setPixmap(QPixmap().fromImage(img));
} }
else else
setPixmap(p->pixmap()->copy(xp,yp,zoomWidth,zoomHeight)); setPixmap(p->pixmap()->copy(xp,yp,zoomWidth,zoomHeight));
} }
move(static_cast<int>(x-float(width())/2),static_cast<int>(y-float(height())/2)); move(static_cast<int>(x-float(width())/2),static_cast<int>(y-float(height())/2));
} }
void MagnifyingGlass::updateImage() void MagnifyingGlass::updateImage()
{ {
if(isVisible()) if(isVisible())
{ {
QPoint p = QPoint(cursor().pos().x(),cursor().pos().y()); QPoint p = QPoint(cursor().pos().x(),cursor().pos().y());
p = this->parentWidget()->mapFromGlobal(p); p = this->parentWidget()->mapFromGlobal(p);
updateImage(p.x(),p.y()); updateImage(p.x(),p.y());
} }
} }
void MagnifyingGlass::wheelEvent(QWheelEvent * event) void MagnifyingGlass::wheelEvent(QWheelEvent * event)
{ {
switch(event->modifiers()) switch(event->modifiers())
{ {
//size //size
case Qt::NoModifier: case Qt::NoModifier:
if(event->delta()<0) if(event->delta()<0)
sizeUp(); sizeUp();
else else
sizeDown(); sizeDown();
break; break;
//size height //size height
case Qt::ControlModifier: case Qt::ControlModifier:
if(event->delta()<0) if(event->delta()<0)
heightUp(); heightUp();
else else
heightDown(); heightDown();
break; break;
//size width //size width
case Qt::AltModifier: case Qt::AltModifier:
if(event->delta()<0) if(event->delta()<0)
widthUp(); widthUp();
else else
widthDown(); widthDown();
break; break;
//zoom level //zoom level
case Qt::ShiftModifier: case Qt::ShiftModifier:
if(event->delta()<0) if(event->delta()<0)
zoomIn(); zoomIn();
else else
zoomOut(); zoomOut();
break; break;
} }
updateImage(); updateImage();
event->setAccepted(true); event->setAccepted(true);
} }
void MagnifyingGlass::zoomIn() void MagnifyingGlass::zoomIn()
{ {
if(zoomLevel>0.2f) if(zoomLevel>0.2f)
zoomLevel -= 0.025f; zoomLevel -= 0.025f;
} }
void MagnifyingGlass::zoomOut() void MagnifyingGlass::zoomOut()
{ {
if(zoomLevel<0.9f) if(zoomLevel<0.9f)
zoomLevel += 0.025f; zoomLevel += 0.025f;
} }
void MagnifyingGlass::sizeUp() void MagnifyingGlass::sizeUp()
{ {
Viewer * p = (Viewer *)parent(); Viewer * p = (Viewer *)parent();
if(width()<(p->width()*0.90f)) if(width()<(p->width()*0.90f))
resize(width()+30,height()+15); resize(width()+30,height()+15);
} }
void MagnifyingGlass::sizeDown() void MagnifyingGlass::sizeDown()
{ {
if(width()>175) if(width()>175)
resize(width()-30,height()-15); resize(width()-30,height()-15);
} }
void MagnifyingGlass::heightUp() void MagnifyingGlass::heightUp()
{ {
Viewer * p = (Viewer *)parent(); Viewer * p = (Viewer *)parent();
if(height()<(p->height()*0.90f)) if(height()<(p->height()*0.90f))
resize(width(),height()+15); resize(width(),height()+15);
} }
void MagnifyingGlass::heightDown() void MagnifyingGlass::heightDown()
{ {
if(height()>80) if(height()>80)
resize(width(),height()-15); resize(width(),height()-15);
} }
void MagnifyingGlass::widthUp() void MagnifyingGlass::widthUp()
{ {
Viewer * p = (Viewer *)parent(); Viewer * p = (Viewer *)parent();
if(width()<(p->width()*0.90f)) if(width()<(p->width()*0.90f))
resize(width()+30,height()); resize(width()+30,height());
} }
void MagnifyingGlass::widthDown() void MagnifyingGlass::widthDown()
{ {
if(width()>175) if(width()>175)
resize(width()-30,height()); resize(width()-30,height());
} }
void MagnifyingGlass::keyPressEvent(QKeyEvent *event) void MagnifyingGlass::keyPressEvent(QKeyEvent *event)
{ {
bool validKey = false; bool validKey = false;
int _key = event->key(); int _key = event->key();
Qt::KeyboardModifiers modifiers = event->modifiers(); Qt::KeyboardModifiers modifiers = event->modifiers();
if(modifiers & Qt::ShiftModifier) if(modifiers & Qt::ShiftModifier)
_key |= Qt::SHIFT; _key |= Qt::SHIFT;
if (modifiers & Qt::ControlModifier) if (modifiers & Qt::ControlModifier)
_key |= Qt::CTRL; _key |= Qt::CTRL;
if (modifiers & Qt::MetaModifier) if (modifiers & Qt::MetaModifier)
_key |= Qt::META; _key |= Qt::META;
if (modifiers & Qt::AltModifier) if (modifiers & Qt::AltModifier)
_key |= Qt::ALT; _key |= Qt::ALT;
QKeySequence key(_key); QKeySequence key(_key);
if (key == ShortcutsManager::getShortcutsManager().getShortcut(SIZE_UP_MGLASS_ACTION_Y)) if (key == ShortcutsManager::getShortcutsManager().getShortcut(SIZE_UP_MGLASS_ACTION_Y))
{ {
sizeUp(); sizeUp();
validKey = true; validKey = true;
} }
else if (key == ShortcutsManager::getShortcutsManager().getShortcut(SIZE_DOWN_MGLASS_ACTION_Y)) else if (key == ShortcutsManager::getShortcutsManager().getShortcut(SIZE_DOWN_MGLASS_ACTION_Y))
{ {
sizeDown(); sizeDown();
validKey = true; validKey = true;
} }
else if (key == ShortcutsManager::getShortcutsManager().getShortcut(ZOOM_IN_MGLASS_ACTION_Y)) else if (key == ShortcutsManager::getShortcutsManager().getShortcut(ZOOM_IN_MGLASS_ACTION_Y))
{ {
zoomIn(); zoomIn();
validKey = true; validKey = true;
} }
else if (key == ShortcutsManager::getShortcutsManager().getShortcut(ZOOM_OUT_MGLASS_ACTION_Y)) else if (key == ShortcutsManager::getShortcutsManager().getShortcut(ZOOM_OUT_MGLASS_ACTION_Y))
{ {
zoomOut(); zoomOut();
validKey = true; validKey = true;
} }
if(validKey) if(validKey)
{ {
updateImage(); updateImage();
event->setAccepted(true); event->setAccepted(true);
} }
} }

View File

@ -1,34 +1,34 @@
#ifndef __MAGNIFYING_GLASS #ifndef __MAGNIFYING_GLASS
#define __MAGNIFYING_GLASS #define __MAGNIFYING_GLASS
#include <QLabel> #include <QLabel>
#include <QtGui> #include <QtGui>
#include <QMouseEvent> #include <QMouseEvent>
#include <QWidget> #include <QWidget>
class MagnifyingGlass : public QLabel class MagnifyingGlass : public QLabel
{ {
Q_OBJECT Q_OBJECT
private: private:
float zoomLevel; float zoomLevel;
void setup(const QSize & size); void setup(const QSize & size);
void keyPressEvent(QKeyEvent * event); void keyPressEvent(QKeyEvent * event);
public: public:
MagnifyingGlass(int width,int height,QWidget * parent); MagnifyingGlass(int width,int height,QWidget * parent);
MagnifyingGlass(const QSize & size, QWidget * parent); MagnifyingGlass(const QSize & size, QWidget * parent);
void mouseMoveEvent(QMouseEvent * event); void mouseMoveEvent(QMouseEvent * event);
public slots: public slots:
void updateImage(int x, int y); void updateImage(int x, int y);
void updateImage(); void updateImage();
void wheelEvent(QWheelEvent * event); void wheelEvent(QWheelEvent * event);
void zoomIn(); void zoomIn();
void zoomOut(); void zoomOut();
void sizeUp(); void sizeUp();
void sizeDown(); void sizeDown();
void heightUp(); void heightUp();
void heightDown(); void heightDown();
void widthUp(); void widthUp();
void widthDown(); void widthDown();
}; };
#endif #endif

View File

@ -1,142 +1,142 @@
#include <QApplication> #include <QApplication>
#include <QDir> #include <QDir>
#include <QTranslator> #include <QTranslator>
#include <QCommandLineParser> #include <QCommandLineParser>
#include "main_window_viewer.h" #include "main_window_viewer.h"
#include "configuration.h" #include "configuration.h"
#include "exit_check.h" #include "exit_check.h"
#include "QsLog.h" #include "QsLog.h"
#include "QsLogDest.h" #include "QsLogDest.h"
using namespace QsLogging; using namespace QsLogging;
#if defined(WIN32) && defined(_DEBUG) #if defined(WIN32) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC #define _CRTDBG_MAP_ALLOC
#include <stdlib.h> #include <stdlib.h>
#include <crtdbg.h> #include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW #define new DEBUG_NEW
#endif #endif
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
#include <QEvent> #include <QEvent>
#include <QFileOpenEvent> #include <QFileOpenEvent>
class YACReaderApplication: public QApplication class YACReaderApplication: public QApplication
{ {
public: public:
YACReaderApplication(int & argc, char ** argv) : QApplication(argc,argv) YACReaderApplication(int & argc, char ** argv) : QApplication(argc,argv)
{} {}
void setWindow(MainWindowViewer * w) void setWindow(MainWindowViewer * w)
{ {
window = w; window = w;
} }
protected: protected:
bool event(QEvent * event) bool event(QEvent * event)
{ {
switch(event->type()) switch(event->type())
{ {
case QEvent::FileOpen: case QEvent::FileOpen:
window->openComicFromPath(static_cast<QFileOpenEvent *>(event)->file()); window->openComicFromPath(static_cast<QFileOpenEvent *>(event)->file());
return true; return true;
default: default:
return QApplication::event(event); return QApplication::event(event);
} }
} }
private: private:
MainWindowViewer * window; MainWindowViewer * window;
}; };
#endif #endif
int main(int argc, char * argv[]) int main(int argc, char * argv[])
{ {
#if defined(_MSC_VER) && defined(_DEBUG) #if defined(_MSC_VER) && defined(_DEBUG)
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif #endif
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
YACReaderApplication app(argc,argv); YACReaderApplication app(argc,argv);
#else #else
QApplication app(argc, argv); QApplication app(argc, argv);
#endif #endif
#ifdef FORCE_ANGLE #ifdef FORCE_ANGLE
app.setAttribute(Qt::AA_UseOpenGLES); app.setAttribute(Qt::AA_UseOpenGLES);
#endif #endif
app.setApplicationName("YACReader"); app.setApplicationName("YACReader");
app.setOrganizationName("YACReader"); app.setOrganizationName("YACReader");
app.setAttribute(Qt::AA_UseHighDpiPixmaps); app.setAttribute(Qt::AA_UseHighDpiPixmaps);
if (QIcon::hasThemeIcon("YACReader")) { if (QIcon::hasThemeIcon("YACReader")) {
app.setWindowIcon(QIcon::fromTheme("YACReader")); app.setWindowIcon(QIcon::fromTheme("YACReader"));
} }
// simple commandline parser // simple commandline parser
QCommandLineParser parser; QCommandLineParser parser;
parser.addHelpOption(); parser.addHelpOption();
parser.addVersionOption(); parser.addVersionOption();
parser.addPositionalArgument("[File|Directory]", "File or directory to open."); parser.addPositionalArgument("[File|Directory]", "File or directory to open.");
QCommandLineOption comicId("comicId", "", "comicId"); QCommandLineOption comicId("comicId", "", "comicId");
QCommandLineOption libraryId("libraryId", "", "libraryId"); QCommandLineOption libraryId("libraryId", "", "libraryId");
// hide comicId and libraryId from help // hide comicId and libraryId from help
#if QT_VERSION >= 0x050800 #if QT_VERSION >= 0x050800
comicId.setFlags(QCommandLineOption::HiddenFromHelp); comicId.setFlags(QCommandLineOption::HiddenFromHelp);
libraryId.setFlags(QCommandLineOption::HiddenFromHelp); libraryId.setFlags(QCommandLineOption::HiddenFromHelp);
#else #else
comicId.setHidden(true); comicId.setHidden(true);
libraryId.setHidden(true); libraryId.setHidden(true);
#endif #endif
// process // process
parser.addOption(comicId); parser.addOption(comicId);
parser.addOption(libraryId); parser.addOption(libraryId);
parser.process(app); parser.process(app);
QString destLog = YACReader::getSettingsPath()+"/yacreader.log"; QString destLog = YACReader::getSettingsPath()+"/yacreader.log";
QDir().mkpath(YACReader::getSettingsPath()); QDir().mkpath(YACReader::getSettingsPath());
Logger& logger = Logger::instance(); Logger& logger = Logger::instance();
logger.setLoggingLevel(QsLogging::InfoLevel); logger.setLoggingLevel(QsLogging::InfoLevel);
DestinationPtr fileDestination(DestinationFactory::MakeFileDestination( DestinationPtr fileDestination(DestinationFactory::MakeFileDestination(
destLog, EnableLogRotation, MaxSizeBytes(1048576), MaxOldLogCount(2))); destLog, EnableLogRotation, MaxSizeBytes(1048576), MaxOldLogCount(2)));
DestinationPtr debugDestination(DestinationFactory::MakeDebugOutputDestination()); DestinationPtr debugDestination(DestinationFactory::MakeDebugOutputDestination());
logger.addDestination(debugDestination); logger.addDestination(debugDestination);
logger.addDestination(fileDestination); logger.addDestination(fileDestination);
QTranslator translator; QTranslator translator;
QString sufix = QLocale::system().name(); QString sufix = QLocale::system().name();
#if defined Q_OS_UNIX && !defined Q_OS_MAC #if defined Q_OS_UNIX && !defined Q_OS_MAC
translator.load(QString(DATADIR)+"/yacreader/languages/yacreader_"+sufix); translator.load(QString(DATADIR)+"/yacreader/languages/yacreader_"+sufix);
#else #else
translator.load(QCoreApplication::applicationDirPath()+"/languages/yacreader_"+sufix); translator.load(QCoreApplication::applicationDirPath()+"/languages/yacreader_"+sufix);
#endif #endif
app.installTranslator(&translator); app.installTranslator(&translator);
MainWindowViewer * mwv = new MainWindowViewer(); MainWindowViewer * mwv = new MainWindowViewer();
// some arguments need to be parsed after MainWindowViewer creation // some arguments need to be parsed after MainWindowViewer creation
QStringList arglist = parser.positionalArguments(); QStringList arglist = parser.positionalArguments();
if (parser.isSet(comicId) && parser.isSet(libraryId) && arglist.count() >=1) if (parser.isSet(comicId) && parser.isSet(libraryId) && arglist.count() >=1)
{ {
mwv->open(arglist.at(0), parser.value(comicId).toULongLong(), parser.value(libraryId).toULongLong()); mwv->open(arglist.at(0), parser.value(comicId).toULongLong(), parser.value(libraryId).toULongLong());
} }
else if (arglist.count() >= 1) else if (arglist.count() >= 1)
{ {
mwv->openComicFromPath(arglist.at(0)); mwv->openComicFromPath(arglist.at(0));
} }
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
app.setWindow(mwv); app.setWindow(mwv);
#endif #endif
mwv->show(); mwv->show();
int ret = app.exec(); int ret = app.exec();
delete mwv; delete mwv;
//Configuration::getConfiguration().save(); //Configuration::getConfiguration().save();
YACReader::exitCheck(ret); YACReader::exitCheck(ret);
return ret; return ret;
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,187 +1,187 @@
#ifndef __MAIN_WINDOW_VIEWER_H #ifndef __MAIN_WINDOW_VIEWER_H
#define __MAIN_WINDOW_VIEWER_H #define __MAIN_WINDOW_VIEWER_H
#include <QMainWindow> #include <QMainWindow>
#include <QScrollArea> #include <QScrollArea>
#include <QToolBar> #include <QToolBar>
#include <QAction> #include <QAction>
#include <QKeyEvent> #include <QKeyEvent>
#include <QMouseEvent> #include <QMouseEvent>
#include <QCloseEvent> #include <QCloseEvent>
#include <QSettings> #include <QSettings>
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
#include "yacreader_macosx_toolbar.h" #include "yacreader_macosx_toolbar.h"
#endif #endif
#include "comic_db.h" #include "comic_db.h"
class Comic; class Comic;
class Viewer; class Viewer;
class OptionsDialog; class OptionsDialog;
class HelpAboutDialog; class HelpAboutDialog;
class HttpVersionChecker; class HttpVersionChecker;
class ShortcutsDialog; class ShortcutsDialog;
class YACReaderSliderAction; class YACReaderSliderAction;
class YACReaderSlider; class YACReaderSlider;
class EditShortcutsDialog; class EditShortcutsDialog;
class MainWindowViewer : public QMainWindow class MainWindowViewer : public QMainWindow
{ {
Q_OBJECT Q_OBJECT
public slots: public slots:
void open(); void open();
void open(QString path, ComicDB & comic, QList<ComicDB> & siblings); void open(QString path, ComicDB & comic, QList<ComicDB> & siblings);
void open(QString path, qint64 comicId, qint64 libraryId); void open(QString path, qint64 comicId, qint64 libraryId);
void openFolder(); void openFolder();
void openRecent(); void openRecent();
void openLatestComic(); void openLatestComic();
void openComicFromRecentAction(QAction *action); void openComicFromRecentAction(QAction *action);
void saveImage(); void saveImage();
void toggleToolBars(); void toggleToolBars();
void hideToolBars(); void hideToolBars();
void showToolBars(); void showToolBars();
void enableActions(); void enableActions();
void disableActions(); void disableActions();
void toggleFullScreen(); void toggleFullScreen();
void toFullScreen(); void toFullScreen();
void toNormal(); void toNormal();
void loadConfiguration(); void loadConfiguration();
void newVersion(); void newVersion();
void openPreviousComic(); void openPreviousComic();
void openNextComic(); void openNextComic();
void openComicFromPath(QString pathFile); void openComicFromPath(QString pathFile);
void openSiblingComic(QString pathFile); void openSiblingComic(QString pathFile);
void openComic(QString pathFile); void openComic(QString pathFile);
void openFolderFromPath(QString pathDir); void openFolderFromPath(QString pathDir);
void openFolderFromPath(QString pathFile, QString atFileName); void openFolderFromPath(QString pathFile, QString atFileName);
void alwaysOnTopSwitch(); void alwaysOnTopSwitch();
void adjustToFullSizeSwitch(); void adjustToFullSizeSwitch();
void fitToPageSwitch(); void fitToPageSwitch();
void resetZoomLevel(); void resetZoomLevel();
void increasePageZoomLevel(); void increasePageZoomLevel();
void decreasePageZoomLevel(); void decreasePageZoomLevel();
void reloadOptions(); void reloadOptions();
void fitToWidth(); void fitToWidth();
void fitToHeight(); void fitToHeight();
void toggleWidthHeight(); void toggleWidthHeight();
void checkNewVersion(); void checkNewVersion();
void processReset(); void processReset();
void setUpShortcutsManagement(); void setUpShortcutsManagement();
void toggleFitToWidthSlider(); void toggleFitToWidthSlider();
/*void viewComic(); /*void viewComic();
void prev(); void prev();
void next(); void next();
void updatePage();*/ void updatePage();*/
private: private:
//!State //!State
bool fullscreen; bool fullscreen;
bool toolbars; bool toolbars;
bool alwaysOnTop; bool alwaysOnTop;
bool fromMaximized; bool fromMaximized;
//QTBUG-41883 //QTBUG-41883
QSize _size; QSize _size;
QPoint _pos; QPoint _pos;
QString currentDirectory; QString currentDirectory;
QString currentDirectoryImgDest; QString currentDirectoryImgDest;
//!Widgets //!Widgets
Viewer * viewer; Viewer * viewer;
//GoToDialog * goToDialog; //GoToDialog * goToDialog;
OptionsDialog * optionsDialog; OptionsDialog * optionsDialog;
HelpAboutDialog * had; HelpAboutDialog * had;
//ShortcutsDialog * shortcutsDialog; //ShortcutsDialog * shortcutsDialog;
EditShortcutsDialog * editShortcutsDialog; EditShortcutsDialog * editShortcutsDialog;
//! ToolBars //! ToolBars
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
YACReaderMacOSXToolbar * comicToolBar; YACReaderMacOSXToolbar * comicToolBar;
#else #else
QToolBar * comicToolBar; QToolBar * comicToolBar;
#endif #endif
//! Actions //! Actions
QAction *openAction; QAction *openAction;
QAction *openFolderAction; QAction *openFolderAction;
QAction *openLatestComicAction; QAction *openLatestComicAction;
QList<QAction*> recentFilesActionList; QList<QAction*> recentFilesActionList;
QAction *clearRecentFilesAction; QAction *clearRecentFilesAction;
QAction *saveImageAction; QAction *saveImageAction;
QAction *openPreviousComicAction; QAction *openPreviousComicAction;
QAction *openNextComicAction; QAction *openNextComicAction;
QAction *nextAction; QAction *nextAction;
QAction *prevAction; QAction *prevAction;
QAction *adjustWidthAction; QAction *adjustWidthAction;
QAction *adjustHeightAction; QAction *adjustHeightAction;
QAction *goToPageAction; QAction *goToPageAction;
QAction *optionsAction; QAction *optionsAction;
QAction *helpAboutAction; QAction *helpAboutAction;
QAction *showMagnifyingGlassAction; QAction *showMagnifyingGlassAction;
QAction *setBookmarkAction; QAction *setBookmarkAction;
QAction *showBookmarksAction; QAction *showBookmarksAction;
QAction *leftRotationAction; QAction *leftRotationAction;
QAction *rightRotationAction; QAction *rightRotationAction;
QAction *showInfoAction; QAction *showInfoAction;
QAction *closeAction; QAction *closeAction;
QAction *doublePageAction; QAction *doublePageAction;
QAction *doubleMangaPageAction; QAction *doubleMangaPageAction;
QAction *showShorcutsAction; QAction *showShorcutsAction;
QAction *showDictionaryAction; QAction *showDictionaryAction;
QAction *alwaysOnTopAction; QAction *alwaysOnTopAction;
QAction *adjustToFullSizeAction; QAction *adjustToFullSizeAction;
QAction *fitToPageAction; QAction *fitToPageAction;
QAction *resetZoomAction; QAction *resetZoomAction;
QAction *showZoomSliderlAction; QAction *showZoomSliderlAction;
QAction *increasePageZoomAction; QAction *increasePageZoomAction;
QAction *decreasePageZoomAction; QAction *decreasePageZoomAction;
QAction *showFlowAction; QAction *showFlowAction;
QAction *showEditShortcutsAction; QAction *showEditShortcutsAction;
YACReaderSlider * zoomSliderAction; YACReaderSlider * zoomSliderAction;
HttpVersionChecker * versionChecker; HttpVersionChecker * versionChecker;
QString previousComicPath; QString previousComicPath;
QString nextComicPath; QString nextComicPath;
//! Método que inicializa el interfaz. //! Método que inicializa el interfaz.
void setupUI(); void setupUI();
void createActions(); void createActions();
void createToolBars(); void createToolBars();
void refreshRecentFilesActionList(); void refreshRecentFilesActionList();
void clearRecentFiles(); void clearRecentFiles();
void getSiblingComics(QString path,QString currentComic); void getSiblingComics(QString path,QString currentComic);
//! Manejadores de evento: //! Manejadores de evento:
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent *event);
//void resizeEvent(QResizeEvent * event); //void resizeEvent(QResizeEvent * event);
void mouseDoubleClickEvent ( QMouseEvent * event ); void mouseDoubleClickEvent ( QMouseEvent * event );
void dropEvent(QDropEvent *event); void dropEvent(QDropEvent *event);
void dragEnterEvent(QDragEnterEvent *event); void dragEnterEvent(QDragEnterEvent *event);
QSettings * settings; QSettings * settings;
ComicDB currentComicDB; ComicDB currentComicDB;
QList<ComicDB> siblingComics; QList<ComicDB> siblingComics;
bool isClient; bool isClient;
QString startComicPath; QString startComicPath;
quint64 libraryId; quint64 libraryId;
//fullscreen mode in Windows for preventing this bug: QTBUG-41309 https://bugreports.qt.io/browse/QTBUG-41309 //fullscreen mode in Windows for preventing this bug: QTBUG-41309 https://bugreports.qt.io/browse/QTBUG-41309
Qt::WindowFlags previousWindowFlags; Qt::WindowFlags previousWindowFlags;
QPoint previousPos; QPoint previousPos;
QSize previousSize; QSize previousSize;
signals: signals:
void closed(); void closed();
protected: protected:
virtual void closeEvent ( QCloseEvent * event ); virtual void closeEvent ( QCloseEvent * event );
void sendComic(); void sendComic();
public: public:
MainWindowViewer(); MainWindowViewer();
~MainWindowViewer(); ~MainWindowViewer();
}; };
#endif #endif

View File

@ -1,76 +1,76 @@
#include "notifications_label_widget.h" #include "notifications_label_widget.h"
#include <QtWidgets> #include <QtWidgets>
NotificationsLabelWidget::NotificationsLabelWidget(QWidget * parent) NotificationsLabelWidget::NotificationsLabelWidget(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
QVBoxLayout *layout = new QVBoxLayout; QVBoxLayout *layout = new QVBoxLayout;
layout->setSpacing(0); layout->setSpacing(0);
layout->setMargin(0); layout->setMargin(0);
setAttribute(Qt::WA_LayoutUsesWidgetRect,true); setAttribute(Qt::WA_LayoutUsesWidgetRect,true);
effect = new QGraphicsOpacityEffect(this); effect = new QGraphicsOpacityEffect(this);
effect->setOpacity(1.0); effect->setOpacity(1.0);
anim = new QPropertyAnimation(effect,"opacity"); anim = new QPropertyAnimation(effect,"opacity");
anim->setDuration(500); anim->setDuration(500);
anim->setStartValue(1.0); anim->setStartValue(1.0);
anim->setEndValue(0.0); anim->setEndValue(0.0);
anim->setEasingCurve(QEasingCurve::InExpo); anim->setEasingCurve(QEasingCurve::InExpo);
connect(anim,SIGNAL(finished()),this,SLOT(hide())); connect(anim,SIGNAL(finished()),this,SLOT(hide()));
textLabel = new QLabel(this); textLabel = new QLabel(this);
textLabel->setAlignment(Qt::AlignVCenter|Qt::AlignHCenter); textLabel->setAlignment(Qt::AlignVCenter|Qt::AlignHCenter);
textLabel->setStyleSheet("QLabel { color : white; font-size:24px; }"); textLabel->setStyleSheet("QLabel { color : white; font-size:24px; }");
textLabel->setAttribute(Qt::WA_LayoutUsesWidgetRect,true); textLabel->setAttribute(Qt::WA_LayoutUsesWidgetRect,true);
textLabel->setFixedSize(200, 120); textLabel->setFixedSize(200, 120);
//TODO check if the effects still be broken in OSX yet //TODO check if the effects still be broken in OSX yet
#ifndef Q_OS_MAC #ifndef Q_OS_MAC
this->setGraphicsEffect(effect); this->setGraphicsEffect(effect);
#endif #endif
layout->addWidget(textLabel); layout->addWidget(textLabel);
setLayout(layout); setLayout(layout);
setFixedSize(200, 120); setFixedSize(200, 120);
updatePosition(); updatePosition();
} }
void NotificationsLabelWidget::paintEvent(QPaintEvent *) void NotificationsLabelWidget::paintEvent(QPaintEvent *)
{ {
QPainter painter(this); QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path; QPainterPath path;
path.addRoundedRect(QRectF(0, 0, width(), height()), 5.0, 5.0); path.addRoundedRect(QRectF(0, 0, width(), height()), 5.0, 5.0);
painter.setPen(Qt::NoPen); painter.setPen(Qt::NoPen);
painter.fillPath(path, QColor("#BB000000")); painter.fillPath(path, QColor("#BB000000"));
painter.drawPath(path); painter.drawPath(path);
} }
void NotificationsLabelWidget::flash() void NotificationsLabelWidget::flash()
{ {
updatePosition(); updatePosition();
anim->stop(); anim->stop();
anim->start(); anim->start();
setVisible(true); setVisible(true);
} }
void NotificationsLabelWidget::setText(const QString & text) void NotificationsLabelWidget::setText(const QString & text)
{ {
textLabel->setText(text); textLabel->setText(text);
} }
void NotificationsLabelWidget::updatePosition() void NotificationsLabelWidget::updatePosition()
{ {
QWidget * parent = dynamic_cast<QWidget *>(this->parent()); QWidget * parent = dynamic_cast<QWidget *>(this->parent());
if(parent == 0) if(parent == 0)
{ {
return; return;
} }
move(QPoint((parent->geometry().size().width()-this->width())/2,(parent->geometry().size().height()-this->height())/2)); move(QPoint((parent->geometry().size().width()-this->width())/2,(parent->geometry().size().height()-this->height())/2));
} }

View File

@ -1,30 +1,30 @@
#ifndef NOTIFICATIONS_LABEL_WIDGET_H #ifndef NOTIFICATIONS_LABEL_WIDGET_H
#define NOTIFICATIONS_LABEL_WIDGET_H #define NOTIFICATIONS_LABEL_WIDGET_H
#include <QWidget> #include <QWidget>
class QLabel; class QLabel;
class QPropertyAnimation; class QPropertyAnimation;
class QGraphicsOpacityEffect; class QGraphicsOpacityEffect;
class NotificationsLabelWidget : public QWidget class NotificationsLabelWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
QLabel * textLabel; QLabel * textLabel;
QPropertyAnimation * anim; QPropertyAnimation * anim;
QGraphicsOpacityEffect * effect; QGraphicsOpacityEffect * effect;
protected: protected:
void paintEvent(QPaintEvent *); void paintEvent(QPaintEvent *);
public: public:
NotificationsLabelWidget(QWidget * parent); NotificationsLabelWidget(QWidget * parent);
public slots: public slots:
void flash(); void flash();
void setText(const QString & text); void setText(const QString & text);
void updatePosition(); void updatePosition();
}; };
#endif #endif

View File

@ -1,325 +1,325 @@
#include "options_dialog.h" #include "options_dialog.h"
#include "configuration.h" #include "configuration.h"
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QFileDialog> #include <QFileDialog>
#include <QGroupBox> #include <QGroupBox>
#include <QRadioButton> #include <QRadioButton>
#include <QTabWidget> #include <QTabWidget>
#include <QSlider> #include <QSlider>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QLabel> #include <QLabel>
#include <QColorDialog> #include <QColorDialog>
#include <QCheckBox> #include <QCheckBox>
#include "yacreader_spin_slider_widget.h" #include "yacreader_spin_slider_widget.h"
#include "yacreader_flow_config_widget.h" #include "yacreader_flow_config_widget.h"
#ifndef NO_OPENGL #ifndef NO_OPENGL
#include "yacreader_gl_flow_config_widget.h" #include "yacreader_gl_flow_config_widget.h"
#endif #endif
OptionsDialog::OptionsDialog(QWidget * parent) OptionsDialog::OptionsDialog(QWidget * parent)
:YACReaderOptionsDialog(parent) :YACReaderOptionsDialog(parent)
{ {
QTabWidget * tabWidget = new QTabWidget(); QTabWidget * tabWidget = new QTabWidget();
QVBoxLayout * layout = new QVBoxLayout(this); QVBoxLayout * layout = new QVBoxLayout(this);
QWidget * pageGeneral = new QWidget(); QWidget * pageGeneral = new QWidget();
QWidget * pageFlow = new QWidget(); QWidget * pageFlow = new QWidget();
QWidget * pageImage = new QWidget(); QWidget * pageImage = new QWidget();
QVBoxLayout * layoutGeneral = new QVBoxLayout(); QVBoxLayout * layoutGeneral = new QVBoxLayout();
QVBoxLayout * layoutFlow = new QVBoxLayout(); QVBoxLayout * layoutFlow = new QVBoxLayout();
QVBoxLayout * layoutImageV = new QVBoxLayout(); QVBoxLayout * layoutImageV = new QVBoxLayout();
QGridLayout * layoutImage = new QGridLayout(); QGridLayout * layoutImage = new QGridLayout();
QGroupBox *slideSizeBox = new QGroupBox(tr("\"Go to flow\" size")); QGroupBox *slideSizeBox = new QGroupBox(tr("\"Go to flow\" size"));
//slideSizeLabel = new QLabel(,this); //slideSizeLabel = new QLabel(,this);
slideSize = new QSlider(this); slideSize = new QSlider(this);
slideSize->setMinimum(125); slideSize->setMinimum(125);
slideSize->setMaximum(350); slideSize->setMaximum(350);
slideSize->setPageStep(5); slideSize->setPageStep(5);
slideSize->setOrientation(Qt::Horizontal); slideSize->setOrientation(Qt::Horizontal);
QHBoxLayout * slideLayout = new QHBoxLayout(); QHBoxLayout * slideLayout = new QHBoxLayout();
slideLayout->addWidget(slideSize); slideLayout->addWidget(slideSize);
slideSizeBox->setLayout(slideLayout); slideSizeBox->setLayout(slideLayout);
QGroupBox *pathBox = new QGroupBox(tr("My comics path")); QGroupBox *pathBox = new QGroupBox(tr("My comics path"));
QHBoxLayout * path = new QHBoxLayout(); QHBoxLayout * path = new QHBoxLayout();
path->addWidget(pathEdit = new QLineEdit()); path->addWidget(pathEdit = new QLineEdit());
path->addWidget(pathFindButton = new QPushButton(QIcon(":/images/find_folder.png"),"")); path->addWidget(pathFindButton = new QPushButton(QIcon(":/images/find_folder.png"),""));
pathBox->setLayout(path); pathBox->setLayout(path);
connect(pathFindButton,SIGNAL(clicked()),this,SLOT(findFolder())); connect(pathFindButton,SIGNAL(clicked()),this,SLOT(findFolder()));
//fitToWidthRatioLabel = new QLabel(tr("Page width stretch"),this); //fitToWidthRatioLabel = new QLabel(tr("Page width stretch"),this);
/*QGroupBox *fitBox = new QGroupBox(tr("Page width stretch")); /*QGroupBox *fitBox = new QGroupBox(tr("Page width stretch"));
fitToWidthRatioS = new QSlider(this); fitToWidthRatioS = new QSlider(this);
fitToWidthRatioS->setMinimum(50); fitToWidthRatioS->setMinimum(50);
fitToWidthRatioS->setMaximum(100); fitToWidthRatioS->setMaximum(100);
fitToWidthRatioS->setPageStep(5); fitToWidthRatioS->setPageStep(5);
fitToWidthRatioS->setOrientation(Qt::Horizontal); fitToWidthRatioS->setOrientation(Qt::Horizontal);
//connect(fitToWidthRatioS,SIGNAL(valueChanged(int)),this,SLOT(fitToWidthRatio(int))); //connect(fitToWidthRatioS,SIGNAL(valueChanged(int)),this,SLOT(fitToWidthRatio(int)));
QHBoxLayout * fitLayout = new QHBoxLayout; QHBoxLayout * fitLayout = new QHBoxLayout;
fitLayout->addWidget(fitToWidthRatioS); fitLayout->addWidget(fitToWidthRatioS);
fitBox->setLayout(fitLayout);*/ fitBox->setLayout(fitLayout);*/
QHBoxLayout * colorSelection = new QHBoxLayout; QHBoxLayout * colorSelection = new QHBoxLayout;
backgroundColor = new QLabel(); backgroundColor = new QLabel();
QPalette pal = backgroundColor->palette(); QPalette pal = backgroundColor->palette();
pal.setColor(backgroundColor->backgroundRole(), Qt::black); pal.setColor(backgroundColor->backgroundRole(), Qt::black);
backgroundColor->setPalette(pal); backgroundColor->setPalette(pal);
backgroundColor->setAutoFillBackground(true); backgroundColor->setAutoFillBackground(true);
colorDialog = new QColorDialog(Qt::red,this); colorDialog = new QColorDialog(Qt::red,this);
connect(colorDialog,SIGNAL(colorSelected(QColor)),this,SLOT(updateColor(QColor))); connect(colorDialog,SIGNAL(colorSelected(QColor)),this,SLOT(updateColor(QColor)));
QGroupBox *colorBox = new QGroupBox(tr("Background color")); QGroupBox *colorBox = new QGroupBox(tr("Background color"));
//backgroundColor->setMinimumWidth(100); //backgroundColor->setMinimumWidth(100);
colorSelection->addWidget(backgroundColor); colorSelection->addWidget(backgroundColor);
colorSelection->addWidget(selectBackgroundColorButton = new QPushButton(tr("Choose"))); colorSelection->addWidget(selectBackgroundColorButton = new QPushButton(tr("Choose")));
colorSelection->setStretchFactor(backgroundColor,1); colorSelection->setStretchFactor(backgroundColor,1);
colorSelection->setStretchFactor(selectBackgroundColorButton,0); colorSelection->setStretchFactor(selectBackgroundColorButton,0);
//colorSelection->addStretch(); //colorSelection->addStretch();
connect(selectBackgroundColorButton, SIGNAL(clicked()), colorDialog, SLOT(show())); connect(selectBackgroundColorButton, SIGNAL(clicked()), colorDialog, SLOT(show()));
colorBox->setLayout(colorSelection); colorBox->setLayout(colorSelection);
brightnessS = new YACReaderSpinSliderWidget(this,true); brightnessS = new YACReaderSpinSliderWidget(this,true);
brightnessS->setRange(0,100); brightnessS->setRange(0,100);
//brightnessS->setText(tr("Brightness")); //brightnessS->setText(tr("Brightness"));
brightnessS->setTracking(false); brightnessS->setTracking(false);
connect(brightnessS,SIGNAL(valueChanged(int)),this,SLOT(brightnessChanged(int))); connect(brightnessS,SIGNAL(valueChanged(int)),this,SLOT(brightnessChanged(int)));
contrastS = new YACReaderSpinSliderWidget(this,true); contrastS = new YACReaderSpinSliderWidget(this,true);
contrastS->setRange(0,250); contrastS->setRange(0,250);
//contrastS->setText(tr("Contrast")); //contrastS->setText(tr("Contrast"));
contrastS->setTracking(false); contrastS->setTracking(false);
connect(contrastS,SIGNAL(valueChanged(int)),this,SLOT(contrastChanged(int))); connect(contrastS,SIGNAL(valueChanged(int)),this,SLOT(contrastChanged(int)));
gammaS = new YACReaderSpinSliderWidget(this,true); gammaS = new YACReaderSpinSliderWidget(this,true);
gammaS->setRange(0,250); gammaS->setRange(0,250);
//gammaS->setText(tr("Gamma")); //gammaS->setText(tr("Gamma"));
gammaS->setTracking(false); gammaS->setTracking(false);
connect(gammaS,SIGNAL(valueChanged(int)),this,SLOT(gammaChanged(int))); connect(gammaS,SIGNAL(valueChanged(int)),this,SLOT(gammaChanged(int)));
//connect(brightnessS,SIGNAL(valueChanged(int)),this,SIGNAL(changedOptions())); //connect(brightnessS,SIGNAL(valueChanged(int)),this,SIGNAL(changedOptions()));
quickNavi = new QCheckBox(tr("Quick Navigation Mode")); quickNavi = new QCheckBox(tr("Quick Navigation Mode"));
disableShowOnMouseOver = new QCheckBox(tr("Disable mouse over activation")); disableShowOnMouseOver = new QCheckBox(tr("Disable mouse over activation"));
QHBoxLayout * buttons = new QHBoxLayout(); QHBoxLayout * buttons = new QHBoxLayout();
buttons->addStretch(); buttons->addStretch();
buttons->addWidget(new QLabel(tr("Restart is needed"))); buttons->addWidget(new QLabel(tr("Restart is needed")));
buttons->addWidget(accept); buttons->addWidget(accept);
buttons->addWidget(cancel); buttons->addWidget(cancel);
layoutGeneral->addWidget(pathBox); layoutGeneral->addWidget(pathBox);
layoutGeneral->addWidget(slideSizeBox); layoutGeneral->addWidget(slideSizeBox);
//layoutGeneral->addWidget(fitBox); //layoutGeneral->addWidget(fitBox);
layoutGeneral->addWidget(colorBox); layoutGeneral->addWidget(colorBox);
layoutGeneral->addWidget(shortcutsBox); layoutGeneral->addWidget(shortcutsBox);
layoutGeneral->addStretch(); layoutGeneral->addStretch();
layoutFlow->addWidget(sw); layoutFlow->addWidget(sw);
#ifndef NO_OPENGL #ifndef NO_OPENGL
layoutFlow->addWidget(gl); layoutFlow->addWidget(gl);
layoutFlow->addWidget(useGL); layoutFlow->addWidget(useGL);
#endif #endif
layoutFlow->addWidget(quickNavi); layoutFlow->addWidget(quickNavi);
layoutFlow->addWidget(disableShowOnMouseOver); layoutFlow->addWidget(disableShowOnMouseOver);
layoutFlow->addStretch(); layoutFlow->addStretch();
layoutImage->addWidget(new QLabel(tr("Brightness")),0,0); layoutImage->addWidget(new QLabel(tr("Brightness")),0,0);
layoutImage->addWidget(new QLabel(tr("Contrast")),1,0); layoutImage->addWidget(new QLabel(tr("Contrast")),1,0);
layoutImage->addWidget(new QLabel(tr("Gamma")),2,0); layoutImage->addWidget(new QLabel(tr("Gamma")),2,0);
layoutImage->addWidget(brightnessS,0,1); layoutImage->addWidget(brightnessS,0,1);
layoutImage->addWidget(contrastS,1,1); layoutImage->addWidget(contrastS,1,1);
layoutImage->addWidget(gammaS,2,1); layoutImage->addWidget(gammaS,2,1);
QPushButton * pushButton = new QPushButton(tr("Reset")); QPushButton * pushButton = new QPushButton(tr("Reset"));
connect(pushButton,SIGNAL(pressed()),this,SLOT(resetImageConfig())); connect(pushButton,SIGNAL(pressed()),this,SLOT(resetImageConfig()));
layoutImage->addWidget(pushButton,3,0); layoutImage->addWidget(pushButton,3,0);
layoutImage->setColumnStretch(1,1); layoutImage->setColumnStretch(1,1);
QGroupBox *imageBox = new QGroupBox(tr("Image options")); QGroupBox *imageBox = new QGroupBox(tr("Image options"));
imageBox->setLayout(layoutImage); imageBox->setLayout(layoutImage);
layoutImageV->addWidget(imageBox); layoutImageV->addWidget(imageBox);
layoutImageV->addStretch(); layoutImageV->addStretch();
pageGeneral->setLayout(layoutGeneral); pageGeneral->setLayout(layoutGeneral);
pageFlow->setLayout(layoutFlow); pageFlow->setLayout(layoutFlow);
pageImage->setLayout(layoutImageV); pageImage->setLayout(layoutImageV);
tabWidget->addTab(pageGeneral,tr("General")); tabWidget->addTab(pageGeneral,tr("General"));
tabWidget->addTab(pageFlow,tr("Page Flow")); tabWidget->addTab(pageFlow,tr("Page Flow"));
tabWidget->addTab(pageImage,tr("Image adjustment")); tabWidget->addTab(pageImage,tr("Image adjustment"));
layout->addWidget(tabWidget); layout->addWidget(tabWidget);
layout->addLayout(buttons); layout->addLayout(buttons);
setLayout(layout); setLayout(layout);
//disable vSyncCheck //disable vSyncCheck
#ifndef NO_OPENGL #ifndef NO_OPENGL
gl->vSyncCheck->hide(); gl->vSyncCheck->hide();
#endif #endif
//restoreOptions(); //load options //restoreOptions(); //load options
//resize(400,0); //resize(400,0);
setModal (true); setModal (true);
setWindowTitle(tr("Options")); setWindowTitle(tr("Options"));
this->layout()->setSizeConstraint(QLayout::SetFixedSize); this->layout()->setSizeConstraint(QLayout::SetFixedSize);
} }
void OptionsDialog::findFolder() void OptionsDialog::findFolder()
{ {
QString s = QFileDialog::getExistingDirectory(0,tr("Comics directory"),"."); QString s = QFileDialog::getExistingDirectory(0,tr("Comics directory"),".");
if(!s.isEmpty()) if(!s.isEmpty())
{ {
pathEdit->setText(s); pathEdit->setText(s);
} }
} }
void OptionsDialog::saveOptions() void OptionsDialog::saveOptions()
{ {
settings->setValue(GO_TO_FLOW_SIZE,QSize(static_cast<int>(slideSize->sliderPosition()/SLIDE_ASPECT_RATIO),slideSize->sliderPosition())); settings->setValue(GO_TO_FLOW_SIZE,QSize(static_cast<int>(slideSize->sliderPosition()/SLIDE_ASPECT_RATIO),slideSize->sliderPosition()));
if(sw->radio1->isChecked()) if(sw->radio1->isChecked())
settings->setValue(FLOW_TYPE_SW,0); settings->setValue(FLOW_TYPE_SW,0);
if(sw->radio2->isChecked()) if(sw->radio2->isChecked())
settings->setValue(FLOW_TYPE_SW,1); settings->setValue(FLOW_TYPE_SW,1);
if(sw->radio3->isChecked()) if(sw->radio3->isChecked())
settings->setValue(FLOW_TYPE_SW,2); settings->setValue(FLOW_TYPE_SW,2);
settings->setValue(PATH,pathEdit->text()); settings->setValue(PATH,pathEdit->text());
settings->setValue(BACKGROUND_COLOR,colorDialog->currentColor()); settings->setValue(BACKGROUND_COLOR,colorDialog->currentColor());
//settings->setValue(FIT_TO_WIDTH_RATIO,fitToWidthRatioS->sliderPosition()/100.0); //settings->setValue(FIT_TO_WIDTH_RATIO,fitToWidthRatioS->sliderPosition()/100.0);
settings->setValue(QUICK_NAVI_MODE,quickNavi->isChecked()); settings->setValue(QUICK_NAVI_MODE,quickNavi->isChecked());
settings->setValue(DISABLE_MOUSE_OVER_GOTO_FLOW,disableShowOnMouseOver->isChecked()); settings->setValue(DISABLE_MOUSE_OVER_GOTO_FLOW,disableShowOnMouseOver->isChecked());
YACReaderOptionsDialog::saveOptions(); YACReaderOptionsDialog::saveOptions();
} }
void OptionsDialog::restoreOptions(QSettings * settings) void OptionsDialog::restoreOptions(QSettings * settings)
{ {
YACReaderOptionsDialog::restoreOptions(settings); YACReaderOptionsDialog::restoreOptions(settings);
slideSize->setSliderPosition(settings->value(GO_TO_FLOW_SIZE).toSize().height()); slideSize->setSliderPosition(settings->value(GO_TO_FLOW_SIZE).toSize().height());
switch(settings->value(FLOW_TYPE_SW).toInt()) switch(settings->value(FLOW_TYPE_SW).toInt())
{ {
case 0: case 0:
sw->radio1->setChecked(true); sw->radio1->setChecked(true);
break; break;
case 1: case 1:
sw->radio2->setChecked(true); sw->radio2->setChecked(true);
break; break;
case 2: case 2:
sw->radio3->setChecked(true); sw->radio3->setChecked(true);
break; break;
default: default:
sw->radio1->setChecked(true); sw->radio1->setChecked(true);
break; break;
} }
pathEdit->setText(settings->value(PATH).toString()); pathEdit->setText(settings->value(PATH).toString());
updateColor(settings->value(BACKGROUND_COLOR).value<QColor>()); updateColor(settings->value(BACKGROUND_COLOR).value<QColor>());
//fitToWidthRatioS->setSliderPosition(settings->value(FIT_TO_WIDTH_RATIO).toFloat()*100); //fitToWidthRatioS->setSliderPosition(settings->value(FIT_TO_WIDTH_RATIO).toFloat()*100);
quickNavi->setChecked(settings->value(QUICK_NAVI_MODE).toBool()); quickNavi->setChecked(settings->value(QUICK_NAVI_MODE).toBool());
disableShowOnMouseOver->setChecked(settings->value(DISABLE_MOUSE_OVER_GOTO_FLOW).toBool()); disableShowOnMouseOver->setChecked(settings->value(DISABLE_MOUSE_OVER_GOTO_FLOW).toBool());
brightnessS->setValue(settings->value(BRIGHTNESS,0).toInt()); brightnessS->setValue(settings->value(BRIGHTNESS,0).toInt());
contrastS->setValue(settings->value(CONTRAST,100).toInt()); contrastS->setValue(settings->value(CONTRAST,100).toInt());
gammaS->setValue(settings->value(GAMMA,100).toInt()); gammaS->setValue(settings->value(GAMMA,100).toInt());
} }
void OptionsDialog::updateColor(const QColor & color) void OptionsDialog::updateColor(const QColor & color)
{ {
QPalette pal = backgroundColor->palette(); QPalette pal = backgroundColor->palette();
pal.setColor(backgroundColor->backgroundRole(), color); pal.setColor(backgroundColor->backgroundRole(), color);
backgroundColor->setPalette(pal); backgroundColor->setPalette(pal);
backgroundColor->setAutoFillBackground(true); backgroundColor->setAutoFillBackground(true);
colorDialog->setCurrentColor(color); colorDialog->setCurrentColor(color);
settings->setValue(BACKGROUND_COLOR,color); settings->setValue(BACKGROUND_COLOR,color);
emit(changedOptions()); emit(changedOptions());
} }
/*void OptionsDialog::fitToWidthRatio(int value) /*void OptionsDialog::fitToWidthRatio(int value)
{ {
Configuration::getConfiguration().setFitToWidthRatio(value/100.0); Configuration::getConfiguration().setFitToWidthRatio(value/100.0);
emit(fitToWidthRatioChanged(value/100.0)); emit(fitToWidthRatioChanged(value/100.0));
}*/ }*/
void OptionsDialog::brightnessChanged(int value) void OptionsDialog::brightnessChanged(int value)
{ {
QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat); QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat);
settings.setValue(BRIGHTNESS,value); settings.setValue(BRIGHTNESS,value);
emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue()); emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue());
//emit(changedImageOptions()); //emit(changedImageOptions());
} }
void OptionsDialog::contrastChanged(int value) void OptionsDialog::contrastChanged(int value)
{ {
QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat); QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat);
settings.setValue(CONTRAST,value); settings.setValue(CONTRAST,value);
emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue()); emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue());
///emit(changedImageOptions()); ///emit(changedImageOptions());
} }
void OptionsDialog::gammaChanged(int value) void OptionsDialog::gammaChanged(int value)
{ {
QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat); QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat);
settings.setValue(GAMMA,value); settings.setValue(GAMMA,value);
emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue()); emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue());
//emit(changedImageOptions()); //emit(changedImageOptions());
} }
void OptionsDialog::resetImageConfig() void OptionsDialog::resetImageConfig()
{ {
brightnessS->setValue(0); brightnessS->setValue(0);
contrastS->setValue(100); contrastS->setValue(100);
gammaS->setValue(100); gammaS->setValue(100);
QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat); QSettings settings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat);
settings.setValue(BRIGHTNESS,0); settings.setValue(BRIGHTNESS,0);
settings.setValue(CONTRAST,100); settings.setValue(CONTRAST,100);
settings.setValue(GAMMA,100); settings.setValue(GAMMA,100);
emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue()); emit changedFilters(brightnessS->getValue(), contrastS->getValue(), gammaS->getValue());
//emit(changedImageOptions()); //emit(changedImageOptions());
} }
void OptionsDialog::show() void OptionsDialog::show()
{ {
//TODO solucionar el tema de las settings, esto sólo debería aparecer en una única línea de código //TODO solucionar el tema de las settings, esto sólo debería aparecer en una única línea de código
QSettings *s = new QSettings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat); QSettings *s = new QSettings(YACReader::getSettingsPath()+"/YACReader.ini",QSettings::IniFormat);
//fitToWidthRatioS->disconnect(); //fitToWidthRatioS->disconnect();
//fitToWidthRatioS->setSliderPosition(settings->value(FIT_TO_WIDTH_RATIO).toFloat()*100); //fitToWidthRatioS->setSliderPosition(settings->value(FIT_TO_WIDTH_RATIO).toFloat()*100);
//connect(fitToWidthRatioS,SIGNAL(valueChanged(int)),this,SLOT(fitToWidthRatio(int))); //connect(fitToWidthRatioS,SIGNAL(valueChanged(int)),this,SLOT(fitToWidthRatio(int)));
QDialog::show(); QDialog::show();
delete s; delete s;
} }
void OptionsDialog::setFilters(int brightness, int contrast, int gamma) void OptionsDialog::setFilters(int brightness, int contrast, int gamma)
{ {
if(brightness != -1) if(brightness != -1)
brightnessS->setValue(brightness); brightnessS->setValue(brightness);
else else
brightnessS->setValue(0); brightnessS->setValue(0);
if(contrast != -1) if(contrast != -1)
contrastS->setValue(contrast); contrastS->setValue(contrast);
else else
contrastS->setValue(100); contrastS->setValue(100);
if(gamma != -1) if(gamma != -1)
gammaS->setValue(gamma); gammaS->setValue(gamma);
else else
gammaS->setValue(100); gammaS->setValue(100);
} }

View File

@ -1,72 +1,72 @@
#ifndef __OPTIONS_DIALOG_H #ifndef __OPTIONS_DIALOG_H
#define __OPTIONS_DIALOG_H #define __OPTIONS_DIALOG_H
#include "yacreader_options_dialog.h" #include "yacreader_options_dialog.h"
class QDialog; class QDialog;
class QLabel; class QLabel;
class QLineEdit; class QLineEdit;
class QPushButton; class QPushButton;
class QSlider; class QSlider;
class QPushButton; class QPushButton;
class QRadioButton; class QRadioButton;
class QColorDialog; class QColorDialog;
class YACReaderSpinSliderWidget; class YACReaderSpinSliderWidget;
class OptionsDialog : public YACReaderOptionsDialog class OptionsDialog : public YACReaderOptionsDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
OptionsDialog(QWidget * parent = 0); OptionsDialog(QWidget * parent = 0);
private: private:
//QLabel * pathLabel; //QLabel * pathLabel;
QLineEdit * pathEdit; QLineEdit * pathEdit;
QPushButton * pathFindButton; QPushButton * pathFindButton;
QCheckBox * quickNavi; QCheckBox * quickNavi;
QCheckBox * disableShowOnMouseOver; QCheckBox * disableShowOnMouseOver;
QLabel * magGlassSizeLabel; QLabel * magGlassSizeLabel;
QLabel * zoomLevel; QLabel * zoomLevel;
//QLabel * slideSizeLabel; //QLabel * slideSizeLabel;
QSlider * slideSize; QSlider * slideSize;
//QLabel * fitToWidthRatioLabel; //QLabel * fitToWidthRatioLabel;
//QSlider * fitToWidthRatioS; //QSlider * fitToWidthRatioS;
QLabel * backgroundColor; QLabel * backgroundColor;
QPushButton * selectBackgroundColorButton; QPushButton * selectBackgroundColorButton;
QColorDialog * colorDialog; QColorDialog * colorDialog;
YACReaderSpinSliderWidget * brightnessS; YACReaderSpinSliderWidget * brightnessS;
YACReaderSpinSliderWidget * contrastS; YACReaderSpinSliderWidget * contrastS;
YACReaderSpinSliderWidget * gammaS; YACReaderSpinSliderWidget * gammaS;
public slots: public slots:
void saveOptions(); void saveOptions();
void restoreOptions(QSettings * settings); void restoreOptions(QSettings * settings);
void findFolder(); void findFolder();
void updateColor(const QColor & color); void updateColor(const QColor & color);
//void fitToWidthRatio(int value); //void fitToWidthRatio(int value);
void brightnessChanged(int value); void brightnessChanged(int value);
void contrastChanged(int value); void contrastChanged(int value);
void gammaChanged(int value); void gammaChanged(int value);
void resetImageConfig(); void resetImageConfig();
void show(); void show();
void setFilters(int brightness, int contrast, int gamma); void setFilters(int brightness, int contrast, int gamma);
signals: signals:
void changedOptions(); void changedOptions();
void changedImageOptions(); void changedImageOptions();
void changedFilters(int brightness, int contrast, int gamma); void changedFilters(int brightness, int contrast, int gamma);
//void fitToWidthRatioChanged(float ratio); //void fitToWidthRatioChanged(float ratio);
}; };
#endif #endif

View File

@ -1,105 +1,105 @@
#include "page_label_widget.h" #include "page_label_widget.h"
#include <QtWidgets> #include <QtWidgets>
PageLabelWidget::PageLabelWidget(QWidget * parent) PageLabelWidget::PageLabelWidget(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
animation = new QPropertyAnimation(this,"pos"); animation = new QPropertyAnimation(this,"pos");
animation->setDuration(150); animation->setDuration(150);
animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),-this->height())); animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),-this->height()));
int verticalRes = QApplication::desktop()->screenGeometry().height(); int verticalRes = QApplication::desktop()->screenGeometry().height();
QHBoxLayout *layout = new QHBoxLayout; QHBoxLayout *layout = new QHBoxLayout;
layout->setMargin(0); layout->setMargin(0);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
QSize labelSize; QSize labelSize;
if (verticalRes <= 1024) if (verticalRes <= 1024)
labelSize = QSize(135, 30); labelSize = QSize(135, 30);
else if (verticalRes <= 1200) else if (verticalRes <= 1200)
labelSize = QSize(170, 35); labelSize = QSize(170, 35);
else else
labelSize = QSize(205, 45); labelSize = QSize(205, 45);
textLabel = new QLabel(this); textLabel = new QLabel(this);
textLabel->setAlignment(Qt::AlignVCenter|Qt::AlignHCenter); textLabel->setAlignment(Qt::AlignVCenter|Qt::AlignHCenter);
if(verticalRes <= 1024) if(verticalRes <= 1024)
textLabel->setStyleSheet("QLabel { color : white; font-size:12px; padding-left:8px; }"); textLabel->setStyleSheet("QLabel { color : white; font-size:12px; padding-left:8px; }");
else if (verticalRes <= 1200) else if (verticalRes <= 1200)
textLabel->setStyleSheet("QLabel { color : white; font-size:16px; padding-left:8px;}"); textLabel->setStyleSheet("QLabel { color : white; font-size:16px; padding-left:8px;}");
else else
textLabel->setStyleSheet("QLabel { color : white; font-size:20px; padding-left:8px; }"); textLabel->setStyleSheet("QLabel { color : white; font-size:20px; padding-left:8px; }");
setFixedSize(labelSize); setFixedSize(labelSize);
if(parent != 0) if(parent != 0)
move(QPoint((parent->geometry().size().width()-this->width()),-this->height())); move(QPoint((parent->geometry().size().width()-this->width()),-this->height()));
layout->addWidget(textLabel, 0 , Qt::AlignCenter); layout->addWidget(textLabel, 0 , Qt::AlignCenter);
setLayout(layout); setLayout(layout);
} }
void PageLabelWidget::show() void PageLabelWidget::show()
{ {
if(this->pos().y() <= 0 && animation->state()!=QPropertyAnimation::Running) if(this->pos().y() <= 0 && animation->state()!=QPropertyAnimation::Running)
{ {
QWidget * parent = dynamic_cast<QWidget *>(this->parent()); QWidget * parent = dynamic_cast<QWidget *>(this->parent());
if(parent == 0) if(parent == 0)
{ {
return; return;
} }
QWidget::show(); QWidget::show();
//connect(animation,SIGNAL(finished()),this,SLOT(QWidget::hide())); //connect(animation,SIGNAL(finished()),this,SLOT(QWidget::hide()));
animation->disconnect(); animation->disconnect();
animation->setStartValue(QPoint((parent->geometry().size().width()-this->width()),-this->height())); animation->setStartValue(QPoint((parent->geometry().size().width()-this->width()),-this->height()));
animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),0)); animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),0));
animation->start(); animation->start();
} }
} }
void PageLabelWidget::hide() void PageLabelWidget::hide()
{ {
if(this->pos().y() >= 0 && animation->state()!=QPropertyAnimation::Running) if(this->pos().y() >= 0 && animation->state()!=QPropertyAnimation::Running)
{ {
QWidget * parent = dynamic_cast<QWidget *>(this->parent()); QWidget * parent = dynamic_cast<QWidget *>(this->parent());
if(parent == 0) if(parent == 0)
{ {
return; return;
} }
//connect(animation,SIGNAL(finished()),this,SLOT(setHidden())); //connect(animation,SIGNAL(finished()),this,SLOT(setHidden()));
animation->setStartValue(QPoint((parent->geometry().size().width()-this->width()),0)); animation->setStartValue(QPoint((parent->geometry().size().width()-this->width()),0));
animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),-this->height())); animation->setEndValue(QPoint((parent->geometry().size().width()-this->width()),-this->height()));
animation->start(); animation->start();
} }
} }
void PageLabelWidget::setText(const QString & text) void PageLabelWidget::setText(const QString & text)
{ {
textLabel->setText(text); textLabel->setText(text);
} }
void PageLabelWidget::paintEvent(QPaintEvent *) void PageLabelWidget::paintEvent(QPaintEvent *)
{ {
QPainter painter(this); QPainter painter(this);
painter.fillRect(0,0,width(),height(),QColor("#BB000000")); painter.fillRect(0,0,width(),height(),QColor("#BB000000"));
} }
void PageLabelWidget::updatePosition() void PageLabelWidget::updatePosition()
{ {
QWidget * parent = dynamic_cast<QWidget *>(this->parent()); QWidget * parent = dynamic_cast<QWidget *>(this->parent());
if(parent == 0) if(parent == 0)
{ {
return; return;
} }
animation->stop(); animation->stop();
if (animation->endValue().toPoint().y() == 0) if (animation->endValue().toPoint().y() == 0)
move(QPoint((parent->geometry().size().width()-this->width()),0)); move(QPoint((parent->geometry().size().width()-this->width()),0));
else else
move(QPoint((parent->geometry().size().width()-this->width()),-this->height())); move(QPoint((parent->geometry().size().width()-this->width()),-this->height()));
} }

View File

@ -1,29 +1,29 @@
#ifndef PAGE_LABEL_WIDGET_H #ifndef PAGE_LABEL_WIDGET_H
#define PAGE_LABEL_WIDGET_H #define PAGE_LABEL_WIDGET_H
#include <QWidget> #include <QWidget>
class QLabel; class QLabel;
class QPropertyAnimation; class QPropertyAnimation;
class PageLabelWidget : public QWidget class PageLabelWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
QLabel * textLabel; QLabel * textLabel;
QPropertyAnimation * animation; QPropertyAnimation * animation;
protected: protected:
virtual void paintEvent(QPaintEvent *); virtual void paintEvent(QPaintEvent *);
public: public:
PageLabelWidget(QWidget * parent); PageLabelWidget(QWidget * parent);
public slots: public slots:
void show(); void show();
void hide(); void hide();
void setText(const QString & text); void setText(const QString & text);
void updatePosition(); void updatePosition();
}; };
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -1,216 +1,216 @@
#ifndef RENDER_H #ifndef RENDER_H
#define RENDER_H #define RENDER_H
#include <QImage> #include <QImage>
#include <QPixmap> #include <QPixmap>
#include <QPainter> #include <QPainter>
#include <QThread> #include <QThread>
#include <QByteArray> #include <QByteArray>
#include <QVector> #include <QVector>
#include "comic.h" #include "comic.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// FILTERS // FILTERS
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <QThread> #include <QThread>
class Comic; class Comic;
class ComicDB; class ComicDB;
class Render; class Render;
class ImageFilter { class ImageFilter {
public: public:
ImageFilter(){}; ImageFilter(){};
virtual ~ImageFilter() {}; virtual ~ImageFilter() {};
virtual QImage setFilter(const QImage & image) = 0; virtual QImage setFilter(const QImage & image) = 0;
inline int getLevel() {return level;}; inline int getLevel() {return level;};
inline void setLevel(int l) {level = l;}; inline void setLevel(int l) {level = l;};
protected: protected:
int level; int level;
}; };
class MeanNoiseReductionFilter : public ImageFilter { class MeanNoiseReductionFilter : public ImageFilter {
public: public:
enum NeighborghoodSize{SMALL=9, LARGE=25 }; enum NeighborghoodSize{SMALL=9, LARGE=25 };
MeanNoiseReductionFilter(enum NeighborghoodSize ns = SMALL); MeanNoiseReductionFilter(enum NeighborghoodSize ns = SMALL);
virtual QImage setFilter(const QImage & image); virtual QImage setFilter(const QImage & image);
private: private:
enum NeighborghoodSize neighborghoodSize; enum NeighborghoodSize neighborghoodSize;
}; };
class MedianNoiseReductionFilter : public ImageFilter { class MedianNoiseReductionFilter : public ImageFilter {
public: public:
enum NeighborghoodSize{SMALL=9, LARGE=25 }; enum NeighborghoodSize{SMALL=9, LARGE=25 };
MedianNoiseReductionFilter(enum NeighborghoodSize ns = SMALL); MedianNoiseReductionFilter(enum NeighborghoodSize ns = SMALL);
virtual QImage setFilter(const QImage & image); virtual QImage setFilter(const QImage & image);
private: private:
enum NeighborghoodSize neighborghoodSize; enum NeighborghoodSize neighborghoodSize;
}; };
class BrightnessFilter : public ImageFilter { class BrightnessFilter : public ImageFilter {
public: public:
BrightnessFilter(int l=-1); BrightnessFilter(int l=-1);
virtual QImage setFilter(const QImage & image); virtual QImage setFilter(const QImage & image);
}; };
class ContrastFilter : public ImageFilter { class ContrastFilter : public ImageFilter {
public: public:
ContrastFilter(int l=-1); ContrastFilter(int l=-1);
virtual QImage setFilter(const QImage & image); virtual QImage setFilter(const QImage & image);
}; };
class GammaFilter : public ImageFilter { class GammaFilter : public ImageFilter {
public: public:
GammaFilter(int l=-1); GammaFilter(int l=-1);
virtual QImage setFilter(const QImage & image); virtual QImage setFilter(const QImage & image);
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// RENDER // RENDER
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
class PageRender : public QThread class PageRender : public QThread
{ {
Q_OBJECT Q_OBJECT
public: public:
PageRender(); PageRender();
PageRender(Render * render,int numPage, const QByteArray & rawData, QImage * page,unsigned int degrees=0, QVector<ImageFilter *> filters = QVector<ImageFilter *>()); PageRender(Render * render,int numPage, const QByteArray & rawData, QImage * page,unsigned int degrees=0, QVector<ImageFilter *> filters = QVector<ImageFilter *>());
int getNumPage(){return numPage;}; int getNumPage(){return numPage;};
void setData(const QByteArray & rawData){data = rawData;}; void setData(const QByteArray & rawData){data = rawData;};
void setPage(QImage * p){page = p;}; void setPage(QImage * p){page = p;};
void setRotation(unsigned int d){degrees = d;}; void setRotation(unsigned int d){degrees = d;};
void setFilters(QVector<ImageFilter *> f){filters = f;}; void setFilters(QVector<ImageFilter *> f){filters = f;};
private: private:
int numPage; int numPage;
QByteArray data; QByteArray data;
QImage * page; QImage * page;
unsigned int degrees; unsigned int degrees;
QVector<ImageFilter *> filters; QVector<ImageFilter *> filters;
void run(); void run();
Render * render; Render * render;
signals: signals:
void pageReady(int); void pageReady(int);
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// RENDER // RENDER
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/*class DoublePageRender : public PageRender /*class DoublePageRender : public PageRender
{ {
Q_OBJECT Q_OBJECT
public: public:
DoublePageRender(Render * render, int firstPage, const QByteArray & firstPageData,const QByteArray & secondPageData, QImage * page,unsigned int degrees=0, QVector<ImageFilter *> filters = QVector<ImageFilter *>()); DoublePageRender(Render * render, int firstPage, const QByteArray & firstPageData,const QByteArray & secondPageData, QImage * page,unsigned int degrees=0, QVector<ImageFilter *> filters = QVector<ImageFilter *>());
private: private:
int numPage; int numPage;
QByteArray data; QByteArray data;
QByteArray data2; QByteArray data2;
QImage * page; QImage * page;
unsigned int degrees; unsigned int degrees;
QVector<ImageFilter *> filters; QVector<ImageFilter *> filters;
void run(); void run();
Render * render; Render * render;
signals: signals:
void pageReady(int); void pageReady(int);
}; };
*/ */
class Render : public QObject { class Render : public QObject {
Q_OBJECT Q_OBJECT
public: public:
Render(); Render();
~Render(); ~Render();
public slots: public slots:
void render(); void render();
QPixmap * getCurrentPage(); QPixmap * getCurrentPage();
QPixmap * getCurrentDoublePage(); QPixmap * getCurrentDoublePage();
QPixmap * getCurrentDoubleMangaPage(); QPixmap * getCurrentDoubleMangaPage();
bool currentPageIsDoublePage(); bool currentPageIsDoublePage();
bool nextPageIsDoublePage(); bool nextPageIsDoublePage();
bool previousPageIsDoublePage(); bool previousPageIsDoublePage();
void goTo(int index); void goTo(int index);
void doublePageSwitch(); void doublePageSwitch();
void doubleMangaPageSwitch(); void doubleMangaPageSwitch();
void setRotation(int degrees); void setRotation(int degrees);
void setComic(Comic * c); void setComic(Comic * c);
void prepareAvailablePage(int page); void prepareAvailablePage(int page);
void update(); void update();
void setNumPages(unsigned int numPages); void setNumPages(unsigned int numPages);
void pageRawDataReady(int page); void pageRawDataReady(int page);
//--comic interface //--comic interface
void nextPage(); void nextPage();
void previousPage(); void previousPage();
void nextDoublePage(); void nextDoublePage();
void previousDoublePage(); void previousDoublePage();
void load(const QString & path, const ComicDB & comic); void load(const QString & path, const ComicDB & comic);
void load(const QString & path, int atPage); void load(const QString & path, int atPage);
void createComic(const QString & path); void createComic(const QString & path);
void loadComic(const QString & path,const ComicDB & comic); void loadComic(const QString & path,const ComicDB & comic);
void loadComic(const QString & path, int atPage); void loadComic(const QString & path, int atPage);
void startLoad(); void startLoad();
void rotateRight(); void rotateRight();
void rotateLeft(); void rotateLeft();
unsigned int getIndex(); unsigned int getIndex();
unsigned int numPages(); unsigned int numPages();
bool hasLoadedComic(); bool hasLoadedComic();
void updateBuffer(); void updateBuffer();
void fillBuffer(); void fillBuffer();
void invalidate(); void invalidate();
QString getCurrentPagesInformation(); QString getCurrentPagesInformation();
void setBookmark(); void setBookmark();
void removeBookmark(); void removeBookmark();
void save(); void save();
void reset(); void reset();
void reload(); void reload();
void updateFilters(int brightness, int contrast, int gamma); void updateFilters(int brightness, int contrast, int gamma);
Bookmarks * getBookmarks(); Bookmarks * getBookmarks();
//sets the firt page to render //sets the firt page to render
void renderAt(int page); void renderAt(int page);
signals: signals:
void currentPageReady(); void currentPageReady();
void processingPage(); void processingPage();
void imagesLoaded(); void imagesLoaded();
void imageLoaded(int index); void imageLoaded(int index);
void imageLoaded(int index,const QByteArray & image); void imageLoaded(int index,const QByteArray & image);
void pageChanged(int index); void pageChanged(int index);
void numPages(unsigned int numPages); void numPages(unsigned int numPages);
void errorOpening(); void errorOpening();
void errorOpening(QString); void errorOpening(QString);
void crcError(QString); void crcError(QString);
void currentPageIsBookmark(bool); void currentPageIsBookmark(bool);
void isLast(); void isLast();
void isCover(); void isCover();
void bookmarksUpdated(); void bookmarksUpdated();
private: private:
Comic * comic; Comic * comic;
bool doublePage; bool doublePage;
bool doubleMangaPage; bool doubleMangaPage;
int previousIndex; int previousIndex;
int currentIndex; int currentIndex;
//QPixmap * currentPage; //QPixmap * currentPage;
int currentPageBufferedIndex; int currentPageBufferedIndex;
int numLeftPages; int numLeftPages;
int numRightPages; int numRightPages;
QList<PageRender *> pageRenders; QList<PageRender *> pageRenders;
QList<QImage *> buffer; QList<QImage *> buffer;
void loadAll(); void loadAll();
void updateRightPages(); void updateRightPages();
void updateLeftPages(); void updateLeftPages();
bool loadedComic; bool loadedComic;
QList<int> pagesEmited; QList<int> pagesEmited;
QVector<bool> pagesReady; QVector<bool> pagesReady;
int imageRotation; int imageRotation;
QVector<ImageFilter *> filters; QVector<ImageFilter *> filters;
QMutex mutex; QMutex mutex;
friend class PageRender; friend class PageRender;
}; };
#endif // RENDER_H #endif // RENDER_H

View File

@ -1,55 +1,55 @@
#include "shortcuts_dialog.h" #include "shortcuts_dialog.h"
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QPushButton> #include <QPushButton>
#include <QTextEdit> #include <QTextEdit>
#include <QLabel> #include <QLabel>
#include <QPixmap> #include <QPixmap>
#include <QFile> #include <QFile>
#include <QTextStream> #include <QTextStream>
#include <QTextCodec> #include <QTextCodec>
ShortcutsDialog::ShortcutsDialog(QWidget * parent) ShortcutsDialog::ShortcutsDialog(QWidget * parent)
:QDialog(parent)//,Qt::FramelessWindowHint) :QDialog(parent)//,Qt::FramelessWindowHint)
{ {
setModal(true); setModal(true);
setWindowIcon(QIcon(":/images/shortcuts.png")); setWindowIcon(QIcon(":/images/shortcuts.png"));
setWindowTitle(tr("YACReader keyboard shortcuts")); setWindowTitle(tr("YACReader keyboard shortcuts"));
QVBoxLayout * mainLayout = new QVBoxLayout; QVBoxLayout * mainLayout = new QVBoxLayout;
close = new QPushButton(tr("Close")); close = new QPushButton(tr("Close"));
connect(close,SIGNAL(clicked()),this,SLOT(close())); connect(close,SIGNAL(clicked()),this,SLOT(close()));
QHBoxLayout *bottomLayout = new QHBoxLayout; QHBoxLayout *bottomLayout = new QHBoxLayout;
bottomLayout->addStretch(); bottomLayout->addStretch();
bottomLayout->addWidget(close); bottomLayout->addWidget(close);
QHBoxLayout * shortcutsLayout = new QHBoxLayout; QHBoxLayout * shortcutsLayout = new QHBoxLayout;
shortcuts = new QTextEdit(); shortcuts = new QTextEdit();
shortcuts->setFrameStyle(QFrame::NoFrame); shortcuts->setFrameStyle(QFrame::NoFrame);
//"<p><b>General functions:</b><hr/><b>O</b> : Open comic<br/><b>Esc</b> : Exit</p>" //"<p><b>General functions:</b><hr/><b>O</b> : Open comic<br/><b>Esc</b> : Exit</p>"
shortcuts->setReadOnly(true); shortcuts->setReadOnly(true);
shortcutsLayout->addWidget(shortcuts); shortcutsLayout->addWidget(shortcuts);
//shortcutsLayout->addWidget(shortcuts2); //shortcutsLayout->addWidget(shortcuts2);
shortcutsLayout->setSpacing(0); shortcutsLayout->setSpacing(0);
mainLayout->addLayout(shortcutsLayout); mainLayout->addLayout(shortcutsLayout);
mainLayout->addLayout(bottomLayout); mainLayout->addLayout(bottomLayout);
setLayout(mainLayout); setLayout(mainLayout);
setFixedSize(QSize(700,500)); setFixedSize(QSize(700,500));
QFile f(":/files/shortcuts.html"); QFile f(":/files/shortcuts.html");
f.open(QIODevice::ReadOnly); f.open(QIODevice::ReadOnly);
QTextStream txtS(&f); QTextStream txtS(&f);
txtS.setCodec(QTextCodec::codecForName("UTF-8")); txtS.setCodec(QTextCodec::codecForName("UTF-8"));
QString content = txtS.readAll(); QString content = txtS.readAll();
f.close(); f.close();
shortcuts->setHtml(content); shortcuts->setHtml(content);
setWindowTitle(tr("Keyboard Shortcuts")); setWindowTitle(tr("Keyboard Shortcuts"));
} }

View File

@ -1,19 +1,19 @@
#ifndef SHORTCUTS_DIALOG_H #ifndef SHORTCUTS_DIALOG_H
#define SHORTCUTS_DIALOG_H #define SHORTCUTS_DIALOG_H
#include <QDialog> #include <QDialog>
#include <QTextEdit> #include <QTextEdit>
#include <QPushButton> #include <QPushButton>
class ShortcutsDialog : public QDialog class ShortcutsDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
ShortcutsDialog(QWidget * parent = 0); ShortcutsDialog(QWidget * parent = 0);
private: private:
QTextEdit * shortcuts; QTextEdit * shortcuts;
QPushButton * close; QPushButton * close;
public slots: public slots:
}; };
#endif // SHORTCUTS_DIALOG_H #endif // SHORTCUTS_DIALOG_H

View File

@ -1,429 +1,429 @@
#include <QUrl> #include <QUrl>
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
#include <QMediaPlayer> #include <QMediaPlayer>
#else #else
#include <Phonon/MediaObject> #include <Phonon/MediaObject>
#include <Phonon/MediaSource> #include <Phonon/MediaSource>
#endif #endif
#include <QPushButton> #include <QPushButton>
#include <QPalette> #include <QPalette>
#include <QMouseEvent> #include <QMouseEvent>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QVBoxLayout> #include <QVBoxLayout>
#include "translator.h" #include "translator.h"
#include "yacreader_busy_widget.h" #include "yacreader_busy_widget.h"
#include <QFile> #include <QFile>
#include <QPoint> #include <QPoint>
#include <QWidget> #include <QWidget>
#include <QTextCodec> #include <QTextCodec>
#include <QLabel> #include <QLabel>
#include <QTextEdit> #include <QTextEdit>
#include <QComboBox> #include <QComboBox>
#include <QThread> #include <QThread>
#include <QEventLoop> #include <QEventLoop>
#include <QTimer> #include <QTimer>
#include <QNetworkRequest> #include <QNetworkRequest>
#include <QNetworkReply> #include <QNetworkReply>
#include <QMessageBox> #include <QMessageBox>
#define APPID "417CEAD93449502CC3C9B69FED26C54118E62BCC" #define APPID "417CEAD93449502CC3C9B69FED26C54118E62BCC"
YACReaderTranslator::YACReaderTranslator(QWidget * parent) YACReaderTranslator::YACReaderTranslator(QWidget * parent)
:QWidget(parent),drag(false) :QWidget(parent),drag(false)
{ {
QString scrollBarStyle = "QScrollBar:vertical { border: none; background: #404040; width: 7px; margin: 0 3px 0 0; }" QString scrollBarStyle = "QScrollBar:vertical { border: none; background: #404040; width: 7px; margin: 0 3px 0 0; }"
"QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }" "QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }"
"QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}" "QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}"
"QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}" "QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none; }"; "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none; }";
this->setCursor(QCursor(Qt::ArrowCursor)); this->setCursor(QCursor(Qt::ArrowCursor));
this->setAutoFillBackground(true); this->setAutoFillBackground(true);
this->setBackgroundRole(QPalette::Window); this->setBackgroundRole(QPalette::Window);
QPalette p(this->palette()); QPalette p(this->palette());
p.setColor(QPalette::Window, QColor("#404040")); p.setColor(QPalette::Window, QColor("#404040"));
this->setPalette(p); this->setPalette(p);
QVBoxLayout *layout = new QVBoxLayout(this); QVBoxLayout *layout = new QVBoxLayout(this);
//TITLE BAR //TITLE BAR
QHBoxLayout * titleBar = new QHBoxLayout(); QHBoxLayout * titleBar = new QHBoxLayout();
QPushButton * close = new QPushButton(QIcon(QPixmap(":/images/close.png")),""); QPushButton * close = new QPushButton(QIcon(QPixmap(":/images/close.png")),"");
close->setFlat(true); close->setFlat(true);
QLabel * title = new QLabel(tr("YACReader translator")); QLabel * title = new QLabel(tr("YACReader translator"));
title->setStyleSheet("QLabel {font-size:18px; font-family:Arial; color:white;}"); title->setStyleSheet("QLabel {font-size:18px; font-family:Arial; color:white;}");
titleBar->addWidget(title); titleBar->addWidget(title);
titleBar->addStretch(); titleBar->addStretch();
close->resize(14,14); close->resize(14,14);
close->setStyleSheet("QPushButton {margin:0;padding:0;border:none;}"); close->setStyleSheet("QPushButton {margin:0;padding:0;border:none;}");
titleBar->addWidget(close); titleBar->addWidget(close);
titleBar->setContentsMargins(0,0,0,0); titleBar->setContentsMargins(0,0,0,0);
titleBar->setSpacing(0); titleBar->setSpacing(0);
connect(close,SIGNAL(clicked()),this->parent(),SLOT(animateHideTranslator())); connect(close,SIGNAL(clicked()),this->parent(),SLOT(animateHideTranslator()));
layout->addLayout(titleBar); layout->addLayout(titleBar);
//INPUT TEXT //INPUT TEXT
text = new QTextEdit(this); text = new QTextEdit(this);
text->setMinimumHeight(110); text->setMinimumHeight(110);
text->setMaximumHeight(110); text->setMaximumHeight(110);
layout->addSpacing(12); layout->addSpacing(12);
layout->addWidget(text); layout->addWidget(text);
text->setStyleSheet("QTextEdit{border:none;background:#2a2a2a;color:white; font-size:12px; padding:6px;}"+scrollBarStyle); text->setStyleSheet("QTextEdit{border:none;background:#2a2a2a;color:white; font-size:12px; padding:6px;}"+scrollBarStyle);
//COMBOBOXES //COMBOBOXES
QHBoxLayout * combos = new QHBoxLayout(); QHBoxLayout * combos = new QHBoxLayout();
from = new QComboBox(this); from = new QComboBox(this);
to = new QComboBox(this); to = new QComboBox(this);
QString comboBoxStyle = "QComboBox {border:none;background:#2a2a2a;color:white;font-size:12px;font-family:Arial;padding-left:8px;}" QString comboBoxStyle = "QComboBox {border:none;background:#2a2a2a;color:white;font-size:12px;font-family:Arial;padding-left:8px;}"
"QComboBox::down-arrow {image: url(:/images/dropDownArrow.png);}" "QComboBox::down-arrow {image: url(:/images/dropDownArrow.png);}"
"QComboBox::drop-down {border:none; padding-right:10px;}" "QComboBox::drop-down {border:none; padding-right:10px;}"
"QComboBox QAbstractItemView {border: none; background:#272727; color:white; selection-background-color: #202020; outline:none;}" "QComboBox QAbstractItemView {border: none; background:#272727; color:white; selection-background-color: #202020; outline:none;}"
"QComboBox QAbstractItemView::item {padding-left:8px;}" + scrollBarStyle "QComboBox QAbstractItemView::item {padding-left:8px;}" + scrollBarStyle
; ;
from->setStyleSheet(comboBoxStyle); from->setStyleSheet(comboBoxStyle);
to->setStyleSheet(comboBoxStyle); to->setStyleSheet(comboBoxStyle);
from->setFixedHeight(22); from->setFixedHeight(22);
to->setFixedHeight(22); to->setFixedHeight(22);
QLabel * arrow = new QLabel(this); QLabel * arrow = new QLabel(this);
QPixmap arrowPixmap(":/images/fromTo.png"); QPixmap arrowPixmap(":/images/fromTo.png");
arrow->setPixmap(arrowPixmap); arrow->setPixmap(arrowPixmap);
QPushButton * searchButton = new QPushButton(this); QPushButton * searchButton = new QPushButton(this);
searchButton->setIcon(QIcon(":/images/translatorSearch.png")); searchButton->setIcon(QIcon(":/images/translatorSearch.png"));
searchButton->setStyleSheet("QPushButton {border:none; background:#2a2a2a;}"); searchButton->setStyleSheet("QPushButton {border:none; background:#2a2a2a;}");
searchButton->setFixedSize(22,22); searchButton->setFixedSize(22,22);
combos->addWidget(from,1); combos->addWidget(from,1);
combos->addSpacing(9); combos->addSpacing(9);
combos->addWidget(arrow,0); combos->addWidget(arrow,0);
combos->addSpacing(9); combos->addSpacing(9);
combos->addWidget(to,1); combos->addWidget(to,1);
combos->addSpacing(9); combos->addSpacing(9);
combos->addWidget(searchButton,0); combos->addWidget(searchButton,0);
layout->addSpacing(12); layout->addSpacing(12);
layout->addLayout(combos); layout->addLayout(combos);
//RESULTS //RESULTS
QHBoxLayout * resultsTitleLayout = new QHBoxLayout(); QHBoxLayout * resultsTitleLayout = new QHBoxLayout();
resultsTitle = new QLabel(tr("Translation")); resultsTitle = new QLabel(tr("Translation"));
resultsTitle->setStyleSheet("QLabel {font-family:Arial;font-size:14px;color:#e3e3e3;}"); resultsTitle->setStyleSheet("QLabel {font-family:Arial;font-size:14px;color:#e3e3e3;}");
speakButton = new QPushButton(this); speakButton = new QPushButton(this);
speakButton->setStyleSheet("QPushButton {border:none;}"); speakButton->setStyleSheet("QPushButton {border:none;}");
speakButton->setIcon(QIcon(":/images/speaker.png")); speakButton->setIcon(QIcon(":/images/speaker.png"));
resultsTitleLayout->addWidget(resultsTitle,0,Qt::AlignVCenter); resultsTitleLayout->addWidget(resultsTitle,0,Qt::AlignVCenter);
resultsTitleLayout->addSpacing(10); resultsTitleLayout->addSpacing(10);
resultsTitleLayout->addWidget(speakButton,0,Qt::AlignVCenter); resultsTitleLayout->addWidget(speakButton,0,Qt::AlignVCenter);
resultsTitleLayout->addStretch(); resultsTitleLayout->addStretch();
layout->addSpacing(15); layout->addSpacing(15);
layout->addLayout(resultsTitleLayout); layout->addLayout(resultsTitleLayout);
layout->addSpacing(12); layout->addSpacing(12);
resultText = new QLabel(); resultText = new QLabel();
resultText->setWordWrap(true); resultText->setWordWrap(true);
resultText->setStyleSheet("QLabel {color:white;font-size:12px;}"); resultText->setStyleSheet("QLabel {color:white;font-size:12px;}");
resultText->setText("<EFBFBD>lkas lakj dflkaj lasd jflie lkajd fie kljads ijef lasei afsliej ljse f"); resultText->setText("<EFBFBD>lkas lakj dflkaj lasd jflie lkajd fie kljads ijef lasei afsliej ljse f");
layout->addWidget(resultText); layout->addWidget(resultText);
layout->addStretch(); layout->addStretch();
//CLEAR BUTTON //CLEAR BUTTON
clearButton = new QPushButton(tr("clear")); clearButton = new QPushButton(tr("clear"));
layout->addWidget(clearButton,0,Qt::AlignRight); layout->addWidget(clearButton,0,Qt::AlignRight);
clearButton->setMinimumWidth(95); clearButton->setMinimumWidth(95);
clearButton->setStyleSheet("QPushButton {border:1px solid #212121; background:#2a2a2a; color:white; font-family:Arial; font-size:12px; padding-top:5px; padding-bottom:5px;}"); clearButton->setStyleSheet("QPushButton {border:1px solid #212121; background:#2a2a2a; color:white; font-family:Arial; font-size:12px; padding-top:5px; padding-bottom:5px;}");
resize(400,479); resize(400,479);
layout->setMargin(0); layout->setMargin(0);
layout->setContentsMargins(18,12,18,12); layout->setContentsMargins(18,12,18,12);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
layout->setSpacing(0); layout->setSpacing(0);
hideResults(); hideResults();
populateCombos(); populateCombos();
busyIndicator = new YACReaderBusyWidget(this); busyIndicator = new YACReaderBusyWidget(this);
busyIndicator->move((this->width()-busyIndicator->width())/2,(this->height()-busyIndicator->height())*2/3); busyIndicator->move((this->width()-busyIndicator->width())/2,(this->height()-busyIndicator->height())*2/3);
busyIndicator->hide(); busyIndicator->hide();
show(); show();
connect(searchButton,SIGNAL(pressed()),this,SLOT(translate())); connect(searchButton,SIGNAL(pressed()),this,SLOT(translate()));
connect(speakButton,SIGNAL(pressed()),this,SLOT(play())); connect(speakButton,SIGNAL(pressed()),this,SLOT(play()));
connect(clearButton,SIGNAL(pressed()),this,SLOT(clear())); connect(clearButton,SIGNAL(pressed()),this,SLOT(clear()));
//multimedia/phonon //multimedia/phonon
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
player = new QMediaPlayer; player = new QMediaPlayer;
#else #else
music = createPlayer(MusicCategory); music = createPlayer(MusicCategory);
#endif #endif
} }
void YACReaderTranslator::hideResults() void YACReaderTranslator::hideResults()
{ {
resultsTitle->setHidden(true); resultsTitle->setHidden(true);
speakButton->setHidden(true); speakButton->setHidden(true);
resultText->setHidden(true); resultText->setHidden(true);
} }
void YACReaderTranslator::clear() void YACReaderTranslator::clear()
{ {
hideResults(); hideResults();
text->clear(); text->clear();
} }
void YACReaderTranslator::translate() void YACReaderTranslator::translate()
{ {
QString text = this->text->toPlainText(); QString text = this->text->toPlainText();
if(text.isEmpty()) if(text.isEmpty())
return; return;
QString from = this->from->itemData(this->from->currentIndex()).toString(); QString from = this->from->itemData(this->from->currentIndex()).toString();
QString to = this->to->itemData(this->to->currentIndex()).toString(); QString to = this->to->itemData(this->to->currentIndex()).toString();
TranslationLoader * translationLoader = new TranslationLoader(text,from,to); TranslationLoader * translationLoader = new TranslationLoader(text,from,to);
connect(translationLoader,SIGNAL(requestFinished(QString)),this,SLOT(setTranslation(QString))); connect(translationLoader,SIGNAL(requestFinished(QString)),this,SLOT(setTranslation(QString)));
connect(translationLoader,SIGNAL(error()),this,SLOT(error())); connect(translationLoader,SIGNAL(error()),this,SLOT(error()));
connect(translationLoader,SIGNAL(timeOut()),this,SLOT(error())); connect(translationLoader,SIGNAL(timeOut()),this,SLOT(error()));
connect(translationLoader,SIGNAL(finished()),translationLoader,SLOT(deleteLater())); connect(translationLoader,SIGNAL(finished()),translationLoader,SLOT(deleteLater()));
TextToSpeachLoader * tts = new TextToSpeachLoader(text,from); TextToSpeachLoader * tts = new TextToSpeachLoader(text,from);
connect(tts,SIGNAL(requestFinished(QUrl)),this,SLOT(setSpeak(QUrl))); connect(tts,SIGNAL(requestFinished(QUrl)),this,SLOT(setSpeak(QUrl)));
connect(tts,SIGNAL(error()),this,SLOT(error())); connect(tts,SIGNAL(error()),this,SLOT(error()));
connect(tts,SIGNAL(timeOut()),this,SLOT(error())); connect(tts,SIGNAL(timeOut()),this,SLOT(error()));
connect(tts,SIGNAL(finished()),tts,SLOT(deleteLater())); connect(tts,SIGNAL(finished()),tts,SLOT(deleteLater()));
translationLoader->start(); translationLoader->start();
tts->start(); tts->start();
resultsTitle->setText(tr("Translation")); resultsTitle->setText(tr("Translation"));
hideResults(); hideResults();
busyIndicator->show(); busyIndicator->show();
} }
void YACReaderTranslator::error() void YACReaderTranslator::error()
{ {
resultsTitle->setText(tr("Service not available")); resultsTitle->setText(tr("Service not available"));
resultsTitle->setHidden(false); resultsTitle->setHidden(false);
busyIndicator->hide(); busyIndicator->hide();
} }
void YACReaderTranslator::setSpeak(const QUrl & url) void YACReaderTranslator::setSpeak(const QUrl & url)
{ {
resultsTitle->setHidden(false); resultsTitle->setHidden(false);
speakButton->setHidden(false); speakButton->setHidden(false);
ttsSource = url; ttsSource = url;
} }
void YACReaderTranslator::setTranslation(const QString & string) void YACReaderTranslator::setTranslation(const QString & string)
{ {
resultText->setText(string); resultText->setText(string);
resultsTitle->setHidden(false); resultsTitle->setHidden(false);
resultText->setHidden(false); resultText->setHidden(false);
busyIndicator->hide(); busyIndicator->hide();
} }
void YACReaderTranslator::populateCombos() void YACReaderTranslator::populateCombos()
{ {
QList<QComboBox *> combos; QList<QComboBox *> combos;
combos.append(from); combos.append(from);
combos.append(to); combos.append(to);
for(int i=0;i<combos.count();i++) for(int i=0;i<combos.count();i++)
{ {
QComboBox * combo = combos.at(i); QComboBox * combo = combos.at(i);
combo->addItem("Arabic","ar"); combo->addItem("Arabic","ar");
combo->addItem("Bulgarian","bg"); combo->addItem("Bulgarian","bg");
combo->addItem("Catalan","ca"); combo->addItem("Catalan","ca");
combo->addItem("Chinese Simplified","zh-CHS"); combo->addItem("Chinese Simplified","zh-CHS");
combo->addItem("Chinese Traditional","zh-CHT"); combo->addItem("Chinese Traditional","zh-CHT");
combo->addItem("Czech","cs"); combo->addItem("Czech","cs");
combo->addItem("Danish","da"); combo->addItem("Danish","da");
combo->addItem("Dutch","nl"); combo->addItem("Dutch","nl");
combo->addItem("English","en"); combo->addItem("English","en");
combo->addItem("Estonian","et"); combo->addItem("Estonian","et");
combo->addItem("Finnish","fi"); combo->addItem("Finnish","fi");
combo->addItem("French","fr"); combo->addItem("French","fr");
combo->addItem("German","de"); combo->addItem("German","de");
combo->addItem("Greek","el"); combo->addItem("Greek","el");
combo->addItem("Haitian Creole","ht"); combo->addItem("Haitian Creole","ht");
combo->addItem("Hebrew","he"); combo->addItem("Hebrew","he");
combo->addItem("Hindi","hi"); combo->addItem("Hindi","hi");
combo->addItem("Hungarian","hu"); combo->addItem("Hungarian","hu");
combo->addItem("Indonesian","id"); combo->addItem("Indonesian","id");
combo->addItem("Italian","it"); combo->addItem("Italian","it");
combo->addItem("Japanese","ja"); combo->addItem("Japanese","ja");
combo->addItem("Korean","ko"); combo->addItem("Korean","ko");
combo->addItem("Latvian","lv"); combo->addItem("Latvian","lv");
combo->addItem("Lithuanian","lt"); combo->addItem("Lithuanian","lt");
combo->addItem("Norwegian","no"); combo->addItem("Norwegian","no");
combo->addItem("Polish","pl"); combo->addItem("Polish","pl");
combo->addItem("Portuguese","pt"); combo->addItem("Portuguese","pt");
combo->addItem("Romanian","ro"); combo->addItem("Romanian","ro");
combo->addItem("Russian","ru"); combo->addItem("Russian","ru");
combo->addItem("Slovak","sk"); combo->addItem("Slovak","sk");
combo->addItem("Slovenian","sl"); combo->addItem("Slovenian","sl");
combo->addItem("Spanish","es"); combo->addItem("Spanish","es");
combo->addItem("Swedish","sv"); combo->addItem("Swedish","sv");
combo->addItem("Thai","th"); combo->addItem("Thai","th");
combo->addItem("Turkish","tr"); combo->addItem("Turkish","tr");
combo->addItem("Ukrainian","uk"); combo->addItem("Ukrainian","uk");
combo->addItem("Vietnamese","vi"); combo->addItem("Vietnamese","vi");
} }
from->setCurrentIndex(from->findText("English")); from->setCurrentIndex(from->findText("English"));
to->setCurrentIndex(from->findText("Spanish")); to->setCurrentIndex(from->findText("Spanish"));
} }
void YACReaderTranslator::play() void YACReaderTranslator::play()
{ {
//QMessageBox::question(this,"xxx",ttsSource.toString()); //QMessageBox::question(this,"xxx",ttsSource.toString());
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
player->setMedia(ttsSource); player->setMedia(ttsSource);
player->play(); player->play();
#else #else
MediaSource src(ttsSource); MediaSource src(ttsSource);
src.setAutoDelete(true); src.setAutoDelete(true);
music->setCurrentSource(src); music->setCurrentSource(src);
music->play(); music->play();
#endif #endif
} }
YACReaderTranslator::~YACReaderTranslator() YACReaderTranslator::~YACReaderTranslator()
{ {
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
#else #else
delete music; delete music;
#endif #endif
} }
void YACReaderTranslator::mousePressEvent(QMouseEvent *event) void YACReaderTranslator::mousePressEvent(QMouseEvent *event)
{ {
QPoint p = mapTo(this,event->pos()); QPoint p = mapTo(this,event->pos());
if(p.y() < 40) if(p.y() < 40)
{ {
drag = true; drag = true;
click = event->pos(); click = event->pos();
} }
} }
void YACReaderTranslator::mouseReleaseEvent(QMouseEvent *event) void YACReaderTranslator::mouseReleaseEvent(QMouseEvent *event)
{ {
drag = false; drag = false;
event->accept(); event->accept();
} }
void YACReaderTranslator::mouseMoveEvent(QMouseEvent * event) void YACReaderTranslator::mouseMoveEvent(QMouseEvent * event)
{ {
if(drag) if(drag)
this->move(QPoint(mapToParent(event->pos())-click)); this->move(QPoint(mapToParent(event->pos())-click));
event->accept(); event->accept();
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
TranslationLoader::TranslationLoader(QString text, QString from, QString to) TranslationLoader::TranslationLoader(QString text, QString from, QString to)
:QThread(),text(text),from(from),to(to) :QThread(),text(text),from(from),to(to)
{ {
} }
void TranslationLoader::run() void TranslationLoader::run()
{ {
QNetworkAccessManager manager; QNetworkAccessManager manager;
QEventLoop q; QEventLoop q;
QTimer tT; QTimer tT;
tT.setSingleShot(true); tT.setSingleShot(true);
connect(&tT, SIGNAL(timeout()), &q, SLOT(quit())); connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
connect(&manager, SIGNAL(finished(QNetworkReply*)),&q, SLOT(quit())); connect(&manager, SIGNAL(finished(QNetworkReply*)),&q, SLOT(quit()));
QString url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appid=%1&from=%2&to=%3&text=%4&contentType=text/plain"; QString url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appid=%1&from=%2&to=%3&text=%4&contentType=text/plain";
url = url.arg(APPID).arg(from).arg(to).arg(text); url = url.arg(APPID).arg(from).arg(to).arg(text);
QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url))); QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url)));
tT.start(5000); // 5s timeout tT.start(5000); // 5s timeout
q.exec(); q.exec();
if(tT.isActive()){ if(tT.isActive()){
// download complete // download complete
if(reply->error() == QNetworkReply::NoError) if(reply->error() == QNetworkReply::NoError)
{ {
QString utf8 = QString::fromUtf8(reply->readAll()); QString utf8 = QString::fromUtf8(reply->readAll());
utf8 = utf8.remove(0,1); utf8 = utf8.remove(0,1);
utf8 = utf8.remove(utf8.count()-1,1); utf8 = utf8.remove(utf8.count()-1,1);
QString translated(utf8); QString translated(utf8);
emit(requestFinished(translated)); emit(requestFinished(translated));
} }
else else
emit(error()); emit(error());
} else { } else {
emit(timeOut()); emit(timeOut());
} }
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
TextToSpeachLoader::TextToSpeachLoader(QString text, QString language) TextToSpeachLoader::TextToSpeachLoader(QString text, QString language)
:QThread(),text(text),language(language) :QThread(),text(text),language(language)
{ {
} }
void TextToSpeachLoader::run() void TextToSpeachLoader::run()
{ {
QNetworkAccessManager manager; QNetworkAccessManager manager;
QEventLoop q; QEventLoop q;
QTimer tT; QTimer tT;
tT.setSingleShot(true); tT.setSingleShot(true);
connect(&tT, SIGNAL(timeout()), &q, SLOT(quit())); connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
connect(&manager, SIGNAL(finished(QNetworkReply*)),&q, SLOT(quit())); connect(&manager, SIGNAL(finished(QNetworkReply*)),&q, SLOT(quit()));
QString url = "http://api.microsofttranslator.com/V2/Ajax.svc/Speak?appid=%1&language=%2&text=%3&contentType=text/plain"; QString url = "http://api.microsofttranslator.com/V2/Ajax.svc/Speak?appid=%1&language=%2&text=%3&contentType=text/plain";
url = url.arg(APPID).arg(language).arg(text); url = url.arg(APPID).arg(language).arg(text);
QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url))); QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url)));
tT.start(5000); // 5s timeout tT.start(5000); // 5s timeout
q.exec(); q.exec();
if(tT.isActive()){ if(tT.isActive()){
// download complete // download complete
if(reply->error() == QNetworkReply::NoError) if(reply->error() == QNetworkReply::NoError)
{ {
QString utf8 = QString::fromUtf8(reply->readAll()); QString utf8 = QString::fromUtf8(reply->readAll());
utf8 = utf8.remove(0,1); utf8 = utf8.remove(0,1);
utf8 = utf8.remove(utf8.count()-1,1); utf8 = utf8.remove(utf8.count()-1,1);
utf8 = utf8.replace("\\",""); utf8 = utf8.replace("\\","");
emit(requestFinished(QUrl(utf8))); emit(requestFinished(QUrl(utf8)));
} }
else else
emit(error()); emit(error());
} else { } else {
emit(timeOut()); emit(timeOut());
} }
} }

View File

@ -1,102 +1,102 @@
#ifndef __TRANSLATOR_H #ifndef __TRANSLATOR_H
#define __TRANSLATOR_H #define __TRANSLATOR_H
class QUrl; class QUrl;
class QMouseEvent; class QMouseEvent;
class QPoint; class QPoint;
class QTextEdit; class QTextEdit;
class QComboBox; class QComboBox;
class QLabel; class QLabel;
class QPushButton; class QPushButton;
class YACReaderBusyWidget; class YACReaderBusyWidget;
#include <QWidget> #include <QWidget>
#include <QThread> #include <QThread>
#include <QUrl> #include <QUrl>
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
class QMediaPlayer; class QMediaPlayer;
#else #else
#include<Phonon/MediaObject> #include<Phonon/MediaObject>
using namespace Phonon; using namespace Phonon;
#endif #endif
class YACReaderTranslator : public QWidget class YACReaderTranslator : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
YACReaderTranslator(QWidget * parent = 0); YACReaderTranslator(QWidget * parent = 0);
~YACReaderTranslator(); ~YACReaderTranslator();
public slots: public slots:
void play(); void play();
protected slots: protected slots:
void translate(); void translate();
void setSpeak(const QUrl & url); void setSpeak(const QUrl & url);
void setTranslation(const QString & string); void setTranslation(const QString & string);
void error(); void error();
void clear(); void clear();
protected: protected:
void mousePressEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent ( QMouseEvent * event ); void mouseMoveEvent ( QMouseEvent * event );
void hideResults(); void hideResults();
void populateCombos(); void populateCombos();
bool drag; bool drag;
QPoint click; QPoint click;
private: private:
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
QMediaPlayer *player; QMediaPlayer *player;
#else #else
MediaObject * music; MediaObject * music;
#endif #endif
QTextEdit * text; QTextEdit * text;
QComboBox * from; QComboBox * from;
QComboBox * to; QComboBox * to;
QLabel * resultsTitle; QLabel * resultsTitle;
QPushButton * speakButton; QPushButton * speakButton;
QLabel * resultText; QLabel * resultText;
YACReaderBusyWidget * busyIndicator; YACReaderBusyWidget * busyIndicator;
QUrl ttsSource; QUrl ttsSource;
QPushButton * clearButton; QPushButton * clearButton;
}; };
class TranslationLoader : public QThread class TranslationLoader : public QThread
{ {
Q_OBJECT Q_OBJECT
public: public:
TranslationLoader(QString text, QString from, QString to); TranslationLoader(QString text, QString from, QString to);
signals: signals:
void requestFinished(QString); void requestFinished(QString);
void timeOut(); void timeOut();
void error(); void error();
private: private:
QString text; QString text;
QString from; QString from;
QString to; QString to;
void run(); void run();
}; };
class TextToSpeachLoader : public QThread class TextToSpeachLoader : public QThread
{ {
Q_OBJECT Q_OBJECT
public: public:
TextToSpeachLoader(QString text, QString language); TextToSpeachLoader(QString text, QString language);
signals: signals:
void requestFinished(QUrl); void requestFinished(QUrl);
void timeOut(); void timeOut();
void error(); void error();
private: private:
QString text; QString text;
QString language; QString language;
void run(); void run();
}; };
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -1,189 +1,189 @@
#ifndef __VIEWER_H #ifndef __VIEWER_H
#define __VIEWER_H #define __VIEWER_H
#include <QMainWindow> #include <QMainWindow>
#include <QScrollArea> #include <QScrollArea>
#include <QAction> #include <QAction>
#include <QTimer> #include <QTimer>
#include <QLabel> #include <QLabel>
#include <QPixmap> #include <QPixmap>
#include <QKeyEvent> #include <QKeyEvent>
#include <QResizeEvent> #include <QResizeEvent>
#include <QWheelEvent> #include <QWheelEvent>
#include <QMouseEvent> #include <QMouseEvent>
#include <QCloseEvent> #include <QCloseEvent>
#include <QPropertyAnimation> #include <QPropertyAnimation>
#include <QParallelAnimationGroup> #include <QParallelAnimationGroup>
#include <QSettings> #include <QSettings>
#include "scroll_management.h" #include "scroll_management.h"
class ComicDB; class ComicDB;
class Comic; class Comic;
class MagnifyingGlass; class MagnifyingGlass;
class GoToFlow; class GoToFlow;
class BookmarksDialog; class BookmarksDialog;
class Render; class Render;
class GoToDialog; class GoToDialog;
class YACReaderTranslator; class YACReaderTranslator;
class GoToFlowWidget; class GoToFlowWidget;
class Bookmarks; class Bookmarks;
class PageLabelWidget; class PageLabelWidget;
class NotificationsLabelWidget; class NotificationsLabelWidget;
class Viewer : public QScrollArea, public ScrollManagement class Viewer : public QScrollArea, public ScrollManagement
{ {
Q_OBJECT Q_OBJECT
public: public:
bool fullscreen; //TODO, change by the right use of windowState(); bool fullscreen; //TODO, change by the right use of windowState();
public slots: public slots:
void increaseZoomFactor(); void increaseZoomFactor();
void decreaseZoomFactor(); void decreaseZoomFactor();
void setZoomFactor(int); void setZoomFactor(int);
int getZoomFactor(); int getZoomFactor();
void prepareForOpening(); void prepareForOpening();
void open(QString pathFile, int atPage = -1); void open(QString pathFile, int atPage = -1);
void open(QString pathFile, const ComicDB & comic); void open(QString pathFile, const ComicDB & comic);
void prev(); void prev();
void next(); void next();
void showGoToDialog(); void showGoToDialog();
void goTo(unsigned int page); void goTo(unsigned int page);
void updatePage(); void updatePage();
void updateContentSize(); void updateContentSize();
void updateVerticalScrollBar(); void updateVerticalScrollBar();
void updateOptions(); void updateOptions();
void scrollDown(); void scrollDown();
void scrollUp(); void scrollUp();
void scrollForwardHorizontalFirst(); void scrollForwardHorizontalFirst();
void scrollBackwardHorizontalFirst(); void scrollBackwardHorizontalFirst();
void scrollForwardVerticalFirst(); void scrollForwardVerticalFirst();
void scrollBackwardVerticalFirst(); void scrollBackwardVerticalFirst();
void magnifyingGlassSwitch(); void magnifyingGlassSwitch();
void showMagnifyingGlass(); void showMagnifyingGlass();
void hideMagnifyingGlass(); void hideMagnifyingGlass();
void informationSwitch(); void informationSwitch();
void updateInformation(); void updateInformation();
void goToFlowSwitch(); void goToFlowSwitch();
void showGoToFlow(); void showGoToFlow();
void moveCursoToGoToFlow(); void moveCursoToGoToFlow();
void animateShowGoToFlow(); void animateShowGoToFlow();
void animateHideGoToFlow(); void animateHideGoToFlow();
void rotateLeft(); void rotateLeft();
void rotateRight(); void rotateRight();
bool magnifyingGlassIsVisible() {return magnifyingGlassShowed;} bool magnifyingGlassIsVisible() {return magnifyingGlassShowed;}
void setBookmark(bool); void setBookmark(bool);
void save(); void save();
void doublePageSwitch(); void doublePageSwitch();
void doubleMangaPageSwitch(); void doubleMangaPageSwitch();
void resetContent(); void resetContent();
void setLoadingMessage(); void setLoadingMessage();
void setPageUnavailableMessage(); void setPageUnavailableMessage();
void configureContent(QString msg); void configureContent(QString msg);
void hideCursor(); void hideCursor();
void showCursor(); void showCursor();
void createConnections(); void createConnections();
void translatorSwitch(); void translatorSwitch();
void animateShowTranslator(); void animateShowTranslator();
void animateHideTranslator(); void animateHideTranslator();
virtual void mousePressEvent ( QMouseEvent * event ); virtual void mousePressEvent ( QMouseEvent * event );
virtual void mouseReleaseEvent ( QMouseEvent * event ); virtual void mouseReleaseEvent ( QMouseEvent * event );
void updateBackgroundColor(const QColor & color); void updateBackgroundColor(const QColor & color);
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void showMessageErrorOpening(); void showMessageErrorOpening();
void showMessageErrorOpening(QString); void showMessageErrorOpening(QString);
void processCRCError(QString message); void processCRCError(QString message);
void setBookmarks(); void setBookmarks();
//deprecated //deprecated
void updateImageOptions(); void updateImageOptions();
void updateFilters(int brightness, int contrast,int gamma); void updateFilters(int brightness, int contrast,int gamma);
void showIsCoverMessage(); void showIsCoverMessage();
void showIsLastMessage(); void showIsLastMessage();
int getCurrentPageNumber(); int getCurrentPageNumber();
void updateZoomRatio(int ratio); void updateZoomRatio(int ratio);
private: private:
bool information; bool information;
bool doublePage; bool doublePage;
bool doubleMangaPage; bool doubleMangaPage;
int zoom; int zoom;
PageLabelWidget * informationLabel; PageLabelWidget * informationLabel;
//QTimer * scroller; //QTimer * scroller;
QPropertyAnimation * verticalScroller; QPropertyAnimation * verticalScroller;
QPropertyAnimation * horizontalScroller; QPropertyAnimation * horizontalScroller;
QParallelAnimationGroup * groupScroller; QParallelAnimationGroup * groupScroller;
int posByStep; int posByStep;
int nextPos; int nextPos;
GoToFlowWidget * goToFlow; GoToFlowWidget * goToFlow;
QPropertyAnimation * showGoToFlowAnimation; QPropertyAnimation * showGoToFlowAnimation;
GoToDialog * goToDialog; GoToDialog * goToDialog;
//!Image properties //!Image properties
//! Comic //! Comic
//Comic * comic; //Comic * comic;
int index; int index;
QPixmap *currentPage; QPixmap *currentPage;
BookmarksDialog * bd; BookmarksDialog * bd;
bool wheelStop; bool wheelStop;
Render * render; Render * render;
QTimer * hideCursorTimer; QTimer * hideCursorTimer;
int direction; int direction;
bool drag; bool drag;
int numScrollSteps; int numScrollSteps;
//!Widgets //!Widgets
QLabel *content; QLabel *content;
YACReaderTranslator * translator; YACReaderTranslator * translator;
int translatorXPos; int translatorXPos;
QPropertyAnimation * translatorAnimation; QPropertyAnimation * translatorAnimation;
int yDragOrigin; int yDragOrigin;
int xDragOrigin; int xDragOrigin;
NotificationsLabelWidget * notificationsLabel; NotificationsLabelWidget * notificationsLabel;
bool shouldOpenNext; bool shouldOpenNext;
bool shouldOpenPrevious; bool shouldOpenPrevious;
private: private:
//!Magnifying glass //!Magnifying glass
MagnifyingGlass *mglass; MagnifyingGlass *mglass;
bool magnifyingGlassShowed; bool magnifyingGlassShowed;
bool restoreMagnifyingGlass; bool restoreMagnifyingGlass;
//! Manejadores de evento: //! Manejadores de evento:
void keyPressEvent(QKeyEvent * event); void keyPressEvent(QKeyEvent * event);
void resizeEvent(QResizeEvent * event); void resizeEvent(QResizeEvent * event);
void wheelEvent(QWheelEvent * event); void wheelEvent(QWheelEvent * event);
void mouseMoveEvent(QMouseEvent * event); void mouseMoveEvent(QMouseEvent * event);
//!ZigzagScroll //!ZigzagScroll
enum scrollDirection{ UP, DOWN, LEFT, RIGHT }; enum scrollDirection{ UP, DOWN, LEFT, RIGHT };
bool isEdge(scrollDirection d); bool isEdge(scrollDirection d);
void scrollZigzag(scrollDirection d1, scrollDirection d2, bool forward); void scrollZigzag(scrollDirection d1, scrollDirection d2, bool forward);
void scrollTo(int x, int y); void scrollTo(int x, int y);
public: public:
Viewer(QWidget * parent = 0); Viewer(QWidget * parent = 0);
~Viewer(); ~Viewer();
void toggleFullScreen(); void toggleFullScreen();
const QPixmap * pixmap(); const QPixmap * pixmap();
//Comic * getComic(){return comic;} //Comic * getComic(){return comic;}
const BookmarksDialog * getBookmarksDialog(){return bd;} const BookmarksDialog * getBookmarksDialog(){return bd;}
//returns the current index starting in 1 [1,nPages] //returns the current index starting in 1 [1,nPages]
unsigned int getIndex(); unsigned int getIndex();
void updateComic(ComicDB & comic); void updateComic(ComicDB & comic);
signals: signals:
void backgroundChanges(); void backgroundChanges();
void pageAvailable(bool); void pageAvailable(bool);
void pageIsBookmark(bool); void pageIsBookmark(bool);
void reset(); void reset();
void openNextComic(); void openNextComic();
void openPreviousComic(); void openPreviousComic();
void zoomUpdated(int); void zoomUpdated(int);
}; };
#endif #endif

View File

@ -1,111 +1,111 @@
#include "width_slider.h" #include "width_slider.h"
#include <QtWidgets> #include <QtWidgets>
#include "configuration.h" #include "configuration.h"
YACReaderSliderAction::YACReaderSliderAction (QWidget * parent) YACReaderSliderAction::YACReaderSliderAction (QWidget * parent)
:QWidgetAction (parent) { :QWidgetAction (parent) {
widget = new YACReaderSlider(); widget = new YACReaderSlider();
setDefaultWidget(widget); setDefaultWidget(widget);
connect(widget,SIGNAL(zoomRatioChanged(int)),this,SIGNAL(zoomRatioChanged(int))); connect(widget,SIGNAL(zoomRatioChanged(int)),this,SIGNAL(zoomRatioChanged(int)));
} }
void YACReaderSliderAction::updateText(int value) void YACReaderSliderAction::updateText(int value)
{ {
widget->updateText(value); widget->updateText(value);
} }
void YACReaderSliderAction::updateZoomRatio(int value) void YACReaderSliderAction::updateZoomRatio(int value)
{ {
widget->updateZoomRatio(value); widget->updateZoomRatio(value);
} }
YACReaderSlider::YACReaderSlider(QWidget *parent) YACReaderSlider::YACReaderSlider(QWidget *parent)
:QWidget(parent) :QWidget(parent)
{ {
const int sliderWidth = 200; const int sliderWidth = 200;
const int contentsMargin = 10; const int contentsMargin = 10;
const int elementsSpacing = 10; const int elementsSpacing = 10;
const int percentageLabelWidth = 30; const int percentageLabelWidth = 30;
setFocusPolicy(Qt::StrongFocus); setFocusPolicy(Qt::StrongFocus);
QHBoxLayout* pLayout = new QHBoxLayout(); QHBoxLayout* pLayout = new QHBoxLayout();
pLayout->addStretch(); pLayout->addStretch();
percentageLabel = new QLabel(); percentageLabel = new QLabel();
percentageLabel->setStyleSheet("QLabel { color : white; }"); percentageLabel->setStyleSheet("QLabel { color : white; }");
percentageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); percentageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
slider = new QSlider(); slider = new QSlider();
slider->setOrientation(Qt::Horizontal); slider->setOrientation(Qt::Horizontal);
slider->setMinimumWidth(sliderWidth); slider->setMinimumWidth(sliderWidth);
QPushButton *resetButton = new QPushButton(tr("Reset")); QPushButton *resetButton = new QPushButton(tr("Reset"));
resetButton->setStyleSheet("QPushButton {border: 1px solid #BB242424; background: #BB2E2E2E; color:white; padding: 3px 5px 5px 5px;}"); resetButton->setStyleSheet("QPushButton {border: 1px solid #BB242424; background: #BB2E2E2E; color:white; padding: 3px 5px 5px 5px;}");
connect(resetButton, &QPushButton::clicked, this, &YACReaderSlider::resetValueToDefault); connect(resetButton, &QPushButton::clicked, this, &YACReaderSlider::resetValueToDefault);
pLayout->addWidget(percentageLabel, 1, Qt::AlignHCenter); pLayout->addWidget(percentageLabel, 1, Qt::AlignHCenter);
pLayout->addWidget(slider, 0, Qt::AlignHCenter | Qt::AlignBottom); pLayout->addWidget(slider, 0, Qt::AlignHCenter | Qt::AlignBottom);
pLayout->addWidget(resetButton, 1, Qt::AlignHCenter | Qt::AlignBottom); pLayout->addWidget(resetButton, 1, Qt::AlignHCenter | Qt::AlignBottom);
pLayout->setSpacing(elementsSpacing); pLayout->setSpacing(elementsSpacing);
pLayout->setMargin(0); pLayout->setMargin(0);
setLayout (pLayout); setLayout (pLayout);
setAutoFillBackground(false); setAutoFillBackground(false);
setContentsMargins(contentsMargin,contentsMargin,contentsMargin,contentsMargin); setContentsMargins(contentsMargin,contentsMargin,contentsMargin,contentsMargin);
setFixedSize(sliderWidth + 2 * contentsMargin + 2 * elementsSpacing + percentageLabelWidth + resetButton->sizeHint().width(), 45); setFixedSize(sliderWidth + 2 * contentsMargin + 2 * elementsSpacing + percentageLabelWidth + resetButton->sizeHint().width(), 45);
slider->setMinimum(30); slider->setMinimum(30);
slider->setMaximum(500); slider->setMaximum(500);
slider->setPageStep(5); slider->setPageStep(5);
slider->setFocusPolicy(Qt::NoFocus); slider->setFocusPolicy(Qt::NoFocus);
resetButton->setFocusPolicy(Qt::NoFocus); resetButton->setFocusPolicy(Qt::NoFocus);
slider->setValue(100); slider->setValue(100);
percentageLabel->setText(QString("%1%").arg(100)); percentageLabel->setText(QString("%1%").arg(100));
connect(slider, &QSlider::valueChanged, this, &YACReaderSlider::updateText); connect(slider, &QSlider::valueChanged, this, &YACReaderSlider::updateText);
} }
void YACReaderSlider::paintEvent(QPaintEvent *) void YACReaderSlider::paintEvent(QPaintEvent *)
{ {
QPainter painter(this); QPainter painter(this);
painter.fillRect(0,0,width(),height(),QColor("#BB000000")); painter.fillRect(0,0,width(),height(),QColor("#BB000000"));
} }
void YACReaderSlider::show() void YACReaderSlider::show()
{ {
QWidget::show(); QWidget::show();
setFocus(); setFocus();
} }
void YACReaderSlider::focusOutEvent(QFocusEvent * event) void YACReaderSlider::focusOutEvent(QFocusEvent * event)
{ {
QWidget::focusOutEvent(event); QWidget::focusOutEvent(event);
hide(); hide();
} }
void YACReaderSlider::updateText(int value) void YACReaderSlider::updateText(int value)
{ {
percentageLabel->setText(QString("%1%").arg(value)); percentageLabel->setText(QString("%1%").arg(value));
emit zoomRatioChanged(value); emit zoomRatioChanged(value);
} }
void YACReaderSlider::updateZoomRatio(int value) void YACReaderSlider::updateZoomRatio(int value)
{ {
slider->setValue(value); slider->setValue(value);
percentageLabel->setText(QString("%1%").arg(value)); percentageLabel->setText(QString("%1%").arg(value));
} }
void YACReaderSlider::resetValueToDefault() void YACReaderSlider::resetValueToDefault()
{ {
slider->setValue(100); slider->setValue(100);
} }

View File

@ -1,53 +1,53 @@
#ifndef WIDTH_SLIDER_H #ifndef WIDTH_SLIDER_H
#define WIDTH_SLIDER_H #define WIDTH_SLIDER_H
#include <QWidgetAction> #include <QWidgetAction>
class QLabel; class QLabel;
class QSlider; class QSlider;
class YACReaderSlider : public QWidget class YACReaderSlider : public QWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
QLabel * percentageLabel; QLabel * percentageLabel;
QSlider * slider; QSlider * slider;
public: public:
YACReaderSlider (QWidget * parent = 0); YACReaderSlider (QWidget * parent = 0);
void show(); void show();
protected: protected:
virtual void focusOutEvent(QFocusEvent * event); virtual void focusOutEvent(QFocusEvent * event);
virtual void paintEvent(QPaintEvent *); virtual void paintEvent(QPaintEvent *);
public slots: public slots:
void updateText(int value); void updateText(int value);
void updateZoomRatio(int value); void updateZoomRatio(int value);
void resetValueToDefault(); void resetValueToDefault();
signals: signals:
void zoomRatioChanged(int value); void zoomRatioChanged(int value);
}; };
class YACReaderSliderAction : public QWidgetAction class YACReaderSliderAction : public QWidgetAction
{ {
Q_OBJECT Q_OBJECT
private: private:
YACReaderSlider * widget; YACReaderSlider * widget;
public: public:
YACReaderSliderAction (QWidget * parent = 0); YACReaderSliderAction (QWidget * parent = 0);
public slots: public slots:
void updateText(int value); void updateText(int value);
void updateZoomRatio(int value); void updateZoomRatio(int value);
signals: signals:
void zoomRatioChanged(int value); void zoomRatioChanged(int value);
}; };
#endif #endif

View File

@ -1,216 +1,216 @@
#include "yacreader_local_client.h" #include "yacreader_local_client.h"
#include "comic_db.h" #include "comic_db.h"
#include "yacreader_global.h" #include "yacreader_global.h"
#include <QLocalSocket> #include <QLocalSocket>
#include "QsLog.h" #include "QsLog.h"
using namespace YACReader; using namespace YACReader;
YACReaderLocalClient::YACReaderLocalClient(QObject *parent) : YACReaderLocalClient::YACReaderLocalClient(QObject *parent) :
QObject(parent) QObject(parent)
{ {
localSocket = new QLocalSocket(this); localSocket = new QLocalSocket(this);
//connect(localSocket, SIGNAL(readyRead()), this, SLOT(readMessage())); //connect(localSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
/*connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), /*connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(displayError(QLocalSocket::LocalSocketError)));*/ this, SLOT(displayError(QLocalSocket::LocalSocketError)));*/
} }
YACReaderLocalClient::~YACReaderLocalClient() YACReaderLocalClient::~YACReaderLocalClient()
{ {
delete localSocket; delete localSocket;
} }
//información de comic recibida... //información de comic recibida...
void YACReaderLocalClient::readMessage() void YACReaderLocalClient::readMessage()
{ {
} }
#include <QMessageBox> #include <QMessageBox>
bool YACReaderLocalClient::requestComicInfo(quint64 libraryId, ComicDB & comic, QList<ComicDB> & siblings) bool YACReaderLocalClient::requestComicInfo(quint64 libraryId, ComicDB & comic, QList<ComicDB> & siblings)
{ {
localSocket->connectToServer(YACREADERLIBRARY_GUID); localSocket->connectToServer(YACREADERLIBRARY_GUID);
if(localSocket->isOpen()) if(localSocket->isOpen())
{ {
QByteArray block; QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly); QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8); out.setVersion(QDataStream::Qt_4_8);
out << (quint32)0; out << (quint32)0;
out << (quint8)YACReader::RequestComicInfo; out << (quint8)YACReader::RequestComicInfo;
out << libraryId; out << libraryId;
out << comic; out << comic;
out.device()->seek(0); out.device()->seek(0);
out << (quint32)(block.size() - sizeof(quint32)); out << (quint32)(block.size() - sizeof(quint32));
int written = 0; int written = 0;
int previousWritten = 0; int previousWritten = 0;
quint16 tries = 0; quint16 tries = 0;
while(written != block.size() && tries < 200) while(written != block.size() && tries < 200)
{ {
written += localSocket->write(block); written += localSocket->write(block);
localSocket->flush(); localSocket->flush();
if(written == previousWritten) //no bytes were written if(written == previousWritten) //no bytes were written
tries++; tries++;
previousWritten = written; previousWritten = written;
} }
if(tries == 200) if(tries == 200)
{ {
localSocket->close(); localSocket->close();
QLOG_ERROR() << "Requesting Comic Info : unable to send request"; QLOG_ERROR() << "Requesting Comic Info : unable to send request";
return false; return false;
} }
localSocket->waitForBytesWritten(2000); localSocket->waitForBytesWritten(2000);
//QByteArray data; //QByteArray data;
tries = 0; tries = 0;
int dataAvailable = 0; int dataAvailable = 0;
QByteArray packageSize; QByteArray packageSize;
localSocket->waitForReadyRead(1000); localSocket->waitForReadyRead(1000);
while(packageSize.size() < sizeof(quint32) && tries < 20) while(packageSize.size() < sizeof(quint32) && tries < 20)
{ {
packageSize.append(localSocket->read(sizeof(quint32) - packageSize.size())); packageSize.append(localSocket->read(sizeof(quint32) - packageSize.size()));
localSocket->waitForReadyRead(100); localSocket->waitForReadyRead(100);
if(dataAvailable == packageSize.size()) if(dataAvailable == packageSize.size())
{ {
tries++; //TODO apply 'tries' fix tries++; //TODO apply 'tries' fix
} }
dataAvailable = packageSize.size(); dataAvailable = packageSize.size();
} }
if(tries == 20) if(tries == 20)
{ {
localSocket->close(); localSocket->close();
QLOG_ERROR() << "Requesting Comic Info : unable to read package size"; QLOG_ERROR() << "Requesting Comic Info : unable to read package size";
return false; return false;
} }
QDataStream sizeStream(packageSize);//localSocket->read(sizeof(quint32))); QDataStream sizeStream(packageSize);//localSocket->read(sizeof(quint32)));
sizeStream.setVersion(QDataStream::Qt_4_8); sizeStream.setVersion(QDataStream::Qt_4_8);
quint32 totalSize = 0; quint32 totalSize = 0;
sizeStream >> totalSize; sizeStream >> totalSize;
QByteArray data; QByteArray data;
tries = 0; tries = 0;
int dataRead = 0; int dataRead = 0;
localSocket->waitForReadyRead(1000); localSocket->waitForReadyRead(1000);
while((unsigned int)data.length() < totalSize && tries < 20 ) while((unsigned int)data.length() < totalSize && tries < 20 )
{ {
data.append(localSocket->readAll()); data.append(localSocket->readAll());
if((unsigned int)data.length() < totalSize) if((unsigned int)data.length() < totalSize)
localSocket->waitForReadyRead(100); localSocket->waitForReadyRead(100);
if(data.length() == dataRead) if(data.length() == dataRead)
tries++; tries++;
dataRead = data.length(); dataRead = data.length();
} }
if(tries == 20) if(tries == 20)
{ {
localSocket->close(); localSocket->close();
QLOG_ERROR() << "Requesting Comic Info : unable to read data (" << data.length() << "," << totalSize << ")"; QLOG_ERROR() << "Requesting Comic Info : unable to read data (" << data.length() << "," << totalSize << ")";
return false; return false;
} }
QDataStream dataStream(data); QDataStream dataStream(data);
dataStream >> comic; dataStream >> comic;
dataStream >> siblings; dataStream >> siblings;
localSocket->close(); localSocket->close();
return true; return true;
} }
else else
{ {
QLOG_ERROR() << "Requesting Comic Info : unable to connect to the server"; QLOG_ERROR() << "Requesting Comic Info : unable to connect to the server";
return false; return false;
} }
} }
bool YACReaderLocalClient::sendComicInfo(quint64 libraryId, ComicDB & comic) bool YACReaderLocalClient::sendComicInfo(quint64 libraryId, ComicDB & comic)
{ {
localSocket->connectToServer(YACREADERLIBRARY_GUID); localSocket->connectToServer(YACREADERLIBRARY_GUID);
if(localSocket->isOpen()) if(localSocket->isOpen())
{ {
//QLOG_INFO() << "Connection opened for sending ComicInfo"; //QLOG_INFO() << "Connection opened for sending ComicInfo";
QByteArray block; QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly); QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8); out.setVersion(QDataStream::Qt_4_8);
out << (quint32)0; out << (quint32)0;
out << (quint8)YACReader::SendComicInfo; out << (quint8)YACReader::SendComicInfo;
out << libraryId; out << libraryId;
out << comic; out << comic;
out.device()->seek(0); out.device()->seek(0);
out << (quint32)(block.size() - sizeof(quint32)); out << (quint32)(block.size() - sizeof(quint32));
int written, previousWritten; int written, previousWritten;
written = previousWritten = 0; written = previousWritten = 0;
int tries = 0; int tries = 0;
while(written != block.size() && tries < 100) while(written != block.size() && tries < 100)
{ {
written += localSocket->write(block); written += localSocket->write(block);
if(written == previousWritten) if(written == previousWritten)
tries++; tries++;
previousWritten = written; previousWritten = written;
} }
localSocket->waitForBytesWritten(2000); localSocket->waitForBytesWritten(2000);
localSocket->close(); localSocket->close();
//QLOG_INFO() << QString("Sending Comic Info : writen data (%1,%2)").arg(written).arg(block.size()); //QLOG_INFO() << QString("Sending Comic Info : writen data (%1,%2)").arg(written).arg(block.size());
if(tries == 100 && written != block.size()) if(tries == 100 && written != block.size())
{ {
emit finished(); emit finished();
QLOG_ERROR() << QString("Sending Comic Info : unable to write data (%1,%2)").arg(written).arg(block.size()); QLOG_ERROR() << QString("Sending Comic Info : unable to write data (%1,%2)").arg(written).arg(block.size());
return false; return false;
} }
emit finished(); emit finished();
return true; return true;
} }
emit finished(); emit finished();
QLOG_ERROR() << "Sending Comic Info : unable to connect to the server"; QLOG_ERROR() << "Sending Comic Info : unable to connect to the server";
return false; return false;
} }
bool YACReaderLocalClient::sendComicInfo(quint64 libraryId, ComicDB & comic, qulonglong nextComicId) bool YACReaderLocalClient::sendComicInfo(quint64 libraryId, ComicDB & comic, qulonglong nextComicId)
{ {
localSocket->connectToServer(YACREADERLIBRARY_GUID); localSocket->connectToServer(YACREADERLIBRARY_GUID);
if(localSocket->isOpen()) if(localSocket->isOpen())
{ {
//QLOG_INFO() << "Connection opened for sending ComicInfo"; //QLOG_INFO() << "Connection opened for sending ComicInfo";
QByteArray block; QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly); QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8); out.setVersion(QDataStream::Qt_4_8);
out << (quint32)0; out << (quint32)0;
out << (quint8)YACReader::SendComicInfo; out << (quint8)YACReader::SendComicInfo;
out << libraryId; out << libraryId;
out << comic; out << comic;
out << nextComicId; out << nextComicId;
out.device()->seek(0); out.device()->seek(0);
out << (quint32)(block.size() - sizeof(quint32)); out << (quint32)(block.size() - sizeof(quint32));
int written, previousWritten; int written, previousWritten;
written = previousWritten = 0; written = previousWritten = 0;
int tries = 0; int tries = 0;
while(written != block.size() && tries < 100) while(written != block.size() && tries < 100)
{ {
written += localSocket->write(block); written += localSocket->write(block);
if(written == previousWritten) if(written == previousWritten)
tries++; tries++;
previousWritten = written; previousWritten = written;
} }
localSocket->waitForBytesWritten(2000); localSocket->waitForBytesWritten(2000);
localSocket->close(); localSocket->close();
//QLOG_INFO() << QString("Sending Comic Info : writen data (%1,%2)").arg(written).arg(block.size()); //QLOG_INFO() << QString("Sending Comic Info : writen data (%1,%2)").arg(written).arg(block.size());
if(tries == 100 && written != block.size()) if(tries == 100 && written != block.size())
{ {
emit finished(); emit finished();
QLOG_ERROR() << QString("Sending Comic Info : unable to write data (%1,%2)").arg(written).arg(block.size()); QLOG_ERROR() << QString("Sending Comic Info : unable to write data (%1,%2)").arg(written).arg(block.size());
return false; return false;
} }
emit finished(); emit finished();
return true; return true;
} }
emit finished(); emit finished();
QLOG_ERROR() << "Sending Comic Info : unable to connect to the server"; QLOG_ERROR() << "Sending Comic Info : unable to connect to the server";
return false; return false;
} }

View File

@ -1,29 +1,29 @@
#ifndef YACREADER_LOCAL_CLIENT_H #ifndef YACREADER_LOCAL_CLIENT_H
#define YACREADER_LOCAL_CLIENT_H #define YACREADER_LOCAL_CLIENT_H
#include <QObject> #include <QObject>
class QLocalSocket; class QLocalSocket;
class ComicDB; class ComicDB;
class YACReaderLocalClient : public QObject class YACReaderLocalClient : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit YACReaderLocalClient(QObject *parent = 0); explicit YACReaderLocalClient(QObject *parent = 0);
~YACReaderLocalClient(); ~YACReaderLocalClient();
signals: signals:
void finished(); void finished();
public slots: public slots:
void readMessage(); void readMessage();
bool requestComicInfo(quint64 libraryId, ComicDB & comic,QList<ComicDB> & siblings); bool requestComicInfo(quint64 libraryId, ComicDB & comic,QList<ComicDB> & siblings);
bool sendComicInfo(quint64 libraryId, ComicDB & comic); bool sendComicInfo(quint64 libraryId, ComicDB & comic);
bool sendComicInfo(quint64 libraryId, ComicDB & comic, qulonglong nextComicId); bool sendComicInfo(quint64 libraryId, ComicDB & comic, qulonglong nextComicId);
private: private:
QLocalSocket * localSocket; QLocalSocket * localSocket;
}; };
#endif // YACREADER_LOCAL_CLIENT_H #endif // YACREADER_LOCAL_CLIENT_H

View File

@ -1,84 +1,84 @@
#include "add_label_dialog.h" #include "add_label_dialog.h"
AddLabelDialog::AddLabelDialog(QWidget *parent) : AddLabelDialog::AddLabelDialog(QWidget *parent) :
QDialog(parent) QDialog(parent)
{ {
QVBoxLayout * layout = new QVBoxLayout; QVBoxLayout * layout = new QVBoxLayout;
layout->addWidget(new QLabel(tr("Label name:"))); layout->addWidget(new QLabel(tr("Label name:")));
layout->addWidget(edit = new QLineEdit()); layout->addWidget(edit = new QLineEdit());
layout->addWidget(new QLabel(tr("Choose a color:"))); layout->addWidget(new QLabel(tr("Choose a color:")));
layout->addWidget(list = new QListWidget() ); layout->addWidget(list = new QListWidget() );
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_red.png"), tr("red"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_red.png"), tr("red")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_orange.png"), tr("orange"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_orange.png"), tr("orange")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_yellow.png"), tr("yellow"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_yellow.png"), tr("yellow")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_green.png"), tr("green"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_green.png"), tr("green")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_cyan.png"), tr("cyan"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_cyan.png"), tr("cyan")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_blue.png"), tr("blue"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_blue.png"), tr("blue")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_violet.png"), tr("violet"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_violet.png"), tr("violet")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_purple.png"), tr("purple"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_purple.png"), tr("purple")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_pink.png"), tr("pink"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_pink.png"), tr("pink")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_white.png"), tr("white"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_white.png"), tr("white")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_light.png"), tr("light"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_light.png"), tr("light")));
list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_dark.png"), tr("dark"))); list->addItem(new QListWidgetItem(QIcon(":/images/lists/label_dark.png"), tr("dark")));
QColor backgroundColor = this->palette().background().color(); QColor backgroundColor = this->palette().background().color();
list->setStyleSheet(QString("QListWidget {border : none; background-color: rgb(%1,%2,%3);}").arg(backgroundColor.red()).arg(backgroundColor.green()).arg(backgroundColor.blue())); list->setStyleSheet(QString("QListWidget {border : none; background-color: rgb(%1,%2,%3);}").arg(backgroundColor.red()).arg(backgroundColor.green()).arg(backgroundColor.blue()));
list->setMinimumHeight(225); list->setMinimumHeight(225);
setModal(true); setModal(true);
setMinimumHeight(340); setMinimumHeight(340);
//buttons //buttons
acceptButton = new QPushButton(tr("accept"),this); acceptButton = new QPushButton(tr("accept"),this);
cancelButton = new QPushButton(tr("cancel"),this); cancelButton = new QPushButton(tr("cancel"),this);
QHBoxLayout * buttons = new QHBoxLayout; QHBoxLayout * buttons = new QHBoxLayout;
buttons->addStretch(); buttons->addStretch();
buttons->addWidget(acceptButton); buttons->addWidget(acceptButton);
buttons->addWidget(cancelButton); buttons->addWidget(cancelButton);
layout->addStretch(); layout->addStretch();
layout->addLayout(buttons); layout->addLayout(buttons);
setLayout(layout); setLayout(layout);
//connections //connections
connect(edit,SIGNAL(textChanged(QString)),this,SLOT(validateName(QString))); connect(edit,SIGNAL(textChanged(QString)),this,SLOT(validateName(QString)));
connect(cancelButton,SIGNAL(clicked()),this,SLOT(close())); connect(cancelButton,SIGNAL(clicked()),this,SLOT(close()));
connect(acceptButton,SIGNAL(clicked()),this,SLOT(accept())); connect(acceptButton,SIGNAL(clicked()),this,SLOT(accept()));
} }
YACReader::LabelColors AddLabelDialog::selectedColor() YACReader::LabelColors AddLabelDialog::selectedColor()
{ {
return YACReader::LabelColors(list->currentRow()+1); return YACReader::LabelColors(list->currentRow()+1);
} }
QString AddLabelDialog::name() QString AddLabelDialog::name()
{ {
return edit->text(); return edit->text();
} }
int AddLabelDialog::exec() int AddLabelDialog::exec()
{ {
edit->clear(); edit->clear();
list->clearSelection(); list->clearSelection();
acceptButton->setDisabled(true); acceptButton->setDisabled(true);
list->setCurrentRow(0); list->setCurrentRow(0);
return QDialog::exec(); return QDialog::exec();
} }
void AddLabelDialog::validateName(const QString &name) void AddLabelDialog::validateName(const QString &name)
{ {
if(name.isEmpty()) if(name.isEmpty())
acceptButton->setDisabled(true); acceptButton->setDisabled(true);
else else
acceptButton->setEnabled(true); acceptButton->setEnabled(true);
} }

View File

@ -1,31 +1,31 @@
#ifndef ADD_LABEL_DIALOG_H #ifndef ADD_LABEL_DIALOG_H
#define ADD_LABEL_DIALOG_H #define ADD_LABEL_DIALOG_H
#include <QtWidgets> #include <QtWidgets>
#include "yacreader_global.h" #include "yacreader_global.h"
class AddLabelDialog : public QDialog class AddLabelDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit AddLabelDialog(QWidget *parent = 0); explicit AddLabelDialog(QWidget *parent = 0);
YACReader::LabelColors selectedColor(); YACReader::LabelColors selectedColor();
QString name(); QString name();
signals: signals:
public slots: public slots:
int exec(); int exec();
protected slots: protected slots:
void validateName(const QString & name); void validateName(const QString & name);
protected: protected:
QLineEdit * edit; QLineEdit * edit;
QListWidget * list; QListWidget * list;
QPushButton * acceptButton; QPushButton * acceptButton;
QPushButton * cancelButton; QPushButton * cancelButton;
}; };
#endif // ADD_LABEL_DIALOG_H #endif // ADD_LABEL_DIALOG_H

View File

@ -1,124 +1,124 @@
#include "add_library_dialog.h" #include "add_library_dialog.h"
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QFileDialog> #include <QFileDialog>
#include <QGridLayout> #include <QGridLayout>
AddLibraryDialog::AddLibraryDialog(QWidget * parent) AddLibraryDialog::AddLibraryDialog(QWidget * parent)
:QDialog(parent) :QDialog(parent)
{ {
setupUI(); setupUI();
} }
void AddLibraryDialog::setupUI() void AddLibraryDialog::setupUI()
{ {
textLabel = new QLabel(tr("Comics folder : ")); textLabel = new QLabel(tr("Comics folder : "));
path = new QLineEdit; path = new QLineEdit;
textLabel->setBuddy(path); textLabel->setBuddy(path);
connect(path,SIGNAL(textChanged(QString)),this,SLOT(pathSetted(QString))); connect(path,SIGNAL(textChanged(QString)),this,SLOT(pathSetted(QString)));
nameLabel = new QLabel(tr("Library name : ")); nameLabel = new QLabel(tr("Library name : "));
nameEdit = new QLineEdit; nameEdit = new QLineEdit;
nameLabel->setBuddy(nameEdit); nameLabel->setBuddy(nameEdit);
connect(nameEdit,SIGNAL(textChanged(QString)),this,SLOT(nameSetted(QString))); connect(nameEdit,SIGNAL(textChanged(QString)),this,SLOT(nameSetted(QString)));
accept = new QPushButton(tr("Add")); accept = new QPushButton(tr("Add"));
accept->setDisabled(true); accept->setDisabled(true);
connect(accept,SIGNAL(clicked()),this,SLOT(add())); connect(accept,SIGNAL(clicked()),this,SLOT(add()));
cancel = new QPushButton(tr("Cancel")); cancel = new QPushButton(tr("Cancel"));
connect(cancel,SIGNAL(clicked()),this,SLOT(close())); connect(cancel,SIGNAL(clicked()),this,SLOT(close()));
find = new QPushButton(QIcon(":/images/find_folder.png"),""); find = new QPushButton(QIcon(":/images/find_folder.png"),"");
connect(find,SIGNAL(clicked()),this,SLOT(findPath())); connect(find,SIGNAL(clicked()),this,SLOT(findPath()));
QGridLayout * content = new QGridLayout; QGridLayout * content = new QGridLayout;
content->addWidget(nameLabel,0,0); content->addWidget(nameLabel,0,0);
content->addWidget(nameEdit,0,1); content->addWidget(nameEdit,0,1);
content->addWidget(textLabel,1,0); content->addWidget(textLabel,1,0);
content->addWidget(path,1,1); content->addWidget(path,1,1);
content->addWidget(find,1,2); content->addWidget(find,1,2);
content->setColumnStretch(2,0); content->setColumnStretch(2,0);
QHBoxLayout *bottomLayout = new QHBoxLayout; QHBoxLayout *bottomLayout = new QHBoxLayout;
bottomLayout->addStretch(); bottomLayout->addStretch();
bottomLayout->addWidget(accept); bottomLayout->addWidget(accept);
bottomLayout->addWidget(cancel); bottomLayout->addWidget(cancel);
QVBoxLayout *mainLayout = new QVBoxLayout; QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(content); mainLayout->addLayout(content);
mainLayout->addStretch(); mainLayout->addStretch();
mainLayout->addLayout(bottomLayout); mainLayout->addLayout(bottomLayout);
QHBoxLayout * imgMainLayout = new QHBoxLayout; QHBoxLayout * imgMainLayout = new QHBoxLayout;
QLabel * imgLabel = new QLabel(this); QLabel * imgLabel = new QLabel(this);
QPixmap p(":/images/openLibrary.png"); QPixmap p(":/images/openLibrary.png");
imgLabel->setPixmap(p); imgLabel->setPixmap(p);
imgMainLayout->addWidget(imgLabel);//,0,Qt::AlignTop); imgMainLayout->addWidget(imgLabel);//,0,Qt::AlignTop);
imgMainLayout->addLayout(mainLayout); imgMainLayout->addLayout(mainLayout);
setLayout(imgMainLayout); setLayout(imgMainLayout);
setModal(true); setModal(true);
setWindowTitle(tr("Add an existing library")); setWindowTitle(tr("Add an existing library"));
} }
void AddLibraryDialog::add() void AddLibraryDialog::add()
{ {
//accept->setEnabled(false); //accept->setEnabled(false);
emit(addLibrary(QDir::cleanPath(path->text()),nameEdit->text())); emit(addLibrary(QDir::cleanPath(path->text()),nameEdit->text()));
} }
void AddLibraryDialog::nameSetted(const QString & text) void AddLibraryDialog::nameSetted(const QString & text)
{ {
if(!text.isEmpty()) if(!text.isEmpty())
{ {
if(!path->text().isEmpty()) if(!path->text().isEmpty())
{ {
QFileInfo fi(path->text()); QFileInfo fi(path->text());
if(fi.isDir()) if(fi.isDir())
accept->setEnabled(true); accept->setEnabled(true);
else else
accept->setEnabled(false); accept->setEnabled(false);
} }
} }
else else
accept->setEnabled(false); accept->setEnabled(false);
} }
void AddLibraryDialog::pathSetted(const QString & text) void AddLibraryDialog::pathSetted(const QString & text)
{ {
QFileInfo fi(text); QFileInfo fi(text);
if(fi.isDir()) if(fi.isDir())
{ {
if(!nameEdit->text().isEmpty()) if(!nameEdit->text().isEmpty())
accept->setEnabled(true); accept->setEnabled(true);
} }
else else
accept->setEnabled(false); accept->setEnabled(false);
} }
void AddLibraryDialog::findPath() void AddLibraryDialog::findPath()
{ {
QString s = QFileDialog::getExistingDirectory(0,"Comics directory","."); QString s = QFileDialog::getExistingDirectory(0,"Comics directory",".");
if(!s.isEmpty()) if(!s.isEmpty())
{ {
path->setText(s); path->setText(s);
if(!nameEdit->text().isEmpty()) if(!nameEdit->text().isEmpty())
accept->setEnabled(true); accept->setEnabled(true);
} }
else else
accept->setEnabled(false); accept->setEnabled(false);
} }
void AddLibraryDialog::close() void AddLibraryDialog::close()
{ {
path->clear(); path->clear();
nameEdit->clear(); nameEdit->clear();
accept->setEnabled(false); accept->setEnabled(false);
QDialog::close(); QDialog::close();
} }

View File

@ -1,13 +1,13 @@
#include "bundle_creator.h" #include "bundle_creator.h"
BundleCreator::BundleCreator(void) BundleCreator::BundleCreator(void)
:QObject() :QObject()
{ {
} }
BundleCreator::~BundleCreator(void) BundleCreator::~BundleCreator(void)
{ {
} }

View File

@ -1,14 +1,14 @@
#ifndef __BUNDLE_CREATOR_H #ifndef __BUNDLE_CREATOR_H
#define __BUNDLE_CREATOR_H #define __BUNDLE_CREATOR_H
#include <QtCore> #include <QtCore>
class BundleCreator : public QObject class BundleCreator : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
BundleCreator(void); BundleCreator(void);
~BundleCreator(void); ~BundleCreator(void);
}; };
#endif #endif

View File

@ -1,382 +1,382 @@
#include "classic_comics_view.h" #include "classic_comics_view.h"
#include "QStackedWidget" #include "QStackedWidget"
#include "comic_flow_widget.h" #include "comic_flow_widget.h"
#include "QsLog.h" #include "QsLog.h"
#include "shortcuts_manager.h" #include "shortcuts_manager.h"
#include "yacreader_table_view.h" #include "yacreader_table_view.h"
#include "yacreader_tool_bar_stretch.h" #include "yacreader_tool_bar_stretch.h"
ClassicComicsView::ClassicComicsView(QWidget *parent) ClassicComicsView::ClassicComicsView(QWidget *parent)
:ComicsView(parent),searching(false) :ComicsView(parent),searching(false)
{ {
QHBoxLayout * layout = new QHBoxLayout; QHBoxLayout * layout = new QHBoxLayout;
settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor
settings->beginGroup("libraryConfig"); settings->beginGroup("libraryConfig");
//FLOW----------------------------------------------------------------------- //FLOW-----------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//FORCE_ANGLE is not used here, because ComicFlowWidgetGL will use OpenGL ES in the future //FORCE_ANGLE is not used here, because ComicFlowWidgetGL will use OpenGL ES in the future
#ifndef NO_OPENGL #ifndef NO_OPENGL
if((settings->value(USE_OPEN_GL).toBool() == true)) if((settings->value(USE_OPEN_GL).toBool() == true))
comicFlow = new ComicFlowWidgetGL(0); comicFlow = new ComicFlowWidgetGL(0);
else else
comicFlow = new ComicFlowWidgetSW(0); comicFlow = new ComicFlowWidgetSW(0);
#else #else
comicFlow = new ComicFlowWidgetSW(0); comicFlow = new ComicFlowWidgetSW(0);
#endif #endif
comicFlow->updateConfig(settings); comicFlow->updateConfig(settings);
comicFlow->setFocusPolicy(Qt::StrongFocus); comicFlow->setFocusPolicy(Qt::StrongFocus);
comicFlow->setShowMarks(true); comicFlow->setShowMarks(true);
setFocusProxy(comicFlow); setFocusProxy(comicFlow);
comicFlow->setFocus(Qt::OtherFocusReason); comicFlow->setFocus(Qt::OtherFocusReason);
comicFlow->setContextMenuPolicy(Qt::CustomContextMenu); comicFlow->setContextMenuPolicy(Qt::CustomContextMenu);
//layout----------------------------------------------- //layout-----------------------------------------------
sVertical = new QSplitter(Qt::Vertical); //spliter derecha sVertical = new QSplitter(Qt::Vertical); //spliter derecha
stack = new QStackedWidget; stack = new QStackedWidget;
stack->addWidget(comicFlow); stack->addWidget(comicFlow);
setupSearchingIcon(); setupSearchingIcon();
stack->addWidget(searchingIcon); stack->addWidget(searchingIcon);
sVertical->addWidget(stack); sVertical->addWidget(stack);
comics = new QWidget; comics = new QWidget;
QVBoxLayout * comicsLayout = new QVBoxLayout; QVBoxLayout * comicsLayout = new QVBoxLayout;
comicsLayout->setSpacing(0); comicsLayout->setSpacing(0);
comicsLayout->setContentsMargins(0,0,0,0); comicsLayout->setContentsMargins(0,0,0,0);
//TODO ComicsView:(set toolbar) comicsLayout->addWidget(editInfoToolBar); //TODO ComicsView:(set toolbar) comicsLayout->addWidget(editInfoToolBar);
tableView = new YACReaderTableView; tableView = new YACReaderTableView;
tableView->verticalHeader()->hide(); tableView->verticalHeader()->hide();
tableView->setFocusPolicy(Qt::StrongFocus); tableView->setFocusPolicy(Qt::StrongFocus);
comicsLayout->addWidget(tableView); comicsLayout->addWidget(tableView);
comics->setLayout(comicsLayout); comics->setLayout(comicsLayout);
sVertical->addWidget(comics); sVertical->addWidget(comics);
tableView->setContextMenuPolicy(Qt::CustomContextMenu); tableView->setContextMenuPolicy(Qt::CustomContextMenu);
//config-------------------------------------------------- //config--------------------------------------------------
if(settings->contains(COMICS_VIEW_HEADERS)) if(settings->contains(COMICS_VIEW_HEADERS))
tableView->horizontalHeader()->restoreState(settings->value(COMICS_VIEW_HEADERS).toByteArray()); tableView->horizontalHeader()->restoreState(settings->value(COMICS_VIEW_HEADERS).toByteArray());
//connections--------------------------------------------- //connections---------------------------------------------
connect(tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(centerComicFlow(QModelIndex))); connect(tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(centerComicFlow(QModelIndex)));
connect(tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectedComicForOpening(QModelIndex))); connect(tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectedComicForOpening(QModelIndex)));
connect(comicFlow, SIGNAL(centerIndexChanged(int)), this, SLOT(updateTableView(int))); connect(comicFlow, SIGNAL(centerIndexChanged(int)), this, SLOT(updateTableView(int)));
connect(tableView, SIGNAL(comicRated(int,QModelIndex)), this, SIGNAL(comicRated(int,QModelIndex))); connect(tableView, SIGNAL(comicRated(int,QModelIndex)), this, SIGNAL(comicRated(int,QModelIndex)));
connect(comicFlow, SIGNAL(selected(uint)), this, SIGNAL(selected(uint))); connect(comicFlow, SIGNAL(selected(uint)), this, SIGNAL(selected(uint)));
connect(tableView->horizontalHeader(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveTableHeadersStatus())); connect(tableView->horizontalHeader(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveTableHeadersStatus()));
connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(saveTableHeadersStatus())); connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(saveTableHeadersStatus()));
connect(comicFlow, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(requestedViewContextMenu(QPoint))); connect(comicFlow, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(requestedViewContextMenu(QPoint)));
connect(tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(requestedItemContextMenu(QPoint))); connect(tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(requestedItemContextMenu(QPoint)));
layout->addWidget(sVertical); layout->addWidget(sVertical);
setLayout(layout); setLayout(layout);
layout->setMargin(0); layout->setMargin(0);
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
sVertical->setCollapsible(1,false); sVertical->setCollapsible(1,false);
#endif #endif
if(settings->contains(COMICS_VIEW_FLOW_SPLITTER_STATUS)) if(settings->contains(COMICS_VIEW_FLOW_SPLITTER_STATUS))
sVertical->restoreState(settings->value(COMICS_VIEW_FLOW_SPLITTER_STATUS).toByteArray()); sVertical->restoreState(settings->value(COMICS_VIEW_FLOW_SPLITTER_STATUS).toByteArray());
//hide flow widgets //hide flow widgets
hideFlowViewAction = new QAction(this); hideFlowViewAction = new QAction(this);
hideFlowViewAction->setText(tr("Hide comic flow")); hideFlowViewAction->setText(tr("Hide comic flow"));
hideFlowViewAction->setData(HIDE_COMIC_VIEW_ACTION_YL); hideFlowViewAction->setData(HIDE_COMIC_VIEW_ACTION_YL);
hideFlowViewAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(HIDE_COMIC_VIEW_ACTION_YL)); hideFlowViewAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(HIDE_COMIC_VIEW_ACTION_YL));
hideFlowViewAction->setIcon(QIcon(":/images/comics_view_toolbar/hideComicFlow.png")); hideFlowViewAction->setIcon(QIcon(":/images/comics_view_toolbar/hideComicFlow.png"));
hideFlowViewAction->setCheckable(true); hideFlowViewAction->setCheckable(true);
hideFlowViewAction->setChecked(false); hideFlowViewAction->setChecked(false);
connect(hideFlowViewAction, SIGNAL(toggled(bool)),this, SLOT(hideComicFlow(bool))); connect(hideFlowViewAction, SIGNAL(toggled(bool)),this, SLOT(hideComicFlow(bool)));
} }
void ClassicComicsView::hideComicFlow(bool hide) void ClassicComicsView::hideComicFlow(bool hide)
{ {
if(hide) if(hide)
{ {
QList<int> sizes; QList<int> sizes;
sizes.append(0); sizes.append(0);
int total = sVertical->sizes().at(0) + sVertical->sizes().at(1); int total = sVertical->sizes().at(0) + sVertical->sizes().at(1);
sizes.append(total); sizes.append(total);
sVertical->setSizes(sizes); sVertical->setSizes(sizes);
} }
else else
{ {
QList<int> sizes; QList<int> sizes;
int total = sVertical->sizes().at(0) + sVertical->sizes().at(1); int total = sVertical->sizes().at(0) + sVertical->sizes().at(1);
sizes.append(2*total/3); sizes.append(2*total/3);
sizes.append(total/3); sizes.append(total/3);
sVertical->setSizes(sizes); sVertical->setSizes(sizes);
} }
} }
//the toolbar has to be populated //the toolbar has to be populated
void ClassicComicsView::setToolBar(QToolBar *toolBar) void ClassicComicsView::setToolBar(QToolBar *toolBar)
{ {
static_cast<QVBoxLayout *>(comics->layout())->insertWidget(0,toolBar); static_cast<QVBoxLayout *>(comics->layout())->insertWidget(0,toolBar);
this->toolbar = toolBar; this->toolbar = toolBar;
toolBarStretch = new YACReaderToolBarStretch(this); toolBarStretch = new YACReaderToolBarStretch(this);
toolBarStretchAction = toolBar->addWidget(toolBarStretch); toolBarStretchAction = toolBar->addWidget(toolBarStretch);
toolBar->addAction(hideFlowViewAction); toolBar->addAction(hideFlowViewAction);
} }
void ClassicComicsView::setModel(ComicModel *model) void ClassicComicsView::setModel(ComicModel *model)
{ {
ComicsView::setModel(model); ComicsView::setModel(model);
if(model == NULL) if(model == NULL)
{ {
comicFlow->clear(); comicFlow->clear();
} }
else else
{ {
connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(applyModelChanges(QModelIndex,QModelIndex,QVector<int>)),Qt::UniqueConnection); connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(applyModelChanges(QModelIndex,QModelIndex,QVector<int>)),Qt::UniqueConnection);
connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(removeItemsFromFlow(QModelIndex,int,int)),Qt::UniqueConnection); connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(removeItemsFromFlow(QModelIndex,int,int)),Qt::UniqueConnection);
connect(model, SIGNAL(resortedIndexes(QList<int>)),comicFlow,SLOT(resortCovers(QList<int>)),Qt::UniqueConnection); connect(model, SIGNAL(resortedIndexes(QList<int>)),comicFlow,SLOT(resortCovers(QList<int>)),Qt::UniqueConnection);
connect(model, SIGNAL(newSelectedIndex(QModelIndex)),this,SLOT(setCurrentIndex(QModelIndex)),Qt::UniqueConnection); connect(model, SIGNAL(newSelectedIndex(QModelIndex)),this,SLOT(setCurrentIndex(QModelIndex)),Qt::UniqueConnection);
tableView->setModel(model); tableView->setModel(model);
if(model->rowCount()>0) if(model->rowCount()>0)
tableView->setCurrentIndex(model->index(0,0)); tableView->setCurrentIndex(model->index(0,0));
tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
tableView->horizontalHeader()->setSectionsMovable(true); tableView->horizontalHeader()->setSectionsMovable(true);
#else #else
tableView->horizontalHeader()->setMovable(true); tableView->horizontalHeader()->setMovable(true);
#endif #endif
//TODO parametrizar la configuración de las columnas //TODO parametrizar la configuración de las columnas
/*if(!settings->contains(COMICS_VIEW_HEADERS)) /*if(!settings->contains(COMICS_VIEW_HEADERS))
{*/ {*/
for(int i = 0;i<tableView->horizontalHeader()->count();i++) for(int i = 0;i<tableView->horizontalHeader()->count();i++)
tableView->horizontalHeader()->hideSection(i); tableView->horizontalHeader()->hideSection(i);
tableView->horizontalHeader()->showSection(ComicModel::Number); tableView->horizontalHeader()->showSection(ComicModel::Number);
tableView->horizontalHeader()->showSection(ComicModel::Title); tableView->horizontalHeader()->showSection(ComicModel::Title);
tableView->horizontalHeader()->showSection(ComicModel::FileName); tableView->horizontalHeader()->showSection(ComicModel::FileName);
tableView->horizontalHeader()->showSection(ComicModel::NumPages); tableView->horizontalHeader()->showSection(ComicModel::NumPages);
tableView->horizontalHeader()->showSection(ComicModel::Hash); //Size is part of the Hash...TODO add Columns::Size to Columns tableView->horizontalHeader()->showSection(ComicModel::Hash); //Size is part of the Hash...TODO add Columns::Size to Columns
tableView->horizontalHeader()->showSection(ComicModel::ReadColumn); tableView->horizontalHeader()->showSection(ComicModel::ReadColumn);
tableView->horizontalHeader()->showSection(ComicModel::CurrentPage); tableView->horizontalHeader()->showSection(ComicModel::CurrentPage);
tableView->horizontalHeader()->showSection(ComicModel::Rating); tableView->horizontalHeader()->showSection(ComicModel::Rating);
//} //}
//debido a un bug, qt4 no es capaz de ajustar el ancho teniendo en cuenta todas la filas (no sólo las visibles) //debido a un bug, qt4 no es capaz de ajustar el ancho teniendo en cuenta todas la filas (no sólo las visibles)
//así que se ecala la primera vez y después se deja el control al usuario. //así que se ecala la primera vez y después se deja el control al usuario.
//if(!settings->contains(COMICS_VIEW_HEADERS)) //if(!settings->contains(COMICS_VIEW_HEADERS))
QStringList paths = model->getPaths(model->getCurrentPath());//TODO ComicsView: get currentpath from somewhere currentPath()); QStringList paths = model->getPaths(model->getCurrentPath());//TODO ComicsView: get currentpath from somewhere currentPath());
comicFlow->setImagePaths(paths); comicFlow->setImagePaths(paths);
comicFlow->setMarks(model->getReadList()); comicFlow->setMarks(model->getReadList());
//comicFlow->setFocus(Qt::OtherFocusReason); //comicFlow->setFocus(Qt::OtherFocusReason);
if(settings->contains(COMICS_VIEW_HEADERS)) if(settings->contains(COMICS_VIEW_HEADERS))
tableView->horizontalHeader()->restoreState(settings->value(COMICS_VIEW_HEADERS).toByteArray()); tableView->horizontalHeader()->restoreState(settings->value(COMICS_VIEW_HEADERS).toByteArray());
tableView->resizeColumnsToContents(); tableView->resizeColumnsToContents();
tableView->horizontalHeader()->setStretchLastSection(true); tableView->horizontalHeader()->setStretchLastSection(true);
} }
} }
void ClassicComicsView::setCurrentIndex(const QModelIndex &index) void ClassicComicsView::setCurrentIndex(const QModelIndex &index)
{ {
tableView->setCurrentIndex(index); tableView->setCurrentIndex(index);
centerComicFlow(index); centerComicFlow(index);
} }
QModelIndex ClassicComicsView::currentIndex() QModelIndex ClassicComicsView::currentIndex()
{ {
return tableView->currentIndex(); return tableView->currentIndex();
} }
QItemSelectionModel *ClassicComicsView::selectionModel() QItemSelectionModel *ClassicComicsView::selectionModel()
{ {
return tableView->selectionModel(); return tableView->selectionModel();
} }
void ClassicComicsView::scrollTo(const QModelIndex & mi, QAbstractItemView::ScrollHint hint) void ClassicComicsView::scrollTo(const QModelIndex & mi, QAbstractItemView::ScrollHint hint)
{ {
Q_UNUSED(hint); Q_UNUSED(hint);
comicFlow->setCenterIndex(mi.row()); comicFlow->setCenterIndex(mi.row());
} }
void ClassicComicsView::toFullScreen() void ClassicComicsView::toFullScreen()
{ {
comicFlow->hide(); comicFlow->hide();
comicFlow->setCenterIndex(comicFlow->centerIndex()); comicFlow->setCenterIndex(comicFlow->centerIndex());
comics->hide(); comics->hide();
//showFullScreen() //parent windows //showFullScreen() //parent windows
comicFlow->show(); comicFlow->show();
comicFlow->setFocus(Qt::OtherFocusReason); comicFlow->setFocus(Qt::OtherFocusReason);
} }
void ClassicComicsView::toNormal() void ClassicComicsView::toNormal()
{ {
comicFlow->hide(); comicFlow->hide();
comicFlow->setCenterIndex(comicFlow->centerIndex()); comicFlow->setCenterIndex(comicFlow->centerIndex());
comicFlow->render(); comicFlow->render();
comics->show(); comics->show();
comicFlow->show(); comicFlow->show();
} }
void ClassicComicsView::updateConfig(QSettings *settings) void ClassicComicsView::updateConfig(QSettings *settings)
{ {
comicFlow->updateConfig(settings); comicFlow->updateConfig(settings);
} }
void ClassicComicsView::enableFilterMode(bool enabled) void ClassicComicsView::enableFilterMode(bool enabled)
{ {
if(enabled) if(enabled)
{ {
comicFlow->clear(); comicFlow->clear();
if(previousSplitterStatus.isEmpty()) if(previousSplitterStatus.isEmpty())
previousSplitterStatus = sVertical->saveState(); previousSplitterStatus = sVertical->saveState();
sVertical->setSizes(QList<int> () << 100 << 10000000); sVertical->setSizes(QList<int> () << 100 << 10000000);
showSearchingIcon(); showSearchingIcon();
}else }else
{ {
hideSearchingIcon(); hideSearchingIcon();
sVertical->restoreState(previousSplitterStatus); sVertical->restoreState(previousSplitterStatus);
previousSplitterStatus.clear(); previousSplitterStatus.clear();
} }
//sVertical->setCollapsible(0,!enabled); //sVertical->setCollapsible(0,!enabled);
searching = enabled; searching = enabled;
} }
void ClassicComicsView::selectIndex(int index) void ClassicComicsView::selectIndex(int index)
{ {
tableView->selectRow(index); tableView->selectRow(index);
} }
void ClassicComicsView::updateCurrentComicView() void ClassicComicsView::updateCurrentComicView()
{ {
} }
void ClassicComicsView::selectAll() void ClassicComicsView::selectAll()
{ {
tableView->selectAll(); tableView->selectAll();
} }
void ClassicComicsView::selectedComicForOpening(const QModelIndex &mi) void ClassicComicsView::selectedComicForOpening(const QModelIndex &mi)
{ {
emit selected(mi.row()); emit selected(mi.row());
} }
void ClassicComicsView::requestedViewContextMenu(const QPoint &point) void ClassicComicsView::requestedViewContextMenu(const QPoint &point)
{ {
emit customContextMenuViewRequested(comicFlow->mapTo(this, point)); emit customContextMenuViewRequested(comicFlow->mapTo(this, point));
} }
void ClassicComicsView::requestedItemContextMenu(const QPoint &point) void ClassicComicsView::requestedItemContextMenu(const QPoint &point)
{ {
emit customContextMenuItemRequested(tableView->mapTo(this, point)); emit customContextMenuItemRequested(tableView->mapTo(this, point));
} }
void ClassicComicsView::setShowMarks(bool show) void ClassicComicsView::setShowMarks(bool show)
{ {
comicFlow->setShowMarks(show); comicFlow->setShowMarks(show);
} }
void ClassicComicsView::centerComicFlow(const QModelIndex & mi) void ClassicComicsView::centerComicFlow(const QModelIndex & mi)
{ {
comicFlow->showSlide(mi.row()); comicFlow->showSlide(mi.row());
comicFlow->setFocus(Qt::OtherFocusReason); comicFlow->setFocus(Qt::OtherFocusReason);
} }
void ClassicComicsView::updateTableView(int i) void ClassicComicsView::updateTableView(int i)
{ {
QModelIndex mi = model->index(i,2); QModelIndex mi = model->index(i,2);
tableView->setCurrentIndex(mi); tableView->setCurrentIndex(mi);
tableView->scrollTo(mi,QAbstractItemView::EnsureVisible); tableView->scrollTo(mi,QAbstractItemView::EnsureVisible);
} }
void ClassicComicsView::saveTableHeadersStatus() void ClassicComicsView::saveTableHeadersStatus()
{ {
settings->setValue(COMICS_VIEW_HEADERS,tableView->horizontalHeader()->saveState()); settings->setValue(COMICS_VIEW_HEADERS,tableView->horizontalHeader()->saveState());
} }
void ClassicComicsView::saveSplitterStatus() void ClassicComicsView::saveSplitterStatus()
{ {
settingsMutex.lock(); settingsMutex.lock();
if(!searching) if(!searching)
settings->setValue(COMICS_VIEW_FLOW_SPLITTER_STATUS, sVertical->saveState()); settings->setValue(COMICS_VIEW_FLOW_SPLITTER_STATUS, sVertical->saveState());
settingsMutex.unlock(); settingsMutex.unlock();
} }
void ClassicComicsView::applyModelChanges(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) void ClassicComicsView::applyModelChanges(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{ {
Q_UNUSED(topLeft); Q_UNUSED(topLeft);
Q_UNUSED(bottomRight); Q_UNUSED(bottomRight);
if(roles.contains(ComicModel::ReadColumnRole)) if(roles.contains(ComicModel::ReadColumnRole))
{ {
comicFlow->setMarks(model->getReadList()); comicFlow->setMarks(model->getReadList());
comicFlow->updateMarks(); comicFlow->updateMarks();
} }
} }
void ClassicComicsView::removeItemsFromFlow(const QModelIndex &parent, int from, int to) void ClassicComicsView::removeItemsFromFlow(const QModelIndex &parent, int from, int to)
{ {
Q_UNUSED(parent); Q_UNUSED(parent);
for(int i = from; i<=to; i++) for(int i = from; i<=to; i++)
comicFlow->remove(i); comicFlow->remove(i);
} }
void ClassicComicsView::closeEvent(QCloseEvent *event) void ClassicComicsView::closeEvent(QCloseEvent *event)
{ {
toolbar->removeAction(toolBarStretchAction); toolbar->removeAction(toolBarStretchAction);
toolbar->removeAction(hideFlowViewAction); toolbar->removeAction(hideFlowViewAction);
saveTableHeadersStatus(); saveTableHeadersStatus();
saveSplitterStatus(); saveSplitterStatus();
ComicsView::closeEvent(event); ComicsView::closeEvent(event);
} }
void ClassicComicsView::setupSearchingIcon() void ClassicComicsView::setupSearchingIcon()
{ {
searchingIcon = new QWidget(comicFlow); searchingIcon = new QWidget(comicFlow);
QHBoxLayout * h = new QHBoxLayout; QHBoxLayout * h = new QHBoxLayout;
QPixmap p(":/images/searching_icon.png"); QPixmap p(":/images/searching_icon.png");
QLabel * l = new QLabel(searchingIcon); QLabel * l = new QLabel(searchingIcon);
l->setPixmap(p); l->setPixmap(p);
l->setFixedSize(p.size()); l->setFixedSize(p.size());
h->addWidget(l,0,Qt::AlignCenter); h->addWidget(l,0,Qt::AlignCenter);
searchingIcon->setLayout(h); searchingIcon->setLayout(h);
QPalette pal(searchingIcon->palette()); QPalette pal(searchingIcon->palette());
pal.setColor(QPalette::Background, Qt::black); pal.setColor(QPalette::Background, Qt::black);
searchingIcon->setAutoFillBackground(true); searchingIcon->setAutoFillBackground(true);
searchingIcon->setPalette(pal); searchingIcon->setPalette(pal);
hideSearchingIcon(); hideSearchingIcon();
} }
void ClassicComicsView::showSearchingIcon() void ClassicComicsView::showSearchingIcon()
{ {
stack->setCurrentWidget(searchingIcon); stack->setCurrentWidget(searchingIcon);
} }
void ClassicComicsView::hideSearchingIcon() void ClassicComicsView::hideSearchingIcon()
{ {
stack->setCurrentWidget(comicFlow); stack->setCurrentWidget(comicFlow);
} }

View File

@ -1,80 +1,80 @@
#ifndef CLASSIC_COMICS_VIEW_H #ifndef CLASSIC_COMICS_VIEW_H
#define CLASSIC_COMICS_VIEW_H #define CLASSIC_COMICS_VIEW_H
#include "comics_view.h" #include "comics_view.h"
#include <QModelIndex> #include <QModelIndex>
#include <QModelIndexList> #include <QModelIndexList>
class QSplitter; class QSplitter;
class QStackedWidget; class QStackedWidget;
class QToolBar; class QToolBar;
class ComicFlowWidget; class ComicFlowWidget;
class ComicModel; class ComicModel;
class YACReaderTableView; class YACReaderTableView;
class YACReaderToolBarStretch; class YACReaderToolBarStretch;
class ClassicComicsView : public ComicsView class ClassicComicsView : public ComicsView
{ {
Q_OBJECT Q_OBJECT
public: public:
ClassicComicsView(QWidget *parent = 0); ClassicComicsView(QWidget *parent = 0);
void setToolBar(QToolBar * toolBar); void setToolBar(QToolBar * toolBar);
void setModel(ComicModel *model); void setModel(ComicModel *model);
QModelIndex currentIndex(); QModelIndex currentIndex();
QItemSelectionModel * selectionModel(); QItemSelectionModel * selectionModel();
void scrollTo(const QModelIndex & mi, QAbstractItemView::ScrollHint hint ); void scrollTo(const QModelIndex & mi, QAbstractItemView::ScrollHint hint );
void toFullScreen(); void toFullScreen();
void toNormal(); void toNormal();
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void enableFilterMode(bool enabled); void enableFilterMode(bool enabled);
void selectIndex(int index); void selectIndex(int index);
void updateCurrentComicView(); void updateCurrentComicView();
public slots: public slots:
void setCurrentIndex(const QModelIndex &index); void setCurrentIndex(const QModelIndex &index);
void centerComicFlow(const QModelIndex & mi); void centerComicFlow(const QModelIndex & mi);
void updateTableView(int i); void updateTableView(int i);
void saveTableHeadersStatus(); void saveTableHeadersStatus();
void saveSplitterStatus(); void saveSplitterStatus();
void applyModelChanges(const QModelIndex & topLeft,const QModelIndex & bottomRight,const QVector<int> & roles); void applyModelChanges(const QModelIndex & topLeft,const QModelIndex & bottomRight,const QVector<int> & roles);
void removeItemsFromFlow(const QModelIndex & parent, int from, int to); void removeItemsFromFlow(const QModelIndex & parent, int from, int to);
//ComicsView //ComicsView
void setShowMarks(bool show); void setShowMarks(bool show);
void selectAll(); void selectAll();
void selectedComicForOpening(const QModelIndex & mi); void selectedComicForOpening(const QModelIndex & mi);
protected slots: protected slots:
void hideComicFlow(bool hide); void hideComicFlow(bool hide);
void requestedViewContextMenu(const QPoint & point); void requestedViewContextMenu(const QPoint & point);
void requestedItemContextMenu(const QPoint & point); void requestedItemContextMenu(const QPoint & point);
private: private:
YACReaderTableView * tableView; YACReaderTableView * tableView;
YACReaderToolBarStretch * toolBarStretch; YACReaderToolBarStretch * toolBarStretch;
QAction * toolBarStretchAction; QAction * toolBarStretchAction;
QToolBar * toolbar; QToolBar * toolbar;
QWidget *comics; QWidget *comics;
QSplitter * sVertical; QSplitter * sVertical;
ComicFlowWidget * comicFlow; ComicFlowWidget * comicFlow;
QSettings * settings; QSettings * settings;
void closeEvent ( QCloseEvent * event ); void closeEvent ( QCloseEvent * event );
QAction * hideFlowViewAction; QAction * hideFlowViewAction;
QStackedWidget * stack; QStackedWidget * stack;
QByteArray previousSplitterStatus; QByteArray previousSplitterStatus;
QWidget * searchingIcon; QWidget * searchingIcon;
bool searching; bool searching;
void setupSearchingIcon(); void setupSearchingIcon();
void showSearchingIcon(); void showSearchingIcon();
void hideSearchingIcon(); void hideSearchingIcon();
void updateSearchingIconPosition(); void updateSearchingIconPosition();
QMutex settingsMutex; QMutex settingsMutex;
}; };
#endif // CLASSIC_COMICS_VIEW_H #endif // CLASSIC_COMICS_VIEW_H

View File

@ -1,108 +1,108 @@
#include "comic_files_manager.h" #include "comic_files_manager.h"
#include <QFile> #include <QFile>
#include <QFileInfo> #include <QFileInfo>
#include <QDir> #include <QDir>
#include <QsLog.h> #include <QsLog.h>
#include "comic.h" #include "comic.h"
ComicFilesManager::ComicFilesManager(QObject *parent) : ComicFilesManager::ComicFilesManager(QObject *parent) :
QObject(parent), canceled(false) QObject(parent), canceled(false)
{ {
} }
void ComicFilesManager::copyComicsTo(const QList<QPair<QString,QString> > &sourceComics, const QString &folderDest, const QModelIndex & dest) void ComicFilesManager::copyComicsTo(const QList<QPair<QString,QString> > &sourceComics, const QString &folderDest, const QModelIndex & dest)
{ {
comics = sourceComics; comics = sourceComics;
folder = folderDest; folder = folderDest;
folderDestinationModelIndex = dest; folderDestinationModelIndex = dest;
move = false; move = false;
} }
void ComicFilesManager::moveComicsTo(const QList<QPair<QString, QString> > &sourceComics, const QString &folderDest, const QModelIndex &dest) void ComicFilesManager::moveComicsTo(const QList<QPair<QString, QString> > &sourceComics, const QString &folderDest, const QModelIndex &dest)
{ {
comics = sourceComics; comics = sourceComics;
folder = folderDest; folder = folderDest;
folderDestinationModelIndex = dest; folderDestinationModelIndex = dest;
move = true; move = true;
} }
QList<QPair<QString, QString> > ComicFilesManager::getDroppedFiles(const QList<QUrl> &urls) QList<QPair<QString, QString> > ComicFilesManager::getDroppedFiles(const QList<QUrl> &urls)
{ {
QList<QPair<QString,QString> > dropedFiles; QList<QPair<QString,QString> > dropedFiles;
QString currentPath; QString currentPath;
foreach(QUrl url, urls) foreach(QUrl url, urls)
{ {
currentPath = url.toLocalFile(); currentPath = url.toLocalFile();
if(currentPath.endsWith('/')) if(currentPath.endsWith('/'))
currentPath = currentPath.remove(currentPath.length()-1,1); //QTBUG-35896 QUrl.toLocalFile inconsistency. currentPath = currentPath.remove(currentPath.length()-1,1); //QTBUG-35896 QUrl.toLocalFile inconsistency.
if(Comic::fileIsComic(currentPath)) if(Comic::fileIsComic(currentPath))
dropedFiles << QPair<QString, QString>(currentPath,"/"); dropedFiles << QPair<QString, QString>(currentPath,"/");
else else
{ {
QLOG_DEBUG() << "XXXXXXXXXXXX :" << currentPath; QLOG_DEBUG() << "XXXXXXXXXXXX :" << currentPath;
QFileInfo info(currentPath); QFileInfo info(currentPath);
if(info.isDir()) if(info.isDir())
{ {
QLOG_DEBUG() << "origin path prior to absoluteFilePath : " << info.absolutePath(); QLOG_DEBUG() << "origin path prior to absoluteFilePath : " << info.absolutePath();
foreach(QString comicPath, Comic::findValidComicFilesInFolder(info.absoluteFilePath())) foreach(QString comicPath, Comic::findValidComicFilesInFolder(info.absoluteFilePath()))
{ {
QFileInfo comicInfo(comicPath); QFileInfo comicInfo(comicPath);
QString path = comicInfo.absolutePath(); QString path = comicInfo.absolutePath();
QLOG_DEBUG() << "comic path : " << comicPath; QLOG_DEBUG() << "comic path : " << comicPath;
QLOG_DEBUG() << "full comic path : " << path; QLOG_DEBUG() << "full comic path : " << path;
QLOG_DEBUG() << "origin path : " << info.absolutePath(); QLOG_DEBUG() << "origin path : " << info.absolutePath();
dropedFiles << QPair<QString, QString>(comicPath, path.remove(info.absolutePath())); dropedFiles << QPair<QString, QString>(comicPath, path.remove(info.absolutePath()));
} }
} }
} }
} }
return dropedFiles; return dropedFiles;
} }
void ComicFilesManager::process() void ComicFilesManager::process()
{ {
int i=0; int i=0;
bool successProcesingFiles = false; bool successProcesingFiles = false;
QPair<QString, QString> source; QPair<QString, QString> source;
foreach (source, comics) { foreach (source, comics) {
if(canceled) if(canceled)
{ {
if(successProcesingFiles) if(successProcesingFiles)
emit success(folderDestinationModelIndex); emit success(folderDestinationModelIndex);
emit finished(); emit finished();
return; //TODO rollback? return; //TODO rollback?
} }
QFileInfo info(source.first); QFileInfo info(source.first);
QString destPath = QDir::cleanPath(folder+'/'+source.second); QString destPath = QDir::cleanPath(folder+'/'+source.second);
QLOG_DEBUG() << "crear : " << destPath; QLOG_DEBUG() << "crear : " << destPath;
QDir().mkpath(destPath); QDir().mkpath(destPath);
if(QFile::copy(source.first, QDir::cleanPath(destPath+'/'+info.fileName()))) if(QFile::copy(source.first, QDir::cleanPath(destPath+'/'+info.fileName())))
{ {
successProcesingFiles = true; successProcesingFiles = true;
if(move) if(move)
{ {
QFile::remove(source.first); //TODO: remove the whole path.... QFile::remove(source.first); //TODO: remove the whole path....
} }
} }
i++; i++;
emit progress(i); emit progress(i);
} }
if(successProcesingFiles) if(successProcesingFiles)
emit success(folderDestinationModelIndex); emit success(folderDestinationModelIndex);
emit finished(); emit finished();
} }
void ComicFilesManager::cancel() void ComicFilesManager::cancel()
{ {
QLOG_DEBUG() << "Operation canceled"; QLOG_DEBUG() << "Operation canceled";
canceled = true; canceled = true;
} }

View File

@ -1,37 +1,37 @@
#ifndef COMIC_FILES_MANAGER_H #ifndef COMIC_FILES_MANAGER_H
#define COMIC_FILES_MANAGER_H #define COMIC_FILES_MANAGER_H
#include <QObject> #include <QObject>
#include <QList> #include <QList>
#include <QPair> #include <QPair>
#include <QModelIndex> #include <QModelIndex>
//this class is intended to work in background, just use moveToThread and process to start working //this class is intended to work in background, just use moveToThread and process to start working
class ComicFilesManager : public QObject class ComicFilesManager : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ComicFilesManager(QObject *parent = 0); explicit ComicFilesManager(QObject *parent = 0);
void copyComicsTo(const QList<QPair<QString,QString> > & sourceComics, const QString & folderDest, const QModelIndex &dest); void copyComicsTo(const QList<QPair<QString,QString> > & sourceComics, const QString & folderDest, const QModelIndex &dest);
void moveComicsTo(const QList<QPair<QString,QString> > & comics, const QString & folderDest, const QModelIndex &dest); void moveComicsTo(const QList<QPair<QString,QString> > & comics, const QString & folderDest, const QModelIndex &dest);
static QList<QPair<QString, QString> > getDroppedFiles(const QList<QUrl> & urls); static QList<QPair<QString, QString> > getDroppedFiles(const QList<QUrl> & urls);
signals: signals:
void currentComic(QString); void currentComic(QString);
void progress(int); void progress(int);
void finished(); void finished();
void success(QModelIndex); //at least one comics has been copied or moved void success(QModelIndex); //at least one comics has been copied or moved
public slots: public slots:
void process(); void process();
void cancel(); void cancel();
protected: protected:
bool move; bool move;
bool canceled; bool canceled;
QList<QPair<QString,QString> > comics; QList<QPair<QString,QString> > comics;
QString folder; QString folder;
QModelIndex folderDestinationModelIndex; QModelIndex folderDestinationModelIndex;
}; };
#endif // COMIC_FILES_MANAGER_H #endif // COMIC_FILES_MANAGER_H

View File

@ -1,265 +1,265 @@
#include "comic_flow.h" #include "comic_flow.h"
#include "qnaturalsorting.h" #include "qnaturalsorting.h"
#include "yacreader_global.h" #include "yacreader_global.h"
#include <algorithm> #include <algorithm>
#include <QMutex> #include <QMutex>
#include <QImageReader> #include <QImageReader>
#include <QTimer> #include <QTimer>
ComicFlow::ComicFlow(QWidget* parent,FlowType flowType) ComicFlow::ComicFlow(QWidget* parent,FlowType flowType)
:YACReaderFlow(parent,flowType) :YACReaderFlow(parent,flowType)
{ {
updateTimer = new QTimer; updateTimer = new QTimer;
connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateImageData())); connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateImageData()));
worker = new ImageLoader; worker = new ImageLoader;
connect(this, SIGNAL(centerIndexChanged(int)), this, SLOT(preload())); connect(this, SIGNAL(centerIndexChanged(int)), this, SLOT(preload()));
connect(this, SIGNAL(centerIndexChangedSilent(int)), this, SLOT(preload())); connect(this, SIGNAL(centerIndexChangedSilent(int)), this, SLOT(preload()));
setReflectionEffect(PlainReflection); setReflectionEffect(PlainReflection);
} }
ComicFlow::~ComicFlow() ComicFlow::~ComicFlow()
{ {
worker->terminate(); worker->terminate();
delete worker; delete worker;
delete updateTimer; delete updateTimer;
} }
void ComicFlow::setImagePaths(const QStringList& paths) void ComicFlow::setImagePaths(const QStringList& paths)
{ {
clear(); clear();
//imagePath = path; //imagePath = path;
imageFiles = paths; imageFiles = paths;
imagesLoaded.clear(); imagesLoaded.clear();
imagesLoaded.fill(false,imageFiles.size()); imagesLoaded.fill(false,imageFiles.size());
numImagesLoaded = 0; numImagesLoaded = 0;
imagesSetted.clear(); imagesSetted.clear();
imagesSetted.fill(false,imageFiles.size()); imagesSetted.fill(false,imageFiles.size());
// populate with empty images // populate with empty images
QImage img; //TODO remove QImage img; //TODO remove
QString s; QString s;
for(int i = 0; i < (int)imageFiles.size(); i++) for(int i = 0; i < (int)imageFiles.size(); i++)
{ {
addSlide(img); addSlide(img);
s = imageFiles.at(i); s = imageFiles.at(i);
s.remove(s.size()-4,4); s.remove(s.size()-4,4);
if(QFileInfo(s+".r").exists()) if(QFileInfo(s+".r").exists())
markSlide(i); markSlide(i);
} }
setCenterIndex(0); setCenterIndex(0);
worker->reset(); worker->reset();
preload(); preload();
} }
void ComicFlow::preload() void ComicFlow::preload()
{ {
if(numImagesLoaded < imagesLoaded.size()) if(numImagesLoaded < imagesLoaded.size())
updateTimer->start(30); //TODO comprobar rendimiento, originalmente era 70 updateTimer->start(30); //TODO comprobar rendimiento, originalmente era 70
} }
void ComicFlow::updateImageData() void ComicFlow::updateImageData()
{ {
// can't do anything, wait for the next possibility // can't do anything, wait for the next possibility
if(worker->busy()) if(worker->busy())
return; return;
// set image of last one // set image of last one
int idx = worker->index(); int idx = worker->index();
if( idx >= 0 && !worker->result().isNull()) if( idx >= 0 && !worker->result().isNull())
{ {
if(!imagesSetted[idx]) if(!imagesSetted[idx])
{ {
setSlide(idx, worker->result()); setSlide(idx, worker->result());
imagesSetted[idx] = true; imagesSetted[idx] = true;
numImagesLoaded++; numImagesLoaded++;
imagesLoaded[idx]=true; imagesLoaded[idx]=true;
} }
} }
// try to load only few images on the left and right side // try to load only few images on the left and right side
// i.e. all visible ones plus some extra // i.e. all visible ones plus some extra
#define COUNT 8 #define COUNT 8
int indexes[2*COUNT+1]; int indexes[2*COUNT+1];
int center = centerIndex(); int center = centerIndex();
indexes[0] = center; indexes[0] = center;
for(int j = 0; j < COUNT; j++) for(int j = 0; j < COUNT; j++)
{ {
indexes[j*2+1] = center+j+1; indexes[j*2+1] = center+j+1;
indexes[j*2+2] = center-j-1; indexes[j*2+2] = center-j-1;
} }
for(int c = 0; c < 2*COUNT+1; c++) for(int c = 0; c < 2*COUNT+1; c++)
{ {
int i = indexes[c]; int i = indexes[c];
if((i >= 0) && (i < slideCount())) if((i >= 0) && (i < slideCount()))
if(!imagesLoaded[i])//slide(i).isNull()) if(!imagesLoaded[i])//slide(i).isNull())
{ {
// schedule thumbnail generation // schedule thumbnail generation
QString fname = imageFiles[i]; QString fname = imageFiles[i];
worker->generate(i, fname, slideSize()); worker->generate(i, fname, slideSize());
return; return;
} }
} }
// no need to generate anything? stop polling... // no need to generate anything? stop polling...
updateTimer->stop(); updateTimer->stop();
} }
void ComicFlow::keyPressEvent(QKeyEvent* event) void ComicFlow::keyPressEvent(QKeyEvent* event)
{ {
PictureFlow::keyPressEvent(event); PictureFlow::keyPressEvent(event);
} }
void ComicFlow::wheelEvent(QWheelEvent * event) void ComicFlow::wheelEvent(QWheelEvent * event)
{ {
if(event->delta()<0) if(event->delta()<0)
showNext(); showNext();
else else
showPrevious(); showPrevious();
event->accept(); event->accept();
} }
void ComicFlow::removeSlide(int cover) void ComicFlow::removeSlide(int cover)
{ {
worker->lock(); worker->lock();
worker->reset(); worker->reset();
imageFiles.removeAt(cover); imageFiles.removeAt(cover);
if(imagesLoaded[cover]) if(imagesLoaded[cover])
numImagesLoaded--; numImagesLoaded--;
imagesLoaded.remove(cover); imagesLoaded.remove(cover);
imagesSetted.remove(cover); imagesSetted.remove(cover);
YACReaderFlow::removeSlide(cover); YACReaderFlow::removeSlide(cover);
worker->unlock(); worker->unlock();
preload(); preload();
} }
void ComicFlow::resortCovers(QList<int> newOrder) void ComicFlow::resortCovers(QList<int> newOrder)
{ {
worker->lock(); worker->lock();
worker->reset(); worker->reset();
YACReaderFlow::resortCovers(newOrder); YACReaderFlow::resortCovers(newOrder);
QStringList imageFilesNew; QStringList imageFilesNew;
QVector<bool> imagesLoadedNew; QVector<bool> imagesLoadedNew;
QVector<bool> imagesSettedNew; QVector<bool> imagesSettedNew;
foreach(int index, newOrder) foreach(int index, newOrder)
{ {
imageFilesNew << imageFiles.at(index); imageFilesNew << imageFiles.at(index);
imagesLoadedNew << imagesLoaded.at(index); imagesLoadedNew << imagesLoaded.at(index);
imagesSettedNew << imagesSetted.at(index); imagesSettedNew << imagesSetted.at(index);
} }
imageFiles = imageFilesNew; imageFiles = imageFilesNew;
imagesLoaded = imagesLoadedNew; imagesLoaded = imagesLoadedNew;
imagesSetted = imagesSettedNew; imagesSetted = imagesSettedNew;
worker->unlock(); worker->unlock();
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//ImageLoader //ImageLoader
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
static QImage loadImage(const QString& fileName) static QImage loadImage(const QString& fileName)
{ {
QImage image; QImage image;
bool result = image.load(fileName); bool result = image.load(fileName);
if(!result) if(!result)
return QImage(); return QImage();
return image; return image;
} }
ImageLoader::ImageLoader(): ImageLoader::ImageLoader():
QThread(), restart(false), working(false), idx(-1) QThread(), restart(false), working(false), idx(-1)
{ {
} }
ImageLoader::~ImageLoader() ImageLoader::~ImageLoader()
{ {
mutex.lock(); mutex.lock();
condition.wakeOne(); condition.wakeOne();
mutex.unlock(); mutex.unlock();
wait(); wait();
} }
bool ImageLoader::busy() const bool ImageLoader::busy() const
{ {
return isRunning() ? working : false; return isRunning() ? working : false;
} }
void ImageLoader::generate(int index, const QString& fileName, QSize size) void ImageLoader::generate(int index, const QString& fileName, QSize size)
{ {
mutex.lock(); mutex.lock();
this->idx = index; this->idx = index;
this->fileName = fileName; this->fileName = fileName;
this->size = size; this->size = size;
this->img = QImage(); this->img = QImage();
mutex.unlock(); mutex.unlock();
if (!isRunning()) if (!isRunning())
start(); start();
else else
{ {
// already running, wake up whenever ready // already running, wake up whenever ready
restart = true; restart = true;
condition.wakeOne(); condition.wakeOne();
} }
} }
void ImageLoader::lock() void ImageLoader::lock()
{ {
mutex.lock(); mutex.lock();
} }
void ImageLoader::unlock() void ImageLoader::unlock()
{ {
mutex.unlock(); mutex.unlock();
} }
void ImageLoader::run() void ImageLoader::run()
{ {
for(;;) for(;;)
{ {
// copy necessary data // copy necessary data
mutex.lock(); mutex.lock();
this->working = true; this->working = true;
QString fileName = this->fileName; QString fileName = this->fileName;
mutex.unlock(); mutex.unlock();
QImage image = loadImage(fileName); QImage image = loadImage(fileName);
// let everyone knows it is ready // let everyone knows it is ready
mutex.lock(); mutex.lock();
this->working = false; this->working = false;
this->img = image; this->img = image;
mutex.unlock(); mutex.unlock();
// put to sleep // put to sleep
mutex.lock(); mutex.lock();
if (!this->restart) if (!this->restart)
condition.wait(&mutex); condition.wait(&mutex);
restart = false; restart = false;
mutex.unlock(); mutex.unlock();
} }
} }
QImage ImageLoader::result() QImage ImageLoader::result()
{ {
return img; return img;
} }

View File

@ -1,78 +1,78 @@
#ifndef __COMICFLOW_H #ifndef __COMICFLOW_H
#define __COMICFLOW_H #define __COMICFLOW_H
#include "yacreader_flow.h" #include "yacreader_flow.h"
#include <QtCore> #include <QtCore>
#include <QObject> #include <QObject>
#include <QThread> #include <QThread>
#include <QImage> #include <QImage>
#include <QMutex> #include <QMutex>
#include <QWaitCondition> #include <QWaitCondition>
#include <QString> #include <QString>
#include <QWheelEvent> #include <QWheelEvent>
class ImageLoader; class ImageLoader;
class ComicFlow : public YACReaderFlow class ComicFlow : public YACReaderFlow
{ {
Q_OBJECT Q_OBJECT
public: public:
ComicFlow(QWidget* parent = 0,FlowType flowType = CoverFlowLike); ComicFlow(QWidget* parent = 0,FlowType flowType = CoverFlowLike);
virtual ~ComicFlow(); virtual ~ComicFlow();
void setImagePaths(const QStringList& paths); void setImagePaths(const QStringList& paths);
//bool eventFilter(QObject *target, QEvent *event); //bool eventFilter(QObject *target, QEvent *event);
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
void removeSlide(int cover); void removeSlide(int cover);
void resortCovers(QList<int> newOrder); void resortCovers(QList<int> newOrder);
private slots: private slots:
void preload(); void preload();
void updateImageData(); void updateImageData();
private: private:
//QString imagePath; //QString imagePath;
QStringList imageFiles; QStringList imageFiles;
QVector<bool> imagesLoaded; QVector<bool> imagesLoaded;
QVector<bool> imagesSetted; QVector<bool> imagesSetted;
int numImagesLoaded; int numImagesLoaded;
QTimer* updateTimer; QTimer* updateTimer;
ImageLoader* worker; ImageLoader* worker;
virtual void wheelEvent(QWheelEvent * event); virtual void wheelEvent(QWheelEvent * event);
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Source code of ImageLoader class was modified from http://code.google.com/p/photoflow/ // Source code of ImageLoader class was modified from http://code.google.com/p/photoflow/
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
class ImageLoader : public QThread class ImageLoader : public QThread
{ {
public: public:
ImageLoader(); ImageLoader();
~ImageLoader(); ~ImageLoader();
// returns FALSE if worker is still busy and can't take the task // returns FALSE if worker is still busy and can't take the task
bool busy() const; bool busy() const;
void generate(int index, const QString& fileName, QSize size); void generate(int index, const QString& fileName, QSize size);
void reset(){idx = -1;}; void reset(){idx = -1;};
int index() const { return idx; }; int index() const { return idx; };
void lock(); void lock();
void unlock(); void unlock();
QImage result(); QImage result();
protected: protected:
void run(); void run();
private: private:
QMutex mutex; QMutex mutex;
QWaitCondition condition; QWaitCondition condition;
bool restart; bool restart;
bool working; bool working;
int idx; int idx;
QString fileName; QString fileName;
QSize size; QSize size;
QImage img; QImage img;
}; };
#endif #endif

View File

@ -1,355 +1,355 @@
#include "comic_flow_widget.h" #include "comic_flow_widget.h"
#include <QVBoxLayout> #include <QVBoxLayout>
ComicFlowWidget::ComicFlowWidget(QWidget * parent) ComicFlowWidget::ComicFlowWidget(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
} }
ComicFlowWidgetSW::ComicFlowWidgetSW(QWidget * parent) ComicFlowWidgetSW::ComicFlowWidgetSW(QWidget * parent)
:ComicFlowWidget(parent) :ComicFlowWidget(parent)
{ {
flow = new ComicFlow(parent); flow = new ComicFlow(parent);
connect(flow,SIGNAL(centerIndexChanged(int)),this,SIGNAL(centerIndexChanged(int))); connect(flow,SIGNAL(centerIndexChanged(int)),this,SIGNAL(centerIndexChanged(int)));
connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(selected(unsigned int))); connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(selected(unsigned int)));
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
l->addWidget(flow); l->addWidget(flow);
setLayout(l); setLayout(l);
//TODO eleminar "padding" //TODO eleminar "padding"
QPalette Pal(palette()); QPalette Pal(palette());
// set black background // set black background
Pal.setColor(QPalette::Background, Qt::black); Pal.setColor(QPalette::Background, Qt::black);
setAutoFillBackground(true); setAutoFillBackground(true);
setPalette(Pal); setPalette(Pal);
//config //config
QMatrix m; QMatrix m;
m.rotate(-90); m.rotate(-90);
m.scale(-1,1); m.scale(-1,1);
QImage image(":/images/setRead.png"); QImage image(":/images/setRead.png");
QImage imageTransformed = image.transformed(m,Qt::SmoothTransformation); QImage imageTransformed = image.transformed(m,Qt::SmoothTransformation);
setMarkImage(imageTransformed); setMarkImage(imageTransformed);
} }
QSize ComicFlowWidgetSW::minimumSizeHint() const QSize ComicFlowWidgetSW::minimumSizeHint() const
{ {
return flow->minimumSizeHint(); return flow->minimumSizeHint();
} }
QSize ComicFlowWidgetSW::sizeHint() const QSize ComicFlowWidgetSW::sizeHint() const
{ {
return flow->sizeHint(); return flow->sizeHint();
} }
void ComicFlowWidgetSW::setShowMarks(bool value) void ComicFlowWidgetSW::setShowMarks(bool value)
{ {
flow->setShowMarks(value); flow->setShowMarks(value);
} }
void ComicFlowWidgetSW::setMarks(QVector<YACReaderComicReadStatus> marks) void ComicFlowWidgetSW::setMarks(QVector<YACReaderComicReadStatus> marks)
{ {
flow->setMarks(marks); flow->setMarks(marks);
} }
void ComicFlowWidgetSW::setMarkImage(QImage & image) void ComicFlowWidgetSW::setMarkImage(QImage & image)
{ {
flow->setMarkImage(image); flow->setMarkImage(image);
} }
void ComicFlowWidgetSW::markSlide(int index, YACReaderComicReadStatus status) void ComicFlowWidgetSW::markSlide(int index, YACReaderComicReadStatus status)
{ {
flow->markSlide(index,status); flow->markSlide(index,status);
} }
void ComicFlowWidgetSW::unmarkSlide(int index) void ComicFlowWidgetSW::unmarkSlide(int index)
{ {
flow->unmarkSlide(index); flow->unmarkSlide(index);
} }
void ComicFlowWidgetSW::setSlideSize(QSize size) void ComicFlowWidgetSW::setSlideSize(QSize size)
{ {
flow->setSlideSize(size); flow->setSlideSize(size);
} }
void ComicFlowWidgetSW::clear() void ComicFlowWidgetSW::clear()
{ {
flow->clear(); flow->clear();
} }
void ComicFlowWidgetSW::setImagePaths(QStringList paths) void ComicFlowWidgetSW::setImagePaths(QStringList paths)
{ {
flow->setImagePaths(paths); flow->setImagePaths(paths);
} }
void ComicFlowWidgetSW::setCenterIndex(int index) void ComicFlowWidgetSW::setCenterIndex(int index)
{ {
flow->setCenterIndex(index); flow->setCenterIndex(index);
} }
void ComicFlowWidgetSW::showSlide(int index) void ComicFlowWidgetSW::showSlide(int index)
{ {
flow->showSlide(index); flow->showSlide(index);
} }
int ComicFlowWidgetSW::centerIndex() int ComicFlowWidgetSW::centerIndex()
{ {
return flow->centerIndex(); return flow->centerIndex();
} }
void ComicFlowWidgetSW::updateMarks() void ComicFlowWidgetSW::updateMarks()
{ {
flow->updateMarks(); flow->updateMarks();
} }
void ComicFlowWidgetSW::setFlowType(FlowType flowType) void ComicFlowWidgetSW::setFlowType(FlowType flowType)
{ {
flow->setFlowType(flowType); flow->setFlowType(flowType);
} }
void ComicFlowWidgetSW::render() void ComicFlowWidgetSW::render()
{ {
flow->render(); flow->render();
} }
void ComicFlowWidgetSW::keyPressEvent(QKeyEvent* event) void ComicFlowWidgetSW::keyPressEvent(QKeyEvent* event)
{ {
flow->keyPressEvent(event); flow->keyPressEvent(event);
} }
void ComicFlowWidgetSW::paintEvent(QPaintEvent *event) void ComicFlowWidgetSW::paintEvent(QPaintEvent *event)
{ {
flow->paintEvent(event); flow->paintEvent(event);
} }
void ComicFlowWidgetSW::mousePressEvent(QMouseEvent* event) void ComicFlowWidgetSW::mousePressEvent(QMouseEvent* event)
{ {
flow->mousePressEvent(event); flow->mousePressEvent(event);
} }
void ComicFlowWidgetSW::resizeEvent(QResizeEvent* event) void ComicFlowWidgetSW::resizeEvent(QResizeEvent* event)
{ {
flow->resizeEvent(event); flow->resizeEvent(event);
} }
void ComicFlowWidgetSW::mouseDoubleClickEvent(QMouseEvent* event) void ComicFlowWidgetSW::mouseDoubleClickEvent(QMouseEvent* event)
{ {
flow->mouseDoubleClickEvent(event); flow->mouseDoubleClickEvent(event);
} }
void ComicFlowWidgetSW::updateConfig(QSettings * settings) void ComicFlowWidgetSW::updateConfig(QSettings * settings)
{ {
switch (settings->value(FLOW_TYPE_SW).toInt()) switch (settings->value(FLOW_TYPE_SW).toInt())
{ {
case CoverFlowLike: case CoverFlowLike:
flow->setFlowType(CoverFlowLike); flow->setFlowType(CoverFlowLike);
return; return;
case Strip: case Strip:
flow->setFlowType(Strip); flow->setFlowType(Strip);
return; return;
case StripOverlapped: case StripOverlapped:
flow->setFlowType(StripOverlapped); flow->setFlowType(StripOverlapped);
return; return;
} }
} }
void ComicFlowWidgetSW::remove(int cover) void ComicFlowWidgetSW::remove(int cover)
{ {
flow->removeSlide(cover); flow->removeSlide(cover);
} }
void ComicFlowWidgetSW::resortCovers(QList<int> newOrder) void ComicFlowWidgetSW::resortCovers(QList<int> newOrder)
{ {
flow->resortCovers(newOrder); flow->resortCovers(newOrder);
} }
#ifndef NO_OPENGL #ifndef NO_OPENGL
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
///OpenGL ComicFlow ///OpenGL ComicFlow
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
ComicFlowWidgetGL::ComicFlowWidgetGL(QWidget * parent) ComicFlowWidgetGL::ComicFlowWidgetGL(QWidget * parent)
:ComicFlowWidget(parent) :ComicFlowWidget(parent)
{ {
flow = new YACReaderComicFlowGL(parent); flow = new YACReaderComicFlowGL(parent);
connect(flow,SIGNAL(centerIndexChanged(int)),this,SIGNAL(centerIndexChanged(int))); connect(flow,SIGNAL(centerIndexChanged(int)),this,SIGNAL(centerIndexChanged(int)));
connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(selected(unsigned int))); connect(flow,SIGNAL(selected(unsigned int)),this,SIGNAL(selected(unsigned int)));
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
l->addWidget(flow); l->addWidget(flow);
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
//TODO eleminar "padding" //TODO eleminar "padding"
QPalette Pal(palette()); QPalette Pal(palette());
// set black background // set black background
Pal.setColor(QPalette::Background, Qt::black); Pal.setColor(QPalette::Background, Qt::black);
setAutoFillBackground(true); setAutoFillBackground(true);
setPalette(Pal); setPalette(Pal);
} }
QSize ComicFlowWidgetGL::minimumSizeHint() const QSize ComicFlowWidgetGL::minimumSizeHint() const
{ {
return flow->minimumSizeHint(); return flow->minimumSizeHint();
} }
QSize ComicFlowWidgetGL::sizeHint() const QSize ComicFlowWidgetGL::sizeHint() const
{ {
return flow->sizeHint(); return flow->sizeHint();
} }
void ComicFlowWidgetGL::setShowMarks(bool value) void ComicFlowWidgetGL::setShowMarks(bool value)
{ {
flow->setShowMarks(value); flow->setShowMarks(value);
} }
void ComicFlowWidgetGL::setMarks(QVector<YACReaderComicReadStatus> marks) void ComicFlowWidgetGL::setMarks(QVector<YACReaderComicReadStatus> marks)
{ {
flow->setMarks(marks); flow->setMarks(marks);
} }
void ComicFlowWidgetGL::setMarkImage(QImage & image) void ComicFlowWidgetGL::setMarkImage(QImage & image)
{ {
flow->setMarkImage(image); flow->setMarkImage(image);
} }
void ComicFlowWidgetGL::markSlide(int index, YACReaderComicReadStatus status) void ComicFlowWidgetGL::markSlide(int index, YACReaderComicReadStatus status)
{ {
flow->markSlide(index,status); flow->markSlide(index,status);
} }
void ComicFlowWidgetGL::unmarkSlide(int index) void ComicFlowWidgetGL::unmarkSlide(int index)
{ {
flow->unmarkSlide(index); flow->unmarkSlide(index);
} }
void ComicFlowWidgetGL::setSlideSize(QSize size) void ComicFlowWidgetGL::setSlideSize(QSize size)
{ {
flow->setSlideSize(size); flow->setSlideSize(size);
} }
void ComicFlowWidgetGL::clear() void ComicFlowWidgetGL::clear()
{ {
flow->clear(); flow->clear();
} }
void ComicFlowWidgetGL::setImagePaths(QStringList paths) void ComicFlowWidgetGL::setImagePaths(QStringList paths)
{ {
flow->setImagePaths(paths); flow->setImagePaths(paths);
} }
void ComicFlowWidgetGL::setCenterIndex(int index) void ComicFlowWidgetGL::setCenterIndex(int index)
{ {
flow->setCenterIndex(index); flow->setCenterIndex(index);
} }
void ComicFlowWidgetGL::showSlide(int index) void ComicFlowWidgetGL::showSlide(int index)
{ {
flow->showSlide(index); flow->showSlide(index);
} }
int ComicFlowWidgetGL::centerIndex() int ComicFlowWidgetGL::centerIndex()
{ {
return flow->centerIndex(); return flow->centerIndex();
} }
void ComicFlowWidgetGL::updateMarks() void ComicFlowWidgetGL::updateMarks()
{ {
flow->updateMarks(); flow->updateMarks();
} }
void ComicFlowWidgetGL::setFlowType(FlowType flowType) void ComicFlowWidgetGL::setFlowType(FlowType flowType)
{ {
if(flowType == CoverFlowLike) if(flowType == CoverFlowLike)
flow->setPreset(presetYACReaderFlowClassicConfig); flow->setPreset(presetYACReaderFlowClassicConfig);
else if(flowType == Strip) else if(flowType == Strip)
flow->setPreset(presetYACReaderFlowStripeConfig); flow->setPreset(presetYACReaderFlowStripeConfig);
else if(flowType == StripOverlapped) else if(flowType == StripOverlapped)
flow->setPreset(presetYACReaderFlowOverlappedStripeConfig); flow->setPreset(presetYACReaderFlowOverlappedStripeConfig);
else else
flow->setPreset(defaultYACReaderFlowConfig); flow->setPreset(defaultYACReaderFlowConfig);
} }
void ComicFlowWidgetGL::render() void ComicFlowWidgetGL::render()
{ {
flow->render(); flow->render();
} }
void ComicFlowWidgetGL::keyPressEvent(QKeyEvent* event) void ComicFlowWidgetGL::keyPressEvent(QKeyEvent* event)
{ {
flow->keyPressEvent(event); flow->keyPressEvent(event);
} }
void ComicFlowWidgetGL::paintEvent(QPaintEvent *event) void ComicFlowWidgetGL::paintEvent(QPaintEvent *event)
{ {
//flow->paintEvent(event); //flow->paintEvent(event);
ComicFlowWidget::paintEvent(event); ComicFlowWidget::paintEvent(event);
} }
void ComicFlowWidgetGL::mousePressEvent(QMouseEvent* event) void ComicFlowWidgetGL::mousePressEvent(QMouseEvent* event)
{ {
flow->mousePressEvent(event); flow->mousePressEvent(event);
} }
void ComicFlowWidgetGL::resizeEvent(QResizeEvent* event) void ComicFlowWidgetGL::resizeEvent(QResizeEvent* event)
{ {
flow->resizeGL(event->size().width(),event->size().height()); flow->resizeGL(event->size().width(),event->size().height());
} }
void ComicFlowWidgetGL::mouseDoubleClickEvent(QMouseEvent* event) void ComicFlowWidgetGL::mouseDoubleClickEvent(QMouseEvent* event)
{ {
flow->mouseDoubleClickEvent(event); flow->mouseDoubleClickEvent(event);
} }
void ComicFlowWidgetGL::updateConfig(QSettings * settings) void ComicFlowWidgetGL::updateConfig(QSettings * settings)
{ {
Performance performance = medium; Performance performance = medium;
switch (settings->value(PERFORMANCE).toInt()) switch (settings->value(PERFORMANCE).toInt())
{ {
case 0: case 0:
performance = low; performance = low;
break; break;
case 1: case 1:
performance = medium; performance = medium;
break; break;
case 2: case 2:
performance = high; performance = high;
break; break;
case 3: case 3:
performance = ultraHigh; performance = ultraHigh;
break; break;
} }
flow->setPerformance(performance); flow->setPerformance(performance);
if(!settings->contains(V_SYNC)) if(!settings->contains(V_SYNC))
flow->useVSync(false); flow->useVSync(false);
else else
flow->useVSync(settings->value(V_SYNC).toBool()); flow->useVSync(settings->value(V_SYNC).toBool());
switch (settings->value(FLOW_TYPE_GL).toInt()) switch (settings->value(FLOW_TYPE_GL).toInt())
{ {
case 0: case 0:
flow->setPreset(presetYACReaderFlowClassicConfig); flow->setPreset(presetYACReaderFlowClassicConfig);
return; return;
case 1: case 1:
flow->setPreset(presetYACReaderFlowStripeConfig); flow->setPreset(presetYACReaderFlowStripeConfig);
return; return;
case 2: case 2:
flow->setPreset(presetYACReaderFlowOverlappedStripeConfig); flow->setPreset(presetYACReaderFlowOverlappedStripeConfig);
return; return;
case 3: case 3:
flow->setPreset(defaultYACReaderFlowConfig); flow->setPreset(defaultYACReaderFlowConfig);
return; return;
case 4: case 4:
flow->setPreset(pressetYACReaderFlowDownConfig); flow->setPreset(pressetYACReaderFlowDownConfig);
return; return;
} }
//custom config //custom config
flow->setCF_RX(settings->value(X_ROTATION).toInt()); flow->setCF_RX(settings->value(X_ROTATION).toInt());
flow->setCF_Y(settings->value(Y_POSITION).toInt()); flow->setCF_Y(settings->value(Y_POSITION).toInt());
flow->setX_Distance(settings->value(COVER_DISTANCE).toInt()); flow->setX_Distance(settings->value(COVER_DISTANCE).toInt());
flow->setCenter_Distance(settings->value(CENTRAL_DISTANCE).toInt()); flow->setCenter_Distance(settings->value(CENTRAL_DISTANCE).toInt());
flow->setCF_Z(settings->value(ZOOM_LEVEL).toInt()); flow->setCF_Z(settings->value(ZOOM_LEVEL).toInt());
flow->setY_Distance(settings->value(Y_COVER_OFFSET).toInt()); flow->setY_Distance(settings->value(Y_COVER_OFFSET).toInt());
flow->setZ_Distance(settings->value(Z_COVER_OFFSET).toInt()); flow->setZ_Distance(settings->value(Z_COVER_OFFSET).toInt());
flow->setRotation(settings->value(COVER_ROTATION).toInt()); flow->setRotation(settings->value(COVER_ROTATION).toInt());
flow->setFadeOutDist(settings->value(FADE_OUT_DIST).toInt()); flow->setFadeOutDist(settings->value(FADE_OUT_DIST).toInt());
flow->setLightStrenght(settings->value(LIGHT_STRENGTH).toInt()); flow->setLightStrenght(settings->value(LIGHT_STRENGTH).toInt());
flow->setMaxAngle(settings->value(MAX_ANGLE).toInt()); flow->setMaxAngle(settings->value(MAX_ANGLE).toInt());
/* flow->setVisibility(settings->value("visibilityDistance").toInt()); /* flow->setVisibility(settings->value("visibilityDistance").toInt());
flow->setLightStrenght(settings->value("lightStrength").toInt())*/; flow->setLightStrenght(settings->value("lightStrength").toInt())*/;
} }
void ComicFlowWidgetGL::remove(int cover) void ComicFlowWidgetGL::remove(int cover)
{ {
flow->remove(cover); flow->remove(cover);
} }
void ComicFlowWidgetGL::resortCovers(QList<int> newOrder) void ComicFlowWidgetGL::resortCovers(QList<int> newOrder)
{ {
flow->resortCovers(newOrder); flow->resortCovers(newOrder);
} }
#endif #endif
//void ComicFlowWidgetGL::setCF_RX(int value){ flow->setCF_RX(value);} //void ComicFlowWidgetGL::setCF_RX(int value){ flow->setCF_RX(value);}
//void ComicFlowWidgetGL::setCF_RY(int value){ flow->setCF_RY(value);} //void ComicFlowWidgetGL::setCF_RY(int value){ flow->setCF_RY(value);}
//void ComicFlowWidgetGL::setCF_RZ(int value){ flow->setCF_RZ(value);} //void ComicFlowWidgetGL::setCF_RZ(int value){ flow->setCF_RZ(value);}
//void ComicFlowWidgetGL::setZoom(int zoom){ flow->setZoom(zoom);} //void ComicFlowWidgetGL::setZoom(int zoom){ flow->setZoom(zoom);}
//void ComicFlowWidgetGL::setRotation(int angle){ flow->setRotation(angle);} //void ComicFlowWidgetGL::setRotation(int angle){ flow->setRotation(angle);}
//void ComicFlowWidgetGL::setX_Distance(int distance){ flow->setX_Distance(distance);} //void ComicFlowWidgetGL::setX_Distance(int distance){ flow->setX_Distance(distance);}
//void ComicFlowWidgetGL::setCenter_Distance(int distance){ flow->setCenter_Distance(distance);} //void ComicFlowWidgetGL::setCenter_Distance(int distance){ flow->setCenter_Distance(distance);}
//void ComicFlowWidgetGL::setZ_Distance(int distance){ flow->setZ_Distance(distance);} //void ComicFlowWidgetGL::setZ_Distance(int distance){ flow->setZ_Distance(distance);}
//void ComicFlowWidgetGL::setCF_Y(int value){ flow->setCF_Y(value);} //void ComicFlowWidgetGL::setCF_Y(int value){ flow->setCF_Y(value);}
//void ComicFlowWidgetGL::setY_Distance(int value){ flow->setY_Distance(value);} //void ComicFlowWidgetGL::setY_Distance(int value){ flow->setY_Distance(value);}
//void ComicFlowWidgetGL::setPreset(const Preset & p){ flow->setPreset(p);} //void ComicFlowWidgetGL::setPreset(const Preset & p){ flow->setPreset(p);}

View File

@ -1,133 +1,133 @@
#ifndef __COMIC_FLOW_WIDGET_H #ifndef __COMIC_FLOW_WIDGET_H
#define __COMIC_FLOW_WIDGET_H #define __COMIC_FLOW_WIDGET_H
#include <QWidget> #include <QWidget>
#include "pictureflow.h" #include "pictureflow.h"
#include "comic_flow.h" #include "comic_flow.h"
#ifndef NO_OPENGL #ifndef NO_OPENGL
#include "yacreader_flow_gl.h" #include "yacreader_flow_gl.h"
#endif #endif
class ComicFlowWidget : public QWidget class ComicFlowWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
ComicFlowWidget(QWidget * paret = 0); ComicFlowWidget(QWidget * paret = 0);
public slots: public slots:
virtual void setShowMarks(bool value) = 0; virtual void setShowMarks(bool value) = 0;
virtual void setMarks(QVector<YACReaderComicReadStatus> marks) = 0; virtual void setMarks(QVector<YACReaderComicReadStatus> marks) = 0;
virtual void setMarkImage(QImage & image) = 0; virtual void setMarkImage(QImage & image) = 0;
virtual void markSlide(int index, YACReaderComicReadStatus status) = 0; virtual void markSlide(int index, YACReaderComicReadStatus status) = 0;
virtual void unmarkSlide(int index) = 0; virtual void unmarkSlide(int index) = 0;
virtual void setSlideSize(QSize size) = 0; virtual void setSlideSize(QSize size) = 0;
virtual void clear() = 0; virtual void clear() = 0;
virtual void setImagePaths(QStringList paths) = 0; virtual void setImagePaths(QStringList paths) = 0;
virtual void setCenterIndex(int index) = 0; virtual void setCenterIndex(int index) = 0;
virtual void showSlide(int index) = 0; virtual void showSlide(int index) = 0;
virtual int centerIndex() = 0; virtual int centerIndex() = 0;
virtual void updateMarks() = 0; virtual void updateMarks() = 0;
virtual void setFlowType(FlowType flowType) = 0; virtual void setFlowType(FlowType flowType) = 0;
virtual void render() = 0; virtual void render() = 0;
virtual void updateConfig(QSettings * settings) = 0; virtual void updateConfig(QSettings * settings) = 0;
virtual void remove(int cover) = 0; virtual void remove(int cover) = 0;
virtual void resortCovers(QList<int> newOrder) = 0; virtual void resortCovers(QList<int> newOrder) = 0;
signals: signals:
void centerIndexChanged(int); void centerIndexChanged(int);
void selected(unsigned int); void selected(unsigned int);
}; };
class ComicFlowWidgetSW : public ComicFlowWidget class ComicFlowWidgetSW : public ComicFlowWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
ComicFlow * flow; ComicFlow * flow;
public: public:
ComicFlowWidgetSW(QWidget * parent = 0); ComicFlowWidgetSW(QWidget * parent = 0);
void setShowMarks(bool value); void setShowMarks(bool value);
void setMarks(QVector<YACReaderComicReadStatus> marks); void setMarks(QVector<YACReaderComicReadStatus> marks);
void setMarkImage(QImage & image); void setMarkImage(QImage & image);
void markSlide(int index, YACReaderComicReadStatus status); void markSlide(int index, YACReaderComicReadStatus status);
void unmarkSlide(int index); void unmarkSlide(int index);
void setSlideSize(QSize size); void setSlideSize(QSize size);
void clear(); void clear();
void setImagePaths(QStringList paths); void setImagePaths(QStringList paths);
void setCenterIndex(int index); void setCenterIndex(int index);
void showSlide(int index); void showSlide(int index);
int centerIndex(); int centerIndex();
void updateMarks(); void updateMarks();
void setFlowType(FlowType flowType); void setFlowType(FlowType flowType);
void render(); void render();
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void remove(int cover); void remove(int cover);
void resortCovers(QList<int> newOrder); void resortCovers(QList<int> newOrder);
protected: protected:
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event);
void resizeEvent(QResizeEvent* event); void resizeEvent(QResizeEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event); void mouseDoubleClickEvent(QMouseEvent* event);
QSize minimumSizeHint() const; QSize minimumSizeHint() const;
QSize sizeHint() const; QSize sizeHint() const;
QSize slideSizeW; QSize slideSizeW;
QSize slideSizeF; QSize slideSizeF;
}; };
#ifndef NO_OPENGL #ifndef NO_OPENGL
class ComicFlowWidgetGL : public ComicFlowWidget class ComicFlowWidgetGL : public ComicFlowWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
YACReaderComicFlowGL * flow; YACReaderComicFlowGL * flow;
public: public:
ComicFlowWidgetGL(QWidget * parent = 0); ComicFlowWidgetGL(QWidget * parent = 0);
void setShowMarks(bool value); void setShowMarks(bool value);
void setMarks(QVector<YACReaderComicReadStatus> marks); void setMarks(QVector<YACReaderComicReadStatus> marks);
void setMarkImage(QImage & image); void setMarkImage(QImage & image);
void markSlide(int index, YACReaderComicReadStatus status); void markSlide(int index, YACReaderComicReadStatus status);
void unmarkSlide(int index); void unmarkSlide(int index);
void setSlideSize(QSize size); void setSlideSize(QSize size);
void clear(); void clear();
void setImagePaths(QStringList paths); void setImagePaths(QStringList paths);
void setCenterIndex(int index); void setCenterIndex(int index);
void showSlide(int index); void showSlide(int index);
int centerIndex(); int centerIndex();
void updateMarks(); void updateMarks();
void setFlowType(FlowType flowType); void setFlowType(FlowType flowType);
void render(); void render();
void updateConfig(QSettings * settings); void updateConfig(QSettings * settings);
void remove(int cover); void remove(int cover);
void resortCovers(QList<int> newOrder); void resortCovers(QList<int> newOrder);
//public slots: //public slots:
// void setCF_RX(int value); // void setCF_RX(int value);
// //the Y Rotation of the Coverflow // //the Y Rotation of the Coverflow
// void setCF_RY(int value); // void setCF_RY(int value);
// //the Z Rotation of the Coverflow // //the Z Rotation of the Coverflow
// void setCF_RZ(int value); // void setCF_RZ(int value);
// //perspective // //perspective
// void setZoom(int zoom); // void setZoom(int zoom);
// void setRotation(int angle); // void setRotation(int angle);
// //sets the distance between the covers // //sets the distance between the covers
// void setX_Distance(int distance); // void setX_Distance(int distance);
// //sets the distance between the centered and the non centered covers // //sets the distance between the centered and the non centered covers
// void setCenter_Distance(int distance); // void setCenter_Distance(int distance);
// //sets the pushback amount // //sets the pushback amount
// void setZ_Distance(int distance); // void setZ_Distance(int distance);
// void setCF_Y(int value); // void setCF_Y(int value);
// void setY_Distance(int value); // void setY_Distance(int value);
// void setPreset(const Preset & p); // void setPreset(const Preset & p);
protected: protected:
void keyPressEvent(QKeyEvent* event); void keyPressEvent(QKeyEvent* event);
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event);
void resizeEvent(QResizeEvent* event); void resizeEvent(QResizeEvent* event);
void mouseDoubleClickEvent(QMouseEvent* event); void mouseDoubleClickEvent(QMouseEvent* event);
QSize minimumSizeHint() const; QSize minimumSizeHint() const;
QSize sizeHint() const; QSize sizeHint() const;
}; };
#endif #endif
#endif #endif

View File

@ -1,68 +1,68 @@
#include "api_key_dialog.h" #include "api_key_dialog.h"
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QSettings> #include <QSettings>
#include "yacreader_global_gui.h" #include "yacreader_global_gui.h"
ApiKeyDialog::ApiKeyDialog(QWidget *parent) : ApiKeyDialog::ApiKeyDialog(QWidget *parent) :
QDialog(parent) QDialog(parent)
{ {
QVBoxLayout * layout = new QVBoxLayout; QVBoxLayout * layout = new QVBoxLayout;
QHBoxLayout * buttonsLayout = new QHBoxLayout; QHBoxLayout * buttonsLayout = new QHBoxLayout;
settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor
settings->beginGroup("ComicVine"); settings->beginGroup("ComicVine");
QLabel * info = new QLabel(tr("Before you can connect to Comic Vine, you need your own API key. Please, get one free <a href=\"http://www.comicvine.com/api/\">here</a>")); QLabel * info = new QLabel(tr("Before you can connect to Comic Vine, you need your own API key. Please, get one free <a href=\"http://www.comicvine.com/api/\">here</a>"));
info->setWordWrap(true); info->setWordWrap(true);
info->setOpenExternalLinks(true); info->setOpenExternalLinks(true);
edit = new QLineEdit(); edit = new QLineEdit();
edit->setPlaceholderText(tr("Paste here your Comic Vine API key")); edit->setPlaceholderText(tr("Paste here your Comic Vine API key"));
connect(edit,SIGNAL(textChanged(QString)),this,SLOT(enableAccept(QString))); connect(edit,SIGNAL(textChanged(QString)),this,SLOT(enableAccept(QString)));
acceptButton = new QPushButton(tr("Accept")); acceptButton = new QPushButton(tr("Accept"));
acceptButton->setDisabled(true); acceptButton->setDisabled(true);
connect(acceptButton,SIGNAL(clicked()),this,SLOT(saveApiKey())); connect(acceptButton,SIGNAL(clicked()),this,SLOT(saveApiKey()));
cancelButton = new QPushButton(tr("Cancel")); cancelButton = new QPushButton(tr("Cancel"));
connect(cancelButton,SIGNAL(clicked()),this,SLOT(reject())); connect(cancelButton,SIGNAL(clicked()),this,SLOT(reject()));
layout->addWidget(info); layout->addWidget(info);
layout->addWidget(edit); layout->addWidget(edit);
layout->addStretch(); layout->addStretch();
buttonsLayout->addStretch(); buttonsLayout->addStretch();
buttonsLayout->addWidget(acceptButton); buttonsLayout->addWidget(acceptButton);
buttonsLayout->addWidget(cancelButton); buttonsLayout->addWidget(cancelButton);
layout->addLayout(buttonsLayout); layout->addLayout(buttonsLayout);
setLayout(layout); setLayout(layout);
resize(400,150); resize(400,150);
if(settings->contains(COMIC_VINE_API_KEY)) if(settings->contains(COMIC_VINE_API_KEY))
edit->setText(settings->value(COMIC_VINE_API_KEY).toString()); edit->setText(settings->value(COMIC_VINE_API_KEY).toString());
} }
ApiKeyDialog::~ApiKeyDialog() ApiKeyDialog::~ApiKeyDialog()
{ {
delete settings; delete settings;
} }
void ApiKeyDialog::enableAccept(const QString &text) void ApiKeyDialog::enableAccept(const QString &text)
{ {
//TODO key validation //TODO key validation
acceptButton->setEnabled(!text.isEmpty()); acceptButton->setEnabled(!text.isEmpty());
} }
void ApiKeyDialog::saveApiKey() void ApiKeyDialog::saveApiKey()
{ {
settings->setValue(COMIC_VINE_API_KEY,edit->text().trimmed()); settings->setValue(COMIC_VINE_API_KEY,edit->text().trimmed());
accept(); accept();
} }

View File

@ -1,31 +1,31 @@
#ifndef API_KEY_DIALOG_H #ifndef API_KEY_DIALOG_H
#define API_KEY_DIALOG_H #define API_KEY_DIALOG_H
#include <QDialog> #include <QDialog>
class QPushButton; class QPushButton;
class QLineEdit; class QLineEdit;
class QSettings; class QSettings;
class ApiKeyDialog : public QDialog class ApiKeyDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ApiKeyDialog(QWidget *parent = 0); explicit ApiKeyDialog(QWidget *parent = 0);
~ApiKeyDialog(); ~ApiKeyDialog();
signals: signals:
public slots: public slots:
protected slots: protected slots:
void enableAccept(const QString & text); void enableAccept(const QString & text);
void saveApiKey(); void saveApiKey();
protected: protected:
QPushButton * acceptButton; QPushButton * acceptButton;
QPushButton * cancelButton; QPushButton * cancelButton;
QLineEdit * edit; QLineEdit * edit;
QSettings * settings; QSettings * settings;
}; };
#endif // API_KEY_DIALOG_H #endif // API_KEY_DIALOG_H

View File

@ -1,97 +1,97 @@
#include "comic_vine_all_volume_comics_retriever.h" #include "comic_vine_all_volume_comics_retriever.h"
#include "http_worker.h" #include "http_worker.h"
#include "response_parser.h" #include "response_parser.h"
#include <QtScript> #include <QtScript>
ComicVineAllVolumeComicsRetriever::ComicVineAllVolumeComicsRetriever(const QString &volumeURLString, QObject *parent) ComicVineAllVolumeComicsRetriever::ComicVineAllVolumeComicsRetriever(const QString &volumeURLString, QObject *parent)
: QObject(parent), volumeURLString(volumeURLString) : QObject(parent), volumeURLString(volumeURLString)
{ {
} }
void ComicVineAllVolumeComicsRetriever::getAllVolumeComics() void ComicVineAllVolumeComicsRetriever::getAllVolumeComics()
{ {
getAllVolumeComics(0); getAllVolumeComics(0);
} }
void ComicVineAllVolumeComicsRetriever::getAllVolumeComics(int range) void ComicVineAllVolumeComicsRetriever::getAllVolumeComics(int range)
{ {
HttpWorker * search = new HttpWorker(volumeURLString.arg(range)); HttpWorker * search = new HttpWorker(volumeURLString.arg(range));
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(appendVolumeComicsInfo(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(appendVolumeComicsInfo(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut()));
connect(search,SIGNAL(timeout()),this,SIGNAL(finished())); connect(search,SIGNAL(timeout()),this,SIGNAL(finished()));
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
void ComicVineAllVolumeComicsRetriever::appendVolumeComicsInfo(const QByteArray &data) void ComicVineAllVolumeComicsRetriever::appendVolumeComicsInfo(const QByteArray &data)
{ {
QString json(data); QString json(data);
jsonResponses.append(data); jsonResponses.append(data);
ResponseParser rp; ResponseParser rp;
rp.loadJSONResponse(json); rp.loadJSONResponse(json);
qint32 currentPage = rp.getCurrentPage(); qint32 currentPage = rp.getCurrentPage();
qint32 totalPages = rp.getTotalPages(); qint32 totalPages = rp.getTotalPages();
bool isLastResponse = currentPage == totalPages; bool isLastResponse = currentPage == totalPages;
if (!isLastResponse) { if (!isLastResponse) {
getAllVolumeComics(currentPage * 100); getAllVolumeComics(currentPage * 100);
} }
else else
{ {
emit allVolumeComicsInfo(consolidateJSON()); emit allVolumeComicsInfo(consolidateJSON());
emit finished(); emit finished();
} }
} }
QString ComicVineAllVolumeComicsRetriever::consolidateJSON() QString ComicVineAllVolumeComicsRetriever::consolidateJSON()
{ {
QJsonObject consolidatedJSON; QJsonObject consolidatedJSON;
QJsonArray comicsInfo; QJsonArray comicsInfo;
foreach (QByteArray json, jsonResponses) { foreach (QByteArray json, jsonResponses) {
QJsonDocument doc = QJsonDocument::fromJson(json); QJsonDocument doc = QJsonDocument::fromJson(json);
if(doc.isNull() || !doc.isObject() || doc.isEmpty()) if(doc.isNull() || !doc.isObject() || doc.isEmpty())
{ {
continue; continue;
} }
QJsonObject main = doc.object(); QJsonObject main = doc.object();
QJsonValue error = main["error"]; QJsonValue error = main["error"];
if (error.isUndefined() || error.toString() != "OK") if (error.isUndefined() || error.toString() != "OK")
{ {
continue; continue;
} }
else else
{ {
QJsonValue results = main["results"]; QJsonValue results = main["results"];
if (results.isUndefined() || !results.isArray()) if (results.isUndefined() || !results.isArray())
{ {
continue; continue;
} }
QJsonArray resultsArray = results.toArray(); QJsonArray resultsArray = results.toArray();
foreach (const QJsonValue & v, resultsArray) foreach (const QJsonValue & v, resultsArray)
comicsInfo.append(v); comicsInfo.append(v);
} }
} }
consolidatedJSON["error"] = "OK"; consolidatedJSON["error"] = "OK";
consolidatedJSON["status_code"] = 1; consolidatedJSON["status_code"] = 1;
consolidatedJSON["number_of_total_results"] = comicsInfo.size(); consolidatedJSON["number_of_total_results"] = comicsInfo.size();
consolidatedJSON["offset"] = 0; consolidatedJSON["offset"] = 0;
consolidatedJSON["results"] = comicsInfo; consolidatedJSON["results"] = comicsInfo;
QJsonDocument doc(consolidatedJSON); QJsonDocument doc(consolidatedJSON);
return doc.toJson(QJsonDocument::Compact); return doc.toJson(QJsonDocument::Compact);
} }

View File

@ -1,28 +1,28 @@
#ifndef COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H #ifndef COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H
#define COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H #define COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H
#include <QObject> #include <QObject>
class ComicVineAllVolumeComicsRetriever : public QObject class ComicVineAllVolumeComicsRetriever : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ComicVineAllVolumeComicsRetriever(const QString &volumeURLString, QObject *parent = 0); explicit ComicVineAllVolumeComicsRetriever(const QString &volumeURLString, QObject *parent = 0);
void getAllVolumeComics(); void getAllVolumeComics();
protected: protected:
void getAllVolumeComics(const int range); void getAllVolumeComics(const int range);
signals: signals:
void allVolumeComicsInfo(QString json); void allVolumeComicsInfo(QString json);
void finished(); void finished();
void timeOut(); void timeOut();
protected slots: protected slots:
void appendVolumeComicsInfo(const QByteArray &data); void appendVolumeComicsInfo(const QByteArray &data);
protected: protected:
QString volumeURLString; QString volumeURLString;
QList<QByteArray> jsonResponses; QList<QByteArray> jsonResponses;
QString consolidateJSON(); QString consolidateJSON();
}; };
#endif // COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H #endif // COMIC_VINE_ALL_VOLUME_COMICS_RETRIEVER_H

View File

@ -1,189 +1,189 @@
#include "comic_vine_client.h" #include "comic_vine_client.h"
#include "yacreader_global_gui.h" #include "yacreader_global_gui.h"
#include "comic_vine_all_volume_comics_retriever.h" #include "comic_vine_all_volume_comics_retriever.h"
//this is the API key used by YACReader to access Comic Vine //this is the API key used by YACReader to access Comic Vine
//please, do not use it in your own software, get one for free at Comic Vine //please, do not use it in your own software, get one for free at Comic Vine
static const QString CV_API_KEY = "%CV_API_KEY%"; //get from settings static const QString CV_API_KEY = "%CV_API_KEY%"; //get from settings
static const QString CV_API_KEY_DEFAULT = "46680bebb358f1de690a5a365e15d325f9649f91"; static const QString CV_API_KEY_DEFAULT = "46680bebb358f1de690a5a365e15d325f9649f91";
static const QString CV_WEB_ADDRESS = "%CV_WEB_ADDRESS%"; //get from settings static const QString CV_WEB_ADDRESS = "%CV_WEB_ADDRESS%"; //get from settings
//gets any volumen containing any comic matching 'query' //gets any volumen containing any comic matching 'query'
static const QString CV_SEARCH = CV_WEB_ADDRESS + "/search/?api_key=" + CV_API_KEY + static const QString CV_SEARCH = CV_WEB_ADDRESS + "/search/?api_key=" + CV_API_KEY +
"&format=json&limit=100&resources=volume" "&format=json&limit=100&resources=volume"
"&field_list=name,start_year,publisher,id,image,count_of_issues,deck" "&field_list=name,start_year,publisher,id,image,count_of_issues,deck"
"&sort=name:asc" "&sort=name:asc"
"&query=%1&page=%2"; "&query=%1&page=%2";
//http://www.comicvine.com/api/search/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json&limit=100&resources=volume&field_list=name,start_year,publisher,id,image,count_of_issues,deck&query=superman //http://www.comicvine.com/api/search/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json&limit=100&resources=volume&field_list=name,start_year,publisher,id,image,count_of_issues,deck&query=superman
//gets the detail for a volume %1 //gets the detail for a volume %1
static const QString CV_SERIES_DETAIL = CV_WEB_ADDRESS + "/volume/4050-%1/?api_key=" + CV_API_KEY + static const QString CV_SERIES_DETAIL = CV_WEB_ADDRESS + "/volume/4050-%1/?api_key=" + CV_API_KEY +
"&format=json&field_list=name,start_year,publisher,image,count_of_issues,id,description"; "&format=json&field_list=name,start_year,publisher,image,count_of_issues,id,description";
//gets info for comics in a volume id %1 //gets info for comics in a volume id %1
static const QString CV_COMICS_INFO = CV_WEB_ADDRESS + "/issues/?api_key=" + CV_API_KEY + static const QString CV_COMICS_INFO = CV_WEB_ADDRESS + "/issues/?api_key=" + CV_API_KEY +
"&limit=1000&format=json&field_list=name,issue_number,id,image&filter=volume:%1" "&limit=1000&format=json&field_list=name,issue_number,id,image&filter=volume:%1"
"&sort=cover_date:asc" //sorting by cover_date, because comic vine doesn't use natural sorting (issue_number -> 1 10 11 ... 100 2 20 21....) "&sort=cover_date:asc" //sorting by cover_date, because comic vine doesn't use natural sorting (issue_number -> 1 10 11 ... 100 2 20 21....)
"&offset=%2"; "&offset=%2";
//"http://www.comicvine.com/api/issues/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json&field_list=name,issue_number,id,image&filter=volume:%1&page=%2 //"http://www.comicvine.com/api/issues/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json&field_list=name,issue_number,id,image&filter=volume:%1&page=%2
//gets id for comic number %2 in a volume id %1 //gets id for comic number %2 in a volume id %1
static const QString CV_COMIC_ID = CV_WEB_ADDRESS + "/issues/?api_key=" + CV_API_KEY + static const QString CV_COMIC_ID = CV_WEB_ADDRESS + "/issues/?api_key=" + CV_API_KEY +
"&format=json&field_list=name,issue_number,id,image" "&format=json&field_list=name,issue_number,id,image"
"&filter=volume:%1,issue_number:%2"; "&filter=volume:%1,issue_number:%2";
//gets comic detail //gets comic detail
static const QString CV_COMIC_DETAIL = CV_WEB_ADDRESS + "/issue/4000-%1/?api_key=" + CV_API_KEY + "&format=json"; static const QString CV_COMIC_DETAIL = CV_WEB_ADDRESS + "/issue/4000-%1/?api_key=" + CV_API_KEY + "&format=json";
//http://www.comicvine.com/api/issue/4000-%1/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json //http://www.comicvine.com/api/issue/4000-%1/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&format=json
//gets comic cover URL //gets comic cover URL
static const QString CV_COVER_URL = CV_WEB_ADDRESS + "/issue/4000-%1/?api_key=" + CV_API_KEY + "&format=json&field_list=image"; static const QString CV_COVER_URL = CV_WEB_ADDRESS + "/issue/4000-%1/?api_key=" + CV_API_KEY + "&format=json&field_list=image";
//gets comics matching name %1 and number %2 //gets comics matching name %1 and number %2
//http://comicvine.com/api/issues/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&limit=20&filter=name:super,issue_number:15 //http://comicvine.com/api/issues/?api_key=46680bebb358f1de690a5a365e15d325f9649f91&limit=20&filter=name:super,issue_number:15
ComicVineClient::ComicVineClient(QObject *parent) : ComicVineClient::ComicVineClient(QObject *parent) :
QObject(parent) QObject(parent)
{ {
settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor settings = new QSettings(YACReader::getSettingsPath()+"/YACReaderLibrary.ini",QSettings::IniFormat); //TODO unificar la creación del fichero de config con el servidor
settings->beginGroup("ComicVine"); settings->beginGroup("ComicVine");
baseURL = settings->value(COMIC_VINE_BASE_URL, "https://comicvine.gamespot.com/api").toString(); baseURL = settings->value(COMIC_VINE_BASE_URL, "https://comicvine.gamespot.com/api").toString();
} }
ComicVineClient::~ComicVineClient() ComicVineClient::~ComicVineClient()
{ {
delete settings; delete settings;
} }
//CV_SEARCH //CV_SEARCH
void ComicVineClient::search(const QString & query, int page) void ComicVineClient::search(const QString & query, int page)
{ {
HttpWorker * search = new HttpWorker(QString(CV_SEARCH).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(query).arg(page)); HttpWorker * search = new HttpWorker(QString(CV_SEARCH).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(query).arg(page));
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessVolumesSearchData(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessVolumesSearchData(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut()));
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
//CV_SEARCH result //CV_SEARCH result
void ComicVineClient::proccessVolumesSearchData(const QByteArray & data) void ComicVineClient::proccessVolumesSearchData(const QByteArray & data)
{ {
QString json(data); QString json(data);
emit searchResult(json); emit searchResult(json);
emit finished(); emit finished();
} }
void ComicVineClient::proccessSeriesDetailData(const QByteArray &data) void ComicVineClient::proccessSeriesDetailData(const QByteArray &data)
{ {
QString json(data); QString json(data);
emit seriesDetail(json); emit seriesDetail(json);
emit finished(); emit finished();
} }
void ComicVineClient::processVolumeComicsInfo(const QByteArray &data) void ComicVineClient::processVolumeComicsInfo(const QByteArray &data)
{ {
QString json(data); QString json(data);
emit volumeComicsInfo(json); emit volumeComicsInfo(json);
emit finished(); emit finished();
} }
void ComicVineClient::proccessComicDetailData(const QByteArray &data) void ComicVineClient::proccessComicDetailData(const QByteArray &data)
{ {
QString json(data); QString json(data);
emit comicDetail(json); emit comicDetail(json);
emit finished(); emit finished();
} }
//CV_SERIES_DETAIL //CV_SERIES_DETAIL
void ComicVineClient::getSeriesDetail(const QString & id) void ComicVineClient::getSeriesDetail(const QString & id)
{ {
HttpWorker * search = new HttpWorker(QString(CV_SERIES_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id)); HttpWorker * search = new HttpWorker(QString(CV_SERIES_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id));
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessSeriesDetailData(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessSeriesDetailData(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut()));
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
void ComicVineClient::getSeriesCover(const QString & url) void ComicVineClient::getSeriesCover(const QString & url)
{ {
HttpWorker * search = new HttpWorker(url); HttpWorker * search = new HttpWorker(url);
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SIGNAL(seriesCover(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SIGNAL(seriesCover(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
//CV_COMIC_IDS //CV_COMIC_IDS
void ComicVineClient::getVolumeComicsInfo(const QString & idVolume, int page) void ComicVineClient::getVolumeComicsInfo(const QString & idVolume, int page)
{ {
HttpWorker * search = new HttpWorker(QString(CV_COMICS_INFO).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(idVolume).arg((page-1)*100)); //page doesn't work for search, using offset instead HttpWorker * search = new HttpWorker(QString(CV_COMICS_INFO).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(idVolume).arg((page-1)*100)); //page doesn't work for search, using offset instead
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(processVolumeComicsInfo(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(processVolumeComicsInfo(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
void ComicVineClient::getAllVolumeComicsInfo(const QString &idVolume) void ComicVineClient::getAllVolumeComicsInfo(const QString &idVolume)
{ {
QString url = QString(CV_COMICS_INFO).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(idVolume); QString url = QString(CV_COMICS_INFO).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(idVolume);
ComicVineAllVolumeComicsRetriever * comicsRetriever = new ComicVineAllVolumeComicsRetriever(url); ComicVineAllVolumeComicsRetriever * comicsRetriever = new ComicVineAllVolumeComicsRetriever(url);
connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::allVolumeComicsInfo, this, &ComicVineClient::volumeComicsInfo); connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::allVolumeComicsInfo, this, &ComicVineClient::volumeComicsInfo);
connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::finished, this, &ComicVineClient::finished); connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::finished, this, &ComicVineClient::finished);
connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::finished, this, &ComicVineAllVolumeComicsRetriever::deleteLater); connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::finished, this, &ComicVineAllVolumeComicsRetriever::deleteLater);
connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::timeOut, this, &ComicVineClient::timeOut); connect(comicsRetriever, &ComicVineAllVolumeComicsRetriever::timeOut, this, &ComicVineClient::timeOut);
comicsRetriever->getAllVolumeComics(); comicsRetriever->getAllVolumeComics();
} }
//CV_COMIC_ID //CV_COMIC_ID
void ComicVineClient::getComicId(const QString & id, int comicNumber) void ComicVineClient::getComicId(const QString & id, int comicNumber)
{ {
Q_UNUSED(id); Q_UNUSED(id);
Q_UNUSED(comicNumber); Q_UNUSED(comicNumber);
} }
//CV_COMIC_DETAIL //CV_COMIC_DETAIL
QByteArray ComicVineClient::getComicDetail(const QString & id, bool & outError, bool & outTimeout) QByteArray ComicVineClient::getComicDetail(const QString & id, bool & outError, bool & outTimeout)
{ {
HttpWorker * search = new HttpWorker(QString(CV_COMIC_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id)); HttpWorker * search = new HttpWorker(QString(CV_COMIC_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id));
//connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessComicDetailData(const QByteArray &))); //connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessComicDetailData(const QByteArray &)));
//connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut()));
//connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); //connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
search->wait(); search->wait();
outError = !(search->wasValid()); outError = !(search->wasValid());
outTimeout = search->wasTimeout(); outTimeout = search->wasTimeout();
QByteArray result = search->getResult(); QByteArray result = search->getResult();
delete search; delete search;
return result; return result;
} }
//CV_COMIC_DETAIL //CV_COMIC_DETAIL
void ComicVineClient::getComicDetailAsync(const QString & id) void ComicVineClient::getComicDetailAsync(const QString & id)
{ {
HttpWorker * search = new HttpWorker(QString(CV_COMIC_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id)); HttpWorker * search = new HttpWorker(QString(CV_COMIC_DETAIL).replace(CV_WEB_ADDRESS, baseURL).replace(CV_API_KEY,settings->value(COMIC_VINE_API_KEY,CV_API_KEY_DEFAULT).toString()).arg(id));
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessComicDetailData(const QByteArray &))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SLOT(proccessComicDetailData(const QByteArray &)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut()));
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
void ComicVineClient::getComicCover(const QString &url) void ComicVineClient::getComicCover(const QString &url)
{ {
HttpWorker * search = new HttpWorker(url); HttpWorker * search = new HttpWorker(url);
connect(search,SIGNAL(dataReady(const QByteArray &)),this,SIGNAL(comicCover(QByteArray))); connect(search,SIGNAL(dataReady(const QByteArray &)),this,SIGNAL(comicCover(QByteArray)));
connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO connect(search,SIGNAL(timeout()),this,SIGNAL(timeOut())); //TODO
connect(search,SIGNAL(finished()),search,SLOT(deleteLater())); connect(search,SIGNAL(finished()),search,SLOT(deleteLater()));
search->get(); search->get();
} }
//CV_COVER_DETAIL //CV_COVER_DETAIL
void ComicVineClient::getCoverURL(const QString & id) void ComicVineClient::getCoverURL(const QString & id)
{ {
Q_UNUSED(id); Q_UNUSED(id);
} }

View File

@ -1,48 +1,48 @@
#ifndef COMIC_VINE_CLIENT_H #ifndef COMIC_VINE_CLIENT_H
#define COMIC_VINE_CLIENT_H #define COMIC_VINE_CLIENT_H
#include "http_worker.h" #include "http_worker.h"
#include <QObject> #include <QObject>
#include <QSettings> #include <QSettings>
class ComicVineClient : public QObject class ComicVineClient : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ComicVineClient(QObject *parent = 0); explicit ComicVineClient(QObject *parent = 0);
~ComicVineClient(); ~ComicVineClient();
signals: signals:
void searchResult(QString); void searchResult(QString);
void seriesDetail(QString);//JSON void seriesDetail(QString);//JSON
void comicDetail(QString);//JSON void comicDetail(QString);//JSON
void seriesCover(const QByteArray &); void seriesCover(const QByteArray &);
void comicCover(const QByteArray &); void comicCover(const QByteArray &);
void volumeComicsInfo(QString); void volumeComicsInfo(QString);
void timeOut(); void timeOut();
void finished(); void finished();
public slots: public slots:
void search(const QString & query, int page = 1); void search(const QString & query, int page = 1);
void getSeriesDetail(const QString & id); void getSeriesDetail(const QString & id);
void getSeriesCover(const QString & url); void getSeriesCover(const QString & url);
void getVolumeComicsInfo(const QString & idVolume, int page=1); void getVolumeComicsInfo(const QString & idVolume, int page=1);
void getAllVolumeComicsInfo(const QString & idVolume); void getAllVolumeComicsInfo(const QString & idVolume);
QByteArray getComicDetail(const QString & id, bool &outError, bool &outTimeout); QByteArray getComicDetail(const QString & id, bool &outError, bool &outTimeout);
void getComicCover(const QString & url); void getComicCover(const QString & url);
void getComicId(const QString & id, int comicNumber); void getComicId(const QString & id, int comicNumber);
void getCoverURL(const QString & id); void getCoverURL(const QString & id);
void getComicDetailAsync(const QString &id); void getComicDetailAsync(const QString &id);
protected slots: protected slots:
void proccessVolumesSearchData(const QByteArray & data); void proccessVolumesSearchData(const QByteArray & data);
void proccessSeriesDetailData(const QByteArray & data); void proccessSeriesDetailData(const QByteArray & data);
void processVolumeComicsInfo(const QByteArray & data); void processVolumeComicsInfo(const QByteArray & data);
void proccessComicDetailData(const QByteArray & data); void proccessComicDetailData(const QByteArray & data);
protected: protected:
QSettings * settings; QSettings * settings;
QString baseURL; QString baseURL;
}; };
#endif // COMIC_VINE_CLIENT_H #endif // COMIC_VINE_CLIENT_H

File diff suppressed because it is too large Load Diff

View File

@ -1,131 +1,131 @@
#ifndef COMIC_VINE_DIALOG_H #ifndef COMIC_VINE_DIALOG_H
#define COMIC_VINE_DIALOG_H #define COMIC_VINE_DIALOG_H
#include <QDialog> #include <QDialog>
#include "comic_db.h" #include "comic_db.h"
class QPushButton; class QPushButton;
class QStackedWidget; class QStackedWidget;
class QLabel; class QLabel;
class QRadioButton; class QRadioButton;
class ComicVineClient; class ComicVineClient;
class QTableView; class QTableView;
class TitleHeader; class TitleHeader;
class SeriesQuestion; class SeriesQuestion;
class SearchSingleComic; class SearchSingleComic;
class SearchVolume; class SearchVolume;
class SelectComic; class SelectComic;
class SelectVolume; class SelectVolume;
class SortVolumeComics; class SortVolumeComics;
class QScriptValue; class QScriptValue;
//TODO this should use a QStateMachine //TODO this should use a QStateMachine
//---------------------------------------- //----------------------------------------
class ComicVineDialog : public QDialog class ComicVineDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ComicVineDialog(QWidget *parent = 0); explicit ComicVineDialog(QWidget *parent = 0);
QString databasePath; QString databasePath;
QString basePath; QString basePath;
void setComics(const QList<ComicDB> & comics); void setComics(const QList<ComicDB> & comics);
QSize sizeHint() const; QSize sizeHint() const;
QSize minimumSizeHint() const; QSize minimumSizeHint() const;
signals: signals:
public slots: public slots:
void show(); void show();
protected slots: protected slots:
void goNext(); void goNext();
void goBack(); void goBack();
void debugClientResults(const QString & string); void debugClientResults(const QString & string);
//show widget methods //show widget methods
void showSeriesQuestion(); void showSeriesQuestion();
void showSearchSingleComic(); void showSearchSingleComic();
void showSearchVolume(); void showSearchVolume();
void showLoading(const QString & message = ""); void showLoading(const QString & message = "");
void search(); void search();
void searchVolume(const QString & v, int page = 1); void searchVolume(const QString & v, int page = 1);
void getVolumeComicsInfo(const QString &vID, int page = 1); void getVolumeComicsInfo(const QString &vID, int page = 1);
void launchSearchVolume(); void launchSearchVolume();
void launchSearchComic(); void launchSearchComic();
void showSelectVolume(const QString & json); void showSelectVolume(const QString & json);
void showSelectVolume(); void showSelectVolume();
void showSelectComic(const QString & json); void showSelectComic(const QString & json);
void showSortVolumeComics(const QString & json); void showSortVolumeComics(const QString & json);
void queryTimeOut(); void queryTimeOut();
void getComicsInfo(QList<QPair<ComicDB,QString> > & matchingInfo, int count, const QString & publisher); void getComicsInfo(QList<QPair<ComicDB,QString> > & matchingInfo, int count, const QString & publisher);
void getComicInfo(const QString & comicId, int count, const QString & publisher); void getComicInfo(const QString & comicId, int count, const QString & publisher);
ComicDB parseComicInfo(ComicDB &comic, const QString & json, int count, const QString &publisher); ComicDB parseComicInfo(ComicDB &comic, const QString & json, int count, const QString &publisher);
void setLoadingMessage(const QString &message); void setLoadingMessage(const QString &message);
void goToNextComic(); void goToNextComic();
private: private:
QString getCharacters(const QScriptValue & json_characters); QString getCharacters(const QScriptValue & json_characters);
QMap<QString,QString> getAuthors(const QScriptValue & json_authors); QMap<QString,QString> getAuthors(const QScriptValue & json_authors);
void toggleSkipButton(); void toggleSkipButton();
enum ScraperMode enum ScraperMode
{ {
SingleComic, //the scraper has been opened for a single comic SingleComic, //the scraper has been opened for a single comic
Volume, //the scraper is trying to get comics info for a whole volume Volume, //the scraper is trying to get comics info for a whole volume
SingleComicInList //the scraper has been opened for a list of unrelated comics SingleComicInList //the scraper has been opened for a list of unrelated comics
}; };
enum ScraperStatus enum ScraperStatus
{ {
AutoSearching, AutoSearching,
AskingForInfo, AskingForInfo,
SelectingComic, SelectingComic,
SelectingSeries, SelectingSeries,
SearchingSingleComic, SearchingSingleComic,
SearchingVolume, SearchingVolume,
SortingComics, SortingComics,
GettingVolumeComics GettingVolumeComics
}; };
ScraperMode mode; ScraperMode mode;
ScraperStatus status; ScraperStatus status;
int currentIndex; int currentIndex;
TitleHeader * titleHeader; TitleHeader * titleHeader;
QPushButton * skipButton; QPushButton * skipButton;
QPushButton * backButton; QPushButton * backButton;
QPushButton * nextButton; QPushButton * nextButton;
QPushButton * searchButton; QPushButton * searchButton;
QPushButton * closeButton; QPushButton * closeButton;
//stacked widgets //stacked widgets
QStackedWidget * content; QStackedWidget * content;
QWidget * infoNotFound; QWidget * infoNotFound;
QWidget * singleComicBrowser; QWidget * singleComicBrowser;
QLabel * loadingMessage; QLabel * loadingMessage;
void doLayout(); void doLayout();
void doStackedWidgets(); void doStackedWidgets();
void doLoading(); void doLoading();
void doConnections(); void doConnections();
QList<ComicDB> comics; QList<ComicDB> comics;
SeriesQuestion * seriesQuestionWidget; SeriesQuestion * seriesQuestionWidget;
SearchSingleComic * searchSingleComicWidget; SearchSingleComic * searchSingleComicWidget;
SearchVolume * searchVolumeWidget; SearchVolume * searchVolumeWidget;
SelectVolume * selectVolumeWidget; SelectVolume * selectVolumeWidget;
SelectComic * selectComicWidget; SelectComic * selectComicWidget;
SortVolumeComics * sortVolumeComicsWidget; SortVolumeComics * sortVolumeComicsWidget;
QString currentVolumeSearchString; QString currentVolumeSearchString;
QString currentVolumeId; QString currentVolumeId;
}; };
#endif // COMIC_VINE_DIALOG_H #endif // COMIC_VINE_DIALOG_H

View File

@ -1,6 +1,6 @@
#include "comics_model.h" #include "comics_model.h"
ComicsModel::ComicsModel(QObject *parent) : ComicsModel::ComicsModel(QObject *parent) :
JSONModel(parent) JSONModel(parent)
{ {
} }

View File

@ -1,18 +1,18 @@
#ifndef COMICS_MODEL_H #ifndef COMICS_MODEL_H
#define COMICS_MODEL_H #define COMICS_MODEL_H
#include "json_model.h" #include "json_model.h"
class ComicsModel : public JSONModel class ComicsModel : public JSONModel
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ComicsModel(QObject *parent = 0); explicit ComicsModel(QObject *parent = 0);
signals: signals:
public slots: public slots:
}; };
#endif // COMICS_MODEL_H #endif // COMICS_MODEL_H

View File

@ -1,6 +1,6 @@
#include "json_model.h" #include "json_model.h"
JSONModel::JSONModel(QObject *parent) : JSONModel::JSONModel(QObject *parent) :
QAbstractItemModel(parent) QAbstractItemModel(parent)
{ {
} }

View File

@ -1,19 +1,19 @@
#ifndef JSON_MODEL_H #ifndef JSON_MODEL_H
#define JSON_MODEL_H #define JSON_MODEL_H
#include <QAbstractItemModel> #include <QAbstractItemModel>
class JSONModel : public QAbstractItemModel class JSONModel : public QAbstractItemModel
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit JSONModel(QObject *parent = 0); explicit JSONModel(QObject *parent = 0);
virtual void load(const QString & json) = 0 ; virtual void load(const QString & json) = 0 ;
signals: signals:
public slots: public slots:
}; };
#endif // JSON_MODEL_H #endif // JSON_MODEL_H

View File

@ -1,184 +1,184 @@
#include "local_comic_list_model.h" #include "local_comic_list_model.h"
LocalComicListModel::LocalComicListModel(QObject *parent) : LocalComicListModel::LocalComicListModel(QObject *parent) :
QAbstractItemModel(parent),numExtraRows(0) QAbstractItemModel(parent),numExtraRows(0)
{ {
} }
void LocalComicListModel::load(QList<ComicDB> &comics) void LocalComicListModel::load(QList<ComicDB> &comics)
{ {
_data = comics; _data = comics;
} }
QModelIndex LocalComicListModel::parent(const QModelIndex &index) const QModelIndex LocalComicListModel::parent(const QModelIndex &index) const
{ {
Q_UNUSED(index) Q_UNUSED(index)
return QModelIndex(); //no parent return QModelIndex(); //no parent
} }
int LocalComicListModel::rowCount(const QModelIndex &parent) const int LocalComicListModel::rowCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
return _data.count(); return _data.count();
} }
int LocalComicListModel::columnCount(const QModelIndex &parent) const int LocalComicListModel::columnCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
if(_data.isEmpty()) if(_data.isEmpty())
return 0; return 0;
else else
return 1;//_data.at(0)->count(); return 1;//_data.at(0)->count();
} }
QVariant LocalComicListModel::data(const QModelIndex &index, int role) const QVariant LocalComicListModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
if (role == Qt::DecorationRole) if (role == Qt::DecorationRole)
{ {
return QVariant(); return QVariant();
} }
if (role == Qt::TextAlignmentRole) if (role == Qt::TextAlignmentRole)
{ {
//TODO //TODO
} }
if(role != Qt::DisplayRole) if(role != Qt::DisplayRole)
return QVariant(); return QVariant();
int row = index.row(); int row = index.row();
//if(row < _data.count()) //if(row < _data.count())
return _data[row].getFileName(); return _data[row].getFileName();
//else //else
//return QVariant(); //return QVariant();
} }
Qt::ItemFlags LocalComicListModel::flags(const QModelIndex &index) const Qt::ItemFlags LocalComicListModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid())
return 0; return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} }
QVariant LocalComicListModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant LocalComicListModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
Q_UNUSED(section); Q_UNUSED(section);
if ( role == Qt::TextAlignmentRole) if ( role == Qt::TextAlignmentRole)
return QVariant(Qt::AlignLeft | Qt::AlignVCenter); return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{ {
return QVariant(QString(tr("file name"))); return QVariant(QString(tr("file name")));
} }
return QVariant(); return QVariant();
} }
QModelIndex LocalComicListModel::index(int row, int column, const QModelIndex &parent) const QModelIndex LocalComicListModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent))
return QModelIndex(); return QModelIndex();
return createIndex(row, column); return createIndex(row, column);
} }
QList<ComicDB> LocalComicListModel::getData() QList<ComicDB> LocalComicListModel::getData()
{ {
return _data; return _data;
} }
void LocalComicListModel::removeComics(const QList<QModelIndex> &selectedIndexes) void LocalComicListModel::removeComics(const QList<QModelIndex> &selectedIndexes)
{ {
QModelIndex mi = selectedIndexes.first(); QModelIndex mi = selectedIndexes.first();
QModelIndex lastMi = selectedIndexes.last(); QModelIndex lastMi = selectedIndexes.last();
int sourceRow = mi.row(); int sourceRow = mi.row();
int sourceLastRow = lastMi.row(); int sourceLastRow = lastMi.row();
beginRemoveRows(QModelIndex(),selectedIndexes.first().row(),selectedIndexes.last().row()); beginRemoveRows(QModelIndex(),selectedIndexes.first().row(),selectedIndexes.last().row());
for(int i = sourceLastRow;i>=sourceRow;i--) for(int i = sourceLastRow;i>=sourceRow;i--)
{ {
_removed.push_front(_data.at(i)); _removed.push_front(_data.at(i));
_data.removeAt(i); _data.removeAt(i);
} }
endRemoveRows(); endRemoveRows();
beginInsertRows(QModelIndex(),_data.count()-_removed.count(),_data.count()-1); beginInsertRows(QModelIndex(),_data.count()-_removed.count(),_data.count()-1);
for(int i = 0; i<_removed.count(); i++) for(int i = 0; i<_removed.count(); i++)
_data.append(ComicDB()); _data.append(ComicDB());
endInsertRows(); endInsertRows();
} }
void LocalComicListModel::restoreAll() void LocalComicListModel::restoreAll()
{ {
int numItemsToRemove = 0; int numItemsToRemove = 0;
for(int i = 0;numItemsToRemove<_removed.count();i++) for(int i = 0;numItemsToRemove<_removed.count();i++)
{ {
if(_data.at(i).getFileName().isEmpty()) if(_data.at(i).getFileName().isEmpty())
{ {
beginRemoveRows(QModelIndex(),i,i); beginRemoveRows(QModelIndex(),i,i);
_data.removeAt(i); _data.removeAt(i);
endRemoveRows(); endRemoveRows();
beginInsertRows(QModelIndex(),i,i); beginInsertRows(QModelIndex(),i,i);
_data.insert(i,_removed.at(numItemsToRemove)); _data.insert(i,_removed.at(numItemsToRemove));
endInsertRows(); endInsertRows();
numItemsToRemove++; numItemsToRemove++;
} }
} }
_removed.clear(); _removed.clear();
} }
void LocalComicListModel::moveSelectionUp(const QList<QModelIndex> &selectedIndexes) void LocalComicListModel::moveSelectionUp(const QList<QModelIndex> &selectedIndexes)
{ {
QModelIndex mi = selectedIndexes.first(); QModelIndex mi = selectedIndexes.first();
QModelIndex lastMi = selectedIndexes.last(); QModelIndex lastMi = selectedIndexes.last();
int sourceRow = mi.row(); int sourceRow = mi.row();
int sourceLastRow = lastMi.row(); int sourceLastRow = lastMi.row();
int destRow = sourceRow - 1; int destRow = sourceRow - 1;
if(destRow < 0) if(destRow < 0)
return; return;
beginMoveRows(mi.parent(),sourceRow,sourceLastRow,mi.parent(),destRow); beginMoveRows(mi.parent(),sourceRow,sourceLastRow,mi.parent(),destRow);
for(int i = sourceRow; i <= sourceLastRow; i++) for(int i = sourceRow; i <= sourceLastRow; i++)
_data.swap(i, i-1); _data.swap(i, i-1);
endMoveRows(); endMoveRows();
} }
void LocalComicListModel::moveSelectionDown(const QList<QModelIndex> &selectedIndexes) void LocalComicListModel::moveSelectionDown(const QList<QModelIndex> &selectedIndexes)
{ {
QModelIndex mi = selectedIndexes.first(); QModelIndex mi = selectedIndexes.first();
QModelIndex lastMi = selectedIndexes.last(); QModelIndex lastMi = selectedIndexes.last();
int sourceRow = mi.row(); int sourceRow = mi.row();
int sourceLastRow = lastMi.row(); int sourceLastRow = lastMi.row();
int destRow = sourceLastRow + 1; int destRow = sourceLastRow + 1;
if(destRow >= _data.count()) if(destRow >= _data.count())
return; return;
beginMoveRows(mi.parent(),sourceRow,sourceLastRow,mi.parent(),destRow+1); beginMoveRows(mi.parent(),sourceRow,sourceLastRow,mi.parent(),destRow+1);
for(int i = sourceLastRow; i >= sourceRow; i--) for(int i = sourceLastRow; i >= sourceRow; i--)
_data.swap(i, i+1); _data.swap(i, i+1);
endMoveRows(); endMoveRows();
} }
void LocalComicListModel::addExtraRows(int numRows) void LocalComicListModel::addExtraRows(int numRows)
{ {
numExtraRows = numRows; numExtraRows = numRows;
for(int i = 0; i<numExtraRows; i++) for(int i = 0; i<numExtraRows; i++)
_data.append(ComicDB()); _data.append(ComicDB());
} }

View File

@ -1,42 +1,42 @@
#ifndef LOCAL_COMIC_LIST_MODEL_H #ifndef LOCAL_COMIC_LIST_MODEL_H
#define LOCAL_COMIC_LIST_MODEL_H #define LOCAL_COMIC_LIST_MODEL_H
#include <QAbstractItemModel> #include <QAbstractItemModel>
#include "comic_db.h" #include "comic_db.h"
class LocalComicListModel : public QAbstractItemModel class LocalComicListModel : public QAbstractItemModel
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit LocalComicListModel(QObject *parent = 0); explicit LocalComicListModel(QObject *parent = 0);
void load(QList<ComicDB> & comics); void load(QList<ComicDB> & comics);
//QAbstractItemModel methods //QAbstractItemModel methods
QModelIndex parent(const QModelIndex &index) const; QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int section, Qt::Orientation orientation, QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const; int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QList<ComicDB> getData(); QList<ComicDB> getData();
void removeComics(const QList<QModelIndex> & selectedIndexes); void removeComics(const QList<QModelIndex> & selectedIndexes);
void restoreAll(); void restoreAll();
signals: signals:
public slots: public slots:
void moveSelectionUp(const QList<QModelIndex> & selectedIndexes); void moveSelectionUp(const QList<QModelIndex> & selectedIndexes);
void moveSelectionDown(const QList<QModelIndex> & selectedIndexes); void moveSelectionDown(const QList<QModelIndex> & selectedIndexes);
void addExtraRows(int numRows); void addExtraRows(int numRows);
private: private:
int numExtraRows; int numExtraRows;
QList<ComicDB> _data; QList<ComicDB> _data;
QList<ComicDB> _removed; QList<ComicDB> _removed;
}; };
#endif // LOCAL_COMIC_LIST_MODEL_H #endif // LOCAL_COMIC_LIST_MODEL_H

View File

@ -1,83 +1,83 @@
#include "response_parser.h" #include "response_parser.h"
#include <QtScript> #include <QtScript>
#include <QDebug> #include <QDebug>
ResponseParser::ResponseParser(QObject *parent) : ResponseParser::ResponseParser(QObject *parent) :
QObject(parent),error(false),numResults(-1),currentPage(-1),totalPages(-1),errorTxt("None") QObject(parent),error(false),numResults(-1),currentPage(-1),totalPages(-1),errorTxt("None")
{ {
} }
bool ResponseParser::responseError() bool ResponseParser::responseError()
{ {
return error; return error;
} }
QString ResponseParser::errorDescription() QString ResponseParser::errorDescription()
{ {
return errorTxt; return errorTxt;
} }
qint32 ResponseParser::getNumResults() qint32 ResponseParser::getNumResults()
{ {
return numResults; return numResults;
} }
qint32 ResponseParser::getCurrentPage() qint32 ResponseParser::getCurrentPage()
{ {
return currentPage; return currentPage;
} }
qint32 ResponseParser::getTotalPages() qint32 ResponseParser::getTotalPages()
{ {
return totalPages; return totalPages;
} }
bool ResponseParser::isError(qint32 error) bool ResponseParser::isError(qint32 error)
{ {
switch(error) switch(error)
{ {
case 100: case 100:
return true; return true;
default: default:
return false; return false;
} }
} }
void ResponseParser::loadJSONResponse(const QString &response) void ResponseParser::loadJSONResponse(const QString &response)
{ {
QScriptEngine engine; QScriptEngine engine;
QScriptValue sc; QScriptValue sc;
sc = engine.evaluate("(" + response + ")"); sc = engine.evaluate("(" + response + ")");
errorTxt = "None"; errorTxt = "None";
if (!sc.property("status_code").isValid() || isError(sc.property("status_code").toInt32())) if (!sc.property("status_code").isValid() || isError(sc.property("status_code").toInt32()))
{ {
error = true; error = true;
if(sc.property("error").isValid()) if(sc.property("error").isValid())
errorTxt = sc.property("error").toString(); errorTxt = sc.property("error").toString();
else else
errorTxt = "Unknown error"; errorTxt = "Unknown error";
} }
else else
{ {
error = false; error = false;
if(sc.property("number_of_total_results").isValid()) if(sc.property("number_of_total_results").isValid())
numResults = sc.property("number_of_total_results").toString().toInt();// sc.property("number_of_total_results").toInt32(); numResults = sc.property("number_of_total_results").toString().toInt();// sc.property("number_of_total_results").toInt32();
else else
qDebug() << sc.property("oops").toString(); qDebug() << sc.property("oops").toString();
int limit = sc.property("limit").toInt32(); int limit = sc.property("limit").toInt32();
int offset = sc.property("offset").toInt32(); int offset = sc.property("offset").toInt32();
int total = sc.property("number_of_total_results").toInt32(); int total = sc.property("number_of_total_results").toInt32();
if(limit > 0) if(limit > 0)
{ {
totalPages = (total / limit) + (total%limit>0?1:0); totalPages = (total / limit) + (total%limit>0?1:0);
currentPage = (offset / limit) + 1; currentPage = (offset / limit) + 1;
} }
else else
totalPages = currentPage = 1; totalPages = currentPage = 1;
} }
} }

View File

@ -1,30 +1,30 @@
#ifndef RESPONSE_PARSER_H #ifndef RESPONSE_PARSER_H
#define RESPONSE_PARSER_H #define RESPONSE_PARSER_H
#include <QObject> #include <QObject>
class ResponseParser : public QObject class ResponseParser : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ResponseParser(QObject *parent = 0); explicit ResponseParser(QObject *parent = 0);
bool responseError(); bool responseError();
QString errorDescription(); QString errorDescription();
qint32 getNumResults(); qint32 getNumResults();
qint32 getCurrentPage(); qint32 getCurrentPage();
qint32 getTotalPages(); qint32 getTotalPages();
bool isError(qint32 error); bool isError(qint32 error);
signals: signals:
public slots: public slots:
void loadJSONResponse(const QString & response); void loadJSONResponse(const QString & response);
protected: protected:
bool error; bool error;
QString errorTxt; QString errorTxt;
qint32 numResults; qint32 numResults;
qint32 currentPage; qint32 currentPage;
qint32 totalPages; qint32 totalPages;
}; };
#endif // RESPONSE_PARSER_H #endif // RESPONSE_PARSER_H

View File

@ -1,180 +1,180 @@
#include "volume_comics_model.h" #include "volume_comics_model.h"
#include "qnaturalsorting.h" #include "qnaturalsorting.h"
#include <QtScript> #include <QtScript>
bool lessThan(const QList<QString> & left, const QList<QString> & right) bool lessThan(const QList<QString> & left, const QList<QString> & right)
{ {
if ((left.count() > 0) && (right.count() > 0)) if ((left.count() > 0) && (right.count() > 0))
return naturalSortLessThanCI(left.at(0),right.at(0)); return naturalSortLessThanCI(left.at(0),right.at(0));
else else
return true; return true;
} }
VolumeComicsModel::VolumeComicsModel(QObject * parent) : VolumeComicsModel::VolumeComicsModel(QObject * parent) :
JSONModel(parent),numExtraRows(0) JSONModel(parent),numExtraRows(0)
{ {
} }
void VolumeComicsModel::load(const QString & json) void VolumeComicsModel::load(const QString & json)
{ {
QScriptEngine engine; QScriptEngine engine;
QScriptValue sc; QScriptValue sc;
sc = engine.evaluate("(" + json + ")"); sc = engine.evaluate("(" + json + ")");
if (!sc.property("error").isValid() && sc.property("error").toString() != "OK") if (!sc.property("error").isValid() && sc.property("error").toString() != "OK")
{ {
qDebug("Error detected"); qDebug("Error detected");
} }
else else
{ {
QScriptValueIterator it(sc.property("results")); QScriptValueIterator it(sc.property("results"));
//bool test; //bool test;
QScriptValue resultsValue; QScriptValue resultsValue;
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
if(it.flags() & QScriptValue::SkipInEnumeration) if(it.flags() & QScriptValue::SkipInEnumeration)
continue; continue;
resultsValue = it.value(); resultsValue = it.value();
QString issueNumber = resultsValue.property("issue_number").toString(); QString issueNumber = resultsValue.property("issue_number").toString();
QScriptValue propertyName = resultsValue.property("name"); QScriptValue propertyName = resultsValue.property("name");
QString name = propertyName.isNull() ? "-" : propertyName.toString(); QString name = propertyName.isNull() ? "-" : propertyName.toString();
QString coverURL = resultsValue.property("image").property("medium_url").toString(); QString coverURL = resultsValue.property("image").property("medium_url").toString();
QString id = resultsValue.property("id").toString(); QString id = resultsValue.property("id").toString();
QStringList l; QStringList l;
l << issueNumber << name << coverURL << id; l << issueNumber << name << coverURL << id;
_data.push_back(l); _data.push_back(l);
} }
qSort(_data.begin(),_data.end(),lessThan); qSort(_data.begin(),_data.end(),lessThan);
} }
} }
/*void VolumeComicsModel::load(const QStringList &jsonList) /*void VolumeComicsModel::load(const QStringList &jsonList)
{ {
foreach (QString json, jsonList) { foreach (QString json, jsonList) {
load(json); load(json);
} }
}*/ }*/
QModelIndex VolumeComicsModel::parent(const QModelIndex &index) const QModelIndex VolumeComicsModel::parent(const QModelIndex &index) const
{ {
Q_UNUSED(index) Q_UNUSED(index)
return QModelIndex(); //no parent return QModelIndex(); //no parent
} }
int VolumeComicsModel::rowCount(const QModelIndex &parent) const int VolumeComicsModel::rowCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
return _data.count() + numExtraRows; return _data.count() + numExtraRows;
} }
int VolumeComicsModel::columnCount(const QModelIndex &parent) const int VolumeComicsModel::columnCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
if(_data.isEmpty()) if(_data.isEmpty())
return 0; return 0;
else else
return 2; return 2;
} }
QVariant VolumeComicsModel::data(const QModelIndex &index, int role) const QVariant VolumeComicsModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
int row = index.row(); int row = index.row();
int column = index.column(); int column = index.column();
if (role == Qt::DecorationRole) if (role == Qt::DecorationRole)
{ {
return QVariant(); return QVariant();
} }
if (role == Qt::TextAlignmentRole) if (role == Qt::TextAlignmentRole)
{ {
switch(column)//TODO obtener esto de la query switch(column)//TODO obtener esto de la query
{ {
case ISSUE: case ISSUE:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
case TITLE: case TITLE:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter); return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
} }
} }
if(role != Qt::DisplayRole) if(role != Qt::DisplayRole)
return QVariant(); return QVariant();
if(row<_data.count()) if(row<_data.count())
return _data[row][column]; return _data[row][column];
else else
return QVariant(); return QVariant();
} }
Qt::ItemFlags VolumeComicsModel::flags(const QModelIndex &index) const Qt::ItemFlags VolumeComicsModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid())
return 0; return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} }
QVariant VolumeComicsModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant VolumeComicsModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{ {
switch(section)//TODO obtener esto de la query switch(section)//TODO obtener esto de la query
{ {
case ISSUE: case ISSUE:
return QVariant(QString("issue")); return QVariant(QString("issue"));
case TITLE: case TITLE:
return QVariant(QString(tr("title"))); return QVariant(QString(tr("title")));
} }
} }
if (orientation == Qt::Horizontal && role == Qt::TextAlignmentRole) if (orientation == Qt::Horizontal && role == Qt::TextAlignmentRole)
{ {
switch(section)//TODO obtener esto de la query switch(section)//TODO obtener esto de la query
{ {
case ISSUE: case ISSUE:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
case TITLE: case TITLE:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter); return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
} }
} }
return QVariant(); return QVariant();
} }
QModelIndex VolumeComicsModel::index(int row, int column, const QModelIndex &parent) const QModelIndex VolumeComicsModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent))
return QModelIndex(); return QModelIndex();
return createIndex(row, column); return createIndex(row, column);
} }
QString VolumeComicsModel::getComicId(const QModelIndex &index) const QString VolumeComicsModel::getComicId(const QModelIndex &index) const
{ {
int row = index.row(); int row = index.row();
if(row >= _data.count()) if(row >= _data.count())
return ""; return "";
return _data[row][ID]; return _data[row][ID];
} }
QString VolumeComicsModel::getComicId(int row) const QString VolumeComicsModel::getComicId(int row) const
{ {
if(row >= _data.count()) if(row >= _data.count())
return ""; return "";
return _data[row][ID]; return _data[row][ID];
} }
QString VolumeComicsModel::getCoverURL(const QModelIndex &index) const QString VolumeComicsModel::getCoverURL(const QModelIndex &index) const
{ {
return _data[index.row()][COVER_URL]; return _data[index.row()][COVER_URL];
} }
void VolumeComicsModel::addExtraRows(int numRows) void VolumeComicsModel::addExtraRows(int numRows)
{ {
numExtraRows = numRows; numExtraRows = numRows;
} }

View File

@ -1,42 +1,42 @@
#ifndef VOLUME_COMICS_MODEL_H #ifndef VOLUME_COMICS_MODEL_H
#define VOLUME_COMICS_MODEL_H #define VOLUME_COMICS_MODEL_H
#include "json_model.h" #include "json_model.h"
class VolumeComicsModel : public JSONModel class VolumeComicsModel : public JSONModel
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit VolumeComicsModel(QObject *parent = 0); explicit VolumeComicsModel(QObject *parent = 0);
void load(const QString & json); void load(const QString & json);
//void load(const QStringList & jsonList); //void load(const QStringList & jsonList);
QModelIndex parent(const QModelIndex &index) const; QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int section, Qt::Orientation orientation, QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const; int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
signals: signals:
public slots: public slots:
QString getComicId(const QModelIndex &index) const; QString getComicId(const QModelIndex &index) const;
QString getComicId(int row) const; QString getComicId(int row) const;
QString getCoverURL(const QModelIndex &index) const; QString getCoverURL(const QModelIndex &index) const;
void addExtraRows(int numRows); void addExtraRows(int numRows);
private: private:
int numExtraRows; int numExtraRows;
QList <QList <QString> > _data; QList <QList <QString> > _data;
enum Column { enum Column {
ISSUE = 0, ISSUE = 0,
TITLE, TITLE,
COVER_URL, COVER_URL,
ID ID
}; };
}; };
#endif // VOLUME_COMICS_MODEL_H #endif // VOLUME_COMICS_MODEL_H

View File

@ -1,180 +1,180 @@
#include "volumes_model.h" #include "volumes_model.h"
#include <QtScript> #include <QtScript>
VolumesModel::VolumesModel(QObject *parent) : VolumesModel::VolumesModel(QObject *parent) :
JSONModel(parent) JSONModel(parent)
{ {
} }
VolumesModel::~VolumesModel() VolumesModel::~VolumesModel()
{ {
//std::for_each(_data.begin(), _data.end(), [](QList<QString> * ptr) { delete ptr; }); //std::for_each(_data.begin(), _data.end(), [](QList<QString> * ptr) { delete ptr; });
} }
void VolumesModel::load(const QString &json) void VolumesModel::load(const QString &json)
{ {
QScriptEngine engine; QScriptEngine engine;
QScriptValue sc; QScriptValue sc;
sc = engine.evaluate("(" + json + ")"); sc = engine.evaluate("(" + json + ")");
if (!sc.property("error").isValid() && sc.property("error").toString() != "OK") if (!sc.property("error").isValid() && sc.property("error").toString() != "OK")
{ {
qDebug("Error detected"); qDebug("Error detected");
} }
else else
{ {
int numResults = sc.property("number_of_total_results").toString().toInt(); //fix to weird behaviour using hasNext int numResults = sc.property("number_of_total_results").toString().toInt(); //fix to weird behaviour using hasNext
QScriptValueIterator it(sc.property("results")); QScriptValueIterator it(sc.property("results"));
bool test; bool test;
QScriptValue resultsValue; QScriptValue resultsValue;
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
resultsValue = it.value(); resultsValue = it.value();
QString numIssues = resultsValue.property("count_of_issues").toString(); QString numIssues = resultsValue.property("count_of_issues").toString();
QString year = resultsValue.property("start_year").toString(); QString year = resultsValue.property("start_year").toString();
QString name = resultsValue.property("name").toString(); QString name = resultsValue.property("name").toString();
QString publisher = resultsValue.property("publisher").property("name").toString(); QString publisher = resultsValue.property("publisher").property("name").toString();
QString url = resultsValue.property("image").property("medium_url").toString(); QString url = resultsValue.property("image").property("medium_url").toString();
QString deck = resultsValue.property("deck").toString(); QString deck = resultsValue.property("deck").toString();
QString id = resultsValue.property("id").toString(); QString id = resultsValue.property("id").toString();
QStringList l; QStringList l;
l << name << year << numIssues << publisher << url << deck << id; l << name << year << numIssues << publisher << url << deck << id;
test = name.isEmpty() && year.isEmpty() && numIssues.isEmpty() && url.isEmpty(); test = name.isEmpty() && year.isEmpty() && numIssues.isEmpty() && url.isEmpty();
if(numResults>0 && !test) if(numResults>0 && !test)
_data.push_back(l); _data.push_back(l);
numResults--; numResults--;
} }
} }
} }
QModelIndex VolumesModel::parent(const QModelIndex &index) const QModelIndex VolumesModel::parent(const QModelIndex &index) const
{ {
Q_UNUSED(index) Q_UNUSED(index)
return QModelIndex(); //no parent return QModelIndex(); //no parent
} }
int VolumesModel::rowCount(const QModelIndex &parent) const int VolumesModel::rowCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
return _data.count(); return _data.count();
} }
int VolumesModel::columnCount(const QModelIndex &parent) const int VolumesModel::columnCount(const QModelIndex &parent) const
{ {
Q_UNUSED(parent) Q_UNUSED(parent)
if(_data.isEmpty()) if(_data.isEmpty())
return 0; return 0;
else else
return 4;//_data.at(0)->count(); return 4;//_data.at(0)->count();
} }
QVariant VolumesModel::data(const QModelIndex &index, int role) const QVariant VolumesModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
if (role == Qt::DecorationRole) if (role == Qt::DecorationRole)
{ {
return QVariant(); return QVariant();
} }
int row = index.row(); int row = index.row();
int column = index.column(); int column = index.column();
if (role == Qt::TextAlignmentRole) if (role == Qt::TextAlignmentRole)
{ {
switch(column) switch(column)
{ {
case YEAR: case YEAR:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
case ISSUES: case ISSUES:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
default: default:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter); return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
} }
} }
if(role != Qt::DisplayRole) if(role != Qt::DisplayRole)
return QVariant(); return QVariant();
if (column == YEAR || column == ISSUES) if (column == YEAR || column == ISSUES)
{ {
return _data[row][column].toInt(); return _data[row][column].toInt();
} }
else else
{ {
return _data[row][column]; return _data[row][column];
} }
} }
Qt::ItemFlags VolumesModel::flags(const QModelIndex &index) const Qt::ItemFlags VolumesModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid())
return 0; return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} }
QVariant VolumesModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant VolumesModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{ {
switch(section)//TODO obtener esto de la query switch(section)//TODO obtener esto de la query
{ {
case SERIES: case SERIES:
return QVariant(QString("series")); return QVariant(QString("series"));
case YEAR: case YEAR:
return QVariant(QString(tr("year"))); return QVariant(QString(tr("year")));
case ISSUES: case ISSUES:
return QVariant(QString(tr("issues"))); return QVariant(QString(tr("issues")));
case PUBLISHER: case PUBLISHER:
return QVariant(QString(tr("publisher"))); return QVariant(QString(tr("publisher")));
} }
} }
if (orientation == Qt::Horizontal && role == Qt::TextAlignmentRole) if (orientation == Qt::Horizontal && role == Qt::TextAlignmentRole)
{ {
switch(section)//TODO obtener esto de la query switch(section)//TODO obtener esto de la query
{ {
case YEAR: case YEAR:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
case ISSUES: case ISSUES:
return QVariant(Qt::AlignRight | Qt::AlignVCenter); return QVariant(Qt::AlignRight | Qt::AlignVCenter);
default: default:
return QVariant(Qt::AlignLeft | Qt::AlignVCenter); return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
} }
} }
return QVariant(); return QVariant();
} }
QModelIndex VolumesModel::index(int row, int column, const QModelIndex &parent) const QModelIndex VolumesModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent))
return QModelIndex(); return QModelIndex();
return createIndex(row, column); return createIndex(row, column);
} }
QString VolumesModel::getVolumeId(const QModelIndex &index) const QString VolumesModel::getVolumeId(const QModelIndex &index) const
{ {
return _data[index.row()][ID]; return _data[index.row()][ID];
} }
int VolumesModel::getNumIssues(const QModelIndex &index) const int VolumesModel::getNumIssues(const QModelIndex &index) const
{ {
return _data[index.row()][ISSUES].toInt(); return _data[index.row()][ISSUES].toInt();
} }
QString VolumesModel::getPublisher(const QModelIndex &index) const QString VolumesModel::getPublisher(const QModelIndex &index) const
{ {
return _data[index.row()][PUBLISHER]; return _data[index.row()][PUBLISHER];
} }
QString VolumesModel::getCoverURL(const QModelIndex &index) const QString VolumesModel::getCoverURL(const QModelIndex &index) const
{ {
return _data[index.row()][COVER_URL]; return _data[index.row()][COVER_URL];
} }

View File

@ -1,53 +1,53 @@
#ifndef VOLUMES_MODEL_H #ifndef VOLUMES_MODEL_H
#define VOLUMES_MODEL_H #define VOLUMES_MODEL_H
#include "json_model.h" #include "json_model.h"
class VolumesModel : public JSONModel class VolumesModel : public JSONModel
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit VolumesModel(QObject *parent = 0); explicit VolumesModel(QObject *parent = 0);
virtual ~VolumesModel(); virtual ~VolumesModel();
//receive a valid json with a list of volumes //receive a valid json with a list of volumes
void load(const QString & json); void load(const QString & json);
//QAbstractItemModel methods //QAbstractItemModel methods
QModelIndex parent(const QModelIndex &index) const; QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int section, Qt::Orientation orientation, QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const; int role = Qt::DisplayRole) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QString getVolumeId(const QModelIndex & index) const; QString getVolumeId(const QModelIndex & index) const;
int getNumIssues(const QModelIndex & index) const; int getNumIssues(const QModelIndex & index) const;
QString getPublisher(const QModelIndex & index) const; QString getPublisher(const QModelIndex & index) const;
QString getCoverURL(const QModelIndex & index) const; QString getCoverURL(const QModelIndex & index) const;
signals: signals:
public slots: public slots:
private: private:
QList <QList <QString> > _data; QList <QList <QString> > _data;
public: public:
enum Column { enum Column {
SERIES = 0, SERIES = 0,
YEAR, YEAR,
ISSUES, ISSUES,
PUBLISHER, PUBLISHER,
COVER_URL, COVER_URL,
DECK, DECK,
ID ID
}; };
enum Role { enum Role {
SORT_ROLE = Qt::UserRole SORT_ROLE = Qt::UserRole
}; };
}; };
#endif // VOLUMES_MODEL_H #endif // VOLUMES_MODEL_H

View File

@ -1,21 +1,21 @@
#include "scraper_lineedit.h" #include "scraper_lineedit.h"
#include <QLabel> #include <QLabel>
ScraperLineEdit::ScraperLineEdit(const QString & title, QWidget * widget) ScraperLineEdit::ScraperLineEdit(const QString & title, QWidget * widget)
:QLineEdit(widget) :QLineEdit(widget)
{ {
titleLabel = new QLabel(title,this); titleLabel = new QLabel(title,this);
titleLabel->setStyleSheet("QLabel {color:white;}"); titleLabel->setStyleSheet("QLabel {color:white;}");
setStyleSheet(QString("QLineEdit {" setStyleSheet(QString("QLineEdit {"
"border:none; background-color: #2E2E2E; color : white; padding-left: %1; padding-bottom: 1px; margin-bottom: 0px;" "border:none; background-color: #2E2E2E; color : white; padding-left: %1; padding-bottom: 1px; margin-bottom: 0px;"
"}").arg(titleLabel->sizeHint().width()+6)); "}").arg(titleLabel->sizeHint().width()+6));
setFixedHeight(22); setFixedHeight(22);
} }
void ScraperLineEdit::resizeEvent(QResizeEvent *) void ScraperLineEdit::resizeEvent(QResizeEvent *)
{ {
QSize szl = titleLabel->sizeHint(); QSize szl = titleLabel->sizeHint();
titleLabel->move(6,(rect().bottom() + 1 - szl.height())/2); titleLabel->move(6,(rect().bottom() + 1 - szl.height())/2);
} }

View File

@ -1,19 +1,19 @@
#ifndef SCRAPPER_LINEEDIT_H #ifndef SCRAPPER_LINEEDIT_H
#define SCRAPPER_LINEEDIT_H #define SCRAPPER_LINEEDIT_H
#include <QLineEdit> #include <QLineEdit>
class QLabel; class QLabel;
class ScraperLineEdit : public QLineEdit class ScraperLineEdit : public QLineEdit
{ {
Q_OBJECT Q_OBJECT
public: public:
ScraperLineEdit(const QString & title, QWidget * widget = 0); ScraperLineEdit(const QString & title, QWidget * widget = 0);
protected: protected:
void resizeEvent(QResizeEvent *); void resizeEvent(QResizeEvent *);
private: private:
QLabel * titleLabel; QLabel * titleLabel;
}; };
#endif // SCRAPPER_LINEEDIT_H #endif // SCRAPPER_LINEEDIT_H

View File

@ -1,75 +1,75 @@
#include "scraper_results_paginator.h" #include "scraper_results_paginator.h"
#include "response_parser.h" #include "response_parser.h"
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QLabel> #include <QLabel>
#include <QToolButton> #include <QToolButton>
#include <QtScript> #include <QtScript>
ScraperResultsPaginator::ScraperResultsPaginator(QWidget *parent) : ScraperResultsPaginator::ScraperResultsPaginator(QWidget *parent) :
QWidget(parent),customLabel("items") QWidget(parent),customLabel("items")
{ {
QHBoxLayout * pagesButtonsLayout = new QHBoxLayout; QHBoxLayout * pagesButtonsLayout = new QHBoxLayout;
QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}"; QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}";
nextPage = new QToolButton; nextPage = new QToolButton;
nextPage->setStyleSheet("QToolButton {border:none;}"); nextPage->setStyleSheet("QToolButton {border:none;}");
QPixmap np(":/images/comic_vine/nextPage.png"); QPixmap np(":/images/comic_vine/nextPage.png");
nextPage->setIconSize(np.size()); nextPage->setIconSize(np.size());
nextPage->setIcon(np); nextPage->setIcon(np);
previousPage = new QToolButton; previousPage = new QToolButton;
previousPage->setStyleSheet("QToolButton {border:none;}"); previousPage->setStyleSheet("QToolButton {border:none;}");
QPixmap pp(":/images/comic_vine/previousPage.png"); QPixmap pp(":/images/comic_vine/previousPage.png");
previousPage->setIconSize(pp.size()); previousPage->setIconSize(pp.size());
previousPage->setIcon(pp); previousPage->setIcon(pp);
connect(nextPage,SIGNAL(clicked()),this,SIGNAL(loadNextPage())); connect(nextPage,SIGNAL(clicked()),this,SIGNAL(loadNextPage()));
connect(previousPage,SIGNAL(clicked()),this,SIGNAL(loadPreviousPage())); connect(previousPage,SIGNAL(clicked()),this,SIGNAL(loadPreviousPage()));
numElements = new QLabel(tr("Number of volumes found : %1")); numElements = new QLabel(tr("Number of volumes found : %1"));
numElements->setStyleSheet(labelStylesheet); numElements->setStyleSheet(labelStylesheet);
numPages = new QLabel(tr("page %1 of %2")); numPages = new QLabel(tr("page %1 of %2"));
numPages->setStyleSheet(labelStylesheet); numPages->setStyleSheet(labelStylesheet);
pagesButtonsLayout->addSpacing(15); pagesButtonsLayout->addSpacing(15);
pagesButtonsLayout->addWidget(numElements); pagesButtonsLayout->addWidget(numElements);
pagesButtonsLayout->addStretch(); pagesButtonsLayout->addStretch();
pagesButtonsLayout->addWidget(numPages); pagesButtonsLayout->addWidget(numPages);
pagesButtonsLayout->addWidget(previousPage); pagesButtonsLayout->addWidget(previousPage);
pagesButtonsLayout->addWidget(nextPage); pagesButtonsLayout->addWidget(nextPage);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
pagesButtonsLayout->setContentsMargins(0,0,0,0); pagesButtonsLayout->setContentsMargins(0,0,0,0);
setLayout(pagesButtonsLayout); setLayout(pagesButtonsLayout);
} }
void ScraperResultsPaginator::update(const QString &json) void ScraperResultsPaginator::update(const QString &json)
{ {
ResponseParser rp; ResponseParser rp;
rp.loadJSONResponse(json); rp.loadJSONResponse(json);
currentPage = rp.getCurrentPage(); currentPage = rp.getCurrentPage();
numElements->setText(tr("Number of %1 found : %2").arg(customLabel).arg(rp.getNumResults())); numElements->setText(tr("Number of %1 found : %2").arg(customLabel).arg(rp.getNumResults()));
numPages->setText(tr("page %1 of %2").arg(currentPage).arg(rp.getTotalPages())); numPages->setText(tr("page %1 of %2").arg(currentPage).arg(rp.getTotalPages()));
previousPage->setDisabled(currentPage == 1); previousPage->setDisabled(currentPage == 1);
nextPage->setDisabled(currentPage == rp.getTotalPages()); nextPage->setDisabled(currentPage == rp.getTotalPages());
numPages->setHidden(rp.getTotalPages()==1); numPages->setHidden(rp.getTotalPages()==1);
previousPage->setHidden(rp.getTotalPages()==1); previousPage->setHidden(rp.getTotalPages()==1);
nextPage->setHidden(rp.getTotalPages()==1); nextPage->setHidden(rp.getTotalPages()==1);
} }
int ScraperResultsPaginator::getCurrentPage() int ScraperResultsPaginator::getCurrentPage()
{ {
return currentPage; return currentPage;
} }
void ScraperResultsPaginator::setCustomLabel(const QString &label) void ScraperResultsPaginator::setCustomLabel(const QString &label)
{ {
customLabel = label; customLabel = label;
} }

View File

@ -1,34 +1,34 @@
#ifndef SCRAPER_RESULTS_PAGINATOR_H #ifndef SCRAPER_RESULTS_PAGINATOR_H
#define SCRAPER_RESULTS_PAGINATOR_H #define SCRAPER_RESULTS_PAGINATOR_H
#include <QWidget> #include <QWidget>
class QToolButton; class QToolButton;
class QLabel; class QLabel;
class ScraperResultsPaginator : public QWidget class ScraperResultsPaginator : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ScraperResultsPaginator(QWidget *parent = 0); explicit ScraperResultsPaginator(QWidget *parent = 0);
void update(const QString & json); void update(const QString & json);
int getCurrentPage(); int getCurrentPage();
void setCustomLabel(const QString & label); void setCustomLabel(const QString & label);
signals: signals:
void loadNextPage(); void loadNextPage();
void loadPreviousPage(); void loadPreviousPage();
public slots: public slots:
private: private:
QToolButton * nextPage; QToolButton * nextPage;
QToolButton * previousPage; QToolButton * previousPage;
QLabel * numElements; QLabel * numElements;
QLabel * numPages; QLabel * numPages;
int currentPage; int currentPage;
QString customLabel; QString customLabel;
}; };
#endif // SCRAPER_RESULTS_PAGINATOR_H #endif // SCRAPER_RESULTS_PAGINATOR_H

View File

@ -1,53 +1,53 @@
#include "scraper_scroll_label.h" #include "scraper_scroll_label.h"
#include <QLabel> #include <QLabel>
#include <QDesktopServices> #include <QDesktopServices>
#include <QUrl> #include <QUrl>
ScraperScrollLabel::ScraperScrollLabel(QWidget *parent) : ScraperScrollLabel::ScraperScrollLabel(QWidget *parent) :
QScrollArea(parent) QScrollArea(parent)
{ {
textLabel = new QLabel(this); textLabel = new QLabel(this);
textLabel->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }"); textLabel->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }");
textLabel->setWordWrap(true); textLabel->setWordWrap(true);
textLabel->setMinimumSize(168,12); textLabel->setMinimumSize(168,12);
setWidget(textLabel); setWidget(textLabel);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setStyleSheet( setStyleSheet(
"QScrollArea {background-color:#2B2B2B; border:none;}" "QScrollArea {background-color:#2B2B2B; border:none;}"
"QScrollBar:vertical { border: none; background: #2B2B2B; width: 3px; margin: 0; }" "QScrollBar:vertical { border: none; background: #2B2B2B; width: 3px; margin: 0; }"
"QScrollBar:horizontal { border: none; background: #2B2B2B; height: 3px; margin: 0; }" "QScrollBar:horizontal { border: none; background: #2B2B2B; height: 3px; margin: 0; }"
"QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }" "QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }"
"QScrollBar::handle:horizontal { background: #DDDDDD; width: 7px; min-height: 20px; }" "QScrollBar::handle:horizontal { background: #DDDDDD; width: 7px; min-height: 20px; }"
"QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::add-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 0 3px 0;}" "QScrollBar::add-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 0 3px 0;}"
"QScrollBar::sub-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 0 3px 0;}" "QScrollBar::sub-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 0 3px 0;}"
"QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}" "QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}"
"QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}" "QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {background: none; }" "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {background: none; }"
); );
connect(textLabel,SIGNAL(linkActivated(QString)),this,SLOT(openLink(QString))); connect(textLabel,SIGNAL(linkActivated(QString)),this,SLOT(openLink(QString)));
} }
void ScraperScrollLabel::setAltText(const QString &text) void ScraperScrollLabel::setAltText(const QString &text)
{ {
textLabel->setAlignment(Qt::AlignTop|Qt::AlignHCenter); textLabel->setAlignment(Qt::AlignTop|Qt::AlignHCenter);
textLabel->setText(text); textLabel->setText(text);
textLabel->adjustSize(); textLabel->adjustSize();
} }
void ScraperScrollLabel::setText(const QString &text) void ScraperScrollLabel::setText(const QString &text)
{ {
textLabel->setAlignment(Qt::AlignTop|Qt::AlignLeft); textLabel->setAlignment(Qt::AlignTop|Qt::AlignLeft);
textLabel->setText(text); textLabel->setText(text);
textLabel->adjustSize(); textLabel->adjustSize();
} }
void ScraperScrollLabel::openLink(const QString & link) void ScraperScrollLabel::openLink(const QString & link)
{ {
QDesktopServices::openUrl(QUrl("http://www.comicvine.com"+link)); QDesktopServices::openUrl(QUrl("http://www.comicvine.com"+link));
} }

View File

@ -1,25 +1,25 @@
#ifndef SCRAPER_SCROLL_LABEL_H #ifndef SCRAPER_SCROLL_LABEL_H
#define SCRAPER_SCROLL_LABEL_H #define SCRAPER_SCROLL_LABEL_H
#include <QScrollArea> #include <QScrollArea>
class QLabel; class QLabel;
class ScraperScrollLabel : public QScrollArea class ScraperScrollLabel : public QScrollArea
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ScraperScrollLabel(QWidget *parent = 0); explicit ScraperScrollLabel(QWidget *parent = 0);
signals: signals:
public slots: public slots:
void setText(const QString & text); void setText(const QString & text);
void setAltText(const QString &text); void setAltText(const QString &text);
void openLink(const QString &link); void openLink(const QString &link);
private: private:
QLabel * textLabel; QLabel * textLabel;
}; };
#endif // SCRAPER_SCROLL_LABEL_H #endif // SCRAPER_SCROLL_LABEL_H

View File

@ -1,25 +1,25 @@
#include "scraper_selector.h" #include "scraper_selector.h"
ScraperSelector::ScraperSelector(QWidget *parent) : ScraperSelector::ScraperSelector(QWidget *parent) :
QWidget(parent) QWidget(parent)
{ {
paginator = new ScraperResultsPaginator; paginator = new ScraperResultsPaginator;
connect(paginator,SIGNAL(loadNextPage()),this,SLOT(loadNextPage())); connect(paginator,SIGNAL(loadNextPage()),this,SLOT(loadNextPage()));
connect(paginator,SIGNAL(loadPreviousPage()),this,SLOT(loadPreviousPage())); connect(paginator,SIGNAL(loadPreviousPage()),this,SLOT(loadPreviousPage()));
} }
void ScraperSelector::load(const QString &json, const QString &searchString) void ScraperSelector::load(const QString &json, const QString &searchString)
{ {
currentSearchString = searchString; currentSearchString = searchString;
paginator->update(json); paginator->update(json);
} }
void ScraperSelector::loadNextPage() void ScraperSelector::loadNextPage()
{ {
emit loadPage(currentSearchString,paginator->getCurrentPage()+1); emit loadPage(currentSearchString,paginator->getCurrentPage()+1);
} }
void ScraperSelector::loadPreviousPage() void ScraperSelector::loadPreviousPage()
{ {
emit loadPage(currentSearchString,paginator->getCurrentPage()-1); emit loadPage(currentSearchString,paginator->getCurrentPage()-1);
} }

View File

@ -1,28 +1,28 @@
#ifndef SCRAPER_SELECTOR_H #ifndef SCRAPER_SELECTOR_H
#define SCRAPER_SELECTOR_H #define SCRAPER_SELECTOR_H
#include <QWidget> #include <QWidget>
#include "scraper_results_paginator.h" #include "scraper_results_paginator.h"
class ScraperSelector : public QWidget class ScraperSelector : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ScraperSelector(QWidget *parent = 0); explicit ScraperSelector(QWidget *parent = 0);
virtual void load(const QString & json, const QString & searchString); virtual void load(const QString & json, const QString & searchString);
public slots: public slots:
signals: signals:
void loadPage(QString,int); void loadPage(QString,int);
private slots: private slots:
void loadNextPage(); void loadNextPage();
void loadPreviousPage(); void loadPreviousPage();
protected: protected:
QString currentSearchString; QString currentSearchString;
ScraperResultsPaginator * paginator; ScraperResultsPaginator * paginator;
}; };
#endif // SCRAPER_SELECTOR_H #endif // SCRAPER_SELECTOR_H

View File

@ -1,60 +1,60 @@
#include "scraper_tableview.h" #include "scraper_tableview.h"
#include <QHeaderView> #include <QHeaderView>
ScraperTableView::ScraperTableView(QWidget *parent) : ScraperTableView::ScraperTableView(QWidget *parent) :
QTableView(parent) QTableView(parent)
{ {
QString tableStylesheet = "QTableView {color:white; border:0px;alternate-background-color: #2E2E2E;background-color: #2B2B2B; outline: 0px;}" QString tableStylesheet = "QTableView {color:white; border:0px;alternate-background-color: #2E2E2E;background-color: #2B2B2B; outline: 0px;}"
"QTableView::item {outline: 0px; border: 0px; color:#FFFFFF;}" "QTableView::item {outline: 0px; border: 0px; color:#FFFFFF;}"
"QTableView::item:selected {outline: 0px; background-color: #555555; }" "QTableView::item:selected {outline: 0px; background-color: #555555; }"
"QHeaderView::section:horizontal {background-color:#292929; border-bottom:1px solid #1F1F1F; border-right:1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #292929, stop: 1 #1F1F1F); border-left:none; border-top:none; padding:4px; color:#ebebeb;}" "QHeaderView::section:horizontal {background-color:#292929; border-bottom:1px solid #1F1F1F; border-right:1px solid qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #292929, stop: 1 #1F1F1F); border-left:none; border-top:none; padding:4px; color:#ebebeb;}"
"QHeaderView::section:vertical {border-bottom: 1px solid #DFDFDF;border-top: 1px solid #FEFEFE;}" "QHeaderView::section:vertical {border-bottom: 1px solid #DFDFDF;border-top: 1px solid #FEFEFE;}"
"QHeaderView::down-arrow {image: url(':/images/comic_vine/downArrow.png');}" "QHeaderView::down-arrow {image: url(':/images/comic_vine/downArrow.png');}"
"QHeaderView::up-arrow {image: url(':/images/comic_vine/upArrow.png');}" "QHeaderView::up-arrow {image: url(':/images/comic_vine/upArrow.png');}"
"QScrollBar:vertical { border: none; background: #2B2B2B; width: 3px; margin: 0; }" "QScrollBar:vertical { border: none; background: #2B2B2B; width: 3px; margin: 0; }"
"QScrollBar:horizontal { border: none; background: #2B2B2B; height: 3px; margin: 0; }" "QScrollBar:horizontal { border: none; background: #2B2B2B; height: 3px; margin: 0; }"
"QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }" "QScrollBar::handle:vertical { background: #DDDDDD; width: 7px; min-height: 20px; }"
"QScrollBar::handle:horizontal { background: #DDDDDD; width: 7px; min-height: 20px; }" "QScrollBar::handle:horizontal { background: #DDDDDD; width: 7px; min-height: 20px; }"
"QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::add-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}" "QScrollBar::sub-line:vertical { border: none; background: #404040; height: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 3px 0 0;}"
"QScrollBar::add-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 0 3px 0;}" "QScrollBar::add-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: bottom; subcontrol-origin: margin; margin: 0 0 3px 0;}"
"QScrollBar::sub-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 0 3px 0;}" "QScrollBar::sub-line:horizontal { border: none; background: #404040; width: 10px; subcontrol-position: top; subcontrol-origin: margin; margin: 0 0 3px 0;}"
"QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}" "QScrollBar::up-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-up.png') center top no-repeat;}"
"QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}" "QScrollBar::down-arrow:vertical {border:none;width: 9px;height: 6px;background: url(':/images/folders_view/line-down.png') center top no-repeat;}"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {background: none; }"; "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {background: none; }";
setStyleSheet(tableStylesheet); setStyleSheet(tableStylesheet);
setShowGrid(false); setShowGrid(false);
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
#else #else
verticalHeader()->setResizeMode(QHeaderView::Fixed); verticalHeader()->setResizeMode(QHeaderView::Fixed);
#endif #endif
horizontalHeader()->setStretchLastSection(true); horizontalHeader()->setStretchLastSection(true);
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
horizontalHeader()->setSectionsClickable(false); horizontalHeader()->setSectionsClickable(false);
#else #else
horizontalHeader()->setClickable(false); horizontalHeader()->setClickable(false);
#endif #endif
//comicView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); //comicView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
verticalHeader()->setDefaultSectionSize(24); verticalHeader()->setDefaultSectionSize(24);
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
verticalHeader()->setSectionsClickable(false); //TODO comportamiento anómalo verticalHeader()->setSectionsClickable(false); //TODO comportamiento anómalo
#else #else
verticalHeader()->setClickable(false); //TODO comportamiento anómalo verticalHeader()->setClickable(false); //TODO comportamiento anómalo
#endif #endif
setCornerButtonEnabled(false); setCornerButtonEnabled(false);
setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection); setSelectionMode(QAbstractItemView::ExtendedSelection);
setAlternatingRowColors(true); setAlternatingRowColors(true);
verticalHeader()->hide(); verticalHeader()->hide();
setSelectionMode(QAbstractItemView::SingleSelection); setSelectionMode(QAbstractItemView::SingleSelection);
} }

View File

@ -1,18 +1,18 @@
#ifndef SCRAPPER_TABLEVIEW_H #ifndef SCRAPPER_TABLEVIEW_H
#define SCRAPPER_TABLEVIEW_H #define SCRAPPER_TABLEVIEW_H
#include <QTableView> #include <QTableView>
class ScraperTableView : public QTableView class ScraperTableView : public QTableView
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ScraperTableView(QWidget *parent = 0); explicit ScraperTableView(QWidget *parent = 0);
signals: signals:
public slots: public slots:
}; };
#endif // SCRAPPER_TABLEVIEW_H #endif // SCRAPPER_TABLEVIEW_H

View File

@ -1,62 +1,62 @@
#include "search_single_comic.h" #include "search_single_comic.h"
#include "scraper_lineedit.h" #include "scraper_lineedit.h"
#include <QLabel> #include <QLabel>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
SearchSingleComic::SearchSingleComic(QWidget * parent) SearchSingleComic::SearchSingleComic(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
//QLabel * label = new QLabel(tr("Please provide some additional information. At least one field is needed.")); //QLabel * label = new QLabel(tr("Please provide some additional information. At least one field is needed."));
QLabel * label = new QLabel(tr("Please provide some additional information.")); QLabel * label = new QLabel(tr("Please provide some additional information."));
label->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}"); label->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}");
//titleEdit = new ScraperLineEdit(tr("Title:")); //titleEdit = new ScraperLineEdit(tr("Title:"));
//numberEdit = new ScraperLineEdit(tr("Number:")); //numberEdit = new ScraperLineEdit(tr("Number:"));
volumeEdit = new ScraperLineEdit(tr("Series:")); volumeEdit = new ScraperLineEdit(tr("Series:"));
//numberEdit->setMaximumWidth(126); //numberEdit->setMaximumWidth(126);
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
//QHBoxLayout * hl = new QHBoxLayout; //QHBoxLayout * hl = new QHBoxLayout;
//hl->addWidget(titleEdit); //hl->addWidget(titleEdit);
//hl->addWidget(numberEdit); //hl->addWidget(numberEdit);
l->addSpacing(35); l->addSpacing(35);
l->addWidget(label); l->addWidget(label);
//l->addLayout(hl); //l->addLayout(hl);
l->addWidget(volumeEdit); l->addWidget(volumeEdit);
l->addStretch(); l->addStretch();
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
} }
QString SearchSingleComic::getVolumeInfo() QString SearchSingleComic::getVolumeInfo()
{ {
return volumeEdit->text(); return volumeEdit->text();
} }
QString SearchSingleComic::getComicInfo() QString SearchSingleComic::getComicInfo()
{ {
//return titleEdit->text(); //return titleEdit->text();
return ""; return "";
} }
int SearchSingleComic::getComicNumber() int SearchSingleComic::getComicNumber()
{ {
//QString numberText = numberEdit->text(); //QString numberText = numberEdit->text();
//if(numberText.isEmpty()) //if(numberText.isEmpty())
// return -1; // return -1;
//return numberText.toInt(); //return numberText.toInt();
return 0; return 0;
} }
void SearchSingleComic::clean() void SearchSingleComic::clean()
{ {
volumeEdit->clear(); volumeEdit->clear();
} }

View File

@ -1,22 +1,22 @@
#ifndef SEARCH_SINGLE_COMIC_H #ifndef SEARCH_SINGLE_COMIC_H
#define SEARCH_SINGLE_COMIC_H #define SEARCH_SINGLE_COMIC_H
#include <QWidget> #include <QWidget>
class ScraperLineEdit; class ScraperLineEdit;
class SearchSingleComic : public QWidget class SearchSingleComic : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
SearchSingleComic(QWidget * parent = 0); SearchSingleComic(QWidget * parent = 0);
QString getVolumeInfo(); QString getVolumeInfo();
QString getComicInfo(); QString getComicInfo();
int getComicNumber(); int getComicNumber();
void clean(); void clean();
private: private:
ScraperLineEdit * titleEdit; ScraperLineEdit * titleEdit;
ScraperLineEdit * numberEdit; ScraperLineEdit * numberEdit;
ScraperLineEdit * volumeEdit; ScraperLineEdit * volumeEdit;
}; };
#endif // SEARCH_SINGLE_COMIC_H #endif // SEARCH_SINGLE_COMIC_H

View File

@ -1,36 +1,36 @@
#include "search_volume.h" #include "search_volume.h"
#include "scraper_lineedit.h" #include "scraper_lineedit.h"
#include <QLabel> #include <QLabel>
#include <QVBoxLayout> #include <QVBoxLayout>
SearchVolume::SearchVolume(QWidget * parent) SearchVolume::SearchVolume(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
QLabel * label = new QLabel(tr("Please provide some additional information.")); QLabel * label = new QLabel(tr("Please provide some additional information."));
label->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}"); label->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}");
volumeEdit = new ScraperLineEdit(tr("Series:")); volumeEdit = new ScraperLineEdit(tr("Series:"));
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
l->addSpacing(35); l->addSpacing(35);
l->addWidget(label); l->addWidget(label);
l->addWidget(volumeEdit); l->addWidget(volumeEdit);
l->addStretch(); l->addStretch();
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
} }
void SearchVolume::clean() void SearchVolume::clean()
{ {
volumeEdit->clear(); volumeEdit->clear();
} }
QString SearchVolume::getVolumeInfo() QString SearchVolume::getVolumeInfo()
{ {
return volumeEdit->text(); return volumeEdit->text();
} }

View File

@ -1,21 +1,21 @@
#ifndef SEARCH_VOLUME_H #ifndef SEARCH_VOLUME_H
#define SEARCH_VOLUME_H #define SEARCH_VOLUME_H
#include <QWidget> #include <QWidget>
class ScraperLineEdit; class ScraperLineEdit;
class SearchVolume : public QWidget class SearchVolume : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
SearchVolume(QWidget * parent = 0); SearchVolume(QWidget * parent = 0);
void clean(); void clean();
public slots: public slots:
QString getVolumeInfo(); QString getVolumeInfo();
private: private:
ScraperLineEdit * volumeEdit; ScraperLineEdit * volumeEdit;
}; };
#endif // SEARCH_VOLUME_H #endif // SEARCH_VOLUME_H

View File

@ -1,144 +1,144 @@
#include "select_comic.h" #include "select_comic.h"
#include "comic_vine_client.h" #include "comic_vine_client.h"
#include "scraper_scroll_label.h" #include "scraper_scroll_label.h"
#include "scraper_tableview.h" #include "scraper_tableview.h"
#include "volume_comics_model.h" #include "volume_comics_model.h"
#include <QLabel> #include <QLabel>
#include <QLayout> #include <QLayout>
#include <QtScript> #include <QtScript>
SelectComic::SelectComic(QWidget *parent) SelectComic::SelectComic(QWidget *parent)
:ScraperSelector(parent),model(0) :ScraperSelector(parent),model(0)
{ {
QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}"; QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}";
QLabel * label = new QLabel(tr("Please, select the right comic info.")); QLabel * label = new QLabel(tr("Please, select the right comic info."));
label->setStyleSheet(labelStylesheet); label->setStyleSheet(labelStylesheet);
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
QWidget * leftWidget = new QWidget; QWidget * leftWidget = new QWidget;
QVBoxLayout * left = new QVBoxLayout; QVBoxLayout * left = new QVBoxLayout;
QGridLayout * content = new QGridLayout; QGridLayout * content = new QGridLayout;
//widgets //widgets
cover = new QLabel(); cover = new QLabel();
cover->setScaledContents(true); cover->setScaledContents(true);
cover->setAlignment(Qt::AlignTop|Qt::AlignHCenter); cover->setAlignment(Qt::AlignTop|Qt::AlignHCenter);
cover->setMinimumSize(168,168*5.0/3); cover->setMinimumSize(168,168*5.0/3);
cover->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }"); cover->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }");
detailLabel = new ScraperScrollLabel(this); detailLabel = new ScraperScrollLabel(this);
tableComics = new ScraperTableView(this); tableComics = new ScraperTableView(this);
//connections //connections
connect(tableComics,SIGNAL(clicked(QModelIndex)),this,SLOT(loadComicInfo(QModelIndex))); connect(tableComics,SIGNAL(clicked(QModelIndex)),this,SLOT(loadComicInfo(QModelIndex)));
paginator->setCustomLabel(tr("comics")); paginator->setCustomLabel(tr("comics"));
left->addWidget(cover); left->addWidget(cover);
left->addWidget(detailLabel,1); left->addWidget(detailLabel,1);
leftWidget->setMaximumWidth(180); leftWidget->setMaximumWidth(180);
leftWidget->setLayout(left); leftWidget->setLayout(left);
left->setContentsMargins(0,0,0,0); left->setContentsMargins(0,0,0,0);
leftWidget->setContentsMargins(0,0,0,0); leftWidget->setContentsMargins(0,0,0,0);
content->addWidget(leftWidget, 0, 0); content->addWidget(leftWidget, 0, 0);
content->addWidget(tableComics, 0, 1); content->addWidget(tableComics, 0, 1);
content->addWidget(paginator, 1, 1); content->addWidget(paginator, 1, 1);
content->setColumnStretch(1, 1); content->setColumnStretch(1, 1);
content->setRowStretch(0, 1);; content->setRowStretch(0, 1);;
l->addSpacing(15); l->addSpacing(15);
l->addWidget(label); l->addWidget(label);
l->addSpacing(5); l->addSpacing(5);
l->addLayout(content); l->addLayout(content);
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
} }
void SelectComic::load(const QString &json, const QString & searchString) void SelectComic::load(const QString &json, const QString & searchString)
{ {
VolumeComicsModel * tempM = new VolumeComicsModel(); VolumeComicsModel * tempM = new VolumeComicsModel();
tempM->load(json); tempM->load(json);
tableComics->setModel(tempM); tableComics->setModel(tempM);
if(model != 0) if(model != 0)
delete model; delete model;
model = tempM; model = tempM;
if(model->rowCount()>0) if(model->rowCount()>0)
{ {
tableComics->selectRow(0); tableComics->selectRow(0);
loadComicInfo(model->index(0,0)); loadComicInfo(model->index(0,0));
} }
tableComics->resizeColumnToContents(0); tableComics->resizeColumnToContents(0);
ScraperSelector::load(json,searchString); ScraperSelector::load(json,searchString);
} }
SelectComic::~SelectComic() {} SelectComic::~SelectComic() {}
void SelectComic::loadComicInfo(const QModelIndex &mi) void SelectComic::loadComicInfo(const QModelIndex &mi)
{ {
QString coverURL = model->getCoverURL(mi); QString coverURL = model->getCoverURL(mi);
QString id = model->getComicId(mi); QString id = model->getComicId(mi);
QString loadingStyle = "<font color='#AAAAAA'>%1</font>"; QString loadingStyle = "<font color='#AAAAAA'>%1</font>";
cover->setText(loadingStyle.arg(tr("loading cover"))); cover->setText(loadingStyle.arg(tr("loading cover")));
detailLabel->setAltText(loadingStyle.arg(tr("loading description"))); detailLabel->setAltText(loadingStyle.arg(tr("loading description")));
ComicVineClient * comicVineClient = new ComicVineClient; ComicVineClient * comicVineClient = new ComicVineClient;
connect(comicVineClient,SIGNAL(comicCover(const QByteArray &)),this,SLOT(setCover(const QByteArray &))); connect(comicVineClient,SIGNAL(comicCover(const QByteArray &)),this,SLOT(setCover(const QByteArray &)));
connect(comicVineClient,SIGNAL(finished()),comicVineClient,SLOT(deleteLater())); connect(comicVineClient,SIGNAL(finished()),comicVineClient,SLOT(deleteLater()));
comicVineClient->getComicCover(coverURL); comicVineClient->getComicCover(coverURL);
ComicVineClient * comicVineClient2 = new ComicVineClient; ComicVineClient * comicVineClient2 = new ComicVineClient;
connect(comicVineClient2,SIGNAL(comicDetail(QString)),this,SLOT(setDescription(QString))); connect(comicVineClient2,SIGNAL(comicDetail(QString)),this,SLOT(setDescription(QString)));
connect(comicVineClient2,SIGNAL(finished()),comicVineClient2,SLOT(deleteLater())); connect(comicVineClient2,SIGNAL(finished()),comicVineClient2,SLOT(deleteLater()));
comicVineClient2->getComicDetailAsync(id); comicVineClient2->getComicDetailAsync(id);
} }
void SelectComic::setCover(const QByteArray & data) void SelectComic::setCover(const QByteArray & data)
{ {
QPixmap p; QPixmap p;
p.loadFromData(data); p.loadFromData(data);
int w = p.width(); int w = p.width();
int h = p.height(); int h = p.height();
cover->setPixmap(p); cover->setPixmap(p);
float aspectRatio = static_cast<float>(w)/h; float aspectRatio = static_cast<float>(w)/h;
cover->setFixedSize(180,static_cast<int>(180/aspectRatio)); cover->setFixedSize(180,static_cast<int>(180/aspectRatio));
cover->update(); cover->update();
} }
void SelectComic::setDescription(const QString &jsonDetail) void SelectComic::setDescription(const QString &jsonDetail)
{ {
QScriptEngine engine; QScriptEngine engine;
QScriptValue sc; QScriptValue sc;
sc = engine.evaluate("(" + jsonDetail + ")"); sc = engine.evaluate("(" + jsonDetail + ")");
if (!sc.property("error").isValid() && sc.property("error").toString() != "OK") if (!sc.property("error").isValid() && sc.property("error").toString() != "OK")
{ {
qDebug("Error detected"); qDebug("Error detected");
} }
else else
{ {
QScriptValue descriptionValues = sc.property("results").property("description"); QScriptValue descriptionValues = sc.property("results").property("description");
bool valid = !descriptionValues.isNull() && descriptionValues.isValid(); bool valid = !descriptionValues.isNull() && descriptionValues.isValid();
detailLabel->setText(valid?descriptionValues.toString().replace("<a","<a style = 'color:#827A68; text-decoration:none;'"):tr("description unavailable")); detailLabel->setText(valid?descriptionValues.toString().replace("<a","<a style = 'color:#827A68; text-decoration:none;'"):tr("description unavailable"));
} }
} }
QString SelectComic::getSelectedComicId() QString SelectComic::getSelectedComicId()
{ {
return model->getComicId(tableComics->currentIndex()); return model->getComicId(tableComics->currentIndex());
} }

View File

@ -1,34 +1,34 @@
#ifndef SELECT_COMIC_H #ifndef SELECT_COMIC_H
#define SELECT_COMIC_H #define SELECT_COMIC_H
#include "scraper_selector.h" #include "scraper_selector.h"
class QLabel; class QLabel;
class VolumeComicsModel; class VolumeComicsModel;
class QModelIndex; class QModelIndex;
class ScraperScrollLabel; class ScraperScrollLabel;
class ScraperTableView; class ScraperTableView;
class SelectComic : public ScraperSelector class SelectComic : public ScraperSelector
{ {
Q_OBJECT Q_OBJECT
public: public:
SelectComic(QWidget * parent = 0); SelectComic(QWidget * parent = 0);
void load(const QString & json, const QString & searchString); void load(const QString & json, const QString & searchString);
virtual ~SelectComic(); virtual ~SelectComic();
public slots: public slots:
void loadComicInfo(const QModelIndex & mi); void loadComicInfo(const QModelIndex & mi);
void setCover(const QByteArray &); void setCover(const QByteArray &);
void setDescription(const QString & jsonDetail); void setDescription(const QString & jsonDetail);
QString getSelectedComicId(); QString getSelectedComicId();
private: private:
QLabel * cover; QLabel * cover;
ScraperScrollLabel * detailLabel; ScraperScrollLabel * detailLabel;
ScraperTableView * tableComics; ScraperTableView * tableComics;
VolumeComicsModel * model; VolumeComicsModel * model;
}; };
#endif // SELECT_COMIC_H #endif // SELECT_COMIC_H

View File

@ -1,185 +1,185 @@
#include "select_volume.h" #include "select_volume.h"
#include <QLabel> #include <QLabel>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QScrollBar> #include <QScrollBar>
#include <QModelIndex> #include <QModelIndex>
#include <QScrollArea> #include <QScrollArea>
#include <QDesktopServices> #include <QDesktopServices>
#include <QHeaderView> #include <QHeaderView>
#include <QToolButton> #include <QToolButton>
#include <QSortFilterProxyModel> #include <QSortFilterProxyModel>
#include "scraper_tableview.h" #include "scraper_tableview.h"
#include <QtScript> #include <QtScript>
#include "volumes_model.h" #include "volumes_model.h"
#include "comic_vine_client.h" #include "comic_vine_client.h"
#include "scraper_scroll_label.h" #include "scraper_scroll_label.h"
#include "response_parser.h" #include "response_parser.h"
#include "scraper_results_paginator.h" #include "scraper_results_paginator.h"
SelectVolume::SelectVolume(QWidget *parent) SelectVolume::SelectVolume(QWidget *parent)
:ScraperSelector(parent),model(0) :ScraperSelector(parent),model(0)
{ {
proxyModel = new QSortFilterProxyModel; proxyModel = new QSortFilterProxyModel;
QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}"; QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}";
QLabel * label = new QLabel(tr("Please, select the right series for your comic.")); QLabel * label = new QLabel(tr("Please, select the right series for your comic."));
label->setStyleSheet(labelStylesheet); label->setStyleSheet(labelStylesheet);
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
QWidget * leftWidget = new QWidget; QWidget * leftWidget = new QWidget;
QVBoxLayout * left = new QVBoxLayout; QVBoxLayout * left = new QVBoxLayout;
QGridLayout * content = new QGridLayout; QGridLayout * content = new QGridLayout;
//widgets //widgets
cover = new QLabel(); cover = new QLabel();
cover->setScaledContents(true); cover->setScaledContents(true);
cover->setAlignment(Qt::AlignTop|Qt::AlignHCenter); cover->setAlignment(Qt::AlignTop|Qt::AlignHCenter);
cover->setMinimumSize(168,168*5.0/3); cover->setMinimumSize(168,168*5.0/3);
cover->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }"); cover->setStyleSheet("QLabel {background-color: #2B2B2B; color:white; font-size:12px; font-family:Arial; }");
detailLabel = new ScraperScrollLabel(); detailLabel = new ScraperScrollLabel();
tableVolumes = new ScraperTableView(); tableVolumes = new ScraperTableView();
tableVolumes->setSortingEnabled(true); tableVolumes->setSortingEnabled(true);
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
tableVolumes->horizontalHeader()->setSectionsClickable(true); tableVolumes->horizontalHeader()->setSectionsClickable(true);
#else #else
tableVolumes->horizontalHeader()->setClickable(true); tableVolumes->horizontalHeader()->setClickable(true);
#endif #endif
//tableVolumes->horizontalHeader()->setSortIndicatorShown(false); //tableVolumes->horizontalHeader()->setSortIndicatorShown(false);
connect(tableVolumes->horizontalHeader(),SIGNAL(sectionClicked(int)), tableVolumes, SLOT(sortByColumn(int))); connect(tableVolumes->horizontalHeader(),SIGNAL(sectionClicked(int)), tableVolumes, SLOT(sortByColumn(int)));
//connections //connections
connect(tableVolumes,SIGNAL(clicked(QModelIndex)),this,SLOT(loadVolumeInfo(QModelIndex))); connect(tableVolumes,SIGNAL(clicked(QModelIndex)),this,SLOT(loadVolumeInfo(QModelIndex)));
paginator->setCustomLabel(tr("volumes")); paginator->setCustomLabel(tr("volumes"));
left->addWidget(cover); left->addWidget(cover);
left->addWidget(detailLabel,1); left->addWidget(detailLabel,1);
leftWidget->setMaximumWidth(180); leftWidget->setMaximumWidth(180);
leftWidget->setLayout(left); leftWidget->setLayout(left);
left->setContentsMargins(0,0,0,0); left->setContentsMargins(0,0,0,0);
leftWidget->setContentsMargins(0,0,0,0); leftWidget->setContentsMargins(0,0,0,0);
content->addWidget(leftWidget, 0, 0); content->addWidget(leftWidget, 0, 0);
content->addWidget(tableVolumes, 0, 1); content->addWidget(tableVolumes, 0, 1);
content->addWidget(paginator, 1, 1); content->addWidget(paginator, 1, 1);
content->setColumnStretch(1, 1); content->setColumnStretch(1, 1);
content->setRowStretch(0, 1); content->setRowStretch(0, 1);
l->addSpacing(15); l->addSpacing(15);
l->addWidget(label); l->addWidget(label);
l->addSpacing(5); l->addSpacing(5);
l->addLayout(content); l->addLayout(content);
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
} }
void SelectVolume::load(const QString & json, const QString & searchString) void SelectVolume::load(const QString & json, const QString & searchString)
{ {
VolumesModel * tempM = new VolumesModel(); VolumesModel * tempM = new VolumesModel();
tempM->load(json); tempM->load(json);
//tableVolumes->setModel(tempM); //tableVolumes->setModel(tempM);
proxyModel->setSourceModel( tempM ); proxyModel->setSourceModel( tempM );
tableVolumes->setModel(proxyModel); tableVolumes->setModel(proxyModel);
tableVolumes->sortByColumn(0,Qt::AscendingOrder); tableVolumes->sortByColumn(0,Qt::AscendingOrder);
tableVolumes->resizeColumnsToContents(); tableVolumes->resizeColumnsToContents();
if(model != 0) if(model != 0)
delete model; delete model;
model = tempM; model = tempM;
if(model->rowCount()>0) if(model->rowCount()>0)
{ {
tableVolumes->selectRow(0); tableVolumes->selectRow(0);
loadVolumeInfo(proxyModel->index(0,0)); loadVolumeInfo(proxyModel->index(0,0));
} }
tableVolumes->setColumnWidth(0,350); tableVolumes->setColumnWidth(0,350);
ScraperSelector::load(json,searchString); ScraperSelector::load(json,searchString);
} }
SelectVolume::~SelectVolume() {} SelectVolume::~SelectVolume() {}
void SelectVolume::loadVolumeInfo(const QModelIndex & omi) void SelectVolume::loadVolumeInfo(const QModelIndex & omi)
{ {
QModelIndex mi = proxyModel->mapToSource(omi); QModelIndex mi = proxyModel->mapToSource(omi);
QString coverURL = model->getCoverURL(mi); QString coverURL = model->getCoverURL(mi);
QString id = model->getVolumeId(mi); QString id = model->getVolumeId(mi);
QString loadingStyle = "<font color='#AAAAAA'>%1</font>"; QString loadingStyle = "<font color='#AAAAAA'>%1</font>";
cover->setText(loadingStyle.arg(tr("loading cover"))); cover->setText(loadingStyle.arg(tr("loading cover")));
detailLabel->setAltText(loadingStyle.arg(tr("loading description"))); detailLabel->setAltText(loadingStyle.arg(tr("loading description")));
ComicVineClient * comicVineClient = new ComicVineClient; ComicVineClient * comicVineClient = new ComicVineClient;
connect(comicVineClient,SIGNAL(seriesCover(const QByteArray &)),this,SLOT(setCover(const QByteArray &))); connect(comicVineClient,SIGNAL(seriesCover(const QByteArray &)),this,SLOT(setCover(const QByteArray &)));
connect(comicVineClient,SIGNAL(finished()),comicVineClient,SLOT(deleteLater())); connect(comicVineClient,SIGNAL(finished()),comicVineClient,SLOT(deleteLater()));
comicVineClient->getSeriesCover(coverURL); comicVineClient->getSeriesCover(coverURL);
ComicVineClient * comicVineClient2 = new ComicVineClient; ComicVineClient * comicVineClient2 = new ComicVineClient;
connect(comicVineClient2,SIGNAL(seriesDetail(QString)),this,SLOT(setDescription(QString))); connect(comicVineClient2,SIGNAL(seriesDetail(QString)),this,SLOT(setDescription(QString)));
connect(comicVineClient2,SIGNAL(finished()),comicVineClient2,SLOT(deleteLater())); connect(comicVineClient2,SIGNAL(finished()),comicVineClient2,SLOT(deleteLater()));
comicVineClient2->getSeriesDetail(id); comicVineClient2->getSeriesDetail(id);
} }
void SelectVolume::setCover(const QByteArray & data) void SelectVolume::setCover(const QByteArray & data)
{ {
QPixmap p; QPixmap p;
p.loadFromData(data); p.loadFromData(data);
int w = p.width(); int w = p.width();
int h = p.height(); int h = p.height();
cover->setPixmap(p); cover->setPixmap(p);
float aspectRatio = static_cast<float>(w)/h; float aspectRatio = static_cast<float>(w)/h;
cover->setFixedSize(180,static_cast<int>(180/aspectRatio)); cover->setFixedSize(180,static_cast<int>(180/aspectRatio));
cover->update(); cover->update();
} }
void SelectVolume::setDescription(const QString & jsonDetail) void SelectVolume::setDescription(const QString & jsonDetail)
{ {
QScriptEngine engine; QScriptEngine engine;
QScriptValue sc; QScriptValue sc;
sc = engine.evaluate("(" + jsonDetail + ")"); sc = engine.evaluate("(" + jsonDetail + ")");
if (!sc.property("error").isValid() && sc.property("error").toString() != "OK") if (!sc.property("error").isValid() && sc.property("error").toString() != "OK")
{ {
qDebug("Error detected"); qDebug("Error detected");
} }
else else
{ {
QScriptValue descriptionValues = sc.property("results").property("description"); QScriptValue descriptionValues = sc.property("results").property("description");
bool valid = !descriptionValues.isNull() && descriptionValues.isValid(); bool valid = !descriptionValues.isNull() && descriptionValues.isValid();
detailLabel->setText(valid?descriptionValues.toString().replace("<a","<a style = 'color:#827A68; text-decoration:none;'"):tr("description unavailable")); detailLabel->setText(valid?descriptionValues.toString().replace("<a","<a style = 'color:#827A68; text-decoration:none;'"):tr("description unavailable"));
} }
} }
QString SelectVolume::getSelectedVolumeId() QString SelectVolume::getSelectedVolumeId()
{ {
return model->getVolumeId(proxyModel->mapToSource(tableVolumes->currentIndex())); return model->getVolumeId(proxyModel->mapToSource(tableVolumes->currentIndex()));
} }
int SelectVolume::getSelectedVolumeNumIssues() int SelectVolume::getSelectedVolumeNumIssues()
{ {
return model->getNumIssues(proxyModel->mapToSource(tableVolumes->currentIndex())); return model->getNumIssues(proxyModel->mapToSource(tableVolumes->currentIndex()));
} }
QString SelectVolume::getSelectedVolumePublisher() QString SelectVolume::getSelectedVolumePublisher()
{ {
return model->getPublisher(proxyModel->mapToSource(tableVolumes->currentIndex())); return model->getPublisher(proxyModel->mapToSource(tableVolumes->currentIndex()));
} }

View File

@ -1,39 +1,39 @@
#ifndef SELECT_VOLUME_H #ifndef SELECT_VOLUME_H
#define SELECT_VOLUME_H #define SELECT_VOLUME_H
#include "scraper_selector.h" #include "scraper_selector.h"
class QLabel; class QLabel;
class VolumesModel; class VolumesModel;
class QModelIndex; class QModelIndex;
class QToolButton; class QToolButton;
class QSortFilterProxyModel; class QSortFilterProxyModel;
class ScraperScrollLabel; class ScraperScrollLabel;
class ScraperTableView; class ScraperTableView;
class SelectVolume : public ScraperSelector class SelectVolume : public ScraperSelector
{ {
Q_OBJECT Q_OBJECT
public: public:
SelectVolume(QWidget * parent = 0); SelectVolume(QWidget * parent = 0);
void load(const QString & json, const QString & searchString); void load(const QString & json, const QString & searchString);
virtual ~SelectVolume(); virtual ~SelectVolume();
public slots: public slots:
void loadVolumeInfo(const QModelIndex & mi); void loadVolumeInfo(const QModelIndex & mi);
void setCover(const QByteArray &); void setCover(const QByteArray &);
void setDescription(const QString & jsonDetail); void setDescription(const QString & jsonDetail);
QString getSelectedVolumeId(); QString getSelectedVolumeId();
int getSelectedVolumeNumIssues(); int getSelectedVolumeNumIssues();
QString getSelectedVolumePublisher(); QString getSelectedVolumePublisher();
private: private:
QLabel * cover; QLabel * cover;
ScraperScrollLabel * detailLabel; ScraperScrollLabel * detailLabel;
ScraperTableView * tableVolumes; ScraperTableView * tableVolumes;
VolumesModel * model; VolumesModel * model;
QSortFilterProxyModel * proxyModel; QSortFilterProxyModel * proxyModel;
}; };
#endif // SELECT_VOLUME_H #endif // SELECT_VOLUME_H

View File

@ -1,46 +1,46 @@
#include "series_question.h" #include "series_question.h"
#include <QRadioButton> #include <QRadioButton>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QLabel> #include <QLabel>
SeriesQuestion::SeriesQuestion(QWidget * parent) SeriesQuestion::SeriesQuestion(QWidget * parent)
:QWidget(parent) :QWidget(parent)
{ {
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
QLabel * questionLabel = new QLabel(tr("You are trying to get information for various comics at once, are they part of the same series?")); QLabel * questionLabel = new QLabel(tr("You are trying to get information for various comics at once, are they part of the same series?"));
questionLabel->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}"); questionLabel->setStyleSheet("QLabel {color:white; font-size:12px;font-family:Arial;}");
yes = new QRadioButton(tr("yes")); yes = new QRadioButton(tr("yes"));
no = new QRadioButton(tr("no")); no = new QRadioButton(tr("no"));
QString rbStyle = "QRadioButton {margin-left:27px; margin-top:5px; color:white;font-size:12px;font-family:Arial;}" QString rbStyle = "QRadioButton {margin-left:27px; margin-top:5px; color:white;font-size:12px;font-family:Arial;}"
"QRadioButton::indicator {width:11px;height:11px;}" "QRadioButton::indicator {width:11px;height:11px;}"
"QRadioButton::indicator::unchecked {image : url(:/images/comic_vine/radioUnchecked.png);}" "QRadioButton::indicator::unchecked {image : url(:/images/comic_vine/radioUnchecked.png);}"
"QRadioButton::indicator::checked {image : url(:/images/comic_vine/radioChecked.png);}"; "QRadioButton::indicator::checked {image : url(:/images/comic_vine/radioChecked.png);}";
yes->setStyleSheet(rbStyle); yes->setStyleSheet(rbStyle);
no->setStyleSheet(rbStyle); no->setStyleSheet(rbStyle);
yes->setChecked(true); yes->setChecked(true);
l->addSpacing(35); l->addSpacing(35);
l->addWidget(questionLabel); l->addWidget(questionLabel);
l->addWidget(yes); l->addWidget(yes);
l->addWidget(no); l->addWidget(no);
l->addStretch(); l->addStretch();
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
} }
bool SeriesQuestion::getYes() bool SeriesQuestion::getYes()
{ {
return yes->isChecked(); return yes->isChecked();
} }
void SeriesQuestion::setYes(bool y) void SeriesQuestion::setYes(bool y)
{ {
yes->setChecked(y); yes->setChecked(y);
} }

View File

@ -1,23 +1,23 @@
#ifndef SERIES_QUESTION_H #ifndef SERIES_QUESTION_H
#define SERIES_QUESTION_H #define SERIES_QUESTION_H
#include <QWidget> #include <QWidget>
class QRadioButton; class QRadioButton;
class SeriesQuestion : public QWidget class SeriesQuestion : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
SeriesQuestion(QWidget * parent = 0); SeriesQuestion(QWidget * parent = 0);
bool getYes(); bool getYes();
void setYes(bool yes = true); void setYes(bool yes = true);
private: private:
QRadioButton * yes; QRadioButton * yes;
QRadioButton * no; QRadioButton * no;
}; };
#endif // SERIES_QUESTION_H #endif // SERIES_QUESTION_H

View File

@ -1,222 +1,222 @@
#include "sort_volume_comics.h" #include "sort_volume_comics.h"
#include <QLabel> #include <QLabel>
#include <QBoxLayout> #include <QBoxLayout>
#include <QPushButton> #include <QPushButton>
#include <QScrollBar> #include <QScrollBar>
#include <QAction> #include <QAction>
#include "scraper_tableview.h" #include "scraper_tableview.h"
#include "local_comic_list_model.h" #include "local_comic_list_model.h"
#include "volume_comics_model.h" #include "volume_comics_model.h"
SortVolumeComics::SortVolumeComics(QWidget *parent) : SortVolumeComics::SortVolumeComics(QWidget *parent) :
ScraperSelector(parent) ScraperSelector(parent)
{ {
QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}"; QString labelStylesheet = "QLabel {color:white; font-size:12px;font-family:Arial;}";
QLabel * label = new QLabel(tr("Please, sort the list of comics on the left until it matches the comics' information.")); QLabel * label = new QLabel(tr("Please, sort the list of comics on the left until it matches the comics' information."));
label->setStyleSheet(labelStylesheet); label->setStyleSheet(labelStylesheet);
QLabel * sortLabel = new QLabel(tr("sort comics to match comic information")); QLabel * sortLabel = new QLabel(tr("sort comics to match comic information"));
sortLabel->setStyleSheet(labelStylesheet); sortLabel->setStyleSheet(labelStylesheet);
moveUpButtonCL = new ScrapperToolButton(ScrapperToolButton::LEFT); moveUpButtonCL = new ScrapperToolButton(ScrapperToolButton::LEFT);
moveUpButtonCL->setIcon(QIcon(":/images/comic_vine/rowUp.png")); moveUpButtonCL->setIcon(QIcon(":/images/comic_vine/rowUp.png"));
moveUpButtonCL->setAutoRepeat(true); moveUpButtonCL->setAutoRepeat(true);
moveDownButtonCL = new ScrapperToolButton(ScrapperToolButton::RIGHT); moveDownButtonCL = new ScrapperToolButton(ScrapperToolButton::RIGHT);
moveDownButtonCL->setIcon(QIcon(":/images/comic_vine/rowDown.png")); moveDownButtonCL->setIcon(QIcon(":/images/comic_vine/rowDown.png"));
moveDownButtonCL->setAutoRepeat(true); moveDownButtonCL->setAutoRepeat(true);
//moveUpButtonIL = new ScrapperToolButton(ScrapperToolButton::LEFT); //moveUpButtonIL = new ScrapperToolButton(ScrapperToolButton::LEFT);
//moveUpButtonIL->setIcon(QIcon(":/images/comic_vine/rowUp.png")); //moveUpButtonIL->setIcon(QIcon(":/images/comic_vine/rowUp.png"));
//moveDownButtonIL = new ScrapperToolButton(ScrapperToolButton::RIGHT); //moveDownButtonIL = new ScrapperToolButton(ScrapperToolButton::RIGHT);
//moveDownButtonIL->setIcon(QIcon(":/images/comic_vine/rowDown.png")); //moveDownButtonIL->setIcon(QIcon(":/images/comic_vine/rowDown.png"));
connect(moveUpButtonCL,SIGNAL(clicked()),this,SLOT(moveUpCL())); connect(moveUpButtonCL,SIGNAL(clicked()),this,SLOT(moveUpCL()));
connect(moveDownButtonCL,SIGNAL(clicked()),this,SLOT(moveDownCL())); connect(moveDownButtonCL,SIGNAL(clicked()),this,SLOT(moveDownCL()));
//connect(moveUpButtonIL,SIGNAL(clicked()),this,SLOT(moveUpIL())); //connect(moveUpButtonIL,SIGNAL(clicked()),this,SLOT(moveUpIL()));
//connect(moveUpButtonIL,SIGNAL(clicked()),this,SLOT(moveDownIL())); //connect(moveUpButtonIL,SIGNAL(clicked()),this,SLOT(moveDownIL()));
QVBoxLayout * l = new QVBoxLayout; QVBoxLayout * l = new QVBoxLayout;
QGridLayout * content = new QGridLayout; QGridLayout * content = new QGridLayout;
QHBoxLayout * sortButtonsLayout = new QHBoxLayout; QHBoxLayout * sortButtonsLayout = new QHBoxLayout;
tableFiles = new ScraperTableView(); tableFiles = new ScraperTableView();
tableVolumeComics = new ScraperTableView(); tableVolumeComics = new ScraperTableView();
tableFiles->setSelectionBehavior(QAbstractItemView::SelectRows); tableFiles->setSelectionBehavior(QAbstractItemView::SelectRows);
tableFiles->setSelectionMode(QAbstractItemView::ContiguousSelection); tableFiles->setSelectionMode(QAbstractItemView::ContiguousSelection);
//content->addWidget(tableVolumes,0,Qt::AlignRight|Qt::AlignTop); //content->addWidget(tableVolumes,0,Qt::AlignRight|Qt::AlignTop);
connect(tableVolumeComics->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int))); connect(tableVolumeComics->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int)));
connect(tableFiles->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int))); connect(tableFiles->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int)));
//connect(tableVolumeComics, SIGNAL(pressed(QModelIndex)), tableFiles, SLOT(setCurrentIndex(QModelIndex))); //connect(tableVolumeComics, SIGNAL(pressed(QModelIndex)), tableFiles, SLOT(setCurrentIndex(QModelIndex)));
//connect(tableFiles, SIGNAL(pressed(QModelIndex)), tableVolumeComics, SLOT(setCurrentIndex(QModelIndex))); //connect(tableFiles, SIGNAL(pressed(QModelIndex)), tableVolumeComics, SLOT(setCurrentIndex(QModelIndex)));
paginator->setCustomLabel(tr("issues")); paginator->setCustomLabel(tr("issues"));
paginator->setMinimumWidth(422); paginator->setMinimumWidth(422);
sortButtonsLayout->addWidget(moveUpButtonCL); sortButtonsLayout->addWidget(moveUpButtonCL);
sortButtonsLayout->addWidget(ScrapperToolButton::getSeparator()); sortButtonsLayout->addWidget(ScrapperToolButton::getSeparator());
sortButtonsLayout->addWidget(moveDownButtonCL); sortButtonsLayout->addWidget(moveDownButtonCL);
sortButtonsLayout->addSpacing(10); sortButtonsLayout->addSpacing(10);
sortButtonsLayout->addWidget(sortLabel); sortButtonsLayout->addWidget(sortLabel);
sortButtonsLayout->addStretch(); sortButtonsLayout->addStretch();
sortButtonsLayout->setSpacing(0); sortButtonsLayout->setSpacing(0);
content->addWidget(tableFiles, 0, 0); content->addWidget(tableFiles, 0, 0);
content->addWidget(tableVolumeComics, 0, 1); content->addWidget(tableVolumeComics, 0, 1);
content->addLayout(sortButtonsLayout, 1, 0); content->addLayout(sortButtonsLayout, 1, 0);
content->addWidget(paginator, 1, 1); content->addWidget(paginator, 1, 1);
content->setRowStretch(0, 1); content->setRowStretch(0, 1);
l->addSpacing(15); l->addSpacing(15);
l->addWidget(label, 0); l->addWidget(label, 0);
l->addSpacing(5); l->addSpacing(5);
l->addLayout(content, 1); l->addLayout(content, 1);
l->addLayout(sortButtonsLayout, 0); l->addLayout(sortButtonsLayout, 0);
l->setContentsMargins(0,0,0,0); l->setContentsMargins(0,0,0,0);
setLayout(l); setLayout(l);
setContentsMargins(0,0,0,0); setContentsMargins(0,0,0,0);
//rows actions //rows actions
QAction * removeItemFromList = new QAction(tr("remove selected comics"),this); QAction * removeItemFromList = new QAction(tr("remove selected comics"),this);
QAction * restoreAllItems = new QAction(tr("restore all removed comics"),this); QAction * restoreAllItems = new QAction(tr("restore all removed comics"),this);
//QAction * restoreItems = new QAction(tr("restore removed comics"),this); //QAction * restoreItems = new QAction(tr("restore removed comics"),this);
tableFiles->setContextMenuPolicy(Qt::ActionsContextMenu); tableFiles->setContextMenuPolicy(Qt::ActionsContextMenu);
tableFiles->addAction(removeItemFromList); tableFiles->addAction(removeItemFromList);
tableFiles->addAction(restoreAllItems); tableFiles->addAction(restoreAllItems);
//tableFiles->addAction(restoreItems); //tableFiles->addAction(restoreItems);
connect(removeItemFromList,SIGNAL(triggered()),this,SLOT(removeSelectedComics())); connect(removeItemFromList,SIGNAL(triggered()),this,SLOT(removeSelectedComics()));
connect(restoreAllItems,SIGNAL(triggered()),this,SLOT(restoreAllComics())); connect(restoreAllItems,SIGNAL(triggered()),this,SLOT(restoreAllComics()));
//connect(restoreItems,SIGNAL(triggered()),this,SLOT(showRemovedComicsSelector())); //connect(restoreItems,SIGNAL(triggered()),this,SLOT(showRemovedComicsSelector()));
} }
void SortVolumeComics::setData(QList<ComicDB> & comics, const QString &json, const QString &vID) void SortVolumeComics::setData(QList<ComicDB> & comics, const QString &json, const QString &vID)
{ {
//set up models //set up models
localComicsModel = new LocalComicListModel; localComicsModel = new LocalComicListModel;
localComicsModel->load(comics); localComicsModel->load(comics);
volumeComicsModel = new VolumeComicsModel; volumeComicsModel = new VolumeComicsModel;
volumeComicsModel->load(json); volumeComicsModel->load(json);
int numLocalComics = localComicsModel->rowCount(); int numLocalComics = localComicsModel->rowCount();
int numVolumeComics = volumeComicsModel->rowCount(); int numVolumeComics = volumeComicsModel->rowCount();
if(numLocalComics > numVolumeComics) if(numLocalComics > numVolumeComics)
volumeComicsModel->addExtraRows(numLocalComics - numVolumeComics); volumeComicsModel->addExtraRows(numLocalComics - numVolumeComics);
if(numLocalComics < numVolumeComics) if(numLocalComics < numVolumeComics)
localComicsModel->addExtraRows(numVolumeComics - numLocalComics); localComicsModel->addExtraRows(numVolumeComics - numLocalComics);
tableFiles->setModel(localComicsModel); tableFiles->setModel(localComicsModel);
tableVolumeComics->setModel(volumeComicsModel); tableVolumeComics->setModel(volumeComicsModel);
tableVolumeComics->resizeColumnToContents(0); tableVolumeComics->resizeColumnToContents(0);
ScraperSelector::load(json,vID); ScraperSelector::load(json,vID);
} }
void SortVolumeComics::synchronizeScroll(int pos) void SortVolumeComics::synchronizeScroll(int pos)
{ {
void * senderObject = sender(); void * senderObject = sender();
if(senderObject == 0) //invalid call if(senderObject == 0) //invalid call
return; return;
QScrollBar * tableVolumeComicsScrollBar = tableVolumeComics->verticalScrollBar(); QScrollBar * tableVolumeComicsScrollBar = tableVolumeComics->verticalScrollBar();
QScrollBar * tableFilesScrollBar = tableFiles->verticalScrollBar(); QScrollBar * tableFilesScrollBar = tableFiles->verticalScrollBar();
if(senderObject == tableVolumeComicsScrollBar) if(senderObject == tableVolumeComicsScrollBar)
{ {
disconnect(tableFilesScrollBar,SIGNAL(valueChanged(int)),this,0); disconnect(tableFilesScrollBar,SIGNAL(valueChanged(int)),this,0);
tableFilesScrollBar->setValue(pos); tableFilesScrollBar->setValue(pos);
connect(tableFilesScrollBar, SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int))); connect(tableFilesScrollBar, SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int)));
} }
else else
{ {
disconnect(tableVolumeComicsScrollBar,SIGNAL(valueChanged(int)),this,0); disconnect(tableVolumeComicsScrollBar,SIGNAL(valueChanged(int)),this,0);
tableVolumeComicsScrollBar->setValue(pos); tableVolumeComicsScrollBar->setValue(pos);
connect(tableVolumeComicsScrollBar, SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int))); connect(tableVolumeComicsScrollBar, SIGNAL(valueChanged(int)), this, SLOT(synchronizeScroll(int)));
} }
} }
void SortVolumeComics::moveUpCL() void SortVolumeComics::moveUpCL()
{ {
QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes(); QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes();
if(selection.count() == 0) if(selection.count() == 0)
return; return;
localComicsModel->moveSelectionUp(selection); localComicsModel->moveSelectionUp(selection);
selection = tableFiles->selectionModel()->selectedIndexes(); selection = tableFiles->selectionModel()->selectedIndexes();
tableFiles->scrollTo(selection.first()); tableFiles->scrollTo(selection.first());
} }
void SortVolumeComics::moveDownCL() void SortVolumeComics::moveDownCL()
{ {
QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes(); QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes();
if(selection.count() > 0) if(selection.count() > 0)
{ {
localComicsModel->moveSelectionDown(selection); localComicsModel->moveSelectionDown(selection);
selection = tableFiles->selectionModel()->selectedIndexes(); selection = tableFiles->selectionModel()->selectedIndexes();
tableFiles->scrollTo(selection.last()); tableFiles->scrollTo(selection.last());
} }
} }
void SortVolumeComics::moveUpIL() void SortVolumeComics::moveUpIL()
{ {
} }
void SortVolumeComics::moveDownIL() void SortVolumeComics::moveDownIL()
{ {
} }
void SortVolumeComics::removeSelectedComics() void SortVolumeComics::removeSelectedComics()
{ {
QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes(); QList<QModelIndex> selection = tableFiles->selectionModel()->selectedIndexes();
localComicsModel->removeComics(selection); localComicsModel->removeComics(selection);
} }
void SortVolumeComics::restoreAllComics() void SortVolumeComics::restoreAllComics()
{ {
localComicsModel->restoreAll(); localComicsModel->restoreAll();
} }
void SortVolumeComics::showRemovedComicsSelector() void SortVolumeComics::showRemovedComicsSelector()
{ {
} }
QList<QPair<ComicDB, QString> > SortVolumeComics::getMatchingInfo() QList<QPair<ComicDB, QString> > SortVolumeComics::getMatchingInfo()
{ {
QList<ComicDB> comicList = localComicsModel->getData(); QList<ComicDB> comicList = localComicsModel->getData();
QList<QPair<ComicDB, QString> > l; QList<QPair<ComicDB, QString> > l;
int index = 0; int index = 0;
QString id; QString id;
foreach(ComicDB c, comicList) foreach(ComicDB c, comicList)
{ {
id = volumeComicsModel->getComicId(index); id = volumeComicsModel->getComicId(index);
if(!c.getFileName().isEmpty() && !id.isEmpty()) //there is a valid comic, and valid comic ID if(!c.getFileName().isEmpty() && !id.isEmpty()) //there is a valid comic, and valid comic ID
{ {
l.push_back(QPair<ComicDB, QString>(c,id)); l.push_back(QPair<ComicDB, QString>(c,id));
} }
index++; index++;
} }
return l; return l;
} }

Some files were not shown because too many files have changed in this diff Show More