Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
78 KB
Referenced Files
None
Subscribers
None
diff --git a/dialogs/historydialog.cpp b/dialogs/historydialog.cpp
index 66914c5..4560ffe 100644
--- a/dialogs/historydialog.cpp
+++ b/dialogs/historydialog.cpp
@@ -1,253 +1,246 @@
#include "historydialog.h"
#include "ui_historydialog.h"
#include "../tools/os.h"
-#include "../tools/qxtcsvmodel.h"
#include "../tools/uploader.h"
#include "../tools/screenshotmanager.h"
#include <QClipboard>
#include <QDesktopServices>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
#include <QUrl>
+#include <QtSql/QSqlDatabase>
+#include <QtSql/QSqlTableModel>
+
#include <QDebug>
HistoryDialog::HistoryDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::HistoryDialog)
{
ui->setupUi(this);
ui->filterEdit->setText(tr("Filter.."));
ui->filterEdit->installEventFilter(this);
- QFile historyFile(ScreenshotManager::instance()->historyPath());
-
- if (!historyFile.exists())
+ if (ScreenshotManager::instance()->history().isOpen())
{
- ui->tableView->setEnabled(false);
- return;
- }
+ QSqlTableModel *model = new QSqlTableModel(this, ScreenshotManager::instance()->history());
+ model->setTable("history");
+ model->setHeaderData(0, Qt::Horizontal, tr("Screenshot"));
+ model->setHeaderData(1, Qt::Horizontal, tr("URL"));
+ model->select();
+
+ mFilterModel = new QSortFilterProxyModel(model);
+ mFilterModel->setSourceModel(model);
+ mFilterModel->setDynamicSortFilter(true);
+ mFilterModel->setSortCaseSensitivity(Qt::CaseInsensitive);
+ mFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
+ mFilterModel->setFilterKeyColumn(-1);
+
+ ui->tableView->setModel(mFilterModel);
+
+ ui->tableView->hideColumn(2); // No delete hash.
+ ui->tableView->hideColumn(3); // No timestamp.
- QFileSystemWatcher *watcher = new QFileSystemWatcher(QStringList() << historyFile.fileName(), this);
- connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(reloadHistory()));
+ ui->tableView->horizontalHeader()->setClickable(false);
+ ui->tableView->horizontalHeader()->setMovable(false);
- reloadHistory();
+ ui->tableView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
+ ui->tableView->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
+
+ ui->tableView->verticalHeader()->hide();
+
+ ui->tableView->setTextElideMode(Qt::ElideLeft);
+ ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ ui->tableView->setAlternatingRowColors(true);
+ ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
+ ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
+ ui->tableView->setSortingEnabled(true);
+
+ if (ui->tableView->model()->rowCount() > 0)
+ {
+ ui->clearButton->setEnabled(true);
+ ui->filterEdit->setEnabled(true);
+ }
+
+ connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
+ connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(open(QModelIndex)));
+ connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint)));
+ }
+ else {
+ ui->tableView->setEnabled(false);
+ ui->clearButton->setEnabled(false);
+ }
ui->uploadProgressBar->setValue (Uploader::instance()->progressSent());
if (Uploader::instance()->progressTotal() == 0) {
ui->uploadProgressBar->setMaximum(1);
}
else {
ui->uploadProgressBar->setMaximum(Uploader::instance()->progressTotal());
}
- ui->tableView->setTextElideMode(Qt::ElideLeft);
- ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
- ui->tableView->setAlternatingRowColors(true);
- ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
- ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
- ui->tableView->setSortingEnabled(true);
-
- if (ui->tableView->model()->rowCount() > 0)
- {
- ui->clearButton->setEnabled(true);
- ui->filterEdit->setEnabled(true);
- }
-
connect(Uploader::instance(), SIGNAL(progress(qint64,qint64)), this, SLOT(uploadProgress(qint64, qint64)));
connect(ui->uploadButton, SIGNAL(clicked()), this, SLOT(upload()));
connect(ui->clearButton , SIGNAL(clicked()), this, SLOT(clear()));
- connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
- connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(open(QModelIndex)));
- connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint)));
}
HistoryDialog::~HistoryDialog()
{
delete ui;
}
void HistoryDialog::clear()
{
if (QMessageBox::question(this,
tr("Clearing the screenshot history"),
tr("Are you sure you want to clear your entire screenshot history?\nThis cannot be undone."),
tr("Clear History"),
tr("Don't Clear")) == 1) {
return;
}
- QFile::remove(ScreenshotManager::instance()->historyPath());
+ ScreenshotManager::instance()->clearHistory();
close();
}
void HistoryDialog::contextMenu(QPoint point)
{
mContextIndex = ui->tableView->indexAt(point);;
QMenu contextMenu(ui->tableView);
QAction copyAction((mContextIndex.column() == 0) ? tr("Copy Path") : tr("Copy URL"), &contextMenu);
connect(&copyAction, SIGNAL(triggered()), this, SLOT(copy()));
contextMenu.addAction(&copyAction);
QAction deleteAction(tr("Delete from imgur.com"), &contextMenu);
QAction locationAction(tr("Open Location"), &contextMenu);
if (mContextIndex.column() == 0)
{
connect(&locationAction, SIGNAL(triggered()), this, SLOT(location()));
contextMenu.addAction(&locationAction);
}
else {
connect(&deleteAction, SIGNAL(triggered()), this, SLOT(deleteImage()));
contextMenu.addAction(&deleteAction);
}
- if (mContextIndex.data().toString() == QObject::tr("- not uploaded -")) {
+ if (mContextIndex.data().toString().isEmpty()) {
copyAction.setEnabled(false);
deleteAction.setEnabled(false);
}
contextMenu.exec(QCursor::pos());
}
void HistoryDialog::copy()
{
qApp->clipboard()->setText(mContextIndex.data().toString());
}
void HistoryDialog::deleteImage()
{
- QDesktopServices::openUrl("http://imgur.com/delete/" + mContextIndex.sibling(mContextIndex.row(), 2).data().toString());
+ QDesktopServices::openUrl(mContextIndex.sibling(mContextIndex.row(), 2).data().toString());
}
void HistoryDialog::location()
{
QDesktopServices::openUrl("file:///" + QFileInfo(mContextIndex.data().toString()).absolutePath());
}
void HistoryDialog::open(QModelIndex index)
{
if (index.column() == 0) {
QDesktopServices::openUrl(QUrl("file:///" + index.data().toString()));
}
else {
QDesktopServices::openUrl(index.data().toUrl());
}
}
void HistoryDialog::reloadHistory()
{
- if (ui->tableView->model()) {
- // Double cast all the way across the sky!
- QxtCsvModel* csv = qobject_cast<QxtCsvModel*>(qobject_cast<QSortFilterProxyModel*>(ui->tableView->model())->sourceModel());
- csv->setSource(ScreenshotManager::instance()->historyPath(), false, '|');
- return;
- }
-
- QFile historyFile(ScreenshotManager::instance()->historyPath());
-
- QxtCsvModel *model = new QxtCsvModel(&historyFile, this, false, '|');
- model->setHeaderData(QStringList() << tr("Screenshot") << tr("URL"));
-
- mFilterModel = new QSortFilterProxyModel(model);
- mFilterModel->setSourceModel(model);
- mFilterModel->setDynamicSortFilter(true);
- mFilterModel->setSortCaseSensitivity(Qt::CaseInsensitive);
- mFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
- mFilterModel->setFilterKeyColumn(-1);
-
- ui->tableView->setModel(mFilterModel);
-
- ui->tableView->hideColumn(2); // No delete hash.
- ui->tableView->hideColumn(3); // No timestamp.
-
- ui->tableView->horizontalHeader()->setClickable(false);
- ui->tableView->horizontalHeader()->setMovable(false);
-
- ui->tableView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
- ui->tableView->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
-
- ui->tableView->verticalHeader()->hide();
+ qobject_cast<QSqlTableModel*>(mFilterModel->sourceModel())->select();
}
void HistoryDialog::selectionChanged(QItemSelection selected, QItemSelection deselected)
{
Q_UNUSED(deselected);
QModelIndex index = selected.indexes().at(0);
QString screenshot, url;
if (index.column() == 0) {
screenshot = index.data().toString();
url = ui->tableView->model()->index(index.row(), 1).data().toString();
}
else {
screenshot = ui->tableView->model()->index(index.row(), 0).data().toString();
url = index.data().toString();
}
mSelectedScreenshot = screenshot;
- ui->uploadButton->setEnabled((url == QObject::tr("- not uploaded -") && QFile::exists(screenshot)));
+ ui->uploadButton->setEnabled((url.isEmpty() && QFile::exists(screenshot)));
}
void HistoryDialog::upload()
{
Uploader::instance()->upload(mSelectedScreenshot);
ui->uploadButton->setEnabled(false);
}
void HistoryDialog::uploadProgress(qint64 sent, qint64 total)
{
ui->uploadProgressBar->setEnabled(true);
ui->uploadProgressBar->setMaximum(total);
ui->uploadProgressBar->setValue(sent);
}
bool HistoryDialog::eventFilter(QObject *object, QEvent *event)
{
if (object == ui->filterEdit) {
if (event->type() == QEvent::FocusIn)
{
if (ui->filterEdit->text() == tr("Filter..")) {
ui->filterEdit->setStyleSheet("");
ui->filterEdit->setText("");
mFilterModel->setFilterWildcard("");
mFilterModel->sort(3, Qt::DescendingOrder);
}
}
else if (event->type() == QEvent::FocusOut)
{
if (ui->filterEdit->text() == "") {
ui->filterEdit->setStyleSheet("color: palette(mid);");
ui->filterEdit->setText(tr("Filter.."));
mFilterModel->sort(3, Qt::DescendingOrder);
}
}
else if (event->type() == QEvent::KeyRelease)
{
if (ui->filterEdit->text() != tr("Filter..") && !ui->filterEdit->text().isEmpty()) {
mFilterModel->setFilterWildcard(ui->filterEdit->text());
mFilterModel->sort(3, Qt::DescendingOrder);
}
else {
mFilterModel->setFilterWildcard("");
mFilterModel->sort(3, Qt::DescendingOrder);
}
}
}
return QDialog::eventFilter(object, event);
}
diff --git a/lightscreen.pro b/lightscreen.pro
index 7f8f0ca..b43fcc7 100644
--- a/lightscreen.pro
+++ b/lightscreen.pro
@@ -1,70 +1,68 @@
TEMPLATE = app
TARGET = lightscreen
HEADERS += tools/os.h \
updater/updater.h \
dialogs/areadialog.h \
dialogs/optionsdialog.h \
widgets/hotkeywidget.h \
lightscreenwindow.h \
tools/screenshot.h \
dialogs/previewdialog.h \
tools/screenshotmanager.h \
tools/windowpicker.h \
tools/uploader.h \
tools/qtimgur.h \
dialogs/updaterdialog.h \
dialogs/screenshotdialog.h \
dialogs/namingdialog.h \
- tools/qxtcsvmodel.h \
dialogs/historydialog.h
SOURCES += tools/os.cpp \
updater/updater.cpp \
dialogs/areadialog.cpp \
dialogs/optionsdialog.cpp \
widgets/hotkeywidget.cpp \
main.cpp \
lightscreenwindow.cpp \
tools/screenshot.cpp \
dialogs/previewdialog.cpp \
tools/screenshotmanager.cpp \
tools/windowpicker.cpp \
tools/uploader.cpp \
tools/qtimgur.cpp \
dialogs/updaterdialog.cpp \
dialogs/screenshotdialog.cpp \
dialogs/namingdialog.cpp \
- tools/qxtcsvmodel.cpp \
dialogs/historydialog.cpp
FORMS += dialogs/optionsdialog.ui \
dialogs/namingdialog.ui \
dialogs/historydialog.ui \
lightscreenwindow.ui
RESOURCES += lightscreen.qrc
TRANSLATIONS += translations/untranslated.ts \
translations/spanish.ts \
translations/russian.ts \
translations/portuguese.ts \
translations/polish.ts \
translations/japanese.ts \
translations/italian.ts \
translations/dutch.ts
RC_FILE += lightscreen.rc
CODECFORSRC = UTF-8
-QT += network core gui xml
+QT += network core gui xml sql
include($$PWD/tools/globalshortcut/globalshortcut.pri)
include($$PWD/tools/qtsingleapplication/qtsingleapplication.pri)
include($$PWD/tools/qwin7utils/qwin7utils.pri)
win32:LIBS += libgdi32 libgcc libuser32 libole32 libshell32 libshlwapi libcomctl32
QMAKE_CXXFLAGS = -Wextra -Wall -Wpointer-arith
OTHER_FILES += TODO.txt
diff --git a/lightscreenwindow.cpp b/lightscreenwindow.cpp
index 03d45c2..a2067de 100644
--- a/lightscreenwindow.cpp
+++ b/lightscreenwindow.cpp
@@ -1,978 +1,983 @@
/*
* Copyright (C) 2011 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <QMainWindow>
#include <QDate>
#include <QDesktopServices>
#include <QFileInfo>
#include <QHttp>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QPointer>
#include <QProcess>
#include <QSettings>
#include <QSound>
#include <QSystemTrayIcon>
#include <QTimer>
#include <QToolTip>
#include <QUrl>
#include <QDebug>
#ifdef Q_WS_WIN
#include <windows.h>
#include "tools/qwin7utils/Taskbar.h"
#include "tools/qwin7utils/TaskbarButton.h"
+ #include "tools/qwin7utils/Utils.h"
using namespace QW7;
#endif
/*
* Lightscreen includes
*/
#include "lightscreenwindow.h"
#include "dialogs/optionsdialog.h"
#include "dialogs/previewdialog.h"
#include "dialogs/historydialog.h"
#include "tools/globalshortcut/globalshortcutmanager.h"
#include "tools/os.h"
#include "tools/screenshot.h"
#include "tools/screenshotmanager.h"
#include "tools/uploader.h"
#include "updater/updater.h"
LightscreenWindow::LightscreenWindow(QWidget *parent) :
QMainWindow(parent),
mDoCache(false),
mHideTrigger(false),
mReviveMain(false),
mWasVisible(true),
mLastMessage(0),
mLastMode(-1),
mLastScreenshot()
{
os::translate(settings()->value("options/language", "English").toString());
ui.setupUi(this);
+#ifdef Q_WS_WIN
+ ExtendFrameIntoClientArea(this);
+#endif
+
setMaximumSize(size());
setMinimumSize(size());
setWindowFlags(Qt::Window);
#ifdef Q_WS_WIN
if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) {
mTaskbarButton = new TaskbarButton(this);
}
#endif
// Actions
connect(ui.screenPushButton, SIGNAL(clicked()), this, SLOT(screenshotAction()));
connect(ui.areaPushButton , SIGNAL(clicked()), this, SLOT(areaHotkey()));
connect(ui.windowPushButton, SIGNAL(clicked()), this, SLOT(windowPickerHotkey()));
connect(ui.optionsPushButton, SIGNAL(clicked()), this, SLOT(showOptions()));
connect(ui.folderPushButton , SIGNAL(clicked()), this, SLOT(goToFolder()));
connect(ui.imgurPushButton, SIGNAL(clicked()), this, SLOT(showUploadMenu()));
// Uploader
connect(Uploader::instance(), SIGNAL(progress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(showUploaderMessage(QString, QString)));
connect(Uploader::instance(), SIGNAL(error(QString)), this, SLOT(showUploaderError(QString)));
// Manager
connect(ScreenshotManager::instance(), SIGNAL(confirm(Screenshot*)), this, SLOT(preview(Screenshot*)));
connect(ScreenshotManager::instance(), SIGNAL(windowCleanup(Screenshot::Options&)), this, SLOT(cleanup(Screenshot::Options&)));
if (!settings()->contains("file/format")) {
showOptions(); // There are no options (or the options config is invalid or incomplete)
}
else {
QTimer::singleShot(0 , this, SLOT(applySettings()));
QTimer::singleShot(5000, this, SLOT(checkForUpdates()));
}
}
LightscreenWindow::~LightscreenWindow()
{
settings()->setValue("lastScreenshot", mLastScreenshot);
settings()->sync();
GlobalShortcutManager::instance()->clear();
delete mTrayIcon;
}
void LightscreenWindow::action(int mode)
{
if (mode == 4) {
goToFolder();
}
else {
show();
}
}
void LightscreenWindow::areaHotkey()
{
screenshotAction(2);
}
void LightscreenWindow::checkForUpdates()
{
if (settings()->value("options/disableUpdater", false).toBool())
return;
if (settings()->value("lastUpdateCheck").toInt() + 7
> QDate::currentDate().dayOfYear())
return; // If 7 days have not passed since the last update check.
connect(Updater::instance(), SIGNAL(done(bool)), this, SLOT(updaterDone(bool)));
Updater::instance()->check();
}
void LightscreenWindow::cleanup(Screenshot::Options &options)
{
// Reversing settings
if (settings()->value("options/hide").toBool()) {
#ifndef Q_WS_X11 // X is not quick enough and the notification ends up everywhere but in the icon
if (settings()->value("options/tray").toBool() && mTrayIcon) {
mTrayIcon->show();
}
#endif
if (mPreviewDialog) {
if (mPreviewDialog->count() <= 1 && mWasVisible) {
show();
}
mPreviewDialog->show();
}
else if (mWasVisible) {
show();
}
mHideTrigger = false;
}
if (settings()->value("options/tray").toBool() && mTrayIcon) {
notify(options.result);
if (settings()->value("options/message").toBool() && options.file) {
showScreenshotMessage(options.result, options.fileName);
}
}
if (settings()->value("options/playSound", false).toBool()) {
if (options.result == Screenshot::Success) {
QSound::play("sounds/ls.screenshot.wav");
}
else {
#ifdef Q_WS_WIN
QSound::play("afakepathtomakewindowsplaythedefaultsoundtheresprobablyabetterwaybuticantbebothered");
#else
QSound::play("sound/ls.error.wav");
#endif
}
}
if (options.result != Screenshot::Success)
return;
mLastScreenshot = options.fileName;
}
bool LightscreenWindow::closingWithoutTray()
{
if (settings()->value("options/disableHideAlert", false).toBool())
return false;
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Lightscreen"));
msgBox.setText(tr("You have chosen to hide Lightscreen when there's no system tray icon, so you will not be able to access the program <b>unless you have selected a hotkey to do so</b>.<br>What do you want to do?"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStyleSheet("QPushButton { padding: 4px 8px; }");
QPushButton *enableButton = msgBox.addButton(tr("Hide but enable tray"),
QMessageBox::ActionRole);
QPushButton *enableAndDenotifyButton = msgBox.addButton(tr("Hide and don't warn"),
QMessageBox::ActionRole);
QPushButton *hideButton = msgBox.addButton(tr("Just hide"),
QMessageBox::ActionRole);
QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel);
Q_UNUSED(abortButton);
msgBox.exec();
if (msgBox.clickedButton() == hideButton) {
return false;
}
else if (msgBox.clickedButton() == enableAndDenotifyButton) {
settings()->setValue("options/disableHideAlert", true);
applySettings();
return false;
}
else if (msgBox.clickedButton() == enableButton) {
settings()->setValue("options/tray", true);
applySettings();
return false;
}
return true; // Cancel
}
void LightscreenWindow::goToFolder()
{
#ifdef Q_WS_WIN
if (!mLastScreenshot.isEmpty()) {
QProcess::startDetached("explorer /select, \"" + mLastScreenshot +"\"");
}
else {
#endif
QString folder = settings()->value("file/target").toString();
if (folder.isEmpty())
folder = qApp->applicationDirPath();
if (QDir::toNativeSeparators(folder.at(folder.size()-1)) != QDir::separator())
folder.append(QDir::separator());
QDesktopServices::openUrl("file:///"+folder);
#ifdef Q_WS_WIN
}
#endif
}
void LightscreenWindow::messageClicked()
{
if (mLastMessage == 1) {
goToFolder();
}
else {
QDesktopServices::openUrl(QUrl(Uploader::instance()->lastUrl()));
}
}
void LightscreenWindow::messageReceived(const QString &message)
{
if (message.contains(' ')) {
foreach (QString argument, message.split(' ')) {
messageReceived(argument);
}
}
if (message == "--wake") {
show();
qApp->alert(this, 500);
return;
}
if (message == "--screen")
screenshotAction();
else if (message == "--area")
screenshotAction(2);
else if (message == "--activewindow")
screenshotAction(1);
else if (message == "--pickwindow")
screenshotAction(3);
else if (message == "--folder")
action(4);
else if (message == "--uploadlast")
uploadLast();
else if (message == "--viewhistory")
showHistoryDialog();
}
void LightscreenWindow::notify(const Screenshot::Result &result)
{
switch (result)
{
case Screenshot::Success:
mTrayIcon->setIcon(QIcon(":/icons/lightscreen.yes"));
#ifdef Q_WS_WIN
if (mTaskbarButton)
mTaskbarButton->SetOverlayIcon(QIcon(":/icons/yes"), tr("Success!"));
#endif
setWindowTitle(tr("Success!"));
break;
case Screenshot::Fail:
mTrayIcon->setIcon(QIcon(":/icons/lightscreen.no"));
setWindowTitle(tr("Failed!"));
#ifdef Q_WS_WIN
if (mTaskbarButton)
mTaskbarButton->SetOverlayIcon(QIcon(":/icons/no"), tr("Failed!"));
#endif
break;
case Screenshot::Cancel:
setWindowTitle(tr("Cancelled!"));
break;
}
QTimer::singleShot(2000, this, SLOT(restoreNotification()));
}
void LightscreenWindow::preview(Screenshot* screenshot)
{
if (screenshot->options().preview) {
if (!mPreviewDialog) {
mPreviewDialog = new PreviewDialog(this);
}
mPreviewDialog->add(screenshot);
}
else {
screenshot->confirm(true);
}
}
void LightscreenWindow::quit()
{
settings()->setValue("position", pos());
int answer = 0;
QString doing;
if (ScreenshotManager::instance()->activeCount() > 0) {
doing = tr("processing");
}
if (Uploader::instance()->uploading() > 0) {
if (doing.isEmpty()) {
doing = tr("uploading");
}
else {
doing = tr("processing and uploading");
}
}
if (!doing.isEmpty()) {
answer = QMessageBox::question(this,
tr("Are you sure you want to quit?"),
tr("Lightscreen is currently %1 screenshots. Are you sure you want to quit?").arg(doing),
tr("Quit"),
tr("Don't Quit"));
}
if (answer == 0)
emit finished();
}
void LightscreenWindow::restoreNotification()
{
if (mTrayIcon)
mTrayIcon->setIcon(QIcon(":/icons/lightscreen.small"));
#ifdef Q_WS_WIN
if (mTaskbarButton)
mTaskbarButton->SetOverlayIcon(QIcon(), "");
#endif
updateUploadStatus();
}
void LightscreenWindow::screenshotAction(int mode)
{
int delayms = -1;
bool optionsHide = settings()->value("options/hide").toBool(); // Option cache, used a couple of times.
if (!mHideTrigger) {
mWasVisible = isVisible();
mHideTrigger = true;
}
// Applying pre-screenshot settings
if (optionsHide) {
hide();
#ifndef Q_WS_X11 // X is not quick enough and the notification ends up everywhere but in the icon
if (mTrayIcon)
mTrayIcon->hide();
#endif
}
// Screenshot delay
delayms = settings()->value("options/delay", 0).toInt();
delayms = delayms * 1000; // Converting the delay to milliseconds.
delayms += 400;
if (optionsHide && mPreviewDialog) {
if (mPreviewDialog->count() >= 1) {
mPreviewDialog->hide();
}
}
// The delayed functions works using the static variable lastMode
// which keeps the argument so a QTimer can call this function again.
if (delayms > 0) {
if (mLastMode < 0) {
mLastMode = mode;
QTimer::singleShot(delayms, this, SLOT(screenshotAction()));
return;
}
else {
mode = mLastMode;
mLastMode = -1;
}
}
static Screenshot::Options options;
if (!mDoCache) {
// Populating the option object that will then be passed to the screenshot engine (sounds fancy huh?)
options.file = settings()->value("file/enabled").toBool();
options.format = (Screenshot::Format) settings()->value("file/format").toInt();
options.prefix = settings()->value("file/prefix").toString();
QDir dir(settings()->value("file/target").toString());
dir.makeAbsolute();
options.directory = dir;
options.quality = settings()->value("options/quality", 100).toInt();
options.currentMonitor = settings()->value("options/currentMonitor", false).toBool();
options.clipboard = settings()->value("options/clipboard", true).toBool();
options.imgurClipboard = settings()->value("options/imgurClipboard", false).toBool();
options.preview = settings()->value("options/preview", false).toBool();
options.magnify = settings()->value("options/magnify", false).toBool();
options.cursor = settings()->value("options/cursor", false).toBool();
options.saveAs = settings()->value("options/saveAs", false).toBool();
options.animations = settings()->value("options/animations", true).toBool();
options.replace = settings()->value("options/replace", false).toBool();
options.upload = settings()->value("options/uploadAuto", false).toBool();
options.optimize = settings()->value("options/optipng", false).toBool();
Screenshot::NamingOptions namingOptions;
namingOptions.naming = (Screenshot::Naming) settings()->value("file/naming").toInt();
namingOptions.leadingZeros = settings()->value("options/naming/leadingZeros", 0).toInt();
namingOptions.flip = settings()->value("options/flip", false).toBool();
namingOptions.dateFormat = settings()->value("options/naming/dateFormat", "yyyy-MM-dd").toString();
options.namingOptions = namingOptions;
mDoCache = true;
}
options.mode = mode;
ScreenshotManager::instance()->take(options);
}
void LightscreenWindow::screenshotActionTriggered(QAction* action)
{
screenshotAction(action->data().toInt());
}
void LightscreenWindow::showHotkeyError(const QStringList &hotkeys)
{
static bool dontShow = false;
if (dontShow)
return;
QString messageText;
messageText = tr("Some hotkeys could not be registered, they might already be in use");
if (hotkeys.count() > 1) {
messageText += tr("<br>The failed hotkeys are the following:") + "<ul>";
foreach(const QString &hotkey, hotkeys) {
messageText += QString("%1%2%3").arg("<li><b>").arg(hotkey).arg("</b></li>");
}
messageText += "</ul>";
}
else {
messageText += tr("<br>The failed hotkey is <b>%1</b>").arg(hotkeys[0]);
}
messageText += tr("<br><i>What do you want to do?</i>");
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Lightscreen"));
msgBox.setText(messageText);
QPushButton *changeButton = msgBox.addButton(tr("Change") , QMessageBox::ActionRole);
QPushButton *disableButton = msgBox.addButton(tr("Disable"), QMessageBox::ActionRole);
QPushButton *exitButton = msgBox.addButton(tr("Quit") , QMessageBox::ActionRole);
msgBox.exec();
if (msgBox.clickedButton() == exitButton) {
dontShow = true;
QTimer::singleShot(10, this, SLOT(quit()));
}
else if (msgBox.clickedButton() == changeButton) {
showOptions();
}
else if (msgBox.clickedButton() == disableButton) {
foreach(const QString &hotkey, hotkeys) {
settings()->setValue(QString("actions/%1/enabled").arg(hotkey), false);
}
}
}
void LightscreenWindow::showHistoryDialog()
{
HistoryDialog historyDialog(this);
historyDialog.exec();
updateUploadStatus();
}
void LightscreenWindow::showOptions()
{
GlobalShortcutManager::clear();
QPointer<OptionsDialog> optionsDialog = new OptionsDialog(this);
optionsDialog->exec();
optionsDialog->deleteLater();
applySettings();
}
void LightscreenWindow::showUploadMenu()
{
QMenu* imgurMenu = new QMenu(tr("Upload"));
QAction *uploadAction = new QAction(QIcon(":/icons/imgur"), tr("&Upload last"), imgurMenu);
uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com"));
connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast()));
QAction *cancelAction = new QAction(QIcon(":/icons/no"), tr("&Cancel upload"), imgurMenu);
cancelAction->setToolTip(tr("Cancel the currently uploading screenshots"));
cancelAction->setEnabled(false);
connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool)));
connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel()));
QAction *historyAction = new QAction(QIcon(":/icons/view-history"), tr("View &History"), imgurMenu);
connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog()));
imgurMenu->addAction(uploadAction);
imgurMenu->addAction(cancelAction);
imgurMenu->addAction(historyAction);
imgurMenu->addSeparator();
ui.imgurPushButton->setMenu(imgurMenu);
ui.imgurPushButton->showMenu();
}
void LightscreenWindow::showScreenshotMessage(const Screenshot::Result &result, const QString &fileName)
{
if (result == Screenshot::Cancel
|| mPreviewDialog)
return;
// Showing message.
QString title;
QString message;
if (result == Screenshot::Success) {
title = QFileInfo(fileName).fileName();
if (settings()->value("file/target").toString().isEmpty()) {
message = QDir::toNativeSeparators(QCoreApplication::applicationDirPath());
}
else {
message = tr("Saved to \"%1\"").arg(settings()->value("file/target").toString());
}
}
else {
title = tr("The screenshot was not taken");
message = tr("An error occurred.");
}
mLastMessage = 1;
mTrayIcon->showMessage(title, message);
}
void LightscreenWindow::showUploaderError(const QString &error)
{
mLastMessage = -1;
if (mTrayIcon && !error.isEmpty()) {
mTrayIcon->showMessage(tr("Upload error"), error);
}
updateUploadStatus();
}
void LightscreenWindow::showUploaderMessage(QString fileName, QString url)
{
if (!mTrayIcon)
return;
QString screenshot = QFileInfo(fileName).fileName();
if (screenshot.startsWith(".lstemp."))
screenshot = tr("Screenshot");
mLastMessage = 2;
mTrayIcon->showMessage(tr("%1 uploaded").arg(screenshot), tr("Click here to go to %1").arg(url));
updateUploadStatus();
}
void LightscreenWindow::toggleVisibility(QSystemTrayIcon::ActivationReason reason)
{
if (reason != QSystemTrayIcon::DoubleClick)
return;
if (isVisible()) {
if (settings()->value("options/tray").toBool() == false
&& closingWithoutTray())
return;
hide();
}
else {
show();
}
}
void LightscreenWindow::updateUploadStatus()
{
int uploadCount = Uploader::instance()->uploading();
QString statusString;
if (uploadCount > 0) {
statusString = tr("%1 uploading - Lightscreen").arg(uploadCount);
ui.imgurPushButton->setIcon(QIcon(":/icons/imgur.upload"));
emit uploading(true);
}
else {
statusString = tr("Lightscreen");
ui.imgurPushButton->setIcon(QIcon(":/icons/imgur"));
emit uploading(false);
#ifdef Q_WS_WIN
if (mTaskbarButton) {
mTaskbarButton->SetProgresValue(0, 0);
mTaskbarButton->SetState(STATE_NOPROGRESS);
}
#endif
}
if (mTrayIcon) {
mTrayIcon->setToolTip(statusString);
}
setWindowTitle(statusString);
}
void LightscreenWindow::updaterDone(bool result)
{
settings()->setValue("lastUpdateCheck", QDate::currentDate().dayOfYear());
if (!result)
return;
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Lightscreen"));
msgBox.setText(tr("There's a new version of Lightscreen available.<br>Would you like to see more information?<br>(<em>You can turn this notification off</em>)"));
msgBox.setIcon(QMessageBox::Information);
QPushButton *yesButton = msgBox.addButton(QMessageBox::Yes);
QPushButton *turnOffButton = msgBox.addButton(tr("Turn Off"), QMessageBox::ActionRole);
QPushButton *remindButton = msgBox.addButton(tr("Remind Me Later"), QMessageBox::RejectRole);
Q_UNUSED(remindButton);
msgBox.exec();
if (msgBox.clickedButton() == yesButton) {
QDesktopServices::openUrl(QUrl("http://lightscreen.sourceforge.net/whatsnew/?from=" + qApp->applicationVersion()));
}
else if (msgBox.clickedButton() == turnOffButton) {
settings()->setValue("options/disableUpdater", true);
}
}
void LightscreenWindow::upload(const QString &fileName)
{
Uploader::instance()->upload(fileName);
}
void LightscreenWindow::uploadCancel()
{
if (Uploader::instance()->uploading() <= 0) {
return;
}
int confirm = QMessageBox::question(this, tr("Upload cancel"), tr("Do you want to cancel all screenshot uploads?"), tr("Cancel"), tr("Don't Cancel"));
if (confirm == 0) {
Uploader::instance()->cancel();
updateUploadStatus();
}
}
void LightscreenWindow::uploadLast()
{
upload(mLastScreenshot);
updateUploadStatus();
}
void LightscreenWindow::uploadProgress(qint64 sent, qint64 total)
{
#ifdef Q_WS_WIN
if (mTaskbarButton)
mTaskbarButton->SetProgresValue(sent, total);
if (isVisible()) {
int uploadCount = Uploader::instance()->uploading();
int progress = (sent*100)/total;
if (uploadCount > 1) {
setWindowTitle(tr("%1% of %2 uploads - Lightscreen").arg(progress).arg(uploadCount));
}
else {
setWindowTitle(tr("%1% - Lightscreen").arg(progress));
}
}
#endif
}
void LightscreenWindow::windowHotkey()
{
screenshotAction(1);
}
void LightscreenWindow::windowPickerHotkey()
{
screenshotAction(3);
}
//
void LightscreenWindow::applySettings()
{
bool tray = settings()->value("options/tray").toBool();
if (tray && !mTrayIcon) {
createTrayIcon();
mTrayIcon->show();
}
else if (!tray && mTrayIcon) {
mTrayIcon->deleteLater();
}
connectHotkeys();
mDoCache = false;
if (settings()->value("lastScreenshot").isValid())
mLastScreenshot = settings()->value("lastScreenshot").toString();
os::setStartup(settings()->value("options/startup").toBool(), settings()->value("options/startupHide").toBool());
}
//
void LightscreenWindow::connectHotkeys()
{
// Set to true because if the hotkey is disabled it will show an error.
bool screen = true, area = true, window = true, windowPicker = true, open = true, directory = true;
if (settings()->value("actions/screen/enabled").toBool())
screen = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/screen/hotkey").value<QKeySequence> (), this, SLOT(screenshotAction()));
if (settings()->value("actions/area/enabled").toBool())
area = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/area/hotkey").value<QKeySequence> (), this, SLOT(areaHotkey()));
if (settings()->value("actions/window/enabled").toBool())
window = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/window/hotkey").value<QKeySequence> (), this, SLOT(windowHotkey()));
if (settings()->value("actions/windowPicker/enabled").toBool())
windowPicker = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/windowPicker/hotkey").value<QKeySequence> (), this, SLOT(windowPickerHotkey()));
if (settings()->value("actions/open/enabled").toBool())
open = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/open/hotkey").value<QKeySequence> (), this, SLOT(show()));
if (settings()->value("actions/directory/enabled").toBool())
directory = GlobalShortcutManager::instance()->connect(settings()->value(
"actions/directory/hotkey").value<QKeySequence> (), this, SLOT(goToFolder()));
QStringList failed;
if (!screen) failed << "screen";
if (!area) failed << "area";
if (!window) failed << "window";
if (!windowPicker) failed << "window picker";
if (!open) failed << "open";
if (!directory) failed << "directory";
if (!failed.isEmpty())
showHotkeyError(failed);
}
void LightscreenWindow::createTrayIcon()
{
mTrayIcon = new QSystemTrayIcon(QIcon(":/icons/lightscreen.small"), this);
updateUploadStatus();
connect(mTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(toggleVisibility(QSystemTrayIcon::ActivationReason)));
connect(mTrayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
QAction *hideAction = new QAction(QIcon(":/icons/lightscreen.small"), tr("Show&/Hide"), mTrayIcon);
connect(hideAction, SIGNAL(triggered()), this, SLOT(toggleVisibility()));
QAction *screenAction = new QAction(QIcon(":/icons/screen"), tr("&Screen"), mTrayIcon);
screenAction->setData(QVariant(0));
QAction *windowAction = new QAction(QIcon(":/icons/window"), tr("Active &Window"), this);
windowAction->setData(QVariant(1));
QAction *windowPickerAction = new QAction(QIcon(":/icons/picker"), tr("&Pick Window"), this);
windowPickerAction->setData(QVariant(3));
QAction *areaAction = new QAction(QIcon(":/icons/area"), tr("&Area"), mTrayIcon);
areaAction->setData(QVariant(2));
QActionGroup *screenshotGroup = new QActionGroup(mTrayIcon);
screenshotGroup->addAction(screenAction);
screenshotGroup->addAction(areaAction);
screenshotGroup->addAction(windowAction);
screenshotGroup->addAction(windowPickerAction);
connect(screenshotGroup, SIGNAL(triggered(QAction*)), this, SLOT(screenshotActionTriggered(QAction*)));
// Duplicated for the screenshot button :(
QAction *uploadAction = new QAction(QIcon(":/icons/imgur"), tr("&Upload last"), mTrayIcon);
uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com"));
connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast()));
QAction *cancelAction = new QAction(QIcon(":/icons/no"), tr("&Cancel upload"), mTrayIcon);
cancelAction->setToolTip(tr("Cancel the currently uploading screenshots"));
cancelAction->setEnabled(false);
connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool)));
connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel()));
QAction *historyAction = new QAction(QIcon(":/icons/view-history"), tr("View History"), mTrayIcon);
connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog()));
//
QAction *optionsAction = new QAction(QIcon(":/icons/configure"), tr("View &Options"), mTrayIcon);
connect(optionsAction, SIGNAL(triggered()), this, SLOT(showOptions()));
QAction *goAction = new QAction(QIcon(":/icons/folder"), tr("&Go to Folder"), mTrayIcon);
connect(goAction, SIGNAL(triggered()), this, SLOT(goToFolder()));
QAction *quitAction = new QAction(tr("&Quit"), mTrayIcon);
connect(quitAction, SIGNAL(triggered()), this, SLOT(quit()));
QMenu* screenshotMenu = new QMenu(tr("Screenshot"));
screenshotMenu->addAction(screenAction);
screenshotMenu->addAction(areaAction);
screenshotMenu->addAction(windowAction);
screenshotMenu->addAction(windowPickerAction);
// Duplicated for the screenshot button :(
QMenu* imgurMenu = new QMenu(tr("Upload"));
imgurMenu->addAction(uploadAction);
imgurMenu->addAction(cancelAction);
imgurMenu->addAction(historyAction);
imgurMenu->addSeparator();
QMenu* trayIconMenu = new QMenu;
trayIconMenu->addAction(hideAction);
trayIconMenu->addSeparator();
trayIconMenu->addMenu(imgurMenu);
trayIconMenu->addSeparator();
trayIconMenu->addMenu(screenshotMenu);
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(goAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
mTrayIcon->setContextMenu(trayIconMenu);
}
#ifdef Q_WS_WIN
bool LightscreenWindow::winEvent(MSG *message, long *result)
{
Taskbar::GetInstance()->winEvent(message, result);
return false;
}
#endif
QSettings *LightscreenWindow::settings() const
{
return ScreenshotManager::instance()->settings();
}
// Event handling
bool LightscreenWindow::event(QEvent *event)
{
if (event->type() == QEvent::Hide) {
settings()->setValue("position", pos());
}
else if (event->type() == QEvent::Close) {
quit();
}
else if (event->type() == QEvent::Show) {
if (!settings()->value("position").toPoint().isNull())
move(settings()->value("position").toPoint());
}
else if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
#ifdef Q_WS_MAC
if (keyEvent->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period) {
keyEvent->ignore();
if(isVisible())
toggleVisibility();
return false;
}
else
#endif
if (!keyEvent->modifiers() && keyEvent->key() == Qt::Key_Escape) {
keyEvent->ignore();
if(isVisible())
toggleVisibility();
return false;
}
}
else if (event->type() == QEvent::LanguageChange) {
ui.retranslateUi(this);
resize(minimumSizeHint());
}
return QMainWindow::event(event);
}
diff --git a/tools/qtimgur.cpp b/tools/qtimgur.cpp
index 713de2b..e7e4e78 100644
--- a/tools/qtimgur.cpp
+++ b/tools/qtimgur.cpp
@@ -1,163 +1,163 @@
/*
* Copyright (C) 2011 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "qtimgur.h"
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QXmlStreamReader>
#include <QDebug>
QtImgur::QtImgur(const QString &APIKey, QObject *parent) : QObject(parent), mAPIKey(APIKey)
{
mNetworkManager = new QNetworkAccessManager(this);
connect(mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(reply(QNetworkReply*)));
}
void QtImgur::cancelAll()
{
foreach (QNetworkReply *reply, mFiles.keys()) {
reply->abort();
mFiles.remove(reply);
}
}
void QtImgur::cancel(const QString &fileName)
{
QNetworkReply *reply = mFiles.key(fileName);
if (!reply) {
return;
}
mFiles.remove(reply);
reply->abort();
}
void QtImgur::upload(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
emit error(fileName, QtImgur::ErrorFile);
return;
}
QByteArray image = file.readAll().toBase64();
file.close();
QByteArray data;
data.append(QString("key=").toUtf8());
data.append(QUrl::toPercentEncoding(mAPIKey));
data.append(QString("&caption=").toUtf8());
data.append(QUrl::toPercentEncoding(tr("Screenshot taken with Lightscreen - http://lightscreen.sf.net")));
data.append(QString("&image=").toUtf8());
data.append(QUrl::toPercentEncoding(image));
QNetworkRequest request(QUrl("http://api.imgur.com/2/upload"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply *reply = mNetworkManager->post(request, data);
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError)));
mFiles.insert(reply, fileName);
}
void QtImgur::progress(qint64 bytesSent, qint64 bytesTotal)
{
qint64 totalSent, totalTotal;
QNetworkReply *senderReply = qobject_cast<QNetworkReply*>(sender());
senderReply->setProperty("bytesSent", bytesSent);
senderReply->setProperty("bytesTotal", bytesTotal);
totalSent = bytesSent;
totalTotal = bytesTotal;
foreach (QNetworkReply *reply, mFiles.keys()) {
if (reply != senderReply) {
totalSent += reply->property("bytesSent").toLongLong();
totalTotal += reply->property("bytesTotal").toLongLong();
}
}
emit uploadProgress(totalSent, totalTotal);
}
void QtImgur::reply(QNetworkReply *reply)
{
QString fileName = mFiles[reply];
mFiles.remove(reply);
if (reply->error() == QNetworkReply::OperationCanceledError) {
qDebug() << "Error: " << reply->errorString();
emit error(fileName, QtImgur::ErrorCancel);
return;
}
if (reply->rawHeader("X-RateLimit-Remaining") == "0") {
emit error(fileName, QtImgur::ErrorCredits);
return;
}
QXmlStreamReader reader(reply->readAll());
QString url;
QString deleteHash;
- bool error = false;
+ bool hasError = false;
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement()) {
if (reader.name() == "error") {
- error = true;
+ hasError = true;
}
if (reader.name() == "deletehash") {
deleteHash = reader.readElementText();
}
if (reader.name() == "imgur_page") {
url = reader.readElementText();
}
}
}
- if (deleteHash.isEmpty() || url.isEmpty() || error) {
+ if (deleteHash.isEmpty() || url.isEmpty() || hasError) {
emit error(fileName, QtImgur::ErrorUpload);
}
else {
emit uploaded(fileName, url, deleteHash);
}
reply->deleteLater();
}
void QtImgur::replyError(QNetworkReply::NetworkError networkError) {
Q_UNUSED(networkError)
emit error(mFiles.value(qobject_cast<QNetworkReply*>(sender())), QtImgur::ErrorNetwork);
}
diff --git a/tools/qxtcsvmodel.cpp b/tools/qxtcsvmodel.cpp
deleted file mode 100644
index e61f539..0000000
--- a/tools/qxtcsvmodel.cpp
+++ /dev/null
@@ -1,552 +0,0 @@
-/****************************************************************************
-** Copyright (c) 2006 - 2011, the LibQxt project.
-** See the Qxt AUTHORS file for a list of authors and copyright holders.
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in the
-** documentation and/or other materials provided with the distribution.
-** * Neither the name of the LibQxt project nor the
-** names of its contributors may be used to endorse or promote products
-** derived from this software without specific prior written permission.
-**
-** 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
-** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
-** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-** (INCLUDING, 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 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 OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-** <http://libqxt.org> <foundation@libqxt.org>
-*****************************************************************************/
-
-/*!
-\class QxtCsvModel
-\inmodule QxtCore
-\brief The QxtCsvModel class provides a QAbstractTableModel for CSV Files
- */
-
-
-
-#include "qxtcsvmodel.h"
-#include <QFile>
-#include <QTextStream>
-#include <QDebug>
-
-class QxtCsvModelPrivate : public QxtPrivate<QxtCsvModel>
-{
-public:
- QxtCsvModelPrivate() : csvData(), header(), maxColumn(0), quoteMode(QxtCsvModel::DefaultQuoteMode)
- {}
- friend class QxtCsvModel;
-
- QList<QStringList> csvData;
- QStringList header;
- int maxColumn;
- QxtCsvModel::QuoteMode quoteMode;
-};
-
-/*!
- Creates an empty QxtCsvModel with parent \a parent.
- */
-QxtCsvModel::QxtCsvModel(QObject *parent) : QAbstractTableModel(parent)
-{
- QXT_INIT_PRIVATE(QxtCsvModel);
-}
-
-/*!
- Creates a QxtCsvModel with the parent \a parent and content loaded from \a file.
-
- See \a setSource for information on the \a withHeader and \a separator properties, or
- if you need control over the quoting method or codec used to parse the file.
-
- \sa setSource
- */
-QxtCsvModel::QxtCsvModel(QIODevice *file, QObject *parent, bool withHeader, QChar separator) : QAbstractTableModel(parent)
-{
- QXT_INIT_PRIVATE(QxtCsvModel);
- setSource(file, withHeader, separator);
-}
-
-/*!
- \overload
-
- Creates a QxtCsvModel with the parent \a parent and content loaded from \a file.
-
- See \a setSource for information on the \a withHeader and \a separator properties, or
- if you need control over the quoting method or codec used to parse the file.
-
- \sa setSource
- */
-QxtCsvModel::QxtCsvModel(const QString filename, QObject *parent, bool withHeader, QChar separator) : QAbstractTableModel(parent)
-{
- QXT_INIT_PRIVATE(QxtCsvModel);
- QFile src(filename);
- setSource(&src, withHeader, separator);
-}
-
-QxtCsvModel::~QxtCsvModel()
-{}
-
-/*!
- \reimp
- */
-int QxtCsvModel::rowCount(const QModelIndex& parent) const
-{
- if (parent.row() != -1 && parent.column() != -1) return 0;
- return qxt_d().csvData.count();
-}
-
-/*!
- \reimp
- */
-int QxtCsvModel::columnCount(const QModelIndex& parent) const
-{
- if (parent.row() != -1 && parent.column() != -1) return 0;
- return qxt_d().maxColumn;
-}
-
-/*!
- \reimp
- */
-QVariant QxtCsvModel::data(const QModelIndex& index, int role) const
-{
- if(index.parent() != QModelIndex()) return QVariant();
- if(role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::ToolTipRole || role == Qt::UserRole) {
- if(index.row() < 0 || index.column() < 0 || index.row() >= rowCount())
- return QVariant();
- const QStringList& row = qxt_d().csvData[index.row()];
- if(index.column() >= row.length())
- return QVariant();
- return row[index.column()];
- }
- return QVariant();
-}
-
-/*!
- \reimp
- */
-QVariant QxtCsvModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if(section < qxt_d().header.count() && orientation == Qt::Horizontal && (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole))
- return qxt_d().header[section];
- else
- return QAbstractTableModel::headerData(section, orientation, role);
-}
-
-/*!
- \overload
-
- Reads in a CSV file from the provided \a file using \a codec.
- */
-void QxtCsvModel::setSource(const QString filename, bool withHeader, QChar separator, QTextCodec* codec)
-{
- QFile src(filename);
- setSource(&src, withHeader, separator, codec);
-}
-
-/*!
- Reads in a CSV file from the provided \a file using \a codec.
-
- The value of \a separator will be used to delimit fields, subject to the specified \a quoteMode.
- If \a withHeader is set to true, the first line of the file will be used to populate the model's
- horizontal header.
-
- \sa quoteMode
- */
-void QxtCsvModel::setSource(QIODevice *file, bool withHeader, QChar separator, QTextCodec* codec)
-{
- QxtCsvModelPrivate* d_ptr = &qxt_d();
- bool headerSet = !withHeader;
- if(!file->isOpen())
- file->open(QIODevice::ReadOnly);
- if(withHeader)
- d_ptr->maxColumn = 0;
- else
- d_ptr->maxColumn = d_ptr->header.size();
- d_ptr->csvData.clear();
- QStringList row;
- QString field;
- QChar quote;
- QChar ch, buffer(0);
- bool readCR = false;
- QTextStream stream(file);
- if(codec) {
- stream.setCodec(codec);
- } else {
- stream.setAutoDetectUnicode(true);
- }
- while(!stream.atEnd()) {
- if(buffer != QChar(0)) {
- ch = buffer;
- buffer = QChar(0);
- } else {
- stream >> ch;
- }
- if(ch == '\n' && readCR)
- continue;
- else if(ch == '\r')
- readCR = true;
- else
- readCR = false;
- if(ch != separator && (ch.category() == QChar::Separator_Line || ch.category() == QChar::Separator_Paragraph || ch.category() == QChar::Other_Control)) {
- row << field;
- field.clear();
- if(!row.isEmpty()) {
- if(!headerSet) {
- d_ptr->header = row;
- headerSet = true;
- } else {
- d_ptr->csvData.append(row);
- }
- if(row.length() > d_ptr->maxColumn) {
- d_ptr->maxColumn = row.length();
- }
- }
- row.clear();
- } else if((d_ptr->quoteMode & DoubleQuote && ch == '"') || (d_ptr->quoteMode & SingleQuote && ch == '\'')) {
- quote = ch;
- do {
- stream >> ch;
- if(ch == '\\' && d_ptr->quoteMode & BackslashEscape) {
- stream >> ch;
- } else if(ch == quote) {
- if(d_ptr->quoteMode & TwoQuoteEscape) {
- stream >> buffer;
- if(buffer == quote) {
- buffer = QChar(0);
- field.append(ch);
- continue;
- }
- }
- break;
- }
- field.append(ch);
- } while(!stream.atEnd());
- } else if(ch == separator) {
- row << field;
- field.clear();
- } else {
- field.append(ch);
- }
- }
- if(!field.isEmpty())
- row << field;
- if(!row.isEmpty()) {
- if(!headerSet)
- d_ptr->header = row;
- else
- d_ptr->csvData.append(row);
- }
- file->close();
-}
-
-/*!
- Sets the horizontal headers of the model to the values provided in \a data.
- */
-void QxtCsvModel::setHeaderData(const QStringList& data)
-{
- qxt_d().header = data;
- emit headerDataChanged(Qt::Horizontal, 0, data.count());
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant& value, int role)
-{
- if(orientation != Qt::Horizontal) return false; // We don't support the vertical header
- if(role != Qt::DisplayRole || role != Qt::EditRole) return false; // We don't support any other roles
- if(section < 0) return false; // Bogus input
- while(section > qxt_d().header.size()) {
- qxt_d().header << QString();
- }
- qxt_d().header[section] = value.toString();
- emit headerDataChanged(Qt::Horizontal, section, section);
- return true;
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::setData(const QModelIndex& index, const QVariant& data, int role)
-{
- if (index.parent() != QModelIndex()) return false;
-
- if(role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole) {
- if(index.row() >= rowCount() || index.column() >= columnCount() || index.row() < 0 || index.column() < 0) return false;
- QStringList& row = qxt_d().csvData[index.row()];
- while(row.length() <= index.column())
- row << QString();
- row[index.column()] = data.toString();
- emit dataChanged(index, index);
- return true;
- }
- return false;
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::insertRow(int row, const QModelIndex& parent)
-{
- return insertRows(row, 1, parent);
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::insertRows(int row, int count, const QModelIndex& parent)
-{
- if (parent != QModelIndex() || row < 0) return false;
- emit beginInsertRows(parent, row, row + count);
- QxtCsvModelPrivate& d_ptr = qxt_d();
- if(row >= rowCount()) {
- for(int i = 0; i < count; i++) d_ptr.csvData << QStringList();
- } else {
- for(int i = 0; i < count; i++) d_ptr.csvData.insert(row, QStringList());
- }
- emit endInsertRows();
- return true;
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::removeRow(int row, const QModelIndex& parent)
-{
- return removeRows(row, 1, parent);
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::removeRows(int row, int count, const QModelIndex& parent)
-{
- if (parent != QModelIndex() || row < 0) return false;
- if (row >= rowCount()) return false;
- if (row + count >= rowCount()) count = rowCount() - row;
- emit beginRemoveRows(parent, row, row + count);
- QxtCsvModelPrivate& d_ptr = qxt_d();
- for (int i = 0;i < count;i++)
- d_ptr.csvData.removeAt(row);
- emit endRemoveRows();
- return true;
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::insertColumn(int col, const QModelIndex& parent)
-{
- return insertColumns(col, 1, parent);
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::insertColumns(int col, int count, const QModelIndex& parent)
-{
- if (parent != QModelIndex() || col < 0) return false;
- emit beginInsertColumns(parent, col, col + count);
- QxtCsvModelPrivate& d_ptr = qxt_d();
- for(int i = 0; i < rowCount(); i++) {
- QStringList& row = d_ptr.csvData[i];
- while(col >= row.length()) row.append(QString());
- for(int j = 0; j < count; j++) {
- row.insert(col, QString());
- }
- }
- for(int i = 0; i < count ;i++)
- d_ptr.header.insert(col, QString());
- d_ptr.maxColumn += count;
- emit endInsertColumns();
- return true;
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::removeColumn(int col, const QModelIndex& parent)
-{
- return removeColumns(col, 1, parent);
-}
-
-/*!
- \reimp
- */
-bool QxtCsvModel::removeColumns(int col, int count, const QModelIndex& parent)
-{
- if (parent != QModelIndex() || col < 0) return false;
- if (col >= columnCount()) return false;
- if (col + count >= columnCount()) count = columnCount() - col;
- emit beginRemoveColumns(parent, col, col + count);
- QxtCsvModelPrivate& d_ptr = qxt_d();
- QString before, after;
- for(int i = 0; i < rowCount(); i++) {
- for(int j = 0; j < count; j++) {
- d_ptr.csvData[i].removeAt(col);
- }
- }
- for(int i = 0; i < count; i++)
- d_ptr.header.removeAt(col);
- emit endRemoveColumns();
- return true;
-}
-
-static QString qxt_addCsvQuotes(QxtCsvModel::QuoteMode mode, QString field)
-{
- bool addDoubleQuotes = ((mode & QxtCsvModel::DoubleQuote) && field.contains('"'));
- bool addSingleQuotes = ((mode & QxtCsvModel::SingleQuote) && field.contains('\''));
- bool quoteField = (mode & QxtCsvModel::AlwaysQuoteOutput) || addDoubleQuotes || addSingleQuotes;
- if(quoteField && !addDoubleQuotes && !addSingleQuotes) {
- if(mode & QxtCsvModel::DoubleQuote)
- addDoubleQuotes = true;
- else if(mode & QxtCsvModel::SingleQuote)
- addSingleQuotes = true;
- }
- if(mode & QxtCsvModel::BackslashEscape) {
- if(addDoubleQuotes)
- return '"' + field.replace("\\", "\\\\").replace("\"", "\\\"") + '"';
- if(addSingleQuotes)
- return '\'' + field.replace("\\", "\\\\").replace("'", "\\'") + '\'';
- } else {
- if(addDoubleQuotes)
- return '"' + field.replace("\"", "\"\"") + '"';
- if(addSingleQuotes)
- return '\'' + field.replace("'", "''") + '\'';
- }
- return field;
-}
-
-/*!
- Outputs the content of the model as a CSV file to the device \a dest using \a codec.
-
- Fields in the output file will be separated by \a separator. Set \a withHeader to true
- to output a row of headers at the top of the file.
- */
-void QxtCsvModel::toCSV(QIODevice* dest, bool withHeader, QChar separator, QTextCodec* codec)
-{
- QxtCsvModelPrivate& d_ptr = qxt_d();
- int row, col, rows, cols;
- rows = rowCount();
- cols = columnCount();
- QString data;
- if(!dest->isOpen()) dest->open(QIODevice::WriteOnly | QIODevice::Truncate);
- QTextStream stream(dest);
- if(codec) stream.setCodec(codec);
- if(withHeader) {
- data = "";
- for(col = 0; col < cols; ++col) {
- if(col > 0) data += separator;
- data += qxt_addCsvQuotes(d_ptr.quoteMode, d_ptr.header.at(col));
- }
- stream << data << endl;
- }
- for(row = 0; row < rows; ++row)
- {
- const QStringList& rowData = d_ptr.csvData[row];
- data = "";
- for(col = 0; col < cols; ++col) {
- if(col > 0) data += separator;
- if(col < rowData.length())
- data += qxt_addCsvQuotes(d_ptr.quoteMode, rowData.at(col));
- else
- data += qxt_addCsvQuotes(d_ptr.quoteMode, QString());;
- }
- stream << data << endl;
- }
- stream << flush;
- dest->close();
-}
-
-/*!
- \overload
-
- Outputs the content of the model as a CSV file to the file specified by \a filename using \a codec.
-
- Fields in the output file will be separated by \a separator. Set \a withHeader to true
- to output a row of headers at the top of the file.
- */
-void QxtCsvModel::toCSV(const QString filename, bool withHeader, QChar separator, QTextCodec* codec)
-{
- QFile dest(filename);
- toCSV(&dest, withHeader, separator, codec);
-}
-
-/*!
- \reimp
- */
-Qt::ItemFlags QxtCsvModel::flags(const QModelIndex& index) const
-{
- return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
-}
-
-/*!
- * Returns the current quoting mode.
- * \sa setQuoteMode
- */
-QxtCsvModel::QuoteMode QxtCsvModel::quoteMode() const
-{
- return qxt_d().quoteMode;
-}
-
-/*!
- * Sets the current quoting mode. The default quoting mode is BothQuotes | BackslashEscape.
- *
- * The quoting mode determines what kinds of quoting is used for reading and writing CSV files.
- * \sa quoteMode
- * \sa QuoteOption
- */
-void QxtCsvModel::setQuoteMode(QuoteMode mode)
-{
- qxt_d().quoteMode = mode;
-}
-
-/*!
- Sets the content of the cell at row \a row and column \a column to \a value.
-
- \sa text
- */
-void QxtCsvModel::setText(int row, int column, const QString& value)
-{
- setData(index(row, column), value);
-}
-
-/*!
- Fetches the content of the cell at row \a row and column \a column.
-
- \sa setText
- */
-QString QxtCsvModel::text(int row, int column) const
-{
- return data(index(row, column)).toString();
-}
-
-/*!
- Sets the content of the header for column \a column to \a value.
-
- \sa headerText
- */
-void QxtCsvModel::setHeaderText(int column, const QString& value)
-{
- setHeaderData(column, Qt::Horizontal, value);
-}
-
-/*!
- Fetches the content of the cell at row \a row and column \a column.
-
- \sa setText
- */
-QString QxtCsvModel::headerText(int column) const
-{
- return headerData(column, Qt::Horizontal).toString();
-}
diff --git a/tools/qxtcsvmodel.h b/tools/qxtcsvmodel.h
deleted file mode 100644
index d3ad26f..0000000
--- a/tools/qxtcsvmodel.h
+++ /dev/null
@@ -1,172 +0,0 @@
-#ifndef QXTCSVMODEL_H
-/****************************************************************************
-** Copyright (c) 2006 - 2011, the LibQxt project.
-** See the Qxt AUTHORS file for a list of authors and copyright holders.
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-** * Redistributions of source code must retain the above copyright
-** notice, this list of conditions and the following disclaimer.
-** * Redistributions in binary form must reproduce the above copyright
-** notice, this list of conditions and the following disclaimer in the
-** documentation and/or other materials provided with the distribution.
-** * Neither the name of the LibQxt project nor the
-** names of its contributors may be used to endorse or promote products
-** derived from this software without specific prior written permission.
-**
-** 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
-** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
-** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-** (INCLUDING, 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 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 OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-** <http://libqxt.org> <foundation@libqxt.org>
-*****************************************************************************/
-
-#define QXTCSVMODEL_H
-
-#include <QAbstractTableModel>
-#include <QVariant>
-#include <QIODevice>
-#include <QChar>
-#include <QString>
-#include <QStringList>
-#include <QModelIndex>
-class QTextCodec;
-
-// From qxtglobal.h
-/****************************************************************************
-** This file is derived from code bearing the following notice:
-** The sole author of this file, Adam Higerd, has explicitly disclaimed all
-** copyright interest and protection for the content within. This file has
-** been placed in the public domain according to United States copyright
-** statute and case law. In jurisdictions where this public domain dedication
-** is not legally recognized, anyone who receives a copy of this file is
-** permitted to use, modify, duplicate, and redistribute this file, in whole
-** or in part, with no restrictions or conditions. In these jurisdictions,
-** this file shall be copyright (C) 2006-2008 by Adam Higerd.
-****************************************************************************/
-
-#define QXT_DECLARE_PRIVATE(PUB) friend class PUB##Private; QxtPrivateInterface<PUB, PUB##Private> qxt_d;
-#define QXT_DECLARE_PUBLIC(PUB) friend class PUB;
-#define QXT_INIT_PRIVATE(PUB) qxt_d.setPublic(this);
-#define QXT_D(PUB) PUB##Private& d = qxt_d()
-#define QXT_P(PUB) PUB& p = qxt_p()
-
-template <typename PUB>
-class QxtPrivate
-{
-public:
- virtual ~QxtPrivate()
- {}
- inline void QXT_setPublic(PUB* pub)
- {
- qxt_p_ptr = pub;
- }
-
-protected:
- inline PUB& qxt_p()
- {
- return *qxt_p_ptr;
- }
- inline const PUB& qxt_p() const
- {
- return *qxt_p_ptr;
- }
-
-private:
- PUB* qxt_p_ptr;
-};
-
-template <typename PUB, typename PVT>
-class QxtPrivateInterface
-{
- friend class QxtPrivate<PUB>;
-public:
- QxtPrivateInterface()
- {
- pvt = new PVT;
- }
- ~QxtPrivateInterface()
- {
- delete pvt;
- }
-
- inline void setPublic(PUB* pub)
- {
- pvt->QXT_setPublic(pub);
- }
- inline PVT& operator()()
- {
- return *static_cast<PVT*>(pvt);
- }
- inline const PVT& operator()() const
- {
- return *static_cast<PVT*>(pvt);
- }
-private:
- QxtPrivateInterface(const QxtPrivateInterface&) { }
- QxtPrivateInterface& operator=(const QxtPrivateInterface&) { }
- QxtPrivate<PUB>* pvt;
-};
-//
-
-class QxtCsvModelPrivate;
-class QxtCsvModel : public QAbstractTableModel
-{
- Q_OBJECT
-public:
- QxtCsvModel(QObject *parent = 0);
- explicit QxtCsvModel(QIODevice *file, QObject *parent = 0, bool withHeader = false, QChar separator = ',');
- explicit QxtCsvModel(const QString filename, QObject *parent = 0, bool withHeader = false, QChar separator = ',');
- ~QxtCsvModel();
-
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex& index, const QVariant& data, int role = Qt::EditRole);
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant& value, int role = Qt::DisplayRole);
- void setHeaderData(const QStringList& data);
- QString text(int row, int column) const;
- void setText(int row, int column, const QString& value);
- QString headerText(int column) const;
- void setHeaderText(int column, const QString& value);
-
-
- bool insertRow(int row, const QModelIndex& parent = QModelIndex());
- bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex());
- bool removeRow(int row, const QModelIndex& parent = QModelIndex());
- bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
- bool insertColumn(int col, const QModelIndex& parent = QModelIndex());
- bool insertColumns(int col, int count, const QModelIndex& parent = QModelIndex());
- bool removeColumn(int col, const QModelIndex& parent = QModelIndex());
- bool removeColumns(int col, int count, const QModelIndex& parent = QModelIndex());
-
- void setSource(QIODevice *file, bool withHeader = false, QChar separator = ',', QTextCodec* codec = 0);
- void setSource(const QString filename, bool withHeader = false, QChar separator = ',', QTextCodec* codec = 0);
-
- void toCSV(QIODevice *file, bool withHeader = false, QChar separator = ',', QTextCodec* codec = 0);
- void toCSV(const QString filename, bool withHeader = false, QChar separator = ',', QTextCodec* codec = 0);
-
- enum QuoteOption { NoQuotes = 0, SingleQuote = 1, DoubleQuote = 2, BothQuotes = 3,
- NoEscape = 0, TwoQuoteEscape = 4, BackslashEscape = 8,
- AlwaysQuoteOutput = 16, DefaultQuoteMode = BothQuotes | BackslashEscape | AlwaysQuoteOutput };
- Q_DECLARE_FLAGS(QuoteMode, QuoteOption)
- QuoteMode quoteMode() const;
- void setQuoteMode(QuoteMode mode);
-
- Qt::ItemFlags flags(const QModelIndex& index) const;
-
-private:
- QXT_DECLARE_PRIVATE(QxtCsvModel)
-};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QxtCsvModel::QuoteMode)
-
-#endif
diff --git a/tools/screenshotmanager.cpp b/tools/screenshotmanager.cpp
index 3e9d617..43786a9 100644
--- a/tools/screenshotmanager.cpp
+++ b/tools/screenshotmanager.cpp
@@ -1,148 +1,154 @@
/*
* Copyright (C) 2011 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "screenshotmanager.h"
#include "screenshot.h"
#include "uploader.h"
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QDesktopServices>
#include <QFile>
#include <QSettings>
+#include <QtSql/QSqlDatabase>
+#include <QtSql/QSqlQuery>
ScreenshotManager::ScreenshotManager(QObject *parent = 0) : QObject(parent)
{
+ QString historyPath;
+
if (QFile::exists(qApp->applicationDirPath() + "/config.ini")) {
mSettings = new QSettings(qApp->applicationDirPath() + QDir::separator() + "config.ini", QSettings::IniFormat);
- mHistoryPath = qApp->applicationDirPath() + QDir::separator() + "history";
mPortableMode = true;
+ historyPath = qApp->applicationDirPath() + QDir::separator() + "history.sqlite";
}
else {
mSettings = new QSettings();
- mHistoryPath = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QDir::separator() + "history";
mPortableMode = false;
+ historyPath = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QDir::separator() + "history.sqlite";
+ }
+
+ // Creating the SQLite database.
+ mHistory = QSqlDatabase::addDatabase("QSQLITE");
+ mHistory.setDatabaseName(historyPath);
+
+ if (mHistory.open()) {
+ mHistory.exec("CREATE TABLE IF NOT EXISTS history (fileName text, URL text, deleteURL text, time integer)");
}
connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(uploadDone(QString, QString, QString)));
}
ScreenshotManager::~ScreenshotManager()
{
delete mSettings;
}
int ScreenshotManager::activeCount() const
{
return mScreenshots.count();
}
-QString& ScreenshotManager::historyPath()
-{
- return mHistoryPath;
-}
-
bool ScreenshotManager::portableMode()
{
return mPortableMode;
}
void ScreenshotManager::saveHistory(QString fileName, QString url, QString deleteHash)
{
if (!mSettings->value("/options/history", true).toBool())
return;
- QFile historyFile(mHistoryPath);
- QTextStream out(&historyFile);
-
- if (!historyFile.exists())
- {
- QString path = mHistoryPath;
- path.chop(7);
+ if (!mHistory.isOpen())
+ return;
- if (!QDir().mkpath(path))
- return;
- }
+ mHistory.exec(QString("INSERT INTO history (fileName, URL, deleteURL, time) VALUES('%1', '%2', '%3', %4)")
+ .arg(fileName)
+ .arg(url)
+ .arg("http://imgur.com/delete/" + deleteHash)
+ .arg(QDateTime::currentMSecsSinceEpoch())
+ );
+}
- if (historyFile.open(QFile::WriteOnly | QFile::Append)) {
- out << QString("%1|%2|%3|%4").arg(fileName).arg(url).arg(deleteHash).arg(QDateTime::currentMSecsSinceEpoch()) << "\n";
- historyFile.close();
- }
+void ScreenshotManager::clearHistory()
+{
+ if (mHistory.isOpen())
+ mHistory.exec("DROP TABLE history");
}
//
void ScreenshotManager::askConfirmation()
{
Screenshot* s = qobject_cast<Screenshot*>(sender());
emit confirm(s);
}
void ScreenshotManager::cleanup()
{
Screenshot* screenshot = qobject_cast<Screenshot*>(sender());
emit windowCleanup(screenshot->options());
}
void ScreenshotManager::finished()
{
Screenshot* screenshot = qobject_cast<Screenshot*>(sender());
mScreenshots.removeOne(screenshot);
screenshot->deleteLater();
}
void ScreenshotManager::take(Screenshot::Options &options)
{
Screenshot* newScreenshot = new Screenshot(this, options);
mScreenshots.append(newScreenshot);
connect(newScreenshot, SIGNAL(askConfirmation()), this, SLOT(askConfirmation()));
connect(newScreenshot, SIGNAL(cleanup()) , this, SLOT(cleanup()));
connect(newScreenshot, SIGNAL(finished()) , this, SLOT(finished()));
newScreenshot->take();
}
void ScreenshotManager::uploadDone(QString fileName, QString url, QString deleteHash)
{
foreach (Screenshot* screenshot, mScreenshots) {
if (screenshot->options().fileName == fileName
|| screenshot->unloadedFileName() == fileName) {
screenshot->uploadDone(url);
if (screenshot->options().file) {
saveHistory(fileName, url, deleteHash);
}
else {
- saveHistory(QObject::tr("- no file -"), url, deleteHash);
+ saveHistory("", url, deleteHash);
}
}
}
}
// Singleton
ScreenshotManager* ScreenshotManager::mInstance = 0;
ScreenshotManager *ScreenshotManager::instance()
{
if (!mInstance)
mInstance = new ScreenshotManager();
return mInstance;
}
diff --git a/tools/screenshotmanager.h b/tools/screenshotmanager.h
index c3d0210..9818416 100644
--- a/tools/screenshotmanager.h
+++ b/tools/screenshotmanager.h
@@ -1,71 +1,72 @@
/*
* Copyright (C) 2011 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef SCREENSHOTMANAGER_H
#define SCREENSHOTMANAGER_H
#include <QObject>
#include <QList>
+#include <QtSql/QSqlDatabase>
#include "screenshot.h"
-#include "qxtcsvmodel.h"
class QSettings;
class ScreenshotManager : public QObject
{
Q_OBJECT
public:
enum State
{
Idle = 0,
Busy = 1,
Disabled = 2
};
public:
ScreenshotManager(QObject *parent);
~ScreenshotManager();
static ScreenshotManager *instance();
int activeCount() const;
- QString &historyPath();
bool portableMode();
- void saveHistory(QString fileName, QString url = QObject::tr("- not uploaded -"), QString deleteHash = "");
+ void saveHistory(QString fileName, QString url = "", QString deleteHash = "");
+ void clearHistory();
QSettings *settings() const { return mSettings; }
+ QSqlDatabase &history() { return mHistory; }
public slots:
void askConfirmation();
void cleanup();
void finished();
void take(Screenshot::Options &options);
void uploadDone(QString fileName, QString url, QString deleteHash);
signals:
void confirm(Screenshot* screenshot);
void windowCleanup(Screenshot::Options &options);
private:
static ScreenshotManager* mInstance;
QList<Screenshot*> mScreenshots;
QSettings *mSettings;
- QString mHistoryPath;
+ QSqlDatabase mHistory;
bool mPortableMode;
};
#endif // SCREENSHOTMANAGER_H

File Metadata

Mime Type
text/x-diff
Expires
Mon, Jun 15, 11:35 PM (2 w, 2 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
70116
Default Alt Text
(78 KB)

Event Timeline