1
mirror of https://invent.kde.org/network/falkon.git synced 2024-12-20 02:36:34 +01:00

Coding style, fixed cppcheck warnings + improved html highlighter

- html highlighter is now highlighting with reg exps, no more with hard
coded tags/tag options
 - all cppecheck warnings fixed + added script (cppcheck.sh)
 - introduced coding style + added astyle script (coding_style.sh)
 - fixed one mistake in czech translate + updated windows installer
This commit is contained in:
nowrep 2011-11-06 17:01:23 +01:00
parent 959fc9b450
commit 2cb067878d
195 changed files with 4316 additions and 3051 deletions

Binary file not shown.

View File

@ -1,2 +1,5 @@
#!/bin/bash #!/bin/bash
cat /usr/share/ca-certificates/*/*.crt > ../other/ca-bundle.crt cat /usr/share/ca-certificates/*/*.crt > ../other/ca-bundle.crt
read -p "Press [ENTER] to close terminal"
exit

View File

@ -21,11 +21,12 @@
// Windows only definitions // Windows only definitions
#ifdef W7API #ifdef W7API
DEFINE_GUID(CLSID_TaskbarList,0x56fdf344,0xfd6d,0x11d0,0x95,0x8a,0x0,0x60,0x97,0xc9,0xa0,0x90); DEFINE_GUID(CLSID_TaskbarList, 0x56fdf344, 0xfd6d, 0x11d0, 0x95, 0x8a, 0x0, 0x60, 0x97, 0xc9, 0xa0, 0x90);
DEFINE_GUID(IID_ITaskbarList3,0xea1afb91,0x9e28,0x4b86,0x90,0xE9,0x9e,0x9f,0x8a,0x5e,0xef,0xaf); DEFINE_GUID(IID_ITaskbarList3, 0xea1afb91, 0x9e28, 0x4b86, 0x90, 0xE9, 0x9e, 0x9f, 0x8a, 0x5e, 0xef, 0xaf);
// Constructor: variabiles initialization // Constructor: variabiles initialization
EcWin7::EcWin7() EcWin7::EcWin7()
, mTaskBar(NULL)
{ {
mOverlayIcon = NULL; mOverlayIcon = NULL;
} }
@ -39,15 +40,14 @@ void EcWin7::init(WId wid)
// Windows event handler callback function // Windows event handler callback function
// (handles taskbar communication initial message) // (handles taskbar communication initial message)
bool EcWin7::winEvent(MSG * message, long * result) bool EcWin7::winEvent(MSG* message, long* result)
{ {
if (message->message == mTaskbarMessageId) if (message->message == mTaskbarMessageId) {
{
HRESULT hr = CoCreateInstance(CLSID_TaskbarList, HRESULT hr = CoCreateInstance(CLSID_TaskbarList,
0, 0,
CLSCTX_INPROC_SERVER, CLSCTX_INPROC_SERVER,
IID_ITaskbarList3, IID_ITaskbarList3,
reinterpret_cast<void**> (&(mTaskbar))); reinterpret_cast<void**>(&(mTaskbar)));
*result = hr; *result = hr;
return true; return true;
} }
@ -72,24 +72,23 @@ void EcWin7::setProgressState(ToolBarProgressState state)
void EcWin7::setOverlayIcon(QString iconName, QString description) void EcWin7::setOverlayIcon(QString iconName, QString description)
{ {
HICON oldIcon = NULL; HICON oldIcon = NULL;
if (mOverlayIcon != NULL) oldIcon = mOverlayIcon; if (mOverlayIcon != NULL) {
if (iconName == "") oldIcon = mOverlayIcon;
{ }
if (iconName == "") {
mTaskbar->SetOverlayIcon(mWindowId, NULL, NULL); mTaskbar->SetOverlayIcon(mWindowId, NULL, NULL);
mOverlayIcon = NULL; mOverlayIcon = NULL;
} }
else else {
{
mOverlayIcon = (HICON) LoadImage(GetModuleHandle(NULL), mOverlayIcon = (HICON) LoadImage(GetModuleHandle(NULL),
iconName.toStdWString().c_str(), iconName.toStdWString().c_str(),
IMAGE_ICON, IMAGE_ICON,
0, 0,
0, 0,
NULL); NULL);
mTaskbar->SetOverlayIcon(mWindowId, mOverlayIcon, description.toStdWString().c_str()); mTaskbar->SetOverlayIcon(mWindowId, mOverlayIcon, description.toStdWString().c_str());
} }
if ((oldIcon != NULL) && (oldIcon != mOverlayIcon)) if ((oldIcon != NULL) && (oldIcon != mOverlayIcon)) {
{
DestroyIcon(oldIcon); DestroyIcon(oldIcon);
} }
} }

14
src/3rdparty/ecwin7.h vendored
View File

@ -41,16 +41,16 @@ class EcWin7
{ {
public: public:
// Initialization methods // Initialization methods
EcWin7(); EcWin7();
void init(WId wid); void init(WId wid);
bool winEvent(MSG * message, long * result); bool winEvent(MSG* message, long* result);
// Overlay icon handling // Overlay icon handling
void setOverlayIcon(QString iconName, QString description); void setOverlayIcon(QString iconName, QString description);
// Progress indicator handling // Progress indicator handling
enum ToolBarProgressState { enum ToolBarProgressState {
NoProgress = 0, NoProgress = 0,
Indeterminate = 1, Indeterminate = 1,
Normal = 2, Normal = 2,
@ -63,7 +63,7 @@ public:
private: private:
WId mWindowId; WId mWindowId;
UINT mTaskbarMessageId; UINT mTaskbarMessageId;
ITaskbarList3 *mTaskbar; ITaskbarList3* mTaskbar;
HICON mOverlayIcon; HICON mOverlayIcon;
}; };
// Windows only data definitions - END // Windows only data definitions - END

View File

@ -56,165 +56,173 @@ const int FancyTabBar::m_textPadding = 4;
void FancyTabProxyStyle::drawControl( void FancyTabProxyStyle::drawControl(
ControlElement element, const QStyleOption* option, ControlElement element, const QStyleOption* option,
QPainter* p, const QWidget* widget) const { QPainter* p, const QWidget* widget) const
{
const QStyleOptionTabV3* v_opt = qstyleoption_cast<const QStyleOptionTabV3*>(option); const QStyleOptionTabV3* v_opt = qstyleoption_cast<const QStyleOptionTabV3*>(option);
if (element != CE_TabBarTab || !v_opt) { if (element != CE_TabBarTab || !v_opt) {
QProxyStyle::drawControl(element, option, p, widget); QProxyStyle::drawControl(element, option, p, widget);
return; return;
} }
const QRect rect = v_opt->rect; const QRect rect = v_opt->rect;
const bool selected = v_opt->state & State_Selected; const bool selected = v_opt->state & State_Selected;
const bool vertical_tabs = v_opt->shape == QTabBar::RoundedWest; const bool vertical_tabs = v_opt->shape == QTabBar::RoundedWest;
const QString text = v_opt->text; const QString text = v_opt->text;
if (selected) {
//background
p->save();
QLinearGradient grad(rect.topLeft(), rect.topRight());
grad.setColorAt(0, QColor(255, 255, 255, 140));
grad.setColorAt(1, QColor(255, 255, 255, 210));
p->fillRect(rect.adjusted(0, 0, 0, -1), grad);
p->restore();
//shadows
p->setPen(QColor(0, 0, 0, 110));
p->drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1));
p->drawLine(rect.bottomLeft(), rect.bottomRight());
p->setPen(QColor(0, 0, 0, 40));
p->drawLine(rect.topLeft(), rect.bottomLeft());
//highlights
p->setPen(QColor(255, 255, 255, 50));
p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2));
p->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1));
p->setPen(QColor(255, 255, 255, 40));
p->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
p->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
p->drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1));
}
QTransform m;
if (vertical_tabs) {
m = QTransform::fromTranslate(rect.left(), rect.bottom());
m.rotate(-90);
}
else {
m = QTransform::fromTranslate(rect.left(), rect.top());
}
const QRect draw_rect(QPoint(0, 0), m.mapRect(rect).size());
if (selected) {
//background
p->save(); p->save();
QLinearGradient grad(rect.topLeft(), rect.topRight()); p->setTransform(m);
grad.setColorAt(0, QColor(255, 255, 255, 140));
grad.setColorAt(1, QColor(255, 255, 255, 210));
p->fillRect(rect.adjusted(0, 0, 0, -1), grad);
p->restore();
//shadows QRect icon_rect(QPoint(8, 0), v_opt->iconSize);
p->setPen(QColor(0, 0, 0, 110)); QRect text_rect(icon_rect.topRight() + QPoint(4, 0), draw_rect.size());
p->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1)); text_rect.setRight(draw_rect.width());
p->drawLine(rect.bottomLeft(), rect.bottomRight()); icon_rect.translate(0, (draw_rect.height() - icon_rect.height()) / 2);
p->setPen(QColor(0, 0, 0, 40));
p->drawLine(rect.topLeft(), rect.bottomLeft());
//highlights QFont boldFont(p->font());
p->setPen(QColor(255, 255, 255, 50)); boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2)); boldFont.setBold(true);
p->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1)); p->setFont(boldFont);
p->setPen(QColor(255, 255, 255, 40)); p->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
p->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()); int textFlags = Qt::AlignHCenter | Qt::AlignVCenter;
p->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)); p->drawText(text_rect, textFlags, text);
p->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1)); p->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
}
QTransform m;
if (vertical_tabs) {
m = QTransform::fromTranslate(rect.left(), rect.bottom());
m.rotate(-90);
} else {
m = QTransform::fromTranslate(rect.left(), rect.top());
}
const QRect draw_rect(QPoint(0, 0), m.mapRect(rect).size());
p->save();
p->setTransform(m);
QRect icon_rect(QPoint(8, 0), v_opt->iconSize);
QRect text_rect(icon_rect.topRight() + QPoint(4, 0), draw_rect.size());
text_rect.setRight(draw_rect.width());
icon_rect.translate(0, (draw_rect.height() - icon_rect.height()) / 2);
QFont boldFont(p->font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true);
p->setFont(boldFont);
p->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
int textFlags = Qt::AlignHCenter | Qt::AlignVCenter;
p->drawText(text_rect, textFlags, text);
p->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
#ifndef Q_WS_MAC #ifndef Q_WS_MAC
if (widget) { if (widget) {
const QString fader_key = "tab_" + text + "_fader"; const QString fader_key = "tab_" + text + "_fader";
const QString animation_key = "tab_" + text + "_animation"; const QString animation_key = "tab_" + text + "_animation";
const QString tab_hover = widget->property("tab_hover").toString(); const QString tab_hover = widget->property("tab_hover").toString();
int fader = widget->property(fader_key.toUtf8().constData()).toInt(); int fader = widget->property(fader_key.toUtf8().constData()).toInt();
QPropertyAnimation* animation = widget->property(animation_key.toUtf8().constData()).value<QPropertyAnimation*>(); QPropertyAnimation* animation = widget->property(animation_key.toUtf8().constData()).value<QPropertyAnimation*>();
if (!animation) { if (!animation) {
QWidget* mut_widget = const_cast<QWidget*>(widget); QWidget* mut_widget = const_cast<QWidget*>(widget);
fader = 0; fader = 0;
mut_widget->setProperty(fader_key.toUtf8().constData(), fader); mut_widget->setProperty(fader_key.toUtf8().constData(), fader);
animation = new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget); animation = new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget);
connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update())); connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update()));
mut_widget->setProperty(animation_key.toUtf8().constData(), QVariant::fromValue(animation)); mut_widget->setProperty(animation_key.toUtf8().constData(), QVariant::fromValue(animation));
}
if (text == tab_hover) {
if (animation->state() != QAbstractAnimation::Running && fader != 40) {
animation->stop();
animation->setDuration(80);
animation->setEndValue(40);
animation->start();
}
}
else {
if (animation->state() != QAbstractAnimation::Running && fader != 0) {
animation->stop();
animation->setDuration(160);
animation->setEndValue(0);
animation->start();
}
}
if (!selected) {
p->save();
QLinearGradient grad(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
p->fillRect(draw_rect, grad);
p->setPen(QPen(grad, 1.0));
p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
p->drawLine(draw_rect.bottomRight(), vertical_tabs ? draw_rect.topRight() : draw_rect.bottomLeft());
p->restore();
}
} }
if (text == tab_hover) {
if (animation->state() != QAbstractAnimation::Running && fader != 40) {
animation->stop();
animation->setDuration(80);
animation->setEndValue(40);
animation->start();
}
} else {
if (animation->state() != QAbstractAnimation::Running && fader != 0) {
animation->stop();
animation->setDuration(160);
animation->setEndValue(0);
animation->start();
}
}
if (!selected) {
p->save();
QLinearGradient grad(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
p->fillRect(draw_rect, grad);
p->setPen(QPen(grad, 1.0));
p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
p->drawLine(draw_rect.bottomRight(), vertical_tabs ? draw_rect.topRight() : draw_rect.bottomLeft());
p->restore();
}
}
#endif #endif
Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, QIcon::Normal); Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, QIcon::Normal);
p->drawText(text_rect.translated(0, -1), textFlags, text); p->drawText(text_rect.translated(0, -1), textFlags, text);
p->restore(); p->restore();
} }
void FancyTabProxyStyle::polish(QWidget* widget) { void FancyTabProxyStyle::polish(QWidget* widget)
if (QString(widget->metaObject()->className()) == "QTabBar") { {
widget->setMouseTracking(true); if (QString(widget->metaObject()->className()) == "QTabBar") {
widget->installEventFilter(this); widget->setMouseTracking(true);
} widget->installEventFilter(this);
QProxyStyle::polish(widget); }
QProxyStyle::polish(widget);
} }
void FancyTabProxyStyle::polish(QApplication* app) { void FancyTabProxyStyle::polish(QApplication* app)
QProxyStyle::polish(app); {
QProxyStyle::polish(app);
} }
void FancyTabProxyStyle::polish(QPalette& palette) { void FancyTabProxyStyle::polish(QPalette &palette)
QProxyStyle::polish(palette); {
QProxyStyle::polish(palette);
} }
bool FancyTabProxyStyle::eventFilter(QObject* o, QEvent* e) { bool FancyTabProxyStyle::eventFilter(QObject* o, QEvent* e)
QTabBar* bar = qobject_cast<QTabBar*>(o); {
if (bar && (e->type() == QEvent::MouseMove || e->type() == QEvent::Leave)) { QTabBar* bar = qobject_cast<QTabBar*>(o);
QMouseEvent* event = static_cast<QMouseEvent*>(e); if (bar && (e->type() == QEvent::MouseMove || e->type() == QEvent::Leave)) {
const QString old_hovered_tab = bar->property("tab_hover").toString(); QMouseEvent* event = static_cast<QMouseEvent*>(e);
const QString hovered_tab = e->type() == QEvent::Leave ? QString() : bar->tabText(bar->tabAt(event->pos())); const QString old_hovered_tab = bar->property("tab_hover").toString();
bar->setProperty("tab_hover", hovered_tab); const QString hovered_tab = e->type() == QEvent::Leave ? QString() : bar->tabText(bar->tabAt(event->pos()));
bar->setProperty("tab_hover", hovered_tab);
if (old_hovered_tab != hovered_tab) if (old_hovered_tab != hovered_tab) {
bar->update(); bar->update();
} }
}
return false; return false;
} }
FancyTab::FancyTab(QWidget* tabbar) FancyTab::FancyTab(QWidget* tabbar)
: QWidget(tabbar), tabbar(tabbar), m_fader(0) : QWidget(tabbar), tabbar(tabbar), m_fader(0)
{ {
animator.setPropertyName("fader"); animator.setPropertyName("fader");
animator.setTargetObject(this); animator.setTargetObject(this);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
} }
void FancyTab::fadeIn() void FancyTab::fadeIn()
@ -239,7 +247,7 @@ void FancyTab::setFader(float value)
tabbar->update(); tabbar->update();
} }
FancyTabBar::FancyTabBar(QWidget *parent) FancyTabBar::FancyTabBar(QWidget* parent)
: QWidget(parent) : QWidget(parent)
{ {
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
@ -265,42 +273,45 @@ FancyTabBar::~FancyTabBar()
delete style(); delete style();
} }
QSize FancyTab::sizeHint() const { QSize FancyTab::sizeHint() const
QFont boldFont(font()); {
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); QFont boldFont(font());
boldFont.setBold(true); boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
QFontMetrics fm(boldFont); boldFont.setBold(true);
int spacing = 8; QFontMetrics fm(boldFont);
int width = 60 + spacing + 2; int spacing = 8;
int iconHeight = 32; int width = 60 + spacing + 2;
QSize ret(width, iconHeight + spacing + fm.height()); int iconHeight = 32;
return ret; QSize ret(width, iconHeight + spacing + fm.height());
return ret;
} }
QSize FancyTabBar::tabSizeHint(bool minimum) const QSize FancyTabBar::tabSizeHint(bool minimum) const
{ {
QFont boldFont(font()); QFont boldFont(font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true); boldFont.setBold(true);
QFontMetrics fm(boldFont); QFontMetrics fm(boldFont);
int spacing = 8; int spacing = 8;
int width = 60 + spacing + 2; int width = 60 + spacing + 2;
int iconHeight = minimum ? 0 : 32; int iconHeight = minimum ? 0 : 32;
return QSize(width, iconHeight + spacing + fm.height()); return QSize(width, iconHeight + spacing + fm.height());
} }
void FancyTabBar::paintEvent(QPaintEvent *event) void FancyTabBar::paintEvent(QPaintEvent* event)
{ {
Q_UNUSED(event) Q_UNUSED(event)
QPainter p(this); QPainter p(this);
for (int i = 0; i < count(); ++i) for (int i = 0; i < count(); ++i)
if (i != currentIndex()) if (i != currentIndex()) {
paintTab(&p, i); paintTab(&p, i);
}
// paint active tab last, since it overlaps the neighbors // paint active tab last, since it overlaps the neighbors
if (currentIndex() != -1) if (currentIndex() != -1) {
paintTab(&p, currentIndex()); paintTab(&p, currentIndex());
}
} }
void FancyTab::enterEvent(QEvent*) void FancyTab::enterEvent(QEvent*)
@ -330,12 +341,14 @@ QRect FancyTabBar::tabRect(int index) const
return m_tabs[index]->geometry(); return m_tabs[index]->geometry();
} }
QString FancyTabBar::tabToolTip(int index) const { QString FancyTabBar::tabToolTip(int index) const
return m_tabs[index]->toolTip(); {
return m_tabs[index]->toolTip();
} }
void FancyTabBar::setTabToolTip(int index, const QString& toolTip) { void FancyTabBar::setTabToolTip(int index, const QString &toolTip)
m_tabs[index]->setToolTip(toolTip); {
m_tabs[index]->setToolTip(toolTip);
} }
// This keeps the sidebar responsive since // This keeps the sidebar responsive since
@ -346,7 +359,7 @@ void FancyTabBar::emitCurrentIndex()
emit currentChanged(m_currentIndex); emit currentChanged(m_currentIndex);
} }
void FancyTabBar::mousePressEvent(QMouseEvent *e) void FancyTabBar::mousePressEvent(QMouseEvent* e)
{ {
e->accept(); e->accept();
for (int index = 0; index < m_tabs.count(); ++index) { for (int index = 0; index < m_tabs.count(); ++index) {
@ -359,20 +372,22 @@ void FancyTabBar::mousePressEvent(QMouseEvent *e)
} }
} }
void FancyTabBar::addTab(const QIcon& icon, const QString& label) { void FancyTabBar::addTab(const QIcon &icon, const QString &label)
FancyTab *tab = new FancyTab(this); {
tab->icon = icon; FancyTab* tab = new FancyTab(this);
tab->text = label; tab->icon = icon;
m_tabs.append(tab); tab->text = label;
qobject_cast<QVBoxLayout*>(layout())->insertWidget(layout()->count()-1, tab); m_tabs.append(tab);
qobject_cast<QVBoxLayout*>(layout())->insertWidget(layout()->count() - 1, tab);
} }
void FancyTabBar::addSpacer(int size) { void FancyTabBar::addSpacer(int size)
qobject_cast<QVBoxLayout*>(layout())->insertSpacerItem(layout()->count()-1, {
new QSpacerItem(0, size, QSizePolicy::Fixed, QSizePolicy::Maximum)); qobject_cast<QVBoxLayout*>(layout())->insertSpacerItem(layout()->count() - 1,
new QSpacerItem(0, size, QSizePolicy::Fixed, QSizePolicy::Maximum));
} }
void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const void FancyTabBar::paintTab(QPainter* painter, int tabIndex) const
{ {
if (!validIndex(tabIndex)) { if (!validIndex(tabIndex)) {
qWarning("invalid index"); qWarning("invalid index");
@ -394,19 +409,19 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
//shadows //shadows
painter->setPen(QColor(0, 0, 0, 110)); painter->setPen(QColor(0, 0, 0, 110));
painter->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1)); painter->drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1));
painter->drawLine(rect.bottomLeft(), rect.bottomRight()); painter->drawLine(rect.bottomLeft(), rect.bottomRight());
painter->setPen(QColor(0, 0, 0, 40)); painter->setPen(QColor(0, 0, 0, 40));
painter->drawLine(rect.topLeft(), rect.bottomLeft()); painter->drawLine(rect.topLeft(), rect.bottomLeft());
//highlights //highlights
painter->setPen(QColor(255, 255, 255, 50)); painter->setPen(QColor(255, 255, 255, 50));
painter->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2)); painter->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2));
painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1)); painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1));
painter->setPen(QColor(255, 255, 255, 40)); painter->setPen(QColor(255, 255, 255, 40));
painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight()); painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
painter->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1)); painter->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
painter->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1)); painter->drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1));
} }
QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), Qt::ElideMiddle, width())); QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), Qt::ElideMiddle, width()));
@ -447,7 +462,8 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
painter->restore(); painter->restore();
} }
void FancyTabBar::setCurrentIndex(int index) { void FancyTabBar::setCurrentIndex(int index)
{
m_currentIndex = index; m_currentIndex = index;
update(); update();
emit currentChanged(m_currentIndex); emit currentChanged(m_currentIndex);
@ -461,19 +477,18 @@ void FancyTabBar::setCurrentIndex(int index) {
class FancyColorButton : public QWidget class FancyColorButton : public QWidget
{ {
public: public:
FancyColorButton(QWidget *parent) FancyColorButton(QWidget* parent)
: m_parent(parent) : m_parent(parent) {
{
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
} }
void mousePressEvent(QMouseEvent *ev) void mousePressEvent(QMouseEvent* ev) {
{ if (ev->modifiers() & Qt::ShiftModifier) {
if (ev->modifiers() & Qt::ShiftModifier)
Utils::StyleHelper::setBaseColor(QColorDialog::getColor(Utils::StyleHelper::requestedBaseColor(), m_parent)); Utils::StyleHelper::setBaseColor(QColorDialog::getColor(Utils::StyleHelper::requestedBaseColor(), m_parent));
}
} }
private: private:
QWidget *m_parent; QWidget* m_parent;
}; };
////// //////
@ -481,163 +496,178 @@ private:
////// //////
FancyTabWidget::FancyTabWidget(QWidget* parent) FancyTabWidget::FancyTabWidget(QWidget* parent)
: QWidget(parent), : QWidget(parent),
mode_(Mode_None), mode_(Mode_None),
tab_bar_(NULL), tab_bar_(NULL),
stack_(new QStackedLayout), stack_(new QStackedLayout),
side_widget_(new QWidget), side_widget_(new QWidget),
side_layout_(new QVBoxLayout), side_layout_(new QVBoxLayout),
top_layout_(new QVBoxLayout), top_layout_(new QVBoxLayout),
use_background_(false), use_background_(false),
menu_(NULL), menu_(NULL),
proxy_style_(new FancyTabProxyStyle) proxy_style_(new FancyTabProxyStyle)
{ {
side_layout_->setSpacing(0); side_layout_->setSpacing(0);
side_layout_->setMargin(0); side_layout_->setMargin(0);
side_layout_->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding)); side_layout_->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding));
side_widget_->setLayout(side_layout_); side_widget_->setLayout(side_layout_);
side_widget_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); side_widget_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
top_layout_->setMargin(0); top_layout_->setMargin(0);
top_layout_->setSpacing(0); top_layout_->setSpacing(0);
top_layout_->addLayout(stack_); top_layout_->addLayout(stack_);
QHBoxLayout* main_layout = new QHBoxLayout; QHBoxLayout* main_layout = new QHBoxLayout;
main_layout->setMargin(0); main_layout->setMargin(0);
main_layout->setSpacing(1); main_layout->setSpacing(1);
main_layout->addWidget(side_widget_); main_layout->addWidget(side_widget_);
main_layout->addLayout(top_layout_); main_layout->addLayout(top_layout_);
setLayout(main_layout); setLayout(main_layout);
} }
void FancyTabWidget::AddTab(QWidget* tab, const QIcon& icon, const QString& label) { void FancyTabWidget::AddTab(QWidget* tab, const QIcon &icon, const QString &label)
stack_->addWidget(tab); {
items_ << Item(icon, label); stack_->addWidget(tab);
items_ << Item(icon, label);
} }
void FancyTabWidget::AddSpacer(int size) { void FancyTabWidget::AddSpacer(int size)
items_ << Item(size); {
items_ << Item(size);
} }
void FancyTabWidget::SetBackgroundPixmap(const QPixmap& pixmap) { void FancyTabWidget::SetBackgroundPixmap(const QPixmap &pixmap)
background_pixmap_ = pixmap; {
update(); background_pixmap_ = pixmap;
update();
} }
void FancyTabWidget::paintEvent(QPaintEvent*) { void FancyTabWidget::paintEvent(QPaintEvent*)
if (!use_background_) {
return; if (!use_background_) {
return;
QPainter painter(this);
QRect rect = side_widget_->rect().adjusted(0, 0, 1, 0);
rect = style()->visualRect(layoutDirection(), geometry(), rect);
Utils::StyleHelper::verticalGradient(&painter, rect, rect);
if (!background_pixmap_.isNull()) {
QRect pixmap_rect(background_pixmap_.rect());
pixmap_rect.moveTo(rect.topLeft());
while (pixmap_rect.top() < rect.bottom()) {
QRect source_rect(pixmap_rect.intersected(rect));
source_rect.moveTo(0, 0);
painter.drawPixmap(pixmap_rect.topLeft(), background_pixmap_, source_rect);
pixmap_rect.moveTop(pixmap_rect.bottom() - 10);
} }
}
painter.setPen(Utils::StyleHelper::borderColor()); QPainter painter(this);
painter.drawLine(rect.topRight(), rect.bottomRight());
QColor light = Utils::StyleHelper::sidebarHighlight(); QRect rect = side_widget_->rect().adjusted(0, 0, 1, 0);
painter.setPen(light); rect = style()->visualRect(layoutDirection(), geometry(), rect);
painter.drawLine(rect.bottomLeft(), rect.bottomRight()); Utils::StyleHelper::verticalGradient(&painter, rect, rect);
if (!background_pixmap_.isNull()) {
QRect pixmap_rect(background_pixmap_.rect());
pixmap_rect.moveTo(rect.topLeft());
while (pixmap_rect.top() < rect.bottom()) {
QRect source_rect(pixmap_rect.intersected(rect));
source_rect.moveTo(0, 0);
painter.drawPixmap(pixmap_rect.topLeft(), background_pixmap_, source_rect);
pixmap_rect.moveTop(pixmap_rect.bottom() - 10);
}
}
painter.setPen(Utils::StyleHelper::borderColor());
painter.drawLine(rect.topRight(), rect.bottomRight());
QColor light = Utils::StyleHelper::sidebarHighlight();
painter.setPen(light);
painter.drawLine(rect.bottomLeft(), rect.bottomRight());
} }
int FancyTabWidget::current_index() const { int FancyTabWidget::current_index() const
return stack_->currentIndex(); {
return stack_->currentIndex();
} }
void FancyTabWidget::SetCurrentIndex(int index) { void FancyTabWidget::SetCurrentIndex(int index)
if (FancyTabBar* bar = qobject_cast<FancyTabBar*>(tab_bar_)) { {
bar->setCurrentIndex(index); if (FancyTabBar* bar = qobject_cast<FancyTabBar*>(tab_bar_)) {
} else if (QTabBar* bar = qobject_cast<QTabBar*>(tab_bar_)) { bar->setCurrentIndex(index);
bar->setCurrentIndex(index); }
} else { else if (QTabBar* bar = qobject_cast<QTabBar*>(tab_bar_)) {
bar->setCurrentIndex(index);
}
else {
stack_->setCurrentIndex(index);
}
}
void FancyTabWidget::ShowWidget(int index)
{
stack_->setCurrentIndex(index); stack_->setCurrentIndex(index);
} emit CurrentChanged(index);
} }
void FancyTabWidget::ShowWidget(int index) { void FancyTabWidget::AddBottomWidget(QWidget* widget)
stack_->setCurrentIndex(index); {
emit CurrentChanged(index); top_layout_->addWidget(widget);
} }
void FancyTabWidget::AddBottomWidget(QWidget* widget) { void FancyTabWidget::SetMode(Mode mode)
top_layout_->addWidget(widget); {
} // Remove previous tab bar
delete tab_bar_;
tab_bar_ = NULL;
void FancyTabWidget::SetMode(Mode mode) { use_background_ = false;
// Remove previous tab bar
delete tab_bar_;
tab_bar_ = NULL;
use_background_ = false; // Create new tab bar
switch (mode) {
// Create new tab bar
switch (mode) {
case Mode_None: case Mode_None:
default: default:
qDebug() << "Unknown fancy tab mode" << mode; qDebug() << "Unknown fancy tab mode" << mode;
// fallthrough // fallthrough
case Mode_LargeSidebar: { case Mode_LargeSidebar: {
FancyTabBar* bar = new FancyTabBar(this); FancyTabBar* bar = new FancyTabBar(this);
side_layout_->insertWidget(0, bar); side_layout_->insertWidget(0, bar);
tab_bar_ = bar; tab_bar_ = bar;
foreach (const Item& item, items_) { foreach(const Item & item, items_) {
if (item.type_ == Item::Type_Spacer) if (item.type_ == Item::Type_Spacer) {
bar->addSpacer(item.spacer_size_); bar->addSpacer(item.spacer_size_);
else }
bar->addTab(item.tab_icon_, item.tab_label_); else {
} bar->addTab(item.tab_icon_, item.tab_label_);
}
}
bar->setCurrentIndex(stack_->currentIndex()); bar->setCurrentIndex(stack_->currentIndex());
connect(bar, SIGNAL(currentChanged(int)), SLOT(ShowWidget(int))); connect(bar, SIGNAL(currentChanged(int)), SLOT(ShowWidget(int)));
use_background_ = true; use_background_ = true;
break; break;
} }
case Mode_Tabs: case Mode_Tabs:
MakeTabBar(QTabBar::RoundedNorth, true, false, false); MakeTabBar(QTabBar::RoundedNorth, true, false, false);
break; break;
case Mode_IconOnlyTabs: case Mode_IconOnlyTabs:
MakeTabBar(QTabBar::RoundedNorth, false, true, false); MakeTabBar(QTabBar::RoundedNorth, false, true, false);
break; break;
case Mode_SmallSidebar: case Mode_SmallSidebar:
MakeTabBar(QTabBar::RoundedWest, true, true, true); MakeTabBar(QTabBar::RoundedWest, true, true, true);
use_background_ = true; use_background_ = true;
break; break;
case Mode_PlainSidebar: case Mode_PlainSidebar:
MakeTabBar(QTabBar::RoundedWest, true, true, false); MakeTabBar(QTabBar::RoundedWest, true, true, false);
break; break;
} }
tab_bar_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); tab_bar_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
mode_ = mode; mode_ = mode;
emit ModeChanged(mode); emit ModeChanged(mode);
update(); update();
} }
void FancyTabWidget::contextMenuEvent(QContextMenuEvent* e) { void FancyTabWidget::contextMenuEvent(QContextMenuEvent* e)
{
Q_UNUSED(e) Q_UNUSED(e)
// if (!menu_) { // if (!menu_) {
// menu_ = new QMenu(this); // menu_ = new QMenu(this);
@ -658,57 +688,66 @@ void FancyTabWidget::contextMenuEvent(QContextMenuEvent* e) {
} }
void FancyTabWidget::AddMenuItem(QSignalMapper* mapper, QActionGroup* group, void FancyTabWidget::AddMenuItem(QSignalMapper* mapper, QActionGroup* group,
const QString& text, Mode mode) { const QString &text, Mode mode)
QAction* action = group->addAction(text); {
action->setCheckable(true); QAction* action = group->addAction(text);
mapper->setMapping(action, mode); action->setCheckable(true);
connect(action, SIGNAL(triggered()), mapper, SLOT(map())); mapper->setMapping(action, mode);
connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
if (mode == mode_) if (mode == mode_) {
action->setChecked(true); action->setChecked(true);
}
} }
void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons, void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons,
bool fancy) { bool fancy)
QTabBar* bar = new QTabBar(this); {
bar->setShape(shape); QTabBar* bar = new QTabBar(this);
bar->setDocumentMode(true); bar->setShape(shape);
bar->setUsesScrollButtons(true); bar->setDocumentMode(true);
bar->setUsesScrollButtons(true);
if (shape == QTabBar::RoundedWest) {
bar->setIconSize(QSize(22, 22));
}
if (fancy) {
bar->setStyle(proxy_style_);
}
if (shape == QTabBar::RoundedNorth)
top_layout_->insertWidget(0, bar);
else
side_layout_->insertWidget(0, bar);
foreach (const Item& item, items_) {
if (item.type_ != Item::Type_Tab)
continue;
QString label = item.tab_label_;
if (shape == QTabBar::RoundedWest) { if (shape == QTabBar::RoundedWest) {
label = QFontMetrics(font()).elidedText(label, Qt::ElideMiddle, 100); bar->setIconSize(QSize(22, 22));
} }
int tab_id = -1; if (fancy) {
if (icons && text) bar->setStyle(proxy_style_);
tab_id = bar->addTab(item.tab_icon_, label); }
else if (icons)
tab_id = bar->addTab(item.tab_icon_, QString());
else if (text)
tab_id = bar->addTab(label);
bar->setTabToolTip(tab_id, item.tab_label_); if (shape == QTabBar::RoundedNorth) {
} top_layout_->insertWidget(0, bar);
}
else {
side_layout_->insertWidget(0, bar);
}
bar->setCurrentIndex(stack_->currentIndex()); foreach(const Item & item, items_) {
connect(bar, SIGNAL(currentChanged(int)), SLOT(ShowWidget(int))); if (item.type_ != Item::Type_Tab) {
tab_bar_ = bar; continue;
}
QString label = item.tab_label_;
if (shape == QTabBar::RoundedWest) {
label = QFontMetrics(font()).elidedText(label, Qt::ElideMiddle, 100);
}
int tab_id = -1;
if (icons && text) {
tab_id = bar->addTab(item.tab_icon_, label);
}
else if (icons) {
tab_id = bar->addTab(item.tab_icon_, QString());
}
else if (text) {
tab_id = bar->addTab(label);
}
bar->setTabToolTip(tab_id, item.tab_label_);
}
bar->setCurrentIndex(stack_->currentIndex());
connect(bar, SIGNAL(currentChanged(int)), SLOT(ShowWidget(int)));
tab_bar_ = bar;
} }

View File

@ -45,29 +45,33 @@ class QStackedLayout;
class QStatusBar; class QStatusBar;
class QVBoxLayout; class QVBoxLayout;
namespace Core { namespace Core
namespace Internal { {
namespace Internal
{
class FancyTabProxyStyle : public QProxyStyle { class FancyTabProxyStyle : public QProxyStyle
Q_OBJECT {
Q_OBJECT
public: public:
void drawControl(ControlElement element, const QStyleOption* option, void drawControl(ControlElement element, const QStyleOption* option,
QPainter* painter, const QWidget* widget) const; QPainter* painter, const QWidget* widget) const;
void polish(QWidget* widget); void polish(QWidget* widget);
void polish(QApplication* app); void polish(QApplication* app);
void polish(QPalette& palette); void polish(QPalette &palette);
protected: protected:
bool eventFilter(QObject* o, QEvent* e); bool eventFilter(QObject* o, QEvent* e);
}; };
class FancyTab : public QWidget{ class FancyTab : public QWidget
{
Q_OBJECT Q_OBJECT
Q_PROPERTY(float fader READ fader WRITE setFader) Q_PROPERTY(float fader READ fader WRITE setFader)
public: public:
FancyTab(QWidget *tabbar); FancyTab(QWidget* tabbar);
float fader() { return m_fader; } float fader() { return m_fader; }
void setFader(float value); void setFader(float value);
@ -80,12 +84,12 @@ public:
QString text; QString text;
protected: protected:
void enterEvent(QEvent *); void enterEvent(QEvent*);
void leaveEvent(QEvent *); void leaveEvent(QEvent*);
private: private:
QPropertyAnimation animator; QPropertyAnimation animator;
QWidget *tabbar; QWidget* tabbar;
float m_fader; float m_fader;
}; };
@ -94,12 +98,12 @@ class FancyTabBar : public QWidget
Q_OBJECT Q_OBJECT
public: public:
FancyTabBar(QWidget *parent = 0); FancyTabBar(QWidget* parent = 0);
~FancyTabBar(); ~FancyTabBar();
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent* event);
void paintTab(QPainter *painter, int tabIndex) const; void paintTab(QPainter* painter, int tabIndex) const;
void mousePressEvent(QMouseEvent *); void mousePressEvent(QMouseEvent*);
bool validIndex(int index) const { return index >= 0 && index < m_tabs.count(); } bool validIndex(int index) const { return index >= 0 && index < m_tabs.count(); }
QSize sizeHint() const; QSize sizeHint() const;
@ -108,13 +112,13 @@ public:
void addTab(const QIcon &icon, const QString &label); void addTab(const QIcon &icon, const QString &label);
void addSpacer(int size = 40); void addSpacer(int size = 40);
void removeTab(int index) { void removeTab(int index) {
FancyTab *tab = m_tabs.takeAt(index); FancyTab* tab = m_tabs.takeAt(index);
delete tab; delete tab;
} }
void setCurrentIndex(int index); void setCurrentIndex(int index);
int currentIndex() const { return m_currentIndex; } int currentIndex() const { return m_currentIndex; }
void setTabToolTip(int index, const QString& toolTip); void setTabToolTip(int index, const QString &toolTip);
QString tabToolTip(int index) const; QString tabToolTip(int index) const;
QIcon tabIcon(int index) const {return m_tabs.at(index)->icon; } QIcon tabIcon(int index) const {return m_tabs.at(index)->icon; }
@ -138,87 +142,88 @@ private:
}; };
class FancyTabWidget : public QWidget { class FancyTabWidget : public QWidget
{
Q_OBJECT Q_OBJECT
Q_PROPERTY(QPixmap bgPixmap READ bgPixmap WRITE SetBackgroundPixmap) Q_PROPERTY(QPixmap bgPixmap READ bgPixmap WRITE SetBackgroundPixmap)
public: public:
FancyTabWidget(QWidget* parent = 0); FancyTabWidget(QWidget* parent = 0);
// Values are persisted - only add to the end // Values are persisted - only add to the end
enum Mode { enum Mode {
Mode_None = 0, Mode_None = 0,
Mode_LargeSidebar = 1, Mode_LargeSidebar = 1,
Mode_SmallSidebar = 2, Mode_SmallSidebar = 2,
Mode_Tabs = 3, Mode_Tabs = 3,
Mode_IconOnlyTabs = 4, Mode_IconOnlyTabs = 4,
Mode_PlainSidebar = 5, Mode_PlainSidebar = 5,
};
struct Item {
Item(const QIcon& icon, const QString& label)
: type_(Type_Tab), tab_label_(label), tab_icon_(icon), spacer_size_(0) {}
Item(int size) : type_(Type_Spacer), spacer_size_(size) {}
enum Type {
Type_Tab,
Type_Spacer,
}; };
Type type_; struct Item {
QString tab_label_; Item(const QIcon &icon, const QString &label)
QIcon tab_icon_; : type_(Type_Tab), tab_label_(label), tab_icon_(icon), spacer_size_(0) {}
int spacer_size_; Item(int size) : type_(Type_Spacer), spacer_size_(size) {}
};
void AddTab(QWidget *tab, const QIcon &icon, const QString &label); enum Type {
void AddSpacer(int size = 40); Type_Tab,
void SetBackgroundPixmap(const QPixmap& pixmap); Type_Spacer,
};
void AddBottomWidget(QWidget* widget); Type type_;
QString tab_label_;
QIcon tab_icon_;
int spacer_size_;
};
int current_index() const; void AddTab(QWidget* tab, const QIcon &icon, const QString &label);
Mode mode() const { return mode_; } void AddSpacer(int size = 40);
QPixmap bgPixmap() { return background_pixmap_; } void SetBackgroundPixmap(const QPixmap &pixmap);
void AddBottomWidget(QWidget* widget);
int current_index() const;
Mode mode() const { return mode_; }
QPixmap bgPixmap() { return background_pixmap_; }
public slots: public slots:
void SetCurrentIndex(int index); void SetCurrentIndex(int index);
void SetMode(Mode mode); void SetMode(Mode mode);
void SetMode(int mode) { SetMode(Mode(mode)); } void SetMode(int mode) { SetMode(Mode(mode)); }
signals: signals:
void CurrentChanged(int index); void CurrentChanged(int index);
void ModeChanged(FancyTabWidget::Mode mode); void ModeChanged(FancyTabWidget::Mode mode);
protected: protected:
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent* event);
void contextMenuEvent(QContextMenuEvent* e); void contextMenuEvent(QContextMenuEvent* e);
private slots: private slots:
void ShowWidget(int index); void ShowWidget(int index);
private: private:
void MakeTabBar(QTabBar::Shape shape, bool text, bool icons, bool fancy); void MakeTabBar(QTabBar::Shape shape, bool text, bool icons, bool fancy);
void AddMenuItem(QSignalMapper* mapper, QActionGroup* group, void AddMenuItem(QSignalMapper* mapper, QActionGroup* group,
const QString& text, Mode mode); const QString &text, Mode mode);
Mode mode_; Mode mode_;
QList<Item> items_; QList<Item> items_;
QWidget* tab_bar_; QWidget* tab_bar_;
QStackedLayout* stack_; QStackedLayout* stack_;
QPixmap background_pixmap_; QPixmap background_pixmap_;
QWidget* side_widget_; QWidget* side_widget_;
QVBoxLayout* side_layout_; QVBoxLayout* side_layout_;
QVBoxLayout* top_layout_; QVBoxLayout* top_layout_;
bool use_background_; bool use_background_;
QMenu* menu_; QMenu* menu_;
FancyTabProxyStyle* proxy_style_; FancyTabProxyStyle* proxy_style_;
}; };
} // namespace Internal } // namespace Internal

View File

@ -7,19 +7,20 @@
#include <QFocusEvent> #include <QFocusEvent>
#include <qdebug.h> #include <qdebug.h>
SideWidget::SideWidget(QWidget *parent) SideWidget::SideWidget(QWidget* parent)
: QWidget(parent) : QWidget(parent)
{ {
} }
bool SideWidget::event(QEvent *event) bool SideWidget::event(QEvent* event)
{ {
if (event->type() == QEvent::LayoutRequest) if (event->type() == QEvent::LayoutRequest) {
emit sizeHintChanged(); emit sizeHintChanged();
}
return QWidget::event(event); return QWidget::event(event);
} }
LineEdit::LineEdit(QWidget *parent) LineEdit::LineEdit(QWidget* parent)
: QLineEdit(parent) : QLineEdit(parent)
, m_leftLayout(0) , m_leftLayout(0)
, m_rightLayout(0) , m_rightLayout(0)
@ -28,7 +29,7 @@ LineEdit::LineEdit(QWidget *parent)
init(); init();
} }
LineEdit::LineEdit(const QString &contents, QWidget *parent) LineEdit::LineEdit(const QString &contents, QWidget* parent)
: QLineEdit(contents, parent) : QLineEdit(contents, parent)
, m_leftWidget(0) , m_leftWidget(0)
, m_rightWidget(0) , m_rightWidget(0)
@ -51,22 +52,26 @@ void LineEdit::init()
m_leftLayout = new QHBoxLayout(m_leftWidget); m_leftLayout = new QHBoxLayout(m_leftWidget);
m_leftLayout->setContentsMargins(0, 0, 0, 0); m_leftLayout->setContentsMargins(0, 0, 0, 0);
if (isRightToLeft()) if (isRightToLeft()) {
m_leftLayout->setDirection(QBoxLayout::RightToLeft); m_leftLayout->setDirection(QBoxLayout::RightToLeft);
else }
else {
m_leftLayout->setDirection(QBoxLayout::LeftToRight); m_leftLayout->setDirection(QBoxLayout::LeftToRight);
}
m_leftLayout->setSizeConstraint(QLayout::SetFixedSize); m_leftLayout->setSizeConstraint(QLayout::SetFixedSize);
m_rightWidget = new SideWidget(this); m_rightWidget = new SideWidget(this);
m_rightWidget->resize(0, 0); m_rightWidget->resize(0, 0);
m_rightLayout = new QHBoxLayout(m_rightWidget); m_rightLayout = new QHBoxLayout(m_rightWidget);
if (isRightToLeft()) if (isRightToLeft()) {
m_rightLayout->setDirection(QBoxLayout::RightToLeft); m_rightLayout->setDirection(QBoxLayout::RightToLeft);
else }
else {
m_rightLayout->setDirection(QBoxLayout::LeftToRight); m_rightLayout->setDirection(QBoxLayout::LeftToRight);
}
m_rightLayout->setContentsMargins(0, 0, 0, 0); m_rightLayout->setContentsMargins(0, 0, 0, 0);
QSpacerItem *horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum); QSpacerItem* horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
m_rightLayout->addItem(horizontalSpacer); m_rightLayout->addItem(horizontalSpacer);
setWidgetSpacing(3); setWidgetSpacing(3);
@ -76,13 +81,14 @@ void LineEdit::init()
this, SLOT(updateTextMargins())); this, SLOT(updateTextMargins()));
} }
bool LineEdit::event(QEvent *event) bool LineEdit::event(QEvent* event)
{ {
if (event->type() == QEvent::LayoutDirectionChange) { if (event->type() == QEvent::LayoutDirectionChange) {
if (isRightToLeft()) { if (isRightToLeft()) {
m_leftLayout->setDirection(QBoxLayout::RightToLeft); m_leftLayout->setDirection(QBoxLayout::RightToLeft);
m_rightLayout->setDirection(QBoxLayout::RightToLeft); m_rightLayout->setDirection(QBoxLayout::RightToLeft);
} else { }
else {
m_leftLayout->setDirection(QBoxLayout::LeftToRight); m_leftLayout->setDirection(QBoxLayout::LeftToRight);
m_rightLayout->setDirection(QBoxLayout::LeftToRight); m_rightLayout->setDirection(QBoxLayout::LeftToRight);
} }
@ -90,25 +96,29 @@ bool LineEdit::event(QEvent *event)
return QLineEdit::event(event); return QLineEdit::event(event);
} }
void LineEdit::addWidget(QWidget *widget, WidgetPosition position) void LineEdit::addWidget(QWidget* widget, WidgetPosition position)
{ {
if (!widget) if (!widget) {
return; return;
}
bool rtl = isRightToLeft(); bool rtl = isRightToLeft();
if (rtl) if (rtl) {
position = (position == LeftSide) ? RightSide : LeftSide; position = (position == LeftSide) ? RightSide : LeftSide;
}
if (position == LeftSide) { if (position == LeftSide) {
m_leftLayout->addWidget(widget); m_leftLayout->addWidget(widget);
} else { }
else {
m_rightLayout->insertWidget(1, widget); m_rightLayout->insertWidget(1, widget);
} }
} }
void LineEdit::removeWidget(QWidget *widget) void LineEdit::removeWidget(QWidget* widget)
{ {
if (!widget) if (!widget) {
return; return;
}
m_leftLayout->removeWidget(widget); m_leftLayout->removeWidget(widget);
m_rightLayout->removeWidget(widget); m_rightLayout->removeWidget(widget);
@ -131,22 +141,27 @@ int LineEdit::textMargin(WidgetPosition position) const
{ {
int spacing = m_rightLayout->spacing(); int spacing = m_rightLayout->spacing();
int w = 0; int w = 0;
if (position == LeftSide) if (position == LeftSide) {
w = m_leftWidget->sizeHint().width(); w = m_leftWidget->sizeHint().width();
else }
else {
w = m_rightWidget->sizeHint().width(); w = m_rightWidget->sizeHint().width();
if (w == 0) }
if (w == 0) {
return 0; return 0;
}
return w + spacing * 2; return w + spacing * 2;
} }
void LineEdit::updateTextMargins() void LineEdit::updateTextMargins()
{ {
int left; int left;
if (m_leftMargin == 0) if (m_leftMargin == 0) {
left = textMargin(LineEdit::LeftSide); left = textMargin(LineEdit::LeftSide);
else }
else {
left = m_leftMargin; left = m_leftMargin;
}
int right = textMargin(LineEdit::RightSide); int right = textMargin(LineEdit::RightSide);
int top = 0; int top = 0;
int bottom = 0; int bottom = 0;
@ -169,8 +184,9 @@ void LineEdit::updateSideWidgetLocations()
if (m_leftLayout->count() > 0) { if (m_leftLayout->count() > 0) {
int leftHeight = midHeight - m_leftWidget->height() / 2; int leftHeight = midHeight - m_leftWidget->height() / 2;
int leftWidth = m_leftWidget->width(); int leftWidth = m_leftWidget->width();
if (leftWidth == 0) if (leftWidth == 0) {
leftHeight = midHeight - m_leftWidget->sizeHint().height() / 2; leftHeight = midHeight - m_leftWidget->sizeHint().height() / 2;
}
m_leftWidget->move(textRect.x(), leftHeight); m_leftWidget->move(textRect.x(), leftHeight);
} }
textRect.setX(left); textRect.setX(left);
@ -179,7 +195,7 @@ void LineEdit::updateSideWidgetLocations()
m_rightWidget->setGeometry(textRect); m_rightWidget->setGeometry(textRect);
} }
void LineEdit::resizeEvent(QResizeEvent *event) void LineEdit::resizeEvent(QResizeEvent* event)
{ {
updateSideWidgetLocations(); updateSideWidgetLocations();
QLineEdit::resizeEvent(event); QLineEdit::resizeEvent(event);
@ -195,7 +211,7 @@ void LineEdit::setInactiveText(const QString &text)
m_inactiveText = text; m_inactiveText = text;
} }
void LineEdit::paintEvent(QPaintEvent *event) void LineEdit::paintEvent(QPaintEvent* event)
{ {
QLineEdit::paintEvent(event); QLineEdit::paintEvent(event);
if (text().isEmpty() && !m_inactiveText.isEmpty() && !hasFocus()) { if (text().isEmpty() && !m_inactiveText.isEmpty() && !hasFocus()) {

View File

@ -54,24 +54,24 @@ public:
RightSide RightSide
}; };
LineEdit(QWidget *parent = 0); LineEdit(QWidget* parent = 0);
LineEdit(const QString &contents, QWidget *parent = 0); LineEdit(const QString &contents, QWidget* parent = 0);
void addWidget(QWidget *widget, WidgetPosition position); void addWidget(QWidget* widget, WidgetPosition position);
void removeWidget(QWidget *widget); void removeWidget(QWidget* widget);
void setWidgetSpacing(int spacing); void setWidgetSpacing(int spacing);
int widgetSpacing() const; int widgetSpacing() const;
int textMargin(WidgetPosition position) const; int textMargin(WidgetPosition position) const;
QString inactiveText() const; QString inactiveText() const;
void setInactiveText(const QString &text); void setInactiveText(const QString &text);
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent* event);
void setLeftMargin(int margin); void setLeftMargin(int margin);
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent* event);
bool event(QEvent *event); bool event(QEvent* event);
protected slots: protected slots:
void updateTextMargins(); void updateTextMargins();
@ -80,10 +80,10 @@ private:
void init(); void init();
void updateSideWidgetLocations(); void updateSideWidgetLocations();
SideWidget *m_leftWidget; SideWidget* m_leftWidget;
SideWidget *m_rightWidget; SideWidget* m_rightWidget;
QHBoxLayout *m_leftLayout; QHBoxLayout* m_leftLayout;
QHBoxLayout *m_rightLayout; QHBoxLayout* m_rightLayout;
QString m_inactiveText; QString m_inactiveText;
int m_leftMargin; int m_leftMargin;
}; };
@ -97,10 +97,10 @@ signals:
void sizeHintChanged(); void sizeHintChanged();
public: public:
SideWidget(QWidget *parent = 0); SideWidget(QWidget* parent = 0);
protected: protected:
bool event(QEvent *event); bool event(QEvent* event);
}; };

View File

@ -23,83 +23,81 @@
#ifndef __IObjectArray_FWD_DEFINED__ #ifndef __IObjectArray_FWD_DEFINED__
#define __IObjectArray_FWD_DEFINED__ #define __IObjectArray_FWD_DEFINED__
typedef interface IObjectArray IObjectArray; typedef interface IObjectArray IObjectArray;
#endif /* __IObjectArray_FWD_DEFINED__ */ #endif /* __IObjectArray_FWD_DEFINED__ */
#ifndef __IObjectCollection_FWD_DEFINED__ #ifndef __IObjectCollection_FWD_DEFINED__
#define __IObjectCollection_FWD_DEFINED__ #define __IObjectCollection_FWD_DEFINED__
typedef interface IObjectCollection IObjectCollection; typedef interface IObjectCollection IObjectCollection;
#endif /* __IObjectCollection_FWD_DEFINED__ */ #endif /* __IObjectCollection_FWD_DEFINED__ */
/* header files for imported files */ /* header files for imported files */
#include "oaidl.h" #include "oaidl.h"
#include "ocidl.h" #include "ocidl.h"
#ifdef __cplusplus #ifdef __cplusplus
extern "C"{ extern "C" {
#endif #endif
/* /*
**************************************************************************************************** ****************************************************************************************************
IObjectArray IObjectArray
<from ObjectArray.h> <from ObjectArray.h>
**************************************************************************************************** ****************************************************************************************************
*/ */
#ifndef __IObjectArray_INTERFACE_DEFINED__ #ifndef __IObjectArray_INTERFACE_DEFINED__
#define __IObjectArray_INTERFACE_DEFINED__ #define __IObjectArray_INTERFACE_DEFINED__
/* interface IObjectArray */ /* interface IObjectArray */
/* [unique][object][uuid][helpstring] */ /* [unique][object][uuid][helpstring] */
EXTERN_C const IID IID_IObjectArray; EXTERN_C const IID IID_IObjectArray;
MIDL_INTERFACE("92CA9DCD-5622-4bba-A805-5E9F541BD8C9") MIDL_INTERFACE("92CA9DCD-5622-4bba-A805-5E9F541BD8C9")
IObjectArray : public IUnknown IObjectArray : public IUnknown {
{
public: public:
virtual HRESULT STDMETHODCALLTYPE GetCount( virtual HRESULT STDMETHODCALLTYPE GetCount(
/* [out] */ __RPC__out UINT *pcObjects) = 0; /* [out] */ __RPC__out UINT* pcObjects) = 0;
virtual HRESULT STDMETHODCALLTYPE GetAt( virtual HRESULT STDMETHODCALLTYPE GetAt(
/* [in] */ UINT uiIndex, /* [in] */ UINT uiIndex,
/* [in] */ __RPC__in REFIID riid, /* [in] */ __RPC__in REFIID riid,
/* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0; /* [iid_is][out] */ __RPC__deref_out_opt void** ppv) = 0;
}; };
#endif /* __IObjectArray_INTERFACE_DEFINED__ */ #endif /* __IObjectArray_INTERFACE_DEFINED__ */
#ifndef __IObjectCollection_INTERFACE_DEFINED__ #ifndef __IObjectCollection_INTERFACE_DEFINED__
#define __IObjectCollection_INTERFACE_DEFINED__ #define __IObjectCollection_INTERFACE_DEFINED__
/* interface IObjectCollection */ /* interface IObjectCollection */
/* [unique][object][uuid] */ /* [unique][object][uuid] */
EXTERN_C const IID IID_IObjectCollection; EXTERN_C const IID IID_IObjectCollection;
MIDL_INTERFACE("5632b1a4-e38a-400a-928a-d4cd63230295") MIDL_INTERFACE("5632b1a4-e38a-400a-928a-d4cd63230295")
IObjectCollection : public IObjectArray IObjectCollection : public IObjectArray {
{
public: public:
virtual HRESULT STDMETHODCALLTYPE AddObject( virtual HRESULT STDMETHODCALLTYPE AddObject(
/* [in] */ __RPC__in_opt IUnknown *punk) = 0; /* [in] */ __RPC__in_opt IUnknown* punk) = 0;
virtual HRESULT STDMETHODCALLTYPE AddFromArray( virtual HRESULT STDMETHODCALLTYPE AddFromArray(
/* [in] */ __RPC__in_opt IObjectArray *poaSource) = 0; /* [in] */ __RPC__in_opt IObjectArray* poaSource) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoveObjectAt( virtual HRESULT STDMETHODCALLTYPE RemoveObjectAt(
/* [in] */ UINT uiIndex) = 0; /* [in] */ UINT uiIndex) = 0;
virtual HRESULT STDMETHODCALLTYPE Clear( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clear(void) = 0;
}; };
#endif /* __IObjectCollection_INTERFACE_DEFINED__ */ #endif /* __IObjectCollection_INTERFACE_DEFINED__ */
/* Additional Prototypes for ALL interfaces */ /* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */ /* end of Additional Prototypes */
#ifdef __cplusplus #ifdef __cplusplus
} }
@ -119,46 +117,45 @@ typedef interface ICustomDestinationList ICustomDestinationList;
/* [unique][object][uuid] */ /* [unique][object][uuid] */
typedef /* [v1_enum] */ typedef /* [v1_enum] */
enum KNOWNDESTCATEGORY enum KNOWNDESTCATEGORY {
{ KDC_FREQUENT = 1, KDC_FREQUENT = 1,
KDC_RECENT = ( KDC_FREQUENT + 1 ) KDC_RECENT = (KDC_FREQUENT + 1)
} KNOWNDESTCATEGORY; } KNOWNDESTCATEGORY;
EXTERN_C const IID IID_ICustomDestinationList; EXTERN_C const IID IID_ICustomDestinationList;
MIDL_INTERFACE("6332debf-87b5-4670-90c0-5e57b408a49e") MIDL_INTERFACE("6332debf-87b5-4670-90c0-5e57b408a49e")
ICustomDestinationList : public IUnknown ICustomDestinationList : public IUnknown {
{ public:
public:
virtual HRESULT STDMETHODCALLTYPE SetAppID( virtual HRESULT STDMETHODCALLTYPE SetAppID(
/* [string][in] */ __RPC__in_string LPCWSTR pszAppID) = 0; /* [string][in] */ __RPC__in_string LPCWSTR pszAppID) = 0;
virtual HRESULT STDMETHODCALLTYPE BeginList( virtual HRESULT STDMETHODCALLTYPE BeginList(
/* [out] */ __RPC__out UINT *pcMinSlots, /* [out] */ __RPC__out UINT* pcMinSlots,
/* [in] */ __RPC__in REFIID riid, /* [in] */ __RPC__in REFIID riid,
/* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0; /* [iid_is][out] */ __RPC__deref_out_opt void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE AppendCategory( virtual HRESULT STDMETHODCALLTYPE AppendCategory(
/* [string][in] */ __RPC__in_string LPCWSTR pszCategory, /* [string][in] */ __RPC__in_string LPCWSTR pszCategory,
/* [in] */ __RPC__in_opt IObjectArray *poa) = 0; /* [in] */ __RPC__in_opt IObjectArray* poa) = 0;
virtual HRESULT STDMETHODCALLTYPE AppendKnownCategory( virtual HRESULT STDMETHODCALLTYPE AppendKnownCategory(
/* [in] */ KNOWNDESTCATEGORY category) = 0; /* [in] */ KNOWNDESTCATEGORY category) = 0;
virtual HRESULT STDMETHODCALLTYPE AddUserTasks( virtual HRESULT STDMETHODCALLTYPE AddUserTasks(
/* [in] */ __RPC__in_opt IObjectArray *poa) = 0; /* [in] */ __RPC__in_opt IObjectArray* poa) = 0;
virtual HRESULT STDMETHODCALLTYPE CommitList( void) = 0; virtual HRESULT STDMETHODCALLTYPE CommitList(void) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRemovedDestinations( virtual HRESULT STDMETHODCALLTYPE GetRemovedDestinations(
/* [in] */ __RPC__in REFIID riid, /* [in] */ __RPC__in REFIID riid,
/* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0; /* [iid_is][out] */ __RPC__deref_out_opt void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE DeleteList( virtual HRESULT STDMETHODCALLTYPE DeleteList(
/* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszAppID) = 0; /* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszAppID) = 0;
virtual HRESULT STDMETHODCALLTYPE AbortList( void) = 0; virtual HRESULT STDMETHODCALLTYPE AbortList(void) = 0;
}; };
/* /*
@ -192,51 +189,50 @@ class DECLSPEC_UUID("77f10cf0-3db5-4966-b520-b7c54fd35ed6")
*/ */
#define DEFINE_ENUM_FLAG_OPERATORS(ENUMTYPE) \ #define DEFINE_ENUM_FLAG_OPERATORS(ENUMTYPE) \
extern "C++" { \ extern "C++" { \
inline ENUMTYPE operator | (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) | ((int)b)); } \ inline ENUMTYPE operator | (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) | ((int)b)); } \
inline ENUMTYPE &operator |= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) |= ((int)b)); } \ inline ENUMTYPE &operator |= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) |= ((int)b)); } \
inline ENUMTYPE operator & (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) & ((int)b)); } \ inline ENUMTYPE operator & (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) & ((int)b)); } \
inline ENUMTYPE &operator &= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) &= ((int)b)); } \ inline ENUMTYPE &operator &= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) &= ((int)b)); } \
inline ENUMTYPE operator ~ (ENUMTYPE a) { return ENUMTYPE(~((int)a)); } \ inline ENUMTYPE operator ~ (ENUMTYPE a) { return ENUMTYPE(~((int)a)); } \
inline ENUMTYPE operator ^ (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) ^ ((int)b)); } \ inline ENUMTYPE operator ^ (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((int)a) ^ ((int)b)); } \
inline ENUMTYPE &operator ^= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) ^= ((int)b)); } \ inline ENUMTYPE &operator ^= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((int &)a) ^= ((int)b)); } \
} }
#ifdef MIDL_PASS #ifdef MIDL_PASS
typedef IUnknown *HIMAGELIST; typedef IUnknown* HIMAGELIST;
#endif #endif
typedef /* [v1_enum] */ typedef /* [v1_enum] */
enum THUMBBUTTONFLAGS enum THUMBBUTTONFLAGS {
{ THBF_ENABLED = 0, THBF_ENABLED = 0,
THBF_DISABLED = 0x1, THBF_DISABLED = 0x1,
THBF_DISMISSONCLICK = 0x2, THBF_DISMISSONCLICK = 0x2,
THBF_NOBACKGROUND = 0x4, THBF_NOBACKGROUND = 0x4,
THBF_HIDDEN = 0x8, THBF_HIDDEN = 0x8,
THBF_NONINTERACTIVE = 0x10 THBF_NONINTERACTIVE = 0x10
} THUMBBUTTONFLAGS; } THUMBBUTTONFLAGS;
DEFINE_ENUM_FLAG_OPERATORS(THUMBBUTTONFLAGS) DEFINE_ENUM_FLAG_OPERATORS(THUMBBUTTONFLAGS)
typedef /* [v1_enum] */ typedef /* [v1_enum] */
enum THUMBBUTTONMASK enum THUMBBUTTONMASK {
{ THB_BITMAP = 0x1, THB_BITMAP = 0x1,
THB_ICON = 0x2, THB_ICON = 0x2,
THB_TOOLTIP = 0x4, THB_TOOLTIP = 0x4,
THB_FLAGS = 0x8 THB_FLAGS = 0x8
} THUMBBUTTONMASK; } THUMBBUTTONMASK;
DEFINE_ENUM_FLAG_OPERATORS(THUMBBUTTONMASK) DEFINE_ENUM_FLAG_OPERATORS(THUMBBUTTONMASK)
#include <pshpack8.h> #include <pshpack8.h>
typedef struct THUMBBUTTON typedef struct THUMBBUTTON {
{
THUMBBUTTONMASK dwMask; THUMBBUTTONMASK dwMask;
UINT iId; UINT iId;
UINT iBitmap; UINT iBitmap;
HICON hIcon; HICON hIcon;
WCHAR szTip[ 260 ]; WCHAR szTip[ 260 ];
THUMBBUTTONFLAGS dwFlags; THUMBBUTTONFLAGS dwFlags;
} THUMBBUTTON; } THUMBBUTTON;
typedef struct THUMBBUTTON *LPTHUMBBUTTON; typedef struct THUMBBUTTON* LPTHUMBBUTTON;
#include <poppack.h> #include <poppack.h>
#define THBN_CLICKED 0x1800 #define THBN_CLICKED 0x1800
@ -249,13 +245,13 @@ extern RPC_IF_HANDLE __MIDL_itf_shobjidl_0000_0093_v0_0_s_ifspec;
/* [object][uuid] */ /* [object][uuid] */
typedef /* [v1_enum] */ typedef /* [v1_enum] */
enum TBPFLAG enum TBPFLAG {
{ TBPF_NOPROGRESS = 0, TBPF_NOPROGRESS = 0,
TBPF_INDETERMINATE = 0x1, TBPF_INDETERMINATE = 0x1,
TBPF_NORMAL = 0x2, TBPF_NORMAL = 0x2,
TBPF_ERROR = 0x4, TBPF_ERROR = 0x4,
TBPF_PAUSED = 0x8 TBPF_PAUSED = 0x8
} TBPFLAG; } TBPFLAG;
DEFINE_ENUM_FLAG_OPERATORS(TBPFLAG) DEFINE_ENUM_FLAG_OPERATORS(TBPFLAG)
@ -263,60 +259,59 @@ EXTERN_C const IID IID_ITaskbarList3;
MIDL_INTERFACE("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf") MIDL_INTERFACE("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")
ITaskbarList3 : public ITaskbarList2 ITaskbarList3 : public ITaskbarList2 {
{ public:
public:
virtual HRESULT STDMETHODCALLTYPE SetProgressValue( virtual HRESULT STDMETHODCALLTYPE SetProgressValue(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ ULONGLONG ullCompleted, /* [in] */ ULONGLONG ullCompleted,
/* [in] */ ULONGLONG ullTotal) = 0; /* [in] */ ULONGLONG ullTotal) = 0;
virtual HRESULT STDMETHODCALLTYPE SetProgressState( virtual HRESULT STDMETHODCALLTYPE SetProgressState(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ TBPFLAG tbpFlags) = 0; /* [in] */ TBPFLAG tbpFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE RegisterTab( virtual HRESULT STDMETHODCALLTYPE RegisterTab(
/* [in] */ __RPC__in HWND hwndTab, /* [in] */ __RPC__in HWND hwndTab,
/* [in] */ __RPC__in HWND hwndMDI) = 0; /* [in] */ __RPC__in HWND hwndMDI) = 0;
virtual HRESULT STDMETHODCALLTYPE UnregisterTab( virtual HRESULT STDMETHODCALLTYPE UnregisterTab(
/* [in] */ __RPC__in HWND hwndTab) = 0; /* [in] */ __RPC__in HWND hwndTab) = 0;
virtual HRESULT STDMETHODCALLTYPE SetTabOrder( virtual HRESULT STDMETHODCALLTYPE SetTabOrder(
/* [in] */ __RPC__in HWND hwndTab, /* [in] */ __RPC__in HWND hwndTab,
/* [in] */ __RPC__in HWND hwndInsertBefore) = 0; /* [in] */ __RPC__in HWND hwndInsertBefore) = 0;
virtual HRESULT STDMETHODCALLTYPE SetTabActive( virtual HRESULT STDMETHODCALLTYPE SetTabActive(
/* [in] */ __RPC__in HWND hwndTab, /* [in] */ __RPC__in HWND hwndTab,
/* [in] */ __RPC__in HWND hwndMDI, /* [in] */ __RPC__in HWND hwndMDI,
/* [in] */ DWORD dwReserved) = 0; /* [in] */ DWORD dwReserved) = 0;
virtual HRESULT STDMETHODCALLTYPE ThumbBarAddButtons( virtual HRESULT STDMETHODCALLTYPE ThumbBarAddButtons(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ UINT cButtons, /* [in] */ UINT cButtons,
/* [size_is][in] */ __RPC__in_ecount_full(cButtons) LPTHUMBBUTTON pButton) = 0; /* [size_is][in] */ __RPC__in_ecount_full(cButtons) LPTHUMBBUTTON pButton) = 0;
virtual HRESULT STDMETHODCALLTYPE ThumbBarUpdateButtons( virtual HRESULT STDMETHODCALLTYPE ThumbBarUpdateButtons(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ UINT cButtons, /* [in] */ UINT cButtons,
/* [size_is][in] */ __RPC__in_ecount_full(cButtons) LPTHUMBBUTTON pButton) = 0; /* [size_is][in] */ __RPC__in_ecount_full(cButtons) LPTHUMBBUTTON pButton) = 0;
virtual HRESULT STDMETHODCALLTYPE ThumbBarSetImageList( virtual HRESULT STDMETHODCALLTYPE ThumbBarSetImageList(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ __RPC__in_opt HIMAGELIST himl) = 0; /* [in] */ __RPC__in_opt HIMAGELIST himl) = 0;
virtual HRESULT STDMETHODCALLTYPE SetOverlayIcon( virtual HRESULT STDMETHODCALLTYPE SetOverlayIcon(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ __RPC__in HICON hIcon, /* [in] */ __RPC__in HICON hIcon,
/* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszDescription) = 0; /* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszDescription) = 0;
virtual HRESULT STDMETHODCALLTYPE SetThumbnailTooltip( virtual HRESULT STDMETHODCALLTYPE SetThumbnailTooltip(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszTip) = 0; /* [string][unique][in] */ __RPC__in_opt_string LPCWSTR pszTip) = 0;
virtual HRESULT STDMETHODCALLTYPE SetThumbnailClip( virtual HRESULT STDMETHODCALLTYPE SetThumbnailClip(
/* [in] */ __RPC__in HWND hwnd, /* [in] */ __RPC__in HWND hwnd,
/* [in] */ __RPC__in RECT *prcClip) = 0; /* [in] */ __RPC__in RECT* prcClip) = 0;
}; };
#endif //_MSC_VER >= 1500 && _MSC_VER < 1600 #endif //_MSC_VER >= 1500 && _MSC_VER < 1600

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
@ -52,14 +52,15 @@
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
#include <QtCore/QLibrary> #include <QtCore/QLibrary>
#include <QtCore/qt_windows.h> #include <QtCore/qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); typedef BOOL(WINAPI* PProcessIdToSessionId)(DWORD, DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0; static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif #endif
#if defined(Q_OS_UNIX) #if defined(Q_OS_UNIX)
#include <time.h> #include <time.h>
#endif #endif
namespace QtLP_Private { namespace QtLP_Private
{
#include "qtlockedfile.cpp" #include "qtlockedfile.cpp"
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
#include "qtlockedfile_win.cpp" #include "qtlockedfile_win.cpp"
@ -115,22 +116,25 @@ QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
bool QtLocalPeer::isClient() bool QtLocalPeer::isClient()
{ {
if (lockFile.isLocked()) if (lockFile.isLocked()) {
return false; return false;
}
if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) {
return true; return true;
}
bool res = server->listen(socketName); bool res = server->listen(socketName);
#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
// ### Workaround // ### Workaround
if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName);
res = server->listen(socketName); res = server->listen(socketName);
} }
#endif #endif
if (!res) if (!res) {
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
}
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false; return false;
} }
@ -138,17 +142,19 @@ bool QtLocalPeer::isClient()
bool QtLocalPeer::sendMessage(const QString &message, int timeout) bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{ {
if (!isClient()) if (!isClient()) {
return false; return false;
}
QLocalSocket socket; QLocalSocket socket;
bool connOk = false; bool connOk = false;
for(int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up // Try twice, in case the other instance is just starting up
socket.connectToServer(socketName); socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2); connOk = socket.waitForConnected(timeout / 2);
if (connOk || i) if (connOk || i) {
break; break;
}
int ms = 250; int ms = 250;
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
Sleep(DWORD(ms)); Sleep(DWORD(ms));
@ -157,8 +163,9 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
nanosleep(&ts, NULL); nanosleep(&ts, NULL);
#endif #endif
} }
if (!connOk) if (!connOk) {
return false; return false;
}
QByteArray uMsg(message.toUtf8()); QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket); QDataStream ds(&socket);
@ -173,11 +180,13 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
void QtLocalPeer::receiveConnection() void QtLocalPeer::receiveConnection()
{ {
QLocalSocket* socket = server->nextPendingConnection(); QLocalSocket* socket = server->nextPendingConnection();
if (!socket) if (!socket) {
return; return;
}
while (socket->bytesAvailable() < (int)sizeof(quint32)) while (socket->bytesAvailable() < (int)sizeof(quint32)) {
socket->waitForReadyRead(); socket->waitForReadyRead();
}
QDataStream ds(socket); QDataStream ds(socket);
QByteArray uMsg; QByteArray uMsg;
quint32 remaining; quint32 remaining;
@ -189,7 +198,8 @@ void QtLocalPeer::receiveConnection()
got = ds.readRawData(uMsgBuf, remaining); got = ds.readRawData(uMsgBuf, remaining);
remaining -= got; remaining -= got;
uMsgBuf += got; uMsgBuf += got;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000)); }
while (remaining && got >= 0 && socket->waitForReadyRead(2000));
if (got < 0) { if (got < 0) {
qWarning("QtLocalPeer: Message reception failed %s", qPrintable(socket->errorString())); qWarning("QtLocalPeer: Message reception failed %s", qPrintable(socket->errorString()));
delete socket; delete socket;

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
@ -49,7 +49,8 @@
#include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalSocket>
#include <QtCore/QDir> #include <QtCore/QDir>
namespace QtLP_Private { namespace QtLP_Private
{
#include "qtlockedfile.h" #include "qtlockedfile.h"
} }
@ -58,11 +59,11 @@ class QtLocalPeer : public QObject
Q_OBJECT Q_OBJECT
public: public:
QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); QtLocalPeer(QObject* parent = 0, const QString &appId = QString());
bool isClient(); bool isClient();
bool sendMessage(const QString &message, int timeout); bool sendMessage(const QString &message, int timeout);
QString applicationId() const QString applicationId() const
{ return id; } { return id; }
Q_SIGNALS: Q_SIGNALS:
void messageReceived(const QString &message); void messageReceived(const QString &message);

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
#include "qtlockedfile.h" #include "qtlockedfile.h"

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
#ifndef QTLOCKEDFILE_H #ifndef QTLOCKEDFILE_H

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
#include <string.h> #include <string.h>
@ -57,15 +57,18 @@ bool QtLockedFile::lock(LockMode mode, bool block)
qWarning("QtLockedFile::lock(): file is not opened"); qWarning("QtLockedFile::lock(): file is not opened");
return false; return false;
} }
if (mode == NoLock)
return unlock();
if (mode == m_lock_mode)
return true;
if (m_lock_mode != NoLock) if (mode == NoLock) {
return unlock();
}
if (mode == m_lock_mode) {
return true;
}
if (m_lock_mode != NoLock) {
unlock(); unlock();
}
struct flock fl; struct flock fl;
fl.l_whence = SEEK_SET; fl.l_whence = SEEK_SET;
@ -74,14 +77,15 @@ bool QtLockedFile::lock(LockMode mode, bool block)
fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;
int cmd = block ? F_SETLKW : F_SETLK; int cmd = block ? F_SETLKW : F_SETLK;
int ret = fcntl(handle(), cmd, &fl); int ret = fcntl(handle(), cmd, &fl);
if (ret == -1) { if (ret == -1) {
if (errno != EINTR && errno != EAGAIN) if (errno != EINTR && errno != EAGAIN) {
qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
}
return false; return false;
} }
m_lock_mode = mode; m_lock_mode = mode;
return true; return true;
} }
@ -94,8 +98,9 @@ bool QtLockedFile::unlock()
return false; return false;
} }
if (!isLocked()) if (!isLocked()) {
return true; return true;
}
struct flock fl; struct flock fl;
fl.l_whence = SEEK_SET; fl.l_whence = SEEK_SET;
@ -103,19 +108,20 @@ bool QtLockedFile::unlock()
fl.l_len = 0; fl.l_len = 0;
fl.l_type = F_UNLCK; fl.l_type = F_UNLCK;
int ret = fcntl(handle(), F_SETLKW, &fl); int ret = fcntl(handle(), F_SETLKW, &fl);
if (ret == -1) { if (ret == -1) {
qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
return false; return false;
} }
m_lock_mode = NoLock; m_lock_mode = NoLock;
return true; return true;
} }
QtLockedFile::~QtLockedFile() QtLockedFile::~QtLockedFile()
{ {
if (isOpen()) if (isOpen()) {
unlock(); unlock();
}
} }

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
#include "qtlockedfile.h" #include "qtlockedfile.h"
@ -60,13 +60,14 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
+ fi.absoluteFilePath().toLower(); + fi.absoluteFilePath().toLower();
} }
QString mname(mutexname); QString mname(mutexname);
if (idx >= 0) if (idx >= 0) {
mname += QString::number(idx); mname += QString::number(idx);
}
Qt::HANDLE mutex; Qt::HANDLE mutex;
if (doCreate) { if (doCreate) {
QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); },
{ mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); });
if (!mutex) { if (!mutex) {
qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); qErrnoWarning("QtLockedFile::lock(): CreateMutex failed");
return 0; return 0;
@ -74,10 +75,11 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
} }
else { else {
QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); },
{ mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); });
if (!mutex) { if (!mutex) {
if (GetLastError() != ERROR_FILE_NOT_FOUND) if (GetLastError() != ERROR_FILE_NOT_FOUND) {
qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); qErrnoWarning("QtLockedFile::lock(): OpenMutex failed");
}
return 0; return 0;
} }
} }
@ -110,27 +112,33 @@ bool QtLockedFile::lock(LockMode mode, bool block)
return false; return false;
} }
if (mode == NoLock) if (mode == NoLock) {
return unlock(); return unlock();
}
if (mode == m_lock_mode) if (mode == m_lock_mode) {
return true; return true;
}
if (m_lock_mode != NoLock) if (m_lock_mode != NoLock) {
unlock(); unlock();
}
if (!wmutex && !(wmutex = getMutexHandle(-1, true))) if (!wmutex && !(wmutex = getMutexHandle(-1, true))) {
return false; return false;
}
if (!waitMutex(wmutex, block)) if (!waitMutex(wmutex, block)) {
return false; return false;
}
if (mode == ReadLock) { if (mode == ReadLock) {
int idx = 0; int idx = 0;
for (; idx < MAX_READERS; idx++) { for (; idx < MAX_READERS; idx++) {
rmutex = getMutexHandle(idx, false); rmutex = getMutexHandle(idx, false);
if (!rmutex || waitMutex(rmutex, false)) if (!rmutex || waitMutex(rmutex, false)) {
break; break;
}
CloseHandle(rmutex); CloseHandle(rmutex);
} }
bool ok = true; bool ok = true;
@ -141,30 +149,34 @@ bool QtLockedFile::lock(LockMode mode, bool block)
} }
else if (!rmutex) { else if (!rmutex) {
rmutex = getMutexHandle(idx, true); rmutex = getMutexHandle(idx, true);
if (!rmutex || !waitMutex(rmutex, false)) if (!rmutex || !waitMutex(rmutex, false)) {
ok = false; ok = false;
}
} }
if (!ok && rmutex) { if (!ok && rmutex) {
CloseHandle(rmutex); CloseHandle(rmutex);
rmutex = 0; rmutex = 0;
} }
ReleaseMutex(wmutex); ReleaseMutex(wmutex);
if (!ok) if (!ok) {
return false; return false;
}
} }
else { else {
Q_ASSERT(rmutexes.isEmpty()); Q_ASSERT(rmutexes.isEmpty());
for (int i = 0; i < MAX_READERS; i++) { for (int i = 0; i < MAX_READERS; i++) {
Qt::HANDLE mutex = getMutexHandle(i, false); Qt::HANDLE mutex = getMutexHandle(i, false);
if (mutex) if (mutex) {
rmutexes.append(mutex); rmutexes.append(mutex);
}
} }
if (rmutexes.size()) { if (rmutexes.size()) {
DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(),
TRUE, block ? INFINITE : 0); TRUE, block ? INFINITE : 0);
if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) {
if (res != WAIT_TIMEOUT) if (res != WAIT_TIMEOUT) {
qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed");
}
m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky
unlock(); unlock();
return false; return false;
@ -183,8 +195,9 @@ bool QtLockedFile::unlock()
return false; return false;
} }
if (!isLocked()) if (!isLocked()) {
return true; return true;
}
if (m_lock_mode == ReadLock) { if (m_lock_mode == ReadLock) {
ReleaseMutex(rmutex); ReleaseMutex(rmutex);
@ -206,8 +219,10 @@ bool QtLockedFile::unlock()
QtLockedFile::~QtLockedFile() QtLockedFile::~QtLockedFile()
{ {
if (isOpen()) if (isOpen()) {
unlock(); unlock();
if (wmutex) }
if (wmutex) {
CloseHandle(wmutex); CloseHandle(wmutex);
}
} }

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
@ -143,7 +143,7 @@ void QtSingleApplication::sysInit(const QString &appId)
{ {
actWin = 0; actWin = 0;
peer = new QtLocalPeer(this, appId); peer = new QtLocalPeer(this, appId);
connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); connect(peer, SIGNAL(messageReceived(const QString &)), SIGNAL(messageReceived(const QString &)));
} }
@ -157,7 +157,7 @@ void QtSingleApplication::sysInit(const QString &appId)
QtSingleCoreApplication instead. QtSingleCoreApplication instead.
*/ */
QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) QtSingleApplication::QtSingleApplication(int &argc, char** argv, bool GUIenabled)
: QApplication(argc, argv, GUIenabled) : QApplication(argc, argv, GUIenabled)
{ {
sysInit(); sysInit();
@ -170,7 +170,7 @@ QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled
QAppliation constructor. QAppliation constructor.
*/ */
QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char** argv)
: QApplication(argc, argv) : QApplication(argc, argv)
{ {
sysInit(appId); sysInit(appId);
@ -182,7 +182,7 @@ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char *
will be QCoreApplication::applicationFilePath(). \a argc, \a will be QCoreApplication::applicationFilePath(). \a argc, \a
argv, and \a type are passed on to the QAppliation constructor. argv, and \a type are passed on to the QAppliation constructor.
*/ */
QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) QtSingleApplication::QtSingleApplication(int &argc, char** argv, Type type)
: QApplication(argc, argv, type) : QApplication(argc, argv, type)
{ {
sysInit(); sysInit();
@ -209,7 +209,7 @@ QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HA
argv, \a visual, and \a cmap are passed on to the QApplication argv, \a visual, and \a cmap are passed on to the QApplication
constructor. constructor.
*/ */
QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) QtSingleApplication::QtSingleApplication(Display* dpy, int &argc, char** argv, Qt::HANDLE visual, Qt::HANDLE cmap)
: QApplication(dpy, argc, argv, visual, cmap) : QApplication(dpy, argc, argv, visual, cmap)
{ {
sysInit(); sysInit();
@ -222,7 +222,7 @@ QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Q
argv, \a visual, and \a cmap are passed on to the QApplication argv, \a visual, and \a cmap are passed on to the QApplication
constructor. constructor.
*/ */
QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char** argv, Qt::HANDLE visual, Qt::HANDLE cmap)
: QApplication(dpy, argc, argv, visual, cmap) : QApplication(dpy, argc, argv, visual, cmap)
{ {
sysInit(appId); sysInit(appId);
@ -291,10 +291,12 @@ QString QtSingleApplication::id() const
void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage)
{ {
actWin = aw; actWin = aw;
if (activateOnMessage) if (activateOnMessage) {
connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); connect(peer, SIGNAL(messageReceived(const QString &)), this, SLOT(activateWindow()));
else }
disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); else {
disconnect(peer, SIGNAL(messageReceived(const QString &)), this, SLOT(activateWindow()));
}
} }

View File

@ -1,17 +1,17 @@
/**************************************************************************** /****************************************************************************
** **
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved. ** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com) ** Contact: Nokia Corporation (qt-info@nokia.com)
** **
** This file is part of a Qt Solutions component. ** This file is part of a Qt Solutions component.
** **
** Commercial Usage ** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in ** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided ** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms ** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia. ** contained in a written agreement between you and Nokia.
** **
** GNU Lesser General Public License Usage ** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser ** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software ** General Public License version 2.1 as published by the Free Software
@ -19,29 +19,29 @@
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements ** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
** **
** In addition, as a special exception, Nokia gives you certain ** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL ** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package. ** package.
** **
** GNU General Public License Usage ** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU ** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software ** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the ** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to ** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be ** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html. ** met: http://www.gnu.org/copyleft/gpl.html.
** **
** Please note Third Party Software included with Qt Solutions may impose ** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure ** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt ** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third ** Solutions Commercial license and the relevant license of the Third
** Party Software they are using. ** Party Software they are using.
** **
** If you are unsure which license is appropriate for your use, please ** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com. ** contact Nokia at qt-info@nokia.com.
** **
****************************************************************************/ ****************************************************************************/
@ -70,13 +70,13 @@ class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication
Q_OBJECT Q_OBJECT
public: public:
QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); QtSingleApplication(int &argc, char** argv, bool GUIenabled = true);
QtSingleApplication(const QString &id, int &argc, char **argv); QtSingleApplication(const QString &id, int &argc, char** argv);
QtSingleApplication(int &argc, char **argv, Type type); QtSingleApplication(int &argc, char** argv, Type type);
#if defined(Q_WS_X11) #if defined(Q_WS_X11)
QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);
QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); QtSingleApplication(Display* dpy, int &argc, char** argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0);
QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display* dpy, const QString &appId, int argc, char** argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);
#endif #endif
bool isRunning(); bool isRunning();
@ -87,7 +87,7 @@ public:
// Obsolete: // Obsolete:
void initialize(bool dummy = true) void initialize(bool dummy = true)
{ isRunning(); Q_UNUSED(dummy) } { isRunning(); Q_UNUSED(dummy) }
public Q_SLOTS: public Q_SLOTS:
bool sendMessage(const QString &message, int timeout = 5000); bool sendMessage(const QString &message, int timeout = 5000);
@ -100,6 +100,6 @@ Q_SIGNALS:
private: private:
void sysInit(const QString &appId = QString()); void sysInit(const QString &appId = QString());
QtLocalPeer *peer; QtLocalPeer* peer;
QWidget *actWin; QWidget* actWin;
}; };

109
src/3rdparty/qtwin.cpp vendored
View File

@ -42,28 +42,27 @@
#define DWM_BB_TRANSITIONONMAXIMIZED 0x00000004 // fTransitionOnMaximized has been specified #define DWM_BB_TRANSITIONONMAXIMIZED 0x00000004 // fTransitionOnMaximized has been specified
#define WM_DWMCOMPOSITIONCHANGED 0x031E // Composition changed window message #define WM_DWMCOMPOSITIONCHANGED 0x031E // Composition changed window message
typedef struct _DWM_BLURBEHIND typedef struct _DWM_BLURBEHIND {
{
DWORD dwFlags; DWORD dwFlags;
BOOL fEnable; BOOL fEnable;
HRGN hRgnBlur; HRGN hRgnBlur;
BOOL fTransitionOnMaximized; BOOL fTransitionOnMaximized;
} DWM_BLURBEHIND, *PDWM_BLURBEHIND; } DWM_BLURBEHIND, *PDWM_BLURBEHIND;
typedef struct _MARGINS //typedef struct _MARGINS
{ //{
int cxLeftWidth; // int cxLeftWidth;
int cxRightWidth; // int cxRightWidth;
int cyTopHeight; // int cyTopHeight;
int cyBottomHeight; // int cyBottomHeight;
} MARGINS, *PMARGINS; //} MARGINS, *PMARGINS;
typedef HRESULT (WINAPI *PtrDwmIsCompositionEnabled)(BOOL* pfEnabled); typedef HRESULT(WINAPI* PtrDwmIsCompositionEnabled)(BOOL* pfEnabled);
typedef HRESULT (WINAPI *PtrDwmExtendFrameIntoClientArea)(HWND hWnd, const MARGINS* pMarInset); typedef HRESULT(WINAPI* PtrDwmExtendFrameIntoClientArea)(HWND hWnd, const MARGINS* pMarInset);
typedef HRESULT (WINAPI *PtrDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind); typedef HRESULT(WINAPI* PtrDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);
typedef HRESULT (WINAPI *PtrDwmGetColorizationColor)(DWORD *pcrColorization, BOOL *pfOpaqueBlend); typedef HRESULT(WINAPI* PtrDwmGetColorizationColor)(DWORD* pcrColorization, BOOL* pfOpaqueBlend);
static PtrDwmIsCompositionEnabled pDwmIsCompositionEnabled= 0; static PtrDwmIsCompositionEnabled pDwmIsCompositionEnabled = 0;
static PtrDwmEnableBlurBehindWindow pDwmEnableBlurBehindWindow = 0; static PtrDwmEnableBlurBehindWindow pDwmEnableBlurBehindWindow = 0;
static PtrDwmExtendFrameIntoClientArea pDwmExtendFrameIntoClientArea = 0; static PtrDwmExtendFrameIntoClientArea pDwmExtendFrameIntoClientArea = 0;
static PtrDwmGetColorizationColor pDwmGetColorizationColor = 0; static PtrDwmGetColorizationColor pDwmGetColorizationColor = 0;
@ -77,10 +76,16 @@ static PtrDwmGetColorizationColor pDwmGetColorizationColor = 0;
class WindowNotifier : public QWidget class WindowNotifier : public QWidget
{ {
public: public:
WindowNotifier() { winId(); } WindowNotifier() {
void addWidget(QWidget *widget) { widgets.append(widget); } winId();
void removeWidget(QWidget *widget) { widgets.removeAll(widget); } }
bool winEvent(MSG *message, long *result); void addWidget(QWidget* widget) {
widgets.append(widget);
}
void removeWidget(QWidget* widget) {
widgets.removeAll(widget);
}
bool winEvent(MSG* message, long* result);
private: private:
QWidgetList widgets; QWidgetList widgets;
@ -90,7 +95,7 @@ static bool resolveLibs()
{ {
if (!pDwmIsCompositionEnabled) { if (!pDwmIsCompositionEnabled) {
QLibrary dwmLib(QString::fromAscii("dwmapi")); QLibrary dwmLib(QString::fromAscii("dwmapi"));
pDwmIsCompositionEnabled =(PtrDwmIsCompositionEnabled)dwmLib.resolve("DwmIsCompositionEnabled"); pDwmIsCompositionEnabled = (PtrDwmIsCompositionEnabled)dwmLib.resolve("DwmIsCompositionEnabled");
pDwmExtendFrameIntoClientArea = (PtrDwmExtendFrameIntoClientArea)dwmLib.resolve("DwmExtendFrameIntoClientArea"); pDwmExtendFrameIntoClientArea = (PtrDwmExtendFrameIntoClientArea)dwmLib.resolve("DwmExtendFrameIntoClientArea");
pDwmEnableBlurBehindWindow = (PtrDwmEnableBlurBehindWindow)dwmLib.resolve("DwmEnableBlurBehindWindow"); pDwmEnableBlurBehindWindow = (PtrDwmEnableBlurBehindWindow)dwmLib.resolve("DwmEnableBlurBehindWindow");
pDwmGetColorizationColor = (PtrDwmGetColorizationColor)dwmLib.resolve("DwmGetColorizationColor"); pDwmGetColorizationColor = (PtrDwmGetColorizationColor)dwmLib.resolve("DwmGetColorizationColor");
@ -133,8 +138,9 @@ bool QtWin::isCompositionEnabled()
HRESULT hr = S_OK; HRESULT hr = S_OK;
BOOL isEnabled = false; BOOL isEnabled = false;
hr = pDwmIsCompositionEnabled(&isEnabled); hr = pDwmIsCompositionEnabled(&isEnabled);
if (SUCCEEDED(hr)) if (SUCCEEDED(hr)) {
return isEnabled; return isEnabled;
}
} }
#endif #endif
return false; return false;
@ -145,7 +151,7 @@ bool QtWin::isCompositionEnabled()
* *
* \a enable tells if the blur should be enabled or not * \a enable tells if the blur should be enabled or not
*/ */
bool QtWin::enableBlurBehindWindow(QWidget *widget, bool enable) bool QtWin::enableBlurBehindWindow(QWidget* widget, bool enable)
{ {
Q_UNUSED(enable); Q_UNUSED(enable);
Q_UNUSED(widget); Q_UNUSED(widget);
@ -182,7 +188,7 @@ bool QtWin::enableBlurBehindWindow(QWidget *widget, bool enable)
* *
* \a enable tells if the blur should be enabled or not * \a enable tells if the blur should be enabled or not
*/ */
bool QtWin::extendFrameIntoClientArea(QWidget *widget, int left, int top, int right, int bottom) bool QtWin::extendFrameIntoClientArea(QWidget* widget, int left, int top, int right, int bottom)
{ {
Q_ASSERT(widget); Q_ASSERT(widget);
@ -225,25 +231,27 @@ QColor QtWin::colorizationColor()
QLibrary dwmLib(QString::fromAscii("dwmapi")); QLibrary dwmLib(QString::fromAscii("dwmapi"));
HRESULT hr = S_OK; HRESULT hr = S_OK;
hr = pDwmGetColorizationColor(&color, &opaque); hr = pDwmGetColorizationColor(&color, &opaque);
if (SUCCEEDED(hr)) if (SUCCEEDED(hr)) {
resultColor = QColor(color); resultColor = QColor(color);
}
} }
#endif #endif
return resultColor; return resultColor;
} }
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
WindowNotifier *QtWin::windowNotifier() WindowNotifier* QtWin::windowNotifier()
{ {
static WindowNotifier *windowNotifierInstance = 0; static WindowNotifier* windowNotifierInstance = 0;
if (!windowNotifierInstance) if (!windowNotifierInstance) {
windowNotifierInstance = new WindowNotifier; windowNotifierInstance = new WindowNotifier;
}
return windowNotifierInstance; return windowNotifierInstance;
} }
/* Notify all enabled windows that the DWM state changed */ /* Notify all enabled windows that the DWM state changed */
bool WindowNotifier::winEvent(MSG *message, long *result) bool WindowNotifier::winEvent(MSG* message, long* result)
{ {
if (message && message->message == WM_DWMCOMPOSITIONCHANGED) { if (message && message->message == WM_DWMCOMPOSITIONCHANGED) {
bool compositionEnabled = QtWin::isCompositionEnabled(); bool compositionEnabled = QtWin::isCompositionEnabled();
@ -259,8 +267,9 @@ bool WindowNotifier::winEvent(MSG *message, long *result)
#ifdef W7API #ifdef W7API
IShellLink* QtWin::CreateShellLink(const QString &title, const QString &description, IShellLink* QtWin::CreateShellLink(const QString &title, const QString &description,
const QString &app_path, const QString &app_args, const QString &app_path, const QString &app_args,
const QString &icon_path, int app_index) { const QString &icon_path, int app_index)
{
const wchar_t* _title = reinterpret_cast<const wchar_t*>(title.utf16()); const wchar_t* _title = reinterpret_cast<const wchar_t*>(title.utf16());
const wchar_t* _description = reinterpret_cast<const wchar_t*>(description.utf16()); const wchar_t* _description = reinterpret_cast<const wchar_t*>(description.utf16());
@ -273,8 +282,8 @@ IShellLink* QtWin::CreateShellLink(const QString &title, const QString &descript
bool is_not_separator = (app_path.length() > 0); bool is_not_separator = (app_path.length() > 0);
HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**> (&(shell_link))); reinterpret_cast<void**>(&(shell_link)));
if(SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
if (is_not_separator) { if (is_not_separator) {
shell_link->SetPath(_app_path); shell_link->SetPath(_app_path);
shell_link->SetArguments(_app_args); shell_link->SetArguments(_app_args);
@ -282,7 +291,7 @@ IShellLink* QtWin::CreateShellLink(const QString &title, const QString &descript
shell_link->SetDescription(_description); shell_link->SetDescription(_description);
} }
hr = shell_link->QueryInterface(IID_IPropertyStore, reinterpret_cast<void**> (&(prop_store))); hr = shell_link->QueryInterface(IID_IPropertyStore, reinterpret_cast<void**>(&(prop_store)));
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
PROPVARIANT pv; PROPVARIANT pv;
@ -292,7 +301,8 @@ IShellLink* QtWin::CreateShellLink(const QString &title, const QString &descript
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
hr = prop_store->SetValue(PKEY_Title, pv); hr = prop_store->SetValue(PKEY_Title, pv);
} }
} else { }
else {
hr = InitPropVariantFromBoolean(TRUE, &pv); hr = InitPropVariantFromBoolean(TRUE, &pv);
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
@ -314,20 +324,21 @@ void QtWin::populateFrequentSites(IObjectCollection* collection, const QString &
{ {
HistoryModel* historyModel = mApp->history(); HistoryModel* historyModel = mApp->history();
QList<HistoryModel::HistoryEntry> mostList = historyModel->mostVisited(6); QList<HistoryModel::HistoryEntry> mostList = historyModel->mostVisited(6);
foreach (HistoryModel::HistoryEntry entry, mostList) foreach(HistoryModel::HistoryEntry entry, mostList)
collection->AddObject(CreateShellLink(entry.title, entry.url.toString(), appPath, " "+entry.url.toEncoded(), appPath, 1)); collection->AddObject(CreateShellLink(entry.title, entry.url.toString(), appPath, " " + entry.url.toEncoded(), appPath, 1));
collection->AddObject(CreateShellLink("", "", "", "", "", 0)); //Spacer collection->AddObject(CreateShellLink("", "", "", "", "", 0)); //Spacer
} }
void QtWin::AddTasksToList(ICustomDestinationList* destinationList) { void QtWin::AddTasksToList(ICustomDestinationList* destinationList)
{
IObjectArray* object_array; IObjectArray* object_array;
IObjectCollection* obj_collection; IObjectCollection* obj_collection;
CoCreateInstance(CLSID_EnumerableObjectCollection, NULL, CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
CLSCTX_INPROC, IID_IObjectCollection, reinterpret_cast<void**> (&(obj_collection))); CLSCTX_INPROC, IID_IObjectCollection, reinterpret_cast<void**>(&(obj_collection)));
obj_collection->QueryInterface(IID_IObjectArray, reinterpret_cast<void**> (&(object_array))); obj_collection->QueryInterface(IID_IObjectArray, reinterpret_cast<void**>(&(object_array)));
QString icons_source = qApp->applicationFilePath(); QString icons_source = qApp->applicationFilePath();
QString app_path = qApp->applicationFilePath(); QString app_path = qApp->applicationFilePath();
@ -335,16 +346,16 @@ void QtWin::AddTasksToList(ICustomDestinationList* destinationList) {
populateFrequentSites(obj_collection, icons_source); populateFrequentSites(obj_collection, icons_source);
obj_collection->AddObject(CreateShellLink(tr("Open new tab"), tr("Opens a new tab if browser is running"), obj_collection->AddObject(CreateShellLink(tr("Open new tab"), tr("Opens a new tab if browser is running"),
app_path, "--new-tab", app_path, "--new-tab",
icons_source, 0)); icons_source, 0));
obj_collection->AddObject(CreateShellLink(tr("Open new window"), tr("Opens a new window if browser is running"), obj_collection->AddObject(CreateShellLink(tr("Open new window"), tr("Opens a new window if browser is running"),
app_path, "--new-window", app_path, "--new-window",
icons_source, 0)); icons_source, 0));
obj_collection->AddObject(CreateShellLink(tr("Open download manager"), tr("Opens a download manager if browser is running"), obj_collection->AddObject(CreateShellLink(tr("Open download manager"), tr("Opens a download manager if browser is running"),
app_path, "--download-manager", app_path, "--download-manager",
icons_source, 0)); icons_source, 0));
destinationList->AddUserTasks(object_array); destinationList->AddUserTasks(object_array);
@ -354,10 +365,12 @@ void QtWin::AddTasksToList(ICustomDestinationList* destinationList) {
#endif //W7API #endif //W7API
#endif //Q_WS_WIN #endif //Q_WS_WIN
void QtWin::setupJumpList() { void QtWin::setupJumpList()
{
#ifdef W7API #ifdef W7API
if (!isRunningWindows7()) if (!isRunningWindows7()) {
return; return;
}
UINT max_count = 0; UINT max_count = 0;
IObjectArray* objectArray; IObjectArray* objectArray;
@ -365,10 +378,10 @@ void QtWin::setupJumpList() {
//create the custom jump list object //create the custom jump list object
CoCreateInstance(CLSID_DestinationList, NULL, CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, CoCreateInstance(CLSID_DestinationList, NULL, CLSCTX_INPROC_SERVER, IID_ICustomDestinationList,
reinterpret_cast<void**> (&(destinationList))); reinterpret_cast<void**>(&(destinationList)));
//initialize list //initialize list
destinationList->BeginList(&max_count, IID_IObjectArray, reinterpret_cast<void**> (&(objectArray))); destinationList->BeginList(&max_count, IID_IObjectArray, reinterpret_cast<void**>(&(objectArray)));
AddTasksToList(destinationList); AddTasksToList(destinationList);
//commit list //commit list

View File

@ -51,8 +51,8 @@ class QtWin : public QObject
Q_OBJECT Q_OBJECT
public: public:
static bool isRunningWindows7(); static bool isRunningWindows7();
static bool enableBlurBehindWindow(QWidget *widget, bool enable = true); static bool enableBlurBehindWindow(QWidget* widget, bool enable = true);
static bool extendFrameIntoClientArea(QWidget *widget, static bool extendFrameIntoClientArea(QWidget* widget,
int left = -1, int top = -1, int left = -1, int top = -1,
int right = -1, int bottom = -1); int right = -1, int bottom = -1);
static bool isCompositionEnabled(); static bool isCompositionEnabled();
@ -62,7 +62,7 @@ public slots:
static void setupJumpList(); static void setupJumpList();
private: private:
static WindowNotifier *windowNotifier(); static WindowNotifier* windowNotifier();
#ifdef W7API #ifdef W7API
static void populateFrequentSites(IObjectCollection* collection, const QString &appPath); static void populateFrequentSites(IObjectCollection* collection, const QString &appPath);
static void AddTasksToList(ICustomDestinationList* destinationList); static void AddTasksToList(ICustomDestinationList* destinationList);

View File

@ -1,11 +1,11 @@
#include "squeezelabelv1.h" #include "squeezelabelv1.h"
SqueezeLabelV1::SqueezeLabelV1(QWidget *parent) SqueezeLabelV1::SqueezeLabelV1(QWidget* parent)
: QLabel(parent) : QLabel(parent)
{ {
} }
void SqueezeLabelV1::paintEvent(QPaintEvent *event) void SqueezeLabelV1::paintEvent(QPaintEvent* event)
{ {
if (m_SqueezedTextCache != text()) { if (m_SqueezedTextCache != text()) {
m_SqueezedTextCache = text(); m_SqueezedTextCache = text();

View File

@ -40,10 +40,10 @@ class SqueezeLabelV1 : public QLabel
Q_OBJECT Q_OBJECT
public: public:
SqueezeLabelV1(QWidget *parent = 0); SqueezeLabelV1(QWidget* parent = 0);
protected: protected:
void paintEvent(QPaintEvent *event); void paintEvent(QPaintEvent* event);
private: private:
QString m_SqueezedTextCache; QString m_SqueezedTextCache;

View File

@ -1,6 +1,6 @@
#include "squeezelabelv2.h" #include "squeezelabelv2.h"
SqueezeLabelV2::SqueezeLabelV2(QWidget *parent) SqueezeLabelV2::SqueezeLabelV2(QWidget* parent)
: QLabel(parent) : QLabel(parent)
{ {
} }
@ -24,7 +24,7 @@ QString SqueezeLabelV2::originalText()
return m_originalText; return m_originalText;
} }
void SqueezeLabelV2::resizeEvent(QResizeEvent *event) void SqueezeLabelV2::resizeEvent(QResizeEvent* event)
{ {
QLabel::resizeEvent(event); QLabel::resizeEvent(event);
QFontMetrics fm = fontMetrics(); QFontMetrics fm = fontMetrics();

View File

@ -40,14 +40,14 @@ class SqueezeLabelV2 : public QLabel
Q_OBJECT Q_OBJECT
public: public:
SqueezeLabelV2(QWidget *parent = 0); SqueezeLabelV2(QWidget* parent = 0);
SqueezeLabelV2(const QString &string); SqueezeLabelV2(const QString &string);
QString originalText(); QString originalText();
void setText(const QString &txt); void setText(const QString &txt);
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent* event);
private: private:
QString m_SqueezedTextCache; QString m_SqueezedTextCache;

View File

@ -45,7 +45,8 @@ static int clamp(float x)
return val < 0 ? 0 : val; return val < 0 ? 0 : val;
} }
namespace Utils { namespace Utils
{
qreal StyleHelper::sidebarFontSize() qreal StyleHelper::sidebarFontSize()
{ {
@ -58,10 +59,12 @@ qreal StyleHelper::sidebarFontSize()
QColor StyleHelper::panelTextColor(bool lightColored) QColor StyleHelper::panelTextColor(bool lightColored)
{ {
if (!lightColored) if (!lightColored) {
return Qt::white; return Qt::white;
else }
else {
return Qt::black; return Qt::black;
}
} }
// Invalid by default, setBaseColor needs to be called at least once // Invalid by default, setBaseColor needs to be called at least once
@ -70,10 +73,12 @@ QColor StyleHelper::m_requestedBaseColor;
QColor StyleHelper::baseColor(bool lightColored) QColor StyleHelper::baseColor(bool lightColored)
{ {
if (!lightColored) if (!lightColored) {
return m_baseColor; return m_baseColor;
else }
else {
return m_baseColor.lighter(230); return m_baseColor.lighter(230);
}
} }
QColor StyleHelper::highlightColor(bool lightColored) QColor StyleHelper::highlightColor(bool lightColored)
@ -81,12 +86,12 @@ QColor StyleHelper::highlightColor(bool lightColored)
QColor result = baseColor(lightColored); QColor result = baseColor(lightColored);
if (!lightColored) if (!lightColored)
result.setHsv(result.hue(), result.setHsv(result.hue(),
clamp(result.saturation()), clamp(result.saturation()),
clamp(result.value() * 1.16)); clamp(result.value() * 1.16));
else else
result.setHsv(result.hue(), result.setHsv(result.hue(),
clamp(result.saturation()), clamp(result.saturation()),
clamp(result.value() * 1.06)); clamp(result.value() * 1.06));
return result; return result;
} }
@ -122,12 +127,12 @@ void StyleHelper::setBaseColor(const QColor &newcolor)
if (color.isValid() && color != m_baseColor) { if (color.isValid() && color != m_baseColor) {
m_baseColor = color; m_baseColor = color;
foreach (QWidget *w, QApplication::topLevelWidgets()) foreach(QWidget * w, QApplication::topLevelWidgets())
w->update(); w->update();
} }
} }
static void verticalGradientHelper(QPainter *p, const QRect &spanRect, const QRect &rect, bool lightColored) static void verticalGradientHelper(QPainter* p, const QRect &spanRect, const QRect &rect, bool lightColored)
{ {
QColor highlight = StyleHelper::highlightColor(lightColored); QColor highlight = StyleHelper::highlightColor(lightColored);
QColor shadow = StyleHelper::shadowColor(lightColored); QColor shadow = StyleHelper::shadowColor(lightColored);
@ -144,14 +149,14 @@ static void verticalGradientHelper(QPainter *p, const QRect &spanRect, const QRe
p->drawLine(rect.topLeft(), rect.bottomLeft()); p->drawLine(rect.topLeft(), rect.bottomLeft());
} }
void StyleHelper::verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect, bool lightColored) void StyleHelper::verticalGradient(QPainter* painter, const QRect &spanRect, const QRect &clipRect, bool lightColored)
{ {
if (StyleHelper::usePixmapCache()) { if (StyleHelper::usePixmapCache()) {
QString key; QString key;
QColor keyColor = baseColor(lightColored); QColor keyColor = baseColor(lightColored);
key.sprintf("mh_vertical %d %d %d %d %d", key.sprintf("mh_vertical %d %d %d %d %d",
spanRect.width(), spanRect.height(), clipRect.width(), spanRect.width(), spanRect.height(), clipRect.width(),
clipRect.height(), keyColor.rgb());; clipRect.height(), keyColor.rgb());;
QPixmap pixmap; QPixmap pixmap;
if (!QPixmapCache::find(key, pixmap)) { if (!QPixmapCache::find(key, pixmap)) {
@ -164,14 +169,15 @@ void StyleHelper::verticalGradient(QPainter *painter, const QRect &spanRect, con
} }
painter->drawPixmap(clipRect.topLeft(), pixmap); painter->drawPixmap(clipRect.topLeft(), pixmap);
} else { }
else {
verticalGradientHelper(painter, spanRect, clipRect, lightColored); verticalGradientHelper(painter, spanRect, clipRect, lightColored);
} }
} }
// Draws a cached pixmap with shadow // Draws a cached pixmap with shadow
void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect, void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect,
QPainter *p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset) QPainter* p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset)
{ {
QPixmap cache; QPixmap cache;
QString pixmapName = QString("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height()); QString pixmapName = QString("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height());
@ -184,9 +190,9 @@ void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect,
QPainter cachePainter(&cache); QPainter cachePainter(&cache);
if (iconMode == QIcon::Disabled) { if (iconMode == QIcon::Disabled) {
QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32); QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32);
for (int y=0; y<im.height(); ++y) { for (int y = 0; y < im.height(); ++y) {
QRgb *scanLine = (QRgb*)im.scanLine(y); QRgb* scanLine = (QRgb*)im.scanLine(y);
for (int x=0; x<im.width(); ++x) { for (int x = 0; x < im.width(); ++x) {
QRgb pixel = *scanLine; QRgb pixel = *scanLine;
char intensity = qGray(pixel); char intensity = qGray(pixel);
*scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)); *scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel));

View File

@ -39,12 +39,13 @@ class QPainter;
class QRect; class QRect;
// Note, this is exported but in a private header as qtopengl depends on it. // Note, this is exported but in a private header as qtopengl depends on it.
// We should consider adding this as a public helper function. // We should consider adding this as a public helper function.
void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0); void qt_blurImage(QPainter* p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0);
QT_END_NAMESPACE QT_END_NAMESPACE
// Helper class holding all custom color values // Helper class holding all custom color values
namespace Utils { namespace Utils
{
class StyleHelper class StyleHelper
{ {
public: public:
@ -68,10 +69,10 @@ public:
static void setBaseColor(const QColor &color); static void setBaseColor(const QColor &color);
// Gradients used for panels // Gradients used for panels
static void verticalGradient(QPainter *painter, const QRect &spanRect, const QRect &clipRect, bool lightColored = false); static void verticalGradient(QPainter* painter, const QRect &spanRect, const QRect &clipRect, bool lightColored = false);
static bool usePixmapCache() { return true; } static bool usePixmapCache() { return true; }
static void drawIconWithShadow(const QIcon &icon, const QRect &rect, QPainter *p, QIcon::Mode iconMode, static void drawIconWithShadow(const QIcon &icon, const QRect &rect, QPainter* p, QIcon::Mode iconMode,
int radius = 3, const QColor &color = QColor(0, 0, 0, 130), int radius = 3, const QColor &color = QColor(0, 0, 0, 130),
const QPoint &offset = QPoint(1, -2)); const QPoint &offset = QPoint(1, -2));

View File

@ -50,7 +50,7 @@
#include <qnetworkrequest.h> #include <qnetworkrequest.h>
#include <qtimer.h> #include <qtimer.h>
AdBlockBlockedNetworkReply::AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule *rule, QObject *parent) AdBlockBlockedNetworkReply::AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule* rule, QObject* parent)
: QNetworkReply(parent) : QNetworkReply(parent)
{ {
setOperation(QNetworkAccessManager::GetOperation); setOperation(QNetworkAccessManager::GetOperation);
@ -60,7 +60,7 @@ AdBlockBlockedNetworkReply::AdBlockBlockedNetworkReply(const QNetworkRequest &re
QTimer::singleShot(0, this, SLOT(delayedFinished())); QTimer::singleShot(0, this, SLOT(delayedFinished()));
} }
qint64 AdBlockBlockedNetworkReply::readData(char *data, qint64 maxSize) qint64 AdBlockBlockedNetworkReply::readData(char* data, qint64 maxSize)
{ {
Q_UNUSED(data); Q_UNUSED(data);
Q_UNUSED(maxSize); Q_UNUSED(maxSize);

View File

@ -54,11 +54,11 @@ class AdBlockBlockedNetworkReply : public QNetworkReply
Q_OBJECT Q_OBJECT
public: public:
AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule *rule, QObject *parent = 0); AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule* rule, QObject* parent = 0);
void abort() {}; void abort() {}
protected: protected:
qint64 readData(char *data, qint64 maxSize); qint64 readData(char* data, qint64 maxSize);
private slots: private slots:
void delayedFinished(); void delayedFinished();

View File

@ -47,7 +47,7 @@
#include "adblocksubscription.h" #include "adblocksubscription.h"
#include "mainapplication.h" #include "mainapplication.h"
AdBlockDialog::AdBlockDialog(QWidget *parent) AdBlockDialog::AdBlockDialog(QWidget* parent)
: QDialog(parent) : QDialog(parent)
, m_itemChangingBlock(false) , m_itemChangingBlock(false)
, m_manager(AdBlockManager::instance()) , m_manager(AdBlockManager::instance())
@ -73,8 +73,9 @@ AdBlockDialog::AdBlockDialog(QWidget *parent)
void AdBlockDialog::editRule() void AdBlockDialog::editRule()
{ {
QTreeWidgetItem* item = treeWidget->currentItem(); QTreeWidgetItem* item = treeWidget->currentItem();
if (!item || !(item->flags() & Qt::ItemIsEditable)) if (!item || !(item->flags() & Qt::ItemIsEditable)) {
return; return;
}
item->setSelected(true); item->setSelected(true);
} }
@ -82,8 +83,9 @@ void AdBlockDialog::editRule()
void AdBlockDialog::deleteRule() void AdBlockDialog::deleteRule()
{ {
QTreeWidgetItem* item = treeWidget->currentItem(); QTreeWidgetItem* item = treeWidget->currentItem();
if (!item) if (!item) {
return; return;
}
int offset = item->whatsThis(0).toInt(); int offset = item->whatsThis(0).toInt();
m_manager->subscription()->removeRule(offset); m_manager->subscription()->removeRule(offset);
@ -103,7 +105,7 @@ void AdBlockDialog::customContextMenuRequested()
void AdBlockDialog::firstRefresh() void AdBlockDialog::firstRefresh()
{ {
refresh(); refresh();
connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(itemChanged(QTreeWidgetItem*))); connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(itemChanged(QTreeWidgetItem*)));
} }
void AdBlockDialog::refreshAfterUpdate() void AdBlockDialog::refreshAfterUpdate()
@ -124,12 +126,12 @@ void AdBlockDialog::refresh()
italicFont.setItalic(true); italicFont.setItalic(true);
m_customRulesItem = new QTreeWidgetItem(treeWidget); m_customRulesItem = new QTreeWidgetItem(treeWidget);
m_customRulesItem->setText(0,tr("Custom Rules")); m_customRulesItem->setText(0, tr("Custom Rules"));
m_customRulesItem->setFont(0, boldFont); m_customRulesItem->setFont(0, boldFont);
treeWidget->addTopLevelItem(m_customRulesItem); treeWidget->addTopLevelItem(m_customRulesItem);
m_easyListItem = new QTreeWidgetItem(treeWidget); m_easyListItem = new QTreeWidgetItem(treeWidget);
m_easyListItem->setText(0,"EasyList"); m_easyListItem->setText(0, "EasyList");
m_easyListItem->setFont(0, boldFont); m_easyListItem->setFont(0, boldFont);
treeWidget->addTopLevelItem(m_easyListItem); treeWidget->addTopLevelItem(m_easyListItem);
@ -137,31 +139,34 @@ void AdBlockDialog::refresh()
QList<AdBlockRule> allRules = m_manager->subscription()->allRules(); QList<AdBlockRule> allRules = m_manager->subscription()->allRules();
int index = 0; int index = 0;
foreach (const AdBlockRule rule, allRules) { foreach(const AdBlockRule & rule, allRules) {
index++; index++;
if (rule.filter().contains("*******- user custom filters")) { if (rule.filter().contains("*******- user custom filters")) {
customRulesStarted = true; customRulesStarted = true;
continue; continue;
} }
QTreeWidgetItem* item = new QTreeWidgetItem(customRulesStarted ? m_customRulesItem : m_easyListItem); QTreeWidgetItem* item = new QTreeWidgetItem(customRulesStarted ? m_customRulesItem : m_easyListItem);
if (item->parent() == m_customRulesItem) if (item->parent() == m_customRulesItem) {
item->setFlags(item->flags() | Qt::ItemIsEditable); item->setFlags(item->flags() | Qt::ItemIsEditable);
}
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(0, (rule.filter().startsWith("!") ) ? Qt::Unchecked : Qt::Checked); item->setCheckState(0, (rule.filter().startsWith("!")) ? Qt::Unchecked : Qt::Checked);
item->setText(0, rule.filter()); item->setText(0, rule.filter());
item->setWhatsThis(0, QString::number(index-1)); item->setWhatsThis(0, QString::number(index - 1));
if (rule.filter().startsWith("!")) if (rule.filter().startsWith("!")) {
item->setFont(0, italicFont); item->setFont(0, italicFont);
}
} }
treeWidget->expandAll(); treeWidget->expandAll();
treeWidget->setUpdatesEnabled(true); treeWidget->setUpdatesEnabled(true);
m_itemChangingBlock = false; m_itemChangingBlock = false;
} }
void AdBlockDialog::itemChanged(QTreeWidgetItem *item) void AdBlockDialog::itemChanged(QTreeWidgetItem* item)
{ {
if (!item || m_itemChangingBlock) if (!item || m_itemChangingBlock) {
return; return;
}
m_itemChangingBlock = true; m_itemChangingBlock = true;
@ -175,7 +180,8 @@ void AdBlockDialog::itemChanged(QTreeWidgetItem *item)
AdBlockRule rul(item->text(0)); AdBlockRule rul(item->text(0));
m_manager->subscription()->replaceRule(rul, offset); m_manager->subscription()->replaceRule(rul, offset);
} else if (item->checkState(0) == Qt::Checked && item->text(0).startsWith("!")) { //Enable rule }
else if (item->checkState(0) == Qt::Checked && item->text(0).startsWith("!")) { //Enable rule
int offset = item->whatsThis(0).toInt(); int offset = item->whatsThis(0).toInt();
item->setFont(0, QFont()); item->setFont(0, QFont());
QString newText = item->text(0).mid(1); QString newText = item->text(0).mid(1);
@ -184,7 +190,8 @@ void AdBlockDialog::itemChanged(QTreeWidgetItem *item)
AdBlockRule rul(newText); AdBlockRule rul(newText);
m_manager->subscription()->replaceRule(rul, offset); m_manager->subscription()->replaceRule(rul, offset);
} else { //Custom rule has been changed }
else { //Custom rule has been changed
int offset = item->whatsThis(0).toInt(); int offset = item->whatsThis(0).toInt();
AdBlockRule rul(item->text(0)); AdBlockRule rul(item->text(0));
@ -199,8 +206,9 @@ void AdBlockDialog::itemChanged(QTreeWidgetItem *item)
void AdBlockDialog::addCustomRule() void AdBlockDialog::addCustomRule()
{ {
QString newRule = QInputDialog::getText(this, tr("Add Custom Rule"), tr("Please write your rule here:")); QString newRule = QInputDialog::getText(this, tr("Add Custom Rule"), tr("Please write your rule here:"));
if (newRule.isEmpty()) if (newRule.isEmpty()) {
return; return;
}
AdBlockSubscription* subscription = m_manager->subscription(); AdBlockSubscription* subscription = m_manager->subscription();
int offset = subscription->addRule(AdBlockRule(newRule)); int offset = subscription->addRule(AdBlockRule(newRule));

View File

@ -68,7 +68,7 @@ class AdBlockDialog : public QDialog, public Ui_AdBlockDialog
Q_OBJECT Q_OBJECT
public: public:
AdBlockDialog(QWidget *parent = 0); AdBlockDialog(QWidget* parent = 0);
private slots: private slots:
void itemChanged(QTreeWidgetItem* item); void itemChanged(QTreeWidgetItem* item);

View File

@ -21,8 +21,8 @@
#include "webpage.h" #include "webpage.h"
AdBlockIcon::AdBlockIcon(QupZilla* mainClass, QWidget* parent) AdBlockIcon::AdBlockIcon(QupZilla* mainClass, QWidget* parent)
: ClickableLabel(parent) : ClickableLabel(parent)
, p_QupZilla(mainClass) , p_QupZilla(mainClass)
{ {
setMaximumHeight(16); setMaximumHeight(16);
setCursor(Qt::PointingHandCursor); setCursor(Qt::PointingHandCursor);
@ -39,11 +39,12 @@ void AdBlockIcon::showMenu(const QPoint &pos)
menu.addAction(tr("Show AdBlock &Settings"), manager, SLOT(showDialog())); menu.addAction(tr("Show AdBlock &Settings"), manager, SLOT(showDialog()));
menu.addSeparator(); menu.addSeparator();
QList<WebPage::AdBlockedEntry> entries = p_QupZilla->weView()->webPage()->adBlockedEntries(); QList<WebPage::AdBlockedEntry> entries = p_QupZilla->weView()->webPage()->adBlockedEntries();
if (entries.isEmpty()) if (entries.isEmpty()) {
menu.addAction(tr("No content blocked"))->setEnabled(false); menu.addAction(tr("No content blocked"))->setEnabled(false);
}
else { else {
menu.addAction(tr("Blocked URL (AdBlock Rule) - click to edit rule"))->setEnabled(false); menu.addAction(tr("Blocked URL (AdBlock Rule) - click to edit rule"))->setEnabled(false);
foreach (WebPage::AdBlockedEntry entry, entries) { foreach(WebPage::AdBlockedEntry entry, entries) {
QString address = entry.url.toString().right(55); QString address = entry.url.toString().right(55);
menu.addAction(tr("%1 with (%2)").arg(address, entry.rule), manager, SLOT(showRule()))->setData(entry.rule); menu.addAction(tr("%1 with (%2)").arg(address, entry.rule), manager, SLOT(showRule()))->setData(entry.rule);
} }
@ -61,10 +62,12 @@ void AdBlockIcon::learnAboutRules()
void AdBlockIcon::setEnabled(bool enabled) void AdBlockIcon::setEnabled(bool enabled)
{ {
if (enabled) if (enabled) {
setPixmap(QPixmap(":icons/other/adblock.png")); setPixmap(QPixmap(":icons/other/adblock.png"));
else }
else {
setPixmap(QPixmap(":icons/other/adblock-disabled.png")); setPixmap(QPixmap(":icons/other/adblock-disabled.png"));
}
} }
AdBlockIcon::~AdBlockIcon() AdBlockIcon::~AdBlockIcon()

View File

@ -60,21 +60,24 @@ AdBlockManager::AdBlockManager(QObject* parent)
, m_adBlockDialog(0) , m_adBlockDialog(0)
, m_adBlockNetwork(0) , m_adBlockNetwork(0)
, m_adBlockPage(0) , m_adBlockPage(0)
, m_subscription(0)
{ {
} }
AdBlockManager* AdBlockManager::instance() AdBlockManager* AdBlockManager::instance()
{ {
if (!s_adBlockManager) if (!s_adBlockManager) {
s_adBlockManager = new AdBlockManager(mApp->networkManager()); s_adBlockManager = new AdBlockManager(mApp->networkManager());
}
return s_adBlockManager; return s_adBlockManager;
} }
void AdBlockManager::setEnabled(bool enabled) void AdBlockManager::setEnabled(bool enabled)
{ {
if (isEnabled() == enabled) if (isEnabled() == enabled) {
return; return;
}
m_enabled = enabled; m_enabled = enabled;
emit rulesChanged(); emit rulesChanged();
mApp->sendMessages(MainApplication::SetAdBlockIconEnabled, enabled); mApp->sendMessages(MainApplication::SetAdBlockIconEnabled, enabled);
@ -82,25 +85,28 @@ void AdBlockManager::setEnabled(bool enabled)
AdBlockNetwork* AdBlockManager::network() AdBlockNetwork* AdBlockManager::network()
{ {
if (!m_adBlockNetwork) if (!m_adBlockNetwork) {
m_adBlockNetwork = new AdBlockNetwork(this); m_adBlockNetwork = new AdBlockNetwork(this);
}
return m_adBlockNetwork; return m_adBlockNetwork;
} }
AdBlockPage* AdBlockManager::page() AdBlockPage* AdBlockManager::page()
{ {
if (!m_adBlockPage) if (!m_adBlockPage) {
m_adBlockPage = new AdBlockPage(this); m_adBlockPage = new AdBlockPage(this);
}
return m_adBlockPage; return m_adBlockPage;
} }
void AdBlockManager::load() void AdBlockManager::load()
{ {
if (m_loaded) if (m_loaded) {
return; return;
}
m_loaded = true; m_loaded = true;
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("AdBlock"); settings.beginGroup("AdBlock");
m_enabled = settings.value("enabled", m_enabled).toBool(); m_enabled = settings.value("enabled", m_enabled).toBool();
settings.endGroup(); settings.endGroup();
@ -112,11 +118,12 @@ void AdBlockManager::load()
void AdBlockManager::save() void AdBlockManager::save()
{ {
if (!m_loaded) if (!m_loaded) {
return; return;
}
m_subscription->saveRules(); m_subscription->saveRules();
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup(QLatin1String("AdBlock")); settings.beginGroup(QLatin1String("AdBlock"));
settings.setValue(QLatin1String("enabled"), m_enabled); settings.setValue(QLatin1String("enabled"), m_enabled);
settings.endGroup(); settings.endGroup();
@ -124,8 +131,9 @@ void AdBlockManager::save()
AdBlockDialog* AdBlockManager::showDialog() AdBlockDialog* AdBlockManager::showDialog()
{ {
if (!m_adBlockDialog) if (!m_adBlockDialog) {
m_adBlockDialog = new AdBlockDialog(mApp->getWindow()); m_adBlockDialog = new AdBlockDialog(mApp->getWindow());
}
m_adBlockDialog->show(); m_adBlockDialog->show();
return m_adBlockDialog; return m_adBlockDialog;

View File

@ -64,7 +64,7 @@ signals:
void rulesChanged(); void rulesChanged();
public: public:
AdBlockManager(QObject *parent = 0); AdBlockManager(QObject* parent = 0);
~AdBlockManager(); ~AdBlockManager();
void load(); void load();
@ -73,8 +73,8 @@ public:
bool isEnabled() { if (!m_loaded) load(); return m_enabled; } bool isEnabled() { if (!m_loaded) load(); return m_enabled; }
AdBlockSubscription* subscription() { return m_subscription; } AdBlockSubscription* subscription() { return m_subscription; }
AdBlockNetwork *network(); AdBlockNetwork* network();
AdBlockPage *page(); AdBlockPage* page();
public slots: public slots:
void setEnabled(bool enabled); void setEnabled(bool enabled);

View File

@ -50,7 +50,7 @@
#include "mainapplication.h" #include "mainapplication.h"
#include "webpage.h" #include "webpage.h"
AdBlockNetwork::AdBlockNetwork(QObject *parent) AdBlockNetwork::AdBlockNetwork(QObject* parent)
: QObject(parent) : QObject(parent)
{ {
} }
@ -58,31 +58,36 @@ AdBlockNetwork::AdBlockNetwork(QObject *parent)
QNetworkReply* AdBlockNetwork::block(const QNetworkRequest &request) QNetworkReply* AdBlockNetwork::block(const QNetworkRequest &request)
{ {
QUrl url = request.url(); QUrl url = request.url();
if (url.scheme() == "data") if (url.scheme() == "data") {
return 0; return 0;
}
AdBlockManager* manager = AdBlockManager::instance(); AdBlockManager* manager = AdBlockManager::instance();
if (!manager->isEnabled()) if (!manager->isEnabled()) {
return 0; return 0;
}
QString urlString = url.toEncoded(); QString urlString = url.toEncoded();
const AdBlockRule* blockedRule = 0; const AdBlockRule* blockedRule = 0;
AdBlockSubscription* subscription = manager->subscription(); AdBlockSubscription* subscription = manager->subscription();
if (subscription->allow(urlString)) if (subscription->allow(urlString)) {
return 0; return 0;
}
if (const AdBlockRule* rule = subscription->block(urlString)) if (const AdBlockRule* rule = subscription->block(urlString)) {
blockedRule = rule; blockedRule = rule;
}
if (blockedRule) { if (blockedRule) {
QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
WebPage* webPage = (WebPage*)(v.value<void*>()); WebPage* webPage = (WebPage*)(v.value<void*>());
if (webPage) if (webPage) {
webPage->addAdBlockRule(blockedRule->filter(), request.url()); webPage->addAdBlockRule(blockedRule->filter(), request.url());
}
AdBlockBlockedNetworkReply* reply = new AdBlockBlockedNetworkReply(request, blockedRule, this); AdBlockBlockedNetworkReply* reply = new AdBlockBlockedNetworkReply(request, blockedRule, this);
return reply; return reply;
} }
return 0; return 0;
} }

View File

@ -55,8 +55,8 @@ class AdBlockNetwork : public QObject
Q_OBJECT Q_OBJECT
public: public:
AdBlockNetwork(QObject *parent = 0); AdBlockNetwork(QObject* parent = 0);
QNetworkReply *block(const QNetworkRequest &request); QNetworkReply* block(const QNetworkRequest &request);
}; };
#endif // ADBLOCKNETWORK_H #endif // ADBLOCKNETWORK_H

View File

@ -42,20 +42,22 @@
// #define ADBLOCKPAGE_DEBUG // #define ADBLOCKPAGE_DEBUG
AdBlockPage::AdBlockPage(QObject *parent) AdBlockPage::AdBlockPage(QObject* parent)
: QObject(parent) : QObject(parent)
{ {
} }
void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QString &host) void AdBlockPage::checkRule(const AdBlockRule* rule, QWebPage* page, const QString &host)
{ {
if (!rule->isEnabled()) if (!rule->isEnabled()) {
return; return;
}
QString filter = rule->filter(); QString filter = rule->filter();
int offset = filter.indexOf(QLatin1String("##")); int offset = filter.indexOf(QLatin1String("##"));
if (offset == -1) if (offset == -1) {
return; return;
}
QString selectorQuery; QString selectorQuery;
if (offset > 0) { if (offset > 0) {
@ -64,33 +66,38 @@ void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QStri
QStringList domains = domainRules.split(QLatin1Char(',')); QStringList domains = domainRules.split(QLatin1Char(','));
bool match = false; bool match = false;
foreach (const QString &domain, domains) { foreach(const QString & domain, domains) {
bool reverse = (domain[0] == QLatin1Char('~')); bool reverse = (domain[0] == QLatin1Char('~'));
if (reverse) { if (reverse) {
QString xdomain = domain.mid(1); QString xdomain = domain.mid(1);
if (host.endsWith(xdomain)) if (host.endsWith(xdomain)) {
return; return;
}
match = true; match = true;
} }
if (host.endsWith(domain)) if (host.endsWith(domain)) {
match = true; match = true;
}
} }
if (!match) if (!match) {
return; return;
}
} }
if (offset == 0) if (offset == 0) {
selectorQuery = filter.mid(2); selectorQuery = filter.mid(2);
}
Q_UNUSED(page); Q_UNUSED(page);
#if QT_VERSION >= 0x040600 #if QT_VERSION >= 0x040600
QWebElement document = page->mainFrame()->documentElement(); QWebElement document = page->mainFrame()->documentElement();
QWebElementCollection elements = document.findAll(selectorQuery); QWebElementCollection elements = document.findAll(selectorQuery);
#if defined(ADBLOCKPAGE_DEBUG) #if defined(ADBLOCKPAGE_DEBUG)
if (elements.count() != 0) if (elements.count() != 0) {
qDebug() << "AdBlockPage::" << __FUNCTION__ << "blocking" << elements.count() << "items" << selectorQuery << elements.count() << "rule:" << rule->filter(); qDebug() << "AdBlockPage::" << __FUNCTION__ << "blocking" << elements.count() << "items" << selectorQuery << elements.count() << "rule:" << rule->filter();
}
#endif #endif
foreach (QWebElement element, elements) { foreach(QWebElement element, elements) {
element.setStyleProperty(QLatin1String("visibility"), QLatin1String("hidden")); element.setStyleProperty(QLatin1String("visibility"), QLatin1String("hidden"));
element.removeFromDocument(); element.removeFromDocument();
} }
@ -98,21 +105,23 @@ void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QStri
#endif #endif
} }
void AdBlockPage::applyRulesToPage(QWebPage *page) void AdBlockPage::applyRulesToPage(QWebPage* page)
{ {
if (!page || !page->mainFrame()) if (!page || !page->mainFrame()) {
return; return;
AdBlockManager *manager = AdBlockManager::instance(); }
if (!manager->isEnabled()) AdBlockManager* manager = AdBlockManager::instance();
if (!manager->isEnabled()) {
return; return;
}
#if QT_VERSION >= 0x040600 #if QT_VERSION >= 0x040600
QString host = page->mainFrame()->url().host(); QString host = page->mainFrame()->url().host();
AdBlockSubscription* subscription = manager->subscription(); AdBlockSubscription* subscription = manager->subscription();
QList<const AdBlockRule*> rules = subscription->pageRules(); QList<const AdBlockRule*> rules = subscription->pageRules();
foreach (const AdBlockRule *rule, rules) { foreach(const AdBlockRule * rule, rules) {
checkRule(rule, page, host); checkRule(rule, page, host);
} }
#endif #endif
} }

View File

@ -38,12 +38,12 @@ class AdBlockPage : public QObject
Q_OBJECT Q_OBJECT
public: public:
AdBlockPage(QObject *parent = 0); AdBlockPage(QObject* parent = 0);
void applyRulesToPage(QWebPage *page); void applyRulesToPage(QWebPage* page);
private: private:
void checkRule(const AdBlockRule *rule, QWebPage *page, const QString &host); void checkRule(const AdBlockRule* rule, QWebPage* page, const QString &host);
}; };
#endif // ADBLOCKPAGE_H #endif // ADBLOCKPAGE_H

View File

@ -74,11 +74,13 @@ void AdBlockRule::setFilter(const QString &filter)
bool regExpRule = false; bool regExpRule = false;
if (filter.startsWith(QLatin1String("!")) if (filter.startsWith(QLatin1String("!"))
|| filter.trimmed().isEmpty()) || filter.trimmed().isEmpty()) {
m_enabled = false; m_enabled = false;
}
if (filter.contains(QLatin1String("##"))) if (filter.contains(QLatin1String("##"))) {
m_cssRule = true; m_cssRule = true;
}
QString parsedLine = filter; QString parsedLine = filter;
if (parsedLine.startsWith(QLatin1String("@@"))) { if (parsedLine.startsWith(QLatin1String("@@"))) {
@ -125,24 +127,27 @@ bool AdBlockRule::networkMatch(const QString &encodedUrl) const
bool matched = m_regExp.indexIn(encodedUrl) != -1; bool matched = m_regExp.indexIn(encodedUrl) != -1;
if (matched if (matched
&& !m_options.isEmpty()) { && !m_options.isEmpty()) {
// we only support domain right now // we only support domain right now
if (m_options.count() == 1) { if (m_options.count() == 1) {
foreach (const QString &option, m_options) { foreach(const QString & option, m_options) {
if (option.startsWith("domain=")) { if (option.startsWith("domain=")) {
QUrl url = QUrl::fromEncoded(encodedUrl.toUtf8()); QUrl url = QUrl::fromEncoded(encodedUrl.toUtf8());
QString host = url.host(); QString host = url.host();
QStringList domainOptions = option.mid(7).split('|'); QStringList domainOptions = option.mid(7).split('|');
foreach (QString domainOption, domainOptions) { foreach(QString domainOption, domainOptions) {
bool negate = domainOption.at(0) == '~'; bool negate = domainOption.at(0) == '~';
if (negate) if (negate) {
domainOption = domainOption.mid(1); domainOption = domainOption.mid(1);
}
bool hostMatched = domainOption == host; bool hostMatched = domainOption == host;
if (hostMatched && !negate) if (hostMatched && !negate) {
return true; return true;
if (!hostMatched && negate) }
if (!hostMatched && negate) {
return true; return true;
}
} }
} }
} }
@ -180,7 +185,8 @@ void AdBlockRule::setEnabled(bool enabled)
m_enabled = enabled; m_enabled = enabled;
if (!enabled) { if (!enabled) {
m_filter = QLatin1String("!") + m_filter; m_filter = QLatin1String("!") + m_filter;
} else { }
else {
m_filter = m_filter.mid(1); m_filter = m_filter.mid(1);
} }
} }
@ -190,21 +196,22 @@ QString AdBlockRule::regExpPattern() const
return m_regExp.pattern(); return m_regExp.pattern();
} }
static QString convertPatternToRegExp(const QString &wildcardPattern) { static QString convertPatternToRegExp(const QString &wildcardPattern)
{
QString pattern = wildcardPattern; QString pattern = wildcardPattern;
return pattern.replace(QRegExp(QLatin1String("\\*+")), QLatin1String("*")) // remove multiple wildcards return pattern.replace(QRegExp(QLatin1String("\\*+")), QLatin1String("*")) // remove multiple wildcards
.replace(QRegExp(QLatin1String("\\^\\|$")), QLatin1String("^")) // remove anchors following separator placeholder .replace(QRegExp(QLatin1String("\\^\\|$")), QLatin1String("^")) // remove anchors following separator placeholder
.replace(QRegExp(QLatin1String("^(\\*)")), QLatin1String("")) // remove leading wildcards .replace(QRegExp(QLatin1String("^(\\*)")), QLatin1String("")) // remove leading wildcards
.replace(QRegExp(QLatin1String("(\\*)$")), QLatin1String("")) .replace(QRegExp(QLatin1String("(\\*)$")), QLatin1String(""))
.replace(QRegExp(QLatin1String("(\\W)")), QLatin1String("\\\\1")) // escape special symbols .replace(QRegExp(QLatin1String("(\\W)")), QLatin1String("\\\\1")) // escape special symbols
.replace(QRegExp(QLatin1String("^\\\\\\|\\\\\\|")), .replace(QRegExp(QLatin1String("^\\\\\\|\\\\\\|")),
QLatin1String("^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?")) // process extended anchor at expression start QLatin1String("^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?")) // process extended anchor at expression start
.replace(QRegExp(QLatin1String("\\\\\\^")), .replace(QRegExp(QLatin1String("\\\\\\^")),
QLatin1String("(?:[^\\w\\d\\-.%]|$)")) // process separator placeholders QLatin1String("(?:[^\\w\\d\\-.%]|$)")) // process separator placeholders
.replace(QRegExp(QLatin1String("^\\\\\\|")), QLatin1String("^")) // process anchor at expression start .replace(QRegExp(QLatin1String("^\\\\\\|")), QLatin1String("^")) // process anchor at expression start
.replace(QRegExp(QLatin1String("\\\\\\|$")), QLatin1String("$")) // process anchor at expression end .replace(QRegExp(QLatin1String("\\\\\\|$")), QLatin1String("$")) // process anchor at expression end
.replace(QRegExp(QLatin1String("\\\\\\*")), QLatin1String(".*")) // replace wildcards by .* .replace(QRegExp(QLatin1String("\\\\\\*")), QLatin1String(".*")) // replace wildcards by .*
; ;
} }
void AdBlockRule::setPattern(const QString &pattern, bool isRegExp) void AdBlockRule::setPattern(const QString &pattern, bool isRegExp)

View File

@ -56,20 +56,22 @@ AdBlockSubscription::AdBlockSubscription(QObject* parent)
void AdBlockSubscription::loadRules() void AdBlockSubscription::loadRules()
{ {
QString fileName = mApp->getActiveProfilPath()+"adblocklist.txt"; QString fileName = mApp->getActiveProfilPath() + "adblocklist.txt";
QFile file(fileName); QFile file(fileName);
if (file.exists()) { if (file.exists()) {
if (!file.open(QFile::ReadOnly)) { if (!file.open(QFile::ReadOnly)) {
qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "Unable to open adblock file for reading" << fileName; qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "Unable to open adblock file for reading" << fileName;
} else { }
else {
QTextStream textStream(&file); QTextStream textStream(&file);
QString header = textStream.readLine(1024); QString header = textStream.readLine(1024);
if (!header.startsWith("[Adblock")) { if (!header.startsWith("[Adblock")) {
qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "adblock file does not start with [Adblock" << fileName << "Header:" << header; qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "adblock file does not start with [Adblock" << fileName << "Header:" << header;
file.close(); file.close();
file.remove(); file.remove();
} else { }
else {
m_rules.clear(); m_rules.clear();
while (!textStream.atEnd()) { while (!textStream.atEnd()) {
QString line = textStream.readLine(); QString line = textStream.readLine();
@ -84,8 +86,9 @@ void AdBlockSubscription::loadRules()
void AdBlockSubscription::updateNow() void AdBlockSubscription::updateNow()
{ {
if (m_downloading) if (m_downloading) {
return; return;
}
QNetworkRequest request(QUrl("https://easylist-downloads.adblockplus.org/easylist.txt")); QNetworkRequest request(QUrl("https://easylist-downloads.adblockplus.org/easylist.txt"));
QNetworkReply* reply = mApp->networkManager()->get(request); QNetworkReply* reply = mApp->networkManager()->get(request);
@ -96,18 +99,21 @@ void AdBlockSubscription::updateNow()
void AdBlockSubscription::rulesDownloaded() void AdBlockSubscription::rulesDownloaded()
{ {
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) if (!reply) {
return; return;
}
QByteArray response = reply->readAll(); QByteArray response = reply->readAll();
reply->close(); reply->close();
reply->deleteLater(); reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) if (reply->error() != QNetworkReply::NoError) {
return; return;
}
if (response.isEmpty()) if (response.isEmpty()) {
return; return;
}
QString fileName = mApp->getActiveProfilPath() + "adblocklist.txt"; QString fileName = mApp->getActiveProfilPath() + "adblocklist.txt";
QFile file(fileName); QFile file(fileName);
@ -119,15 +125,16 @@ void AdBlockSubscription::rulesDownloaded()
response = response.left(response.indexOf("!-----------------General element hiding rules-----------------!")); response = response.left(response.indexOf("!-----------------General element hiding rules-----------------!"));
bool customRules = false; bool customRules = false;
foreach (const AdBlockRule rule, allRules()) { foreach(const AdBlockRule & rule, allRules()) {
if (rule.filter().contains("*******- user custom filters")) { if (rule.filter().contains("*******- user custom filters")) {
customRules = true; customRules = true;
response.append("! *******- user custom filters -*************\n"); response.append("! *******- user custom filters -*************\n");
continue; continue;
} }
if (!customRules) if (!customRules) {
continue; continue;
response.append(rule.filter()+"\n"); }
response.append(rule.filter() + "\n");
} }
file.write(response); file.write(response);
@ -139,7 +146,7 @@ void AdBlockSubscription::rulesDownloaded()
void AdBlockSubscription::saveRules() void AdBlockSubscription::saveRules()
{ {
QString fileName = mApp->getActiveProfilPath()+"adblocklist.txt"; QString fileName = mApp->getActiveProfilPath() + "adblocklist.txt";
QFile file(fileName); QFile file(fileName);
if (!file.open(QFile::ReadWrite | QIODevice::Truncate)) { if (!file.open(QFile::ReadWrite | QIODevice::Truncate)) {
@ -149,24 +156,26 @@ void AdBlockSubscription::saveRules()
QTextStream textStream(&file); QTextStream textStream(&file);
textStream << "[Adblock Plus 1.1.1]" << endl; textStream << "[Adblock Plus 1.1.1]" << endl;
foreach (const AdBlockRule &rule, m_rules) foreach(const AdBlockRule & rule, m_rules)
textStream << rule.filter() << endl; textStream << rule.filter() << endl;
} }
const AdBlockRule* AdBlockSubscription::allow(const QString &urlString) const const AdBlockRule* AdBlockSubscription::allow(const QString &urlString) const
{ {
foreach (const AdBlockRule* rule, m_networkExceptionRules) { foreach(const AdBlockRule * rule, m_networkExceptionRules) {
if (rule->networkMatch(urlString)) if (rule->networkMatch(urlString)) {
return rule; return rule;
}
} }
return 0; return 0;
} }
const AdBlockRule* AdBlockSubscription::block(const QString &urlString) const const AdBlockRule* AdBlockSubscription::block(const QString &urlString) const
{ {
foreach (const AdBlockRule* rule, m_networkBlockRules) { foreach(const AdBlockRule * rule, m_networkBlockRules) {
if (rule->networkMatch(urlString)) if (rule->networkMatch(urlString)) {
return rule; return rule;
}
} }
return 0; return 0;
} }
@ -186,8 +195,9 @@ int AdBlockSubscription::addRule(const AdBlockRule &rule)
void AdBlockSubscription::removeRule(int offset) void AdBlockSubscription::removeRule(int offset)
{ {
if (offset < 0 || offset >= m_rules.count()) if (offset < 0 || offset >= m_rules.count()) {
return; return;
}
m_rules.removeAt(offset); m_rules.removeAt(offset);
populateCache(); populateCache();
emit rulesChanged(); emit rulesChanged();
@ -195,8 +205,9 @@ void AdBlockSubscription::removeRule(int offset)
void AdBlockSubscription::replaceRule(const AdBlockRule &rule, int offset) void AdBlockSubscription::replaceRule(const AdBlockRule &rule, int offset)
{ {
if (offset < 0 || offset >= m_rules.count()) if (offset < 0 || offset >= m_rules.count()) {
return; return;
}
m_rules[offset] = rule; m_rules[offset] = rule;
populateCache(); populateCache();
emit rulesChanged(); emit rulesChanged();
@ -210,8 +221,9 @@ void AdBlockSubscription::populateCache()
for (int i = 0; i < m_rules.count(); ++i) { for (int i = 0; i < m_rules.count(); ++i) {
const AdBlockRule* rule = &m_rules.at(i); const AdBlockRule* rule = &m_rules.at(i);
if (!rule->isEnabled()) if (!rule->isEnabled()) {
continue; continue;
}
if (rule->isCSSRule()) { if (rule->isCSSRule()) {
m_pageRules.append(rule); m_pageRules.append(rule);
@ -220,7 +232,8 @@ void AdBlockSubscription::populateCache()
if (rule->isException()) { if (rule->isException()) {
m_networkExceptionRules.append(rule); m_networkExceptionRules.append(rule);
} else { }
else {
m_networkBlockRules.append(rule); m_networkBlockRules.append(rule);
} }
} }

View File

@ -67,7 +67,7 @@ signals:
void rulesChanged(); void rulesChanged();
public: public:
AdBlockSubscription(QObject *parent = 0); AdBlockSubscription(QObject* parent = 0);
QString title() const { return m_title; } QString title() const { return m_title; }
void setTitle(const QString &title) { m_title = title; } void setTitle(const QString &title) { m_title = title; }

View File

@ -19,15 +19,17 @@
#include "mainapplication.h" #include "mainapplication.h"
AutoSaver::AutoSaver(QObject* parent) : AutoSaver::AutoSaver(QObject* parent) :
QObject(parent) QObject(parent)
{ {
m_timer.start(1000*5, this); m_timer.start(1000 * 5, this);
} }
void AutoSaver::timerEvent(QTimerEvent* event) void AutoSaver::timerEvent(QTimerEvent* event)
{ {
if (event->timerId() == m_timer.timerId() && mApp->isStateChanged()) if (event->timerId() == m_timer.timerId() && mApp->isStateChanged()) {
emit saveApp(); emit saveApp();
else }
else {
QObject::timerEvent(event); QObject::timerEvent(event);
}
} }

View File

@ -18,10 +18,10 @@
#include "commandlineoptions.h" #include "commandlineoptions.h"
#include "qupzilla.h" #include "qupzilla.h"
CommandLineOptions::CommandLineOptions(int &argc, char **argv) : CommandLineOptions::CommandLineOptions(int &argc, char** argv) :
QObject(0) QObject(0)
,m_argc(argc) , m_argc(argc)
,m_argv(argv) , m_argv(argv)
{ {
parseActions(); parseActions();
} }
@ -133,7 +133,7 @@ void CommandLineOptions::parseActions()
} }
} }
QString url(m_argv[m_argc-1]); QString url(m_argv[m_argc - 1]);
if (m_argc > 1 && !url.isEmpty() && !url.startsWith("-")) { if (m_argc > 1 && !url.isEmpty() && !url.startsWith("-")) {
found = true; found = true;
cout << "starting with url " << url.toAscii().data() << endl; cout << "starting with url " << url.toAscii().data() << endl;

View File

@ -33,7 +33,7 @@ public:
QString text; QString text;
}; };
explicit CommandLineOptions(int &argc, char **argv); explicit CommandLineOptions(int &argc, char** argv);
QList<ActionPair> getActions() { return m_actions; } QList<ActionPair> getActions() { return m_actions; }
private: private:
@ -41,7 +41,7 @@ private:
void parseActions(); void parseActions();
int m_argc; int m_argc;
char **m_argv; char** m_argv;
QList<ActionPair> m_actions; QList<ActionPair> m_actions;
}; };

View File

@ -42,7 +42,7 @@
#include "searchenginesmanager.h" #include "searchenginesmanager.h"
#include "operaimporter.h" #include "operaimporter.h"
MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cmdActions, int &argc, char **argv) MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cmdActions, int &argc, char** argv)
: QtSingleApplication("QupZillaWebBrowser", argc, argv) : QtSingleApplication("QupZillaWebBrowser", argc, argv)
, m_cookiemanager(0) , m_cookiemanager(0)
, m_browsingLibrary(0) , m_browsingLibrary(0)
@ -83,7 +83,7 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
QString startProfile; QString startProfile;
if (argc > 1) { if (argc > 1) {
foreach (CommandLineOptions::ActionPair pair, cmdActions) { foreach(CommandLineOptions::ActionPair pair, cmdActions) {
switch (pair.action) { switch (pair.action) {
case CommandLineOptions::StartWithoutAddons: case CommandLineOptions::StartWithoutAddons:
noAddons = true; noAddons = true;
@ -124,28 +124,33 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
setOrganizationDomain("qupzilla"); setOrganizationDomain("qupzilla");
QString homePath = QDir::homePath(); QString homePath = QDir::homePath();
homePath+="/.qupzilla/"; homePath += "/.qupzilla/";
checkSettingsDir(); checkSettingsDir();
QSettings::setDefaultFormat(QSettings::IniFormat); QSettings::setDefaultFormat(QSettings::IniFormat);
if (startProfile.isEmpty()) { if (startProfile.isEmpty()) {
QSettings settings(homePath+"profiles/profiles.ini", QSettings::IniFormat); QSettings settings(homePath + "profiles/profiles.ini", QSettings::IniFormat);
if (settings.value("Profiles/startProfile","default").toString().contains("/")) if (settings.value("Profiles/startProfile", "default").toString().contains("/")) {
m_activeProfil=homePath+"profiles/default/"; m_activeProfil = homePath + "profiles/default/";
else }
m_activeProfil=homePath+"profiles/"+settings.value("Profiles/startProfile","default").toString()+"/"; else {
} else m_activeProfil = homePath + "profiles/" + settings.value("Profiles/startProfile", "default").toString() + "/";
m_activeProfil = homePath+"profiles/"+startProfile+"/"; }
}
else {
m_activeProfil = homePath + "profiles/" + startProfile + "/";
}
ProfileUpdater u(m_activeProfil, DATADIR); ProfileUpdater u(m_activeProfil, DATADIR);
u.checkProfile(); u.checkProfile();
connectDatabase(); connectDatabase();
QSettings settings2(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings2(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings2.beginGroup("SessionRestore"); settings2.beginGroup("SessionRestore");
if (settings2.value("isRunning",false).toBool() ) if (settings2.value("isRunning", false).toBool()) {
settings2.setValue("isCrashed", true); settings2.setValue("isCrashed", true);
}
settings2.setValue("isRunning", true); settings2.setValue("isRunning", true);
settings2.endGroup(); settings2.endGroup();
@ -156,14 +161,15 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
QupZilla* qupzilla = new QupZilla(QupZilla::FirstAppWindow, startUrl); QupZilla* qupzilla = new QupZilla(QupZilla::FirstAppWindow, startUrl);
m_mainWindows.append(qupzilla); m_mainWindows.append(qupzilla);
connect(qupzilla, SIGNAL(message(MainApplication::MessageType,bool)), this, SLOT(sendMessages(MainApplication::MessageType,bool))); connect(qupzilla, SIGNAL(message(MainApplication::MessageType, bool)), this, SLOT(sendMessages(MainApplication::MessageType, bool)));
qupzilla->show(); qupzilla->show();
AutoSaver* saver = new AutoSaver(); AutoSaver* saver = new AutoSaver();
connect(saver, SIGNAL(saveApp()), this, SLOT(saveStateSlot())); connect(saver, SIGNAL(saveApp()), this, SLOT(saveStateSlot()));
if (settings2.value("Web-Browser-Settings/CheckUpdates", true).toBool()) if (settings2.value("Web-Browser-Settings/CheckUpdates", true).toBool()) {
m_updater = new Updater(qupzilla); m_updater = new Updater(qupzilla);
}
if (noAddons) { if (noAddons) {
settings2.setValue("Plugin-Settings/AllowedPlugins", QStringList()); settings2.setValue("Plugin-Settings/AllowedPlugins", QStringList());
@ -175,12 +181,12 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
loadSettings(); loadSettings();
QTimer::singleShot(2000, this, SLOT(restoreCursor())); QTimer::singleShot(2000, this, SLOT(restoreCursor()));
QTimer::singleShot(10*1000, this, SLOT(setupJumpList())); QTimer::singleShot(10 * 1000, this, SLOT(setupJumpList()));
} }
void MainApplication::loadSettings() void MainApplication::loadSettings()
{ {
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Themes"); settings.beginGroup("Themes");
QString activeTheme = settings.value("activeTheme", QString activeTheme = settings.value("activeTheme",
#ifdef Q_WS_X11 #ifdef Q_WS_X11
@ -188,7 +194,7 @@ void MainApplication::loadSettings()
#else #else
"windows" "windows"
#endif #endif
).toString(); ).toString();
settings.endGroup(); settings.endGroup();
m_activeThemePath = THEMESDIR + activeTheme + "/"; m_activeThemePath = THEMESDIR + activeTheme + "/";
QFile cssFile(m_activeThemePath + "main.css"); QFile cssFile(m_activeThemePath + "main.css");
@ -220,18 +226,18 @@ void MainApplication::loadSettings()
webSettings(); webSettings();
//Web browsing settings //Web browsing settings
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
bool allowFlash = settings.value("allowFlash",true).toBool(); bool allowFlash = settings.value("allowFlash", true).toBool();
bool allowJavaScript = settings.value("allowJavaScript",true).toBool(); bool allowJavaScript = settings.value("allowJavaScript", true).toBool();
bool allowJavaScriptOpenWindow = settings.value("allowJavaScriptOpenWindow",false).toBool(); bool allowJavaScriptOpenWindow = settings.value("allowJavaScriptOpenWindow", false).toBool();
bool allowJava = settings.value("allowJava",true).toBool(); bool allowJava = settings.value("allowJava", true).toBool();
bool allowPersistentStorage = settings.value("allowPersistentStorage",true).toBool(); bool allowPersistentStorage = settings.value("allowPersistentStorage", true).toBool();
bool allowImages = settings.value("autoLoadImages",true).toBool(); bool allowImages = settings.value("autoLoadImages", true).toBool();
bool dnsPrefetch = settings.value("DNS-Prefetch", false).toBool(); bool dnsPrefetch = settings.value("DNS-Prefetch", false).toBool();
bool jsClipboard = settings.value("JavaScriptCanAccessClipboard", true).toBool(); bool jsClipboard = settings.value("JavaScriptCanAccessClipboard", true).toBool();
bool linkInFocuschain = settings.value("IncludeLinkInFocusChain", false).toBool(); bool linkInFocuschain = settings.value("IncludeLinkInFocusChain", false).toBool();
bool zoomTextOnly = settings.value("zoomTextOnly", false).toBool(); bool zoomTextOnly = settings.value("zoomTextOnly", false).toBool();
bool printElBg = settings.value("PrintElementBackground", true).toBool(); bool printElBg = settings.value("PrintElementBackground", true).toBool();
int maxCachedPages = settings.value("maximumCachedPages",3).toInt(); int maxCachedPages = settings.value("maximumCachedPages", 3).toInt();
int scrollingLines = settings.value("wheelScrollLines", wheelScrollLines()).toInt(); int scrollingLines = settings.value("wheelScrollLines", wheelScrollLines()).toInt();
QUrl userStyleSheet = settings.value("userStyleSheet", QUrl()).toUrl(); QUrl userStyleSheet = settings.value("userStyleSheet", QUrl()).toUrl();
m_defaultZoom = settings.value("DefaultZoom", 100).toInt(); m_defaultZoom = settings.value("DefaultZoom", 100).toInt();
@ -264,25 +270,28 @@ void MainApplication::loadSettings()
m_websettings->setFontFamily(QWebSettings::FixedFont, settings.value("FixedFont", m_websettings->fontFamily(QWebSettings::FixedFont)).toString()); m_websettings->setFontFamily(QWebSettings::FixedFont, settings.value("FixedFont", m_websettings->fontFamily(QWebSettings::FixedFont)).toString());
m_websettings->setFontFamily(QWebSettings::SansSerifFont, settings.value("SansSerifFont", m_websettings->fontFamily(QWebSettings::SansSerifFont)).toString()); m_websettings->setFontFamily(QWebSettings::SansSerifFont, settings.value("SansSerifFont", m_websettings->fontFamily(QWebSettings::SansSerifFont)).toString());
m_websettings->setFontFamily(QWebSettings::SerifFont, settings.value("SerifFont", m_websettings->fontFamily(QWebSettings::SerifFont)).toString()); m_websettings->setFontFamily(QWebSettings::SerifFont, settings.value("SerifFont", m_websettings->fontFamily(QWebSettings::SerifFont)).toString());
m_websettings->setFontSize(QWebSettings::DefaultFontSize, settings.value("DefaultFontSize", m_websettings->fontSize(QWebSettings::DefaultFontSize)).toInt() ); m_websettings->setFontSize(QWebSettings::DefaultFontSize, settings.value("DefaultFontSize", m_websettings->fontSize(QWebSettings::DefaultFontSize)).toInt());
m_websettings->setFontSize(QWebSettings::DefaultFixedFontSize, settings.value("FixedFontSize", m_websettings->fontSize(QWebSettings::DefaultFixedFontSize)).toInt() ); m_websettings->setFontSize(QWebSettings::DefaultFixedFontSize, settings.value("FixedFontSize", m_websettings->fontSize(QWebSettings::DefaultFixedFontSize)).toInt());
m_websettings->setUserStyleSheetUrl(userStyleSheet); m_websettings->setUserStyleSheetUrl(userStyleSheet);
m_websettings->setDefaultTextEncoding("System"); m_websettings->setDefaultTextEncoding("System");
m_websettings->setWebGraphic(QWebSettings::DefaultFrameIconGraphic, IconProvider::fromTheme("text-plain").pixmap(16,16)); m_websettings->setWebGraphic(QWebSettings::DefaultFrameIconGraphic, IconProvider::fromTheme("text-plain").pixmap(16, 16));
if (allowPersistentStorage) m_websettings->enablePersistentStorage(m_activeProfil); if (allowPersistentStorage) {
m_websettings->enablePersistentStorage(m_activeProfil);
}
m_websettings->setMaximumPagesInCache(maxCachedPages); m_websettings->setMaximumPagesInCache(maxCachedPages);
setWheelScrollLines(scrollingLines); setWheelScrollLines(scrollingLines);
if (m_downloadManager) if (m_downloadManager) {
m_downloadManager->loadSettings(); m_downloadManager->loadSettings();
}
} }
void MainApplication::restoreCursor() void MainApplication::restoreCursor()
{ {
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
} }
void MainApplication::setupJumpList() void MainApplication::setupJumpList()
@ -292,9 +301,10 @@ void MainApplication::setupJumpList()
QupZilla* MainApplication::getWindow() QupZilla* MainApplication::getWindow()
{ {
for(int i=0; i<m_mainWindows.count(); i++) { for (int i = 0; i < m_mainWindows.count(); i++) {
if (!m_mainWindows.at(i)) if (!m_mainWindows.at(i)) {
continue; continue;
}
return m_mainWindows.at(i); return m_mainWindows.at(i);
} }
return 0; return 0;
@ -325,14 +335,18 @@ void MainApplication::receiveAppMessage(QString message)
if (message.startsWith("URL:")) { if (message.startsWith("URL:")) {
QString url(message.remove("URL:")); QString url(message.remove("URL:"));
addNewTab(WebView::guessUrlFromString(url)); addNewTab(WebView::guessUrlFromString(url));
} else if (message.startsWith("ACTION:")) { }
else if (message.startsWith("ACTION:")) {
QString text = message.mid(7); QString text = message.mid(7);
if (text == "NewTab") if (text == "NewTab") {
addNewTab(); addNewTab();
else if (text == "NewWindow") }
else if (text == "NewWindow") {
makeNewWindow(false); makeNewWindow(false);
else if (text == "ShowDownloadManager") }
else if (text == "ShowDownloadManager") {
downManager()->show(); downManager()->show();
}
} }
QupZilla* actWin = getWindow(); QupZilla* actWin = getWindow();
@ -348,29 +362,33 @@ void MainApplication::receiveAppMessage(QString message)
void MainApplication::addNewTab(const QUrl &url) void MainApplication::addNewTab(const QUrl &url)
{ {
if (!getWindow()) if (!getWindow()) {
return; return;
}
getWindow()->tabWidget()->addView(url); getWindow()->tabWidget()->addView(url);
} }
void MainApplication::makeNewWindow(bool tryRestore, const QUrl &startUrl) void MainApplication::makeNewWindow(bool tryRestore, const QUrl &startUrl)
{ {
QupZilla::StartBehaviour behaviour; QupZilla::StartBehaviour behaviour;
if (tryRestore) if (tryRestore) {
behaviour = QupZilla::OtherRestoredWindow; behaviour = QupZilla::OtherRestoredWindow;
else }
else {
behaviour = QupZilla::NewWindow; behaviour = QupZilla::NewWindow;
}
QupZilla* newWindow = new QupZilla(behaviour, startUrl); QupZilla* newWindow = new QupZilla(behaviour, startUrl);
connect(newWindow, SIGNAL(message(MainApplication::MessageType,bool)), this, SLOT(sendMessages(MainApplication::MessageType,bool))); connect(newWindow, SIGNAL(message(MainApplication::MessageType, bool)), this, SLOT(sendMessages(MainApplication::MessageType, bool)));
m_mainWindows.append(newWindow); m_mainWindows.append(newWindow);
newWindow->show(); newWindow->show();
} }
void MainApplication::connectDatabase() void MainApplication::connectDatabase()
{ {
if (m_databaseConnected) if (m_databaseConnected) {
return; return;
}
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(m_activeProfil + "browsedata.db"); db.setDatabaseName(m_activeProfil + "browsedata.db");
@ -379,8 +397,9 @@ void MainApplication::connectDatabase()
db.setDatabaseName(m_activeProfil + "browsedata.db"); db.setDatabaseName(m_activeProfil + "browsedata.db");
qWarning("Cannot find SQLite database file! Copying and using the defaults!"); qWarning("Cannot find SQLite database file! Copying and using the defaults!");
} }
if (!db.open()) if (!db.open()) {
qWarning("Cannot open SQLite database! Continuing without database...."); qWarning("Cannot open SQLite database! Continuing without database....");
}
m_databaseConnected = true; m_databaseConnected = true;
} }
@ -388,20 +407,22 @@ void MainApplication::connectDatabase()
void MainApplication::translateApp() void MainApplication::translateApp()
{ {
QLocale locale; QLocale locale;
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Language"); settings.beginGroup("Language");
QString file = settings.value("language",locale.name()+".qm").toString(); QString file = settings.value("language", locale.name() + ".qm").toString();
QString shortLoc = file.left(2); QString shortLoc = file.left(2);
if (file == "" || !QFile::exists(TRANSLATIONSDIR + file) ) if (file == "" || !QFile::exists(TRANSLATIONSDIR + file)) {
return; return;
}
QTranslator* app = new QTranslator(); QTranslator* app = new QTranslator();
app->load(DATADIR+"locale/"+file); app->load(DATADIR + "locale/" + file);
QTranslator* sys = new QTranslator(); QTranslator* sys = new QTranslator();
if (QFile::exists(TRANSLATIONSDIR + "qt_" + shortLoc + ".qm")) if (QFile::exists(TRANSLATIONSDIR + "qt_" + shortLoc + ".qm")) {
sys->load(TRANSLATIONSDIR + "qt_" + shortLoc + ".qm"); sys->load(TRANSLATIONSDIR + "qt_" + shortLoc + ".qm");
}
m_activeLanguage = file; m_activeLanguage = file;
@ -416,22 +437,25 @@ void MainApplication::quitApplication()
return; return;
} }
m_isClosing = true; m_isClosing = true;
if (m_mainWindows.count() > 0) if (m_mainWindows.count() > 0) {
saveStateSlot(); saveStateSlot();
}
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("SessionRestore"); settings.beginGroup("SessionRestore");
settings.setValue("isRunning",false); settings.setValue("isRunning", false);
settings.setValue("isCrashed", false); settings.setValue("isCrashed", false);
settings.endGroup(); settings.endGroup();
bool deleteCookies = settings.value("Web-Browser-Settings/deleteCookiesOnClose", false).toBool(); bool deleteCookies = settings.value("Web-Browser-Settings/deleteCookiesOnClose", false).toBool();
bool deleteHistory = settings.value("Web-Browser-Settings/deleteHistoryOnClose", false).toBool(); bool deleteHistory = settings.value("Web-Browser-Settings/deleteHistoryOnClose", false).toBool();
if (deleteCookies) if (deleteCookies) {
QFile::remove(m_activeProfil+"cookies.dat"); QFile::remove(m_activeProfil + "cookies.dat");
if (deleteHistory) }
if (deleteHistory) {
m_historymodel->clearHistory(); m_historymodel->clearHistory();
}
m_searchEnginesManager->saveSettings(); m_searchEnginesManager->saveSettings();
cookieJar()->saveCookies(); cookieJar()->saveCookies();
@ -447,43 +471,49 @@ void MainApplication::quitApplication()
BrowsingLibrary* MainApplication::browsingLibrary() BrowsingLibrary* MainApplication::browsingLibrary()
{ {
if (!m_browsingLibrary) if (!m_browsingLibrary) {
m_browsingLibrary = new BrowsingLibrary(getWindow()); m_browsingLibrary = new BrowsingLibrary(getWindow());
}
return m_browsingLibrary; return m_browsingLibrary;
} }
PluginProxy* MainApplication::plugins() PluginProxy* MainApplication::plugins()
{ {
if (!m_plugins) if (!m_plugins) {
m_plugins = new PluginProxy(); m_plugins = new PluginProxy();
}
return m_plugins; return m_plugins;
} }
CookieManager* MainApplication::cookieManager() CookieManager* MainApplication::cookieManager()
{ {
if (!m_cookiemanager) if (!m_cookiemanager) {
m_cookiemanager = new CookieManager(); m_cookiemanager = new CookieManager();
}
return m_cookiemanager; return m_cookiemanager;
} }
HistoryModel* MainApplication::history() HistoryModel* MainApplication::history()
{ {
if (!m_historymodel) if (!m_historymodel) {
m_historymodel = new HistoryModel(getWindow()); m_historymodel = new HistoryModel(getWindow());
}
return m_historymodel; return m_historymodel;
} }
QWebSettings* MainApplication::webSettings() QWebSettings* MainApplication::webSettings()
{ {
if (!m_websettings) if (!m_websettings) {
m_websettings = QWebSettings::globalSettings(); m_websettings = QWebSettings::globalSettings();
}
return m_websettings; return m_websettings;
} }
NetworkManager* MainApplication::networkManager() NetworkManager* MainApplication::networkManager()
{ {
if (!m_networkmanager) if (!m_networkmanager) {
m_networkmanager = new NetworkManager(getWindow()); m_networkmanager = new NetworkManager(getWindow());
}
return m_networkmanager; return m_networkmanager;
} }
@ -498,50 +528,57 @@ CookieJar* MainApplication::cookieJar()
RSSManager* MainApplication::rssManager() RSSManager* MainApplication::rssManager()
{ {
if (!m_rssmanager) if (!m_rssmanager) {
m_rssmanager = new RSSManager(getWindow()); m_rssmanager = new RSSManager(getWindow());
}
return m_rssmanager; return m_rssmanager;
} }
BookmarksModel* MainApplication::bookmarksModel() BookmarksModel* MainApplication::bookmarksModel()
{ {
if (!m_bookmarksModel) if (!m_bookmarksModel) {
m_bookmarksModel = new BookmarksModel(this); m_bookmarksModel = new BookmarksModel(this);
}
return m_bookmarksModel; return m_bookmarksModel;
} }
DownloadManager* MainApplication::downManager() DownloadManager* MainApplication::downManager()
{ {
if (!m_downloadManager) if (!m_downloadManager) {
m_downloadManager = new DownloadManager(); m_downloadManager = new DownloadManager();
}
return m_downloadManager; return m_downloadManager;
} }
AutoFillModel* MainApplication::autoFill() AutoFillModel* MainApplication::autoFill()
{ {
if (!m_autofill) if (!m_autofill) {
m_autofill = new AutoFillModel(getWindow()); m_autofill = new AutoFillModel(getWindow());
}
return m_autofill; return m_autofill;
} }
SearchEnginesManager* MainApplication::searchEnginesManager() SearchEnginesManager* MainApplication::searchEnginesManager()
{ {
if (!m_searchEnginesManager) if (!m_searchEnginesManager) {
m_searchEnginesManager = new SearchEnginesManager(); m_searchEnginesManager = new SearchEnginesManager();
}
return m_searchEnginesManager; return m_searchEnginesManager;
} }
DesktopNotificationsFactory* MainApplication::desktopNotifications() DesktopNotificationsFactory* MainApplication::desktopNotifications()
{ {
if (!m_desktopNotifications) if (!m_desktopNotifications) {
m_desktopNotifications = new DesktopNotificationsFactory(this); m_desktopNotifications = new DesktopNotificationsFactory(this);
}
return m_desktopNotifications; return m_desktopNotifications;
} }
void MainApplication::aboutToCloseWindow(QupZilla* window) void MainApplication::aboutToCloseWindow(QupZilla* window)
{ {
if (!window) if (!window) {
return; return;
}
m_mainWindows.removeOne(window); m_mainWindows.removeOne(window);
} }
@ -551,14 +588,15 @@ static const int sessionVersion = 0x0002;
bool MainApplication::saveStateSlot() bool MainApplication::saveStateSlot()
{ {
if (m_websettings->testAttribute(QWebSettings::PrivateBrowsingEnabled) || m_isRestoring) if (m_websettings->testAttribute(QWebSettings::PrivateBrowsingEnabled) || m_isRestoring) {
return false; return false;
}
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("SessionRestore"); settings.beginGroup("SessionRestore");
settings.setValue("restoreSession",false); settings.setValue("restoreSession", false);
QFile file(m_activeProfil+"session.dat"); QFile file(m_activeProfil + "session.dat");
file.open(QIODevice::WriteOnly); file.open(QIODevice::WriteOnly);
QDataStream stream(&file); QDataStream stream(&file);
@ -566,19 +604,22 @@ bool MainApplication::saveStateSlot()
stream << m_mainWindows.count(); stream << m_mainWindows.count();
for (int i = 0; i < m_mainWindows.count(); i++) { for (int i = 0; i < m_mainWindows.count(); i++) {
stream << m_mainWindows.at(i)->tabWidget()->saveState(); stream << m_mainWindows.at(i)->tabWidget()->saveState();
if (m_mainWindows.at(i)->isFullScreen()) if (m_mainWindows.at(i)->isFullScreen()) {
stream << QByteArray(); stream << QByteArray();
else }
else {
stream << m_mainWindows.at(i)->saveState(); stream << m_mainWindows.at(i)->saveState();
}
} }
file.close(); file.close();
settings.setValue("restoreSession",true); settings.setValue("restoreSession", true);
settings.endGroup(); settings.endGroup();
QupZilla* qupzilla_ = getWindow(); QupZilla* qupzilla_ = getWindow();
if (qupzilla_) if (qupzilla_) {
qupzilla_->tabWidget()->savePinnedTabs(); qupzilla_->tabWidget()->savePinnedTabs();
}
return true; return true;
} }
@ -586,29 +627,29 @@ bool MainApplication::saveStateSlot()
bool MainApplication::restoreStateSlot(QupZilla* window) bool MainApplication::restoreStateSlot(QupZilla* window)
{ {
m_isRestoring = true; m_isRestoring = true;
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
int afterStart = settings.value("Web-URL-Settings/afterLaunch", 1).toInt(); int afterStart = settings.value("Web-URL-Settings/afterLaunch", 1).toInt();
settings.beginGroup("SessionRestore"); settings.beginGroup("SessionRestore");
if (!settings.value("restoreSession",false).toBool()) { if (!settings.value("restoreSession", false).toBool()) {
m_isRestoring = false; m_isRestoring = false;
return false; return false;
} }
if (settings.value("isCrashed",false).toBool() && afterStart != 2) { if (settings.value("isCrashed", false).toBool() && afterStart != 2) {
QMessageBox::StandardButton button = QMessageBox::warning(window, tr("Last session crashed"), QMessageBox::StandardButton button = QMessageBox::warning(window, tr("Last session crashed"),
tr("<b>QupZilla crashed :-(</b><br/>Oops, last session of QupZilla ends with its crash. We are very sorry. Would you try to restore saved state?"), tr("<b>QupZilla crashed :-(</b><br/>Oops, last session of QupZilla ends with its crash. We are very sorry. Would you try to restore saved state?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (button != QMessageBox::Yes) { if (button != QMessageBox::Yes) {
m_isRestoring = false; m_isRestoring = false;
return false; return false;
} }
} }
if (!QFile::exists(m_activeProfil+"session.dat")) { if (!QFile::exists(m_activeProfil + "session.dat")) {
m_isRestoring = false; m_isRestoring = false;
return false; return false;
} }
settings.setValue("isCrashed",false); settings.setValue("isCrashed", false);
QFile file(m_activeProfil+"session.dat"); QFile file(m_activeProfil + "session.dat");
file.open(QIODevice::ReadOnly); file.open(QIODevice::ReadOnly);
QDataStream stream(&file); QDataStream stream(&file);
@ -636,7 +677,7 @@ bool MainApplication::restoreStateSlot(QupZilla* window)
QupZilla* window = new QupZilla(QupZilla::OtherRestoredWindow); QupZilla* window = new QupZilla(QupZilla::OtherRestoredWindow);
m_mainWindows.append(window); m_mainWindows.append(window);
connect(window, SIGNAL(message(MainApplication::MessageType,bool)), this, SLOT(sendMessages(MainApplication::MessageType,bool))); connect(window, SIGNAL(message(MainApplication::MessageType, bool)), this, SLOT(sendMessages(MainApplication::MessageType, bool)));
QEventLoop eLoop; QEventLoop eLoop;
connect(window, SIGNAL(startingCompleted()), &eLoop, SLOT(quit())); connect(window, SIGNAL(startingCompleted()), &eLoop, SLOT(quit()));
eLoop.exec(); eLoop.exec();
@ -668,8 +709,9 @@ bool MainApplication::checkSettingsDir()
*/ */
QString homePath = QDir::homePath() + "/.qupzilla/"; QString homePath = QDir::homePath() + "/.qupzilla/";
if (QDir(homePath).exists() && QFile(homePath + "profiles/profiles.ini").exists()) if (QDir(homePath).exists() && QFile(homePath + "profiles/profiles.ini").exists()) {
return true; return true;
}
std::cout << "Creating new profile directory" << std::endl; std::cout << "Creating new profile directory" << std::endl;

View File

@ -56,15 +56,15 @@ public:
QString PLUGINSDIR; QString PLUGINSDIR;
QString TRANSLATIONSDIR; QString TRANSLATIONSDIR;
QString THEMESDIR; QString THEMESDIR;
explicit MainApplication(const QList<CommandLineOptions::ActionPair> &cmdActions, int &argc, char **argv); explicit MainApplication(const QList<CommandLineOptions::ActionPair> &cmdActions, int &argc, char** argv);
enum MessageType{ SetAdBlockIconEnabled, CheckPrivateBrowsing, ReloadSettings, HistoryStateChanged, BookmarksChanged }; enum MessageType { SetAdBlockIconEnabled, CheckPrivateBrowsing, ReloadSettings, HistoryStateChanged, BookmarksChanged };
void connectDatabase(); void connectDatabase();
void loadSettings(); void loadSettings();
void reloadSettings() { loadSettings(); emit message(ReloadSettings, true); } void reloadSettings() { loadSettings(); emit message(ReloadSettings, true); }
bool restoreStateSlot(QupZilla* window); bool restoreStateSlot(QupZilla* window);
void makeNewWindow(bool tryRestore, const QUrl &startUrl=QUrl()); void makeNewWindow(bool tryRestore, const QUrl &startUrl = QUrl());
void addNewTab(const QUrl &url = QUrl()); void addNewTab(const QUrl &url = QUrl());
void aboutToCloseWindow(QupZilla* window); void aboutToCloseWindow(QupZilla* window);
bool isStateChanged(); bool isStateChanged();

View File

@ -44,8 +44,10 @@ void ProfileUpdater::checkProfile()
versionFile.remove(); versionFile.remove();
updateProfile(QupZilla::VERSION, profileVersion.trimmed()); updateProfile(QupZilla::VERSION, profileVersion.trimmed());
} else }
else {
copyDataToProfile(); copyDataToProfile();
}
versionFile.open(QFile::WriteOnly); versionFile.open(QFile::WriteOnly);
versionFile.write(QupZilla::VERSION.toAscii()); versionFile.write(QupZilla::VERSION.toAscii());
@ -54,8 +56,9 @@ void ProfileUpdater::checkProfile()
void ProfileUpdater::updateProfile(const QString &current, const QString &profile) void ProfileUpdater::updateProfile(const QString &current, const QString &profile)
{ {
if (current == profile) if (current == profile) {
return; return;
}
// Updater::Version currentVersion = Updater::parseVersionFromString(current); // Updater::Version currentVersion = Updater::parseVersionFromString(current);
Updater::Version profileVersion = Updater::parseVersionFromString(profile); Updater::Version profileVersion = Updater::parseVersionFromString(profile);

View File

@ -108,7 +108,7 @@ QupZilla::QupZilla(StartBehaviour behaviour, QUrl startUrl)
setupUi(); setupUi();
setupMenu(); setupMenu();
QTimer::singleShot(0, this, SLOT(postLaunch())); QTimer::singleShot(0, this, SLOT(postLaunch()));
connect(mApp, SIGNAL(message(MainApplication::MessageType,bool)), this, SLOT(receiveMessage(MainApplication::MessageType,bool))); connect(mApp, SIGNAL(message(MainApplication::MessageType, bool)), this, SLOT(receiveMessage(MainApplication::MessageType, bool)));
} }
void QupZilla::postLaunch() void QupZilla::postLaunch()
@ -119,43 +119,50 @@ void QupZilla::postLaunch()
//Open tab from command line argument //Open tab from command line argument
bool addTab = true; bool addTab = true;
QStringList arguments = qApp->arguments(); QStringList arguments = qApp->arguments();
for (int i = 0;i<qApp->arguments().count();i++) { for (int i = 0; i < qApp->arguments().count(); i++) {
QString arg = arguments.at(i); QString arg = arguments.at(i);
if (arg.startsWith("-url=")) { if (arg.startsWith("-url=")) {
m_tabWidget->addView(QUrl(arg.replace("-url=",""))); m_tabWidget->addView(QUrl(arg.replace("-url=", "")));
addTab = false; addTab = false;
} }
} }
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-URL-Settings"); settings.beginGroup("Web-URL-Settings");
int afterLaunch = settings.value("afterLaunch",1).toInt(); int afterLaunch = settings.value("afterLaunch", 1).toInt();
settings.endGroup(); settings.endGroup();
settings.beginGroup("SessionRestore"); settings.beginGroup("SessionRestore");
bool startingAfterCrash = settings.value("isCrashed",false).toBool(); bool startingAfterCrash = settings.value("isCrashed", false).toBool();
settings.endGroup(); settings.endGroup();
QUrl startUrl; QUrl startUrl;
switch (m_startBehaviour) { switch (m_startBehaviour) {
case FirstAppWindow: case FirstAppWindow:
if (afterLaunch == 0) if (afterLaunch == 0) {
startUrl = QUrl(""); startUrl = QUrl("");
else if (afterLaunch == 1) }
else if (afterLaunch == 1) {
startUrl = m_homepage; startUrl = m_homepage;
else }
else {
startUrl = m_homepage; startUrl = m_homepage;
}
if ( startingAfterCrash || (addTab && afterLaunch == 2) ) if (startingAfterCrash || (addTab && afterLaunch == 2)) {
addTab = !mApp->restoreStateSlot(this); addTab = !mApp->restoreStateSlot(this);
}
break; break;
case NewWindow: case NewWindow:
if (afterLaunch == 0) if (afterLaunch == 0) {
startUrl = QUrl(""); startUrl = QUrl("");
else if (afterLaunch == 1) }
else if (afterLaunch == 1) {
startUrl = m_homepage; startUrl = m_homepage;
else }
else {
startUrl = m_homepage; startUrl = m_homepage;
}
addTab = true; addTab = true;
break; break;
@ -170,14 +177,16 @@ void QupZilla::postLaunch()
addTab = true; addTab = true;
} }
if (addTab) if (addTab) {
m_tabWidget->addView(startUrl); m_tabWidget->addView(startUrl);
}
aboutToShowHistoryMenu(false); aboutToShowHistoryMenu(false);
aboutToShowBookmarksMenu(); aboutToShowBookmarksMenu();
if (m_tabWidget->getTabBar()->normalTabsCount() <= 0) //Something went really wrong .. add one tab if (m_tabWidget->getTabBar()->normalTabsCount() <= 0) { //Something went really wrong .. add one tab
m_tabWidget->addView(m_homepage); m_tabWidget->addView(m_homepage);
}
setUpdatesEnabled(true); setUpdatesEnabled(true);
emit startingCompleted(); emit startingCompleted();
@ -188,12 +197,13 @@ void QupZilla::setupUi()
int locationBarWidth; int locationBarWidth;
int websearchBarWidth; int websearchBarWidth;
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Browser-View-Settings"); settings.beginGroup("Browser-View-Settings");
if (settings.value("WindowMaximised", false).toBool()) { if (settings.value("WindowMaximised", false).toBool()) {
resize(800, 550); resize(800, 550);
setWindowState(Qt::WindowMaximized); setWindowState(Qt::WindowMaximized);
} else { }
else {
setGeometry(settings.value("WindowGeometry", QRect(20, 20, 800, 550)).toRect()); setGeometry(settings.value("WindowGeometry", QRect(20, 20, 800, 550)).toRect());
} }
@ -204,7 +214,7 @@ void QupZilla::setupUi()
setCentralWidget(widget); setCentralWidget(widget);
m_mainLayout = new QVBoxLayout(widget); m_mainLayout = new QVBoxLayout(widget);
m_mainLayout->setContentsMargins(0,0,0,0); m_mainLayout->setContentsMargins(0, 0, 0, 0);
m_mainLayout->setSpacing(0); m_mainLayout->setSpacing(0);
m_mainSplitter = new QSplitter(this); m_mainSplitter = new QSplitter(this);
m_mainSplitter->setObjectName("sidebar-splitter"); m_mainSplitter->setObjectName("sidebar-splitter");
@ -261,7 +271,8 @@ void QupZilla::setupMenu()
m_menuFile->addAction(QIcon::fromTheme("document-save"), tr("&Save Page As..."), this, SLOT(savePage()))->setShortcut(QKeySequence("Ctrl+S")); m_menuFile->addAction(QIcon::fromTheme("document-save"), tr("&Save Page As..."), this, SLOT(savePage()))->setShortcut(QKeySequence("Ctrl+S"));
m_menuFile->addAction(tr("Save Page Screen"), this, SLOT(savePageScreen())); m_menuFile->addAction(tr("Save Page Screen"), this, SLOT(savePageScreen()));
m_menuFile->addAction(tr("Send Link..."), this, SLOT(sendLink())); m_menuFile->addAction(tr("Send Link..."), this, SLOT(sendLink()));
m_menuFile->addAction(QIcon::fromTheme("document-print"), tr("&Print"), this, SLOT(printPage())); m_menuFile->addSeparator(); m_menuFile->addAction(QIcon::fromTheme("document-print"), tr("&Print"), this, SLOT(printPage()));
m_menuFile->addSeparator();
m_menuFile->addSeparator(); m_menuFile->addSeparator();
m_menuFile->addAction(tr("Import bookmarks..."), this, SLOT(showBookmarkImport())); m_menuFile->addAction(tr("Import bookmarks..."), this, SLOT(showBookmarkImport()));
m_menuFile->addAction(QIcon::fromTheme("application-exit"), tr("Quit"), this, SLOT(quitApp()))->setShortcut(QKeySequence("Ctrl+Q")); m_menuFile->addAction(QIcon::fromTheme("application-exit"), tr("Quit"), this, SLOT(quitApp()))->setShortcut(QKeySequence("Ctrl+Q"));
@ -362,7 +373,7 @@ void QupZilla::setupMenu()
aboutToShowToolsMenu(); aboutToShowToolsMenu();
aboutToShowHelpMenu(); aboutToShowHelpMenu();
m_actionRestoreTab = new QAction(QIcon::fromTheme("user-trash"),tr("Restore &Closed Tab"), this); m_actionRestoreTab = new QAction(QIcon::fromTheme("user-trash"), tr("Restore &Closed Tab"), this);
m_actionRestoreTab->setShortcut(QKeySequence("Ctrl+Shift+T")); m_actionRestoreTab->setShortcut(QKeySequence("Ctrl+Shift+T"));
connect(m_actionRestoreTab, SIGNAL(triggered()), m_tabWidget, SLOT(restoreClosedTab())); connect(m_actionRestoreTab, SIGNAL(triggered()), m_tabWidget, SLOT(restoreClosedTab()));
addAction(m_actionRestoreTab); addAction(m_actionRestoreTab);
@ -374,10 +385,11 @@ void QupZilla::setupMenu()
// Make shortcuts available even in fullscreen (menu hidden) // Make shortcuts available even in fullscreen (menu hidden)
QList<QAction*> actions = menuBar()->actions(); QList<QAction*> actions = menuBar()->actions();
foreach (QAction* action, actions) { foreach(QAction * action, actions) {
if (action->menu()) if (action->menu()) {
actions += action->menu()->actions(); actions += action->menu()->actions();
addAction(action); }
addAction(action);
} }
m_superMenu->addMenu(m_menuFile); m_superMenu->addMenu(m_menuFile);
@ -391,12 +403,12 @@ void QupZilla::setupMenu()
void QupZilla::loadSettings() void QupZilla::loadSettings()
{ {
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
//Url settings //Url settings
settings.beginGroup("Web-URL-Settings"); settings.beginGroup("Web-URL-Settings");
m_homepage = settings.value("homepage","qupzilla:start").toUrl(); m_homepage = settings.value("homepage", "qupzilla:start").toUrl();
m_newtab = settings.value("newTabUrl","").toUrl(); m_newtab = settings.value("newTabUrl", "").toUrl();
settings.endGroup(); settings.endGroup();
QWebSettings* websettings = mApp->webSettings(); QWebSettings* websettings = mApp->webSettings();
@ -405,14 +417,14 @@ void QupZilla::loadSettings()
//Browser Window settings //Browser Window settings
settings.beginGroup("Browser-View-Settings"); settings.beginGroup("Browser-View-Settings");
m_menuTextColor = settings.value("menuTextColor", QColor(Qt::black)).value<QColor>(); m_menuTextColor = settings.value("menuTextColor", QColor(Qt::black)).value<QColor>();
bool showStatusBar = settings.value("showStatusBar",true).toBool(); bool showStatusBar = settings.value("showStatusBar", true).toBool();
bool showHomeIcon = settings.value("showHomeButton",true).toBool(); bool showHomeIcon = settings.value("showHomeButton", true).toBool();
bool showBackForwardIcons = settings.value("showBackForwardButtons",true).toBool(); bool showBackForwardIcons = settings.value("showBackForwardButtons", true).toBool();
bool showBookmarksToolbar = settings.value("showBookmarksToolbar",true).toBool(); bool showBookmarksToolbar = settings.value("showBookmarksToolbar", true).toBool();
bool showNavigationToolbar = settings.value("showNavigationToolbar",true).toBool(); bool showNavigationToolbar = settings.value("showNavigationToolbar", true).toBool();
bool showMenuBar = settings.value("showMenubar",true).toBool(); bool showMenuBar = settings.value("showMenubar", true).toBool();
bool showAddTab = settings.value("showAddTabButton", false).toBool(); bool showAddTab = settings.value("showAddTabButton", false).toBool();
bool makeTransparent = settings.value("useTransparentBackground",false).toBool(); bool makeTransparent = settings.value("useTransparentBackground", false).toBool();
m_sideBarWidth = settings.value("SideBarWidth", 250).toInt(); m_sideBarWidth = settings.value("SideBarWidth", 250).toInt();
QString activeSideBar = settings.value("SideBar", "None").toString(); QString activeSideBar = settings.value("SideBar", "None").toString();
settings.endGroup(); settings.endGroup();
@ -432,18 +444,21 @@ void QupZilla::loadSettings()
m_navigationBar->buttonAddTab()->setVisible(showAddTab); m_navigationBar->buttonAddTab()->setVisible(showAddTab);
if (activeSideBar != "None") { if (activeSideBar != "None") {
if (activeSideBar == "Bookmarks") if (activeSideBar == "Bookmarks") {
m_actionShowBookmarksSideBar->trigger(); m_actionShowBookmarksSideBar->trigger();
else if (activeSideBar == "History") }
else if (activeSideBar == "History") {
m_actionShowHistorySideBar->trigger(); m_actionShowHistorySideBar->trigger();
}
} }
//Private browsing //Private browsing
m_actionPrivateBrowsing->setChecked( mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled) ); m_actionPrivateBrowsing->setChecked(mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled));
m_privateBrowsing->setVisible( mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled) ); m_privateBrowsing->setVisible(mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled));
if (!makeTransparent) if (!makeTransparent) {
return; return;
}
//Opacity //Opacity
#ifdef Q_WS_X11 #ifdef Q_WS_X11
setAttribute(Qt::WA_TranslucentBackground); setAttribute(Qt::WA_TranslucentBackground);
@ -464,10 +479,12 @@ void QupZilla::loadSettings()
void QupZilla::setWindowTitle(const QString &t) void QupZilla::setWindowTitle(const QString &t)
{ {
if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
QMainWindow::setWindowTitle(t + tr(" (Private Browsing)")); QMainWindow::setWindowTitle(t + tr(" (Private Browsing)"));
else }
else {
QMainWindow::setWindowTitle(t); QMainWindow::setWindowTitle(t);
}
} }
void QupZilla::receiveMessage(MainApplication::MessageType mes, bool state) void QupZilla::receiveMessage(MainApplication::MessageType mes, bool state)
@ -480,10 +497,12 @@ void QupZilla::receiveMessage(MainApplication::MessageType mes, bool state)
case MainApplication::CheckPrivateBrowsing: case MainApplication::CheckPrivateBrowsing:
m_privateBrowsing->setVisible(state); m_privateBrowsing->setVisible(state);
m_actionPrivateBrowsing->setChecked(state); m_actionPrivateBrowsing->setChecked(state);
if (state) if (state) {
setWindowTitle(windowTitle()); setWindowTitle(windowTitle());
else }
else {
setWindowTitle(windowTitle().remove(tr(" (Private Browsing)"))); setWindowTitle(windowTitle().remove(tr(" (Private Browsing)")));
}
break; break;
case MainApplication::ReloadSettings: case MainApplication::ReloadSettings:
@ -508,8 +527,9 @@ void QupZilla::receiveMessage(MainApplication::MessageType mes, bool state)
void QupZilla::aboutToShowBookmarksMenu() void QupZilla::aboutToShowBookmarksMenu()
{ {
if (!m_bookmarksMenuChanged) if (!m_bookmarksMenuChanged) {
return; return;
}
m_bookmarksMenuChanged = false; m_bookmarksMenuChanged = false;
m_menuBookmarks->clear(); m_menuBookmarks->clear();
@ -519,13 +539,13 @@ void QupZilla::aboutToShowBookmarksMenu()
m_menuBookmarks->addSeparator(); m_menuBookmarks->addSeparator();
QSqlQuery query; QSqlQuery query;
query.exec("SELECT title, url, icon FROM bookmarks WHERE folder='bookmarksMenu'"); query.exec("SELECT title, url, icon FROM bookmarks WHERE folder='bookmarksMenu'");
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray()); QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray());
if (title.length()>40) { if (title.length() > 40) {
title.truncate(40); title.truncate(40);
title+=".."; title += "..";
} }
m_menuBookmarks->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url); m_menuBookmarks->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url);
} }
@ -534,40 +554,42 @@ void QupZilla::aboutToShowBookmarksMenu()
folderBookmarks->setIcon(QIcon(style()->standardIcon(QStyle::SP_DirOpenIcon))); folderBookmarks->setIcon(QIcon(style()->standardIcon(QStyle::SP_DirOpenIcon)));
query.exec("SELECT title, url, icon FROM bookmarks WHERE folder='bookmarksToolbar'"); query.exec("SELECT title, url, icon FROM bookmarks WHERE folder='bookmarksToolbar'");
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray()); QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray());
if (title.length()>40) { if (title.length() > 40) {
title.truncate(40); title.truncate(40);
title+=".."; title += "..";
} }
folderBookmarks->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url); folderBookmarks->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url);
} }
if (folderBookmarks->isEmpty()) if (folderBookmarks->isEmpty()) {
folderBookmarks->addAction(tr("Empty")); folderBookmarks->addAction(tr("Empty"));
}
m_menuBookmarks->addMenu(folderBookmarks); m_menuBookmarks->addMenu(folderBookmarks);
query.exec("SELECT name FROM folders"); query.exec("SELECT name FROM folders");
while(query.next()) { while (query.next()) {
QString folderName = query.value(0).toString(); QString folderName = query.value(0).toString();
QMenu* tempFolder = new QMenu(folderName, m_menuBookmarks); QMenu* tempFolder = new QMenu(folderName, m_menuBookmarks);
tempFolder->setIcon(QIcon(style()->standardIcon(QStyle::SP_DirOpenIcon))); tempFolder->setIcon(QIcon(style()->standardIcon(QStyle::SP_DirOpenIcon)));
QSqlQuery query2; QSqlQuery query2;
query2.exec("SELECT title, url, icon FROM bookmarks WHERE folder='" + folderName + "'"); query2.exec("SELECT title, url, icon FROM bookmarks WHERE folder='" + folderName + "'");
while(query2.next()) { while (query2.next()) {
QString title = query2.value(0).toString(); QString title = query2.value(0).toString();
QUrl url = query2.value(1).toUrl(); QUrl url = query2.value(1).toUrl();
QIcon icon = IconProvider::iconFromBase64(query2.value(2).toByteArray()); QIcon icon = IconProvider::iconFromBase64(query2.value(2).toByteArray());
if (title.length()>40) { if (title.length() > 40) {
title.truncate(40); title.truncate(40);
title+=".."; title += "..";
} }
tempFolder->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url); tempFolder->addAction(icon, title, this, SLOT(loadActionUrl()))->setData(url);
} }
if (tempFolder->isEmpty()) if (tempFolder->isEmpty()) {
tempFolder->addAction(tr("Empty")); tempFolder->addAction(tr("Empty"));
}
m_menuBookmarks->addMenu(tempFolder); m_menuBookmarks->addMenu(tempFolder);
} }
@ -575,20 +597,23 @@ void QupZilla::aboutToShowBookmarksMenu()
void QupZilla::aboutToShowHistoryMenu(bool loadHistory) void QupZilla::aboutToShowHistoryMenu(bool loadHistory)
{ {
if (!weView()) if (!weView()) {
return; return;
}
if (!m_historyMenuChanged) { if (!m_historyMenuChanged) {
if (!m_menuHistory || m_menuHistory->actions().count() < 3) if (!m_menuHistory || m_menuHistory->actions().count() < 3) {
return; return;
}
m_menuHistory->actions().at(0)->setEnabled(WebHistoryWrapper::canGoBack(weView()->history())); m_menuHistory->actions().at(0)->setEnabled(WebHistoryWrapper::canGoBack(weView()->history()));
m_menuHistory->actions().at(1)->setEnabled(WebHistoryWrapper::canGoForward(weView()->history())); m_menuHistory->actions().at(1)->setEnabled(WebHistoryWrapper::canGoForward(weView()->history()));
return; return;
} }
m_historyMenuChanged = false; m_historyMenuChanged = false;
if (!loadHistory) if (!loadHistory) {
m_historyMenuChanged = true; m_historyMenuChanged = true;
}
m_menuHistory->clear(); m_menuHistory->clear();
m_menuHistory->addAction(IconProvider::standardIcon(QStyle::SP_ArrowBack), tr("&Back"), this, SLOT(goBack()))->setShortcut(QKeySequence("Ctrl+Left")); m_menuHistory->addAction(IconProvider::standardIcon(QStyle::SP_ArrowBack), tr("&Back"), this, SLOT(goBack()))->setShortcut(QKeySequence("Ctrl+Left"));
@ -598,18 +623,18 @@ void QupZilla::aboutToShowHistoryMenu(bool loadHistory)
m_menuHistory->actions().at(0)->setEnabled(WebHistoryWrapper::canGoBack(weView()->history())); m_menuHistory->actions().at(0)->setEnabled(WebHistoryWrapper::canGoBack(weView()->history()));
m_menuHistory->actions().at(1)->setEnabled(WebHistoryWrapper::canGoForward(weView()->history())); m_menuHistory->actions().at(1)->setEnabled(WebHistoryWrapper::canGoForward(weView()->history()));
m_menuHistory->addAction(QIcon(":/icons/menu/history.png"), tr("Show &All History"), this, SLOT(showHistoryManager())); m_menuHistory->addAction(QIcon(":/icons/menu/history.png"), tr("Show &All History"), this, SLOT(showHistoryManager()))->setShortcut(QKeySequence("Ctrl+Shift+H"));
m_menuHistory->addSeparator(); m_menuHistory->addSeparator();
if (loadHistory) { if (loadHistory) {
QSqlQuery query; QSqlQuery query;
query.exec("SELECT title, url FROM history ORDER BY date DESC LIMIT 10"); query.exec("SELECT title, url FROM history ORDER BY date DESC LIMIT 10");
while(query.next()) { while (query.next()) {
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
QString title = query.value(0).toString(); QString title = query.value(0).toString();
if (title.length()>40) { if (title.length() > 40) {
title.truncate(40); title.truncate(40);
title+=".."; title += "..";
} }
m_menuHistory->addAction(_iconForUrl(url), title, this, SLOT(loadActionUrl()))->setData(url); m_menuHistory->addAction(_iconForUrl(url), title, this, SLOT(loadActionUrl()))->setData(url);
} }
@ -620,8 +645,9 @@ void QupZilla::aboutToShowHistoryMenu(bool loadHistory)
void QupZilla::aboutToHideHistoryMenu() void QupZilla::aboutToHideHistoryMenu()
{ {
if (!m_menuHistory || m_menuHistory->actions().count() < 3) if (!m_menuHistory || m_menuHistory->actions().count() < 3) {
return; return;
}
m_menuHistory->actions().at(0)->setEnabled(true); m_menuHistory->actions().at(0)->setEnabled(true);
m_menuHistory->actions().at(1)->setEnabled(true); m_menuHistory->actions().at(1)->setEnabled(true);
@ -631,18 +657,19 @@ void QupZilla::aboutToShowClosedTabsMenu()
{ {
m_menuClosedTabs->clear(); m_menuClosedTabs->clear();
int i = 0; int i = 0;
foreach (ClosedTabsManager::Tab tab, m_tabWidget->closedTabsManager()->allClosedTabs()) { foreach(ClosedTabsManager::Tab tab, m_tabWidget->closedTabsManager()->allClosedTabs()) {
QString title = tab.title; QString title = tab.title;
if (title.length()>40) { if (title.length() > 40) {
title.truncate(40); title.truncate(40);
title+=".."; title += "..";
} }
m_menuClosedTabs->addAction(_iconForUrl(tab.url), title, m_tabWidget, SLOT(restoreClosedTab()))->setData(i); m_menuClosedTabs->addAction(_iconForUrl(tab.url), title, m_tabWidget, SLOT(restoreClosedTab()))->setData(i);
i++; i++;
} }
m_menuClosedTabs->addSeparator(); m_menuClosedTabs->addSeparator();
if (i == 0) if (i == 0) {
m_menuClosedTabs->addAction(tr("Empty"))->setEnabled(false); m_menuClosedTabs->addAction(tr("Empty"))->setEnabled(false);
}
else { else {
m_menuClosedTabs->addAction(tr("Restore All Closed Tabs"), m_tabWidget, SLOT(restoreAllClosedTabs())); m_menuClosedTabs->addAction(tr("Restore All Closed Tabs"), m_tabWidget, SLOT(restoreAllClosedTabs()));
m_menuClosedTabs->addAction(tr("Clear list"), m_tabWidget, SLOT(clearClosedTabsList())); m_menuClosedTabs->addAction(tr("Clear list"), m_tabWidget, SLOT(clearClosedTabsList()));
@ -657,7 +684,11 @@ void QupZilla::aboutToShowHelpMenu()
m_menuHelp->addAction(QIcon(":/icons/menu/qt.png"), tr("About &Qt"), qApp, SLOT(aboutQt())); m_menuHelp->addAction(QIcon(":/icons/menu/qt.png"), tr("About &Qt"), qApp, SLOT(aboutQt()));
m_menuHelp->addAction(QIcon(":/icons/qupzilla.png"), tr("&About QupZilla"), this, SLOT(aboutQupZilla())); m_menuHelp->addAction(QIcon(":/icons/qupzilla.png"), tr("&About QupZilla"), this, SLOT(aboutQupZilla()));
m_menuHelp->addSeparator(); m_menuHelp->addSeparator();
m_menuHelp->addAction(QIcon(":/icons/menu/informations.png"), tr("Informations about application"), this, SLOT(loadActionUrlInNewTab()))->setData(QUrl("qupzilla:about")); QAction* infoAction = new QAction(QIcon(":/icons/menu/informations.png"), tr("Informations about application"), m_menuHelp);
infoAction->setData(QUrl("qupzilla:about"));
infoAction->setShortcut(QKeySequence(QKeySequence::HelpContents));
connect(infoAction, SIGNAL(triggered()), this, SLOT(loadActionUrlInNewTab()));
m_menuHelp->addAction(infoAction);
m_menuHelp->addAction(tr("Report &Issue"), this, SLOT(loadActionUrlInNewTab()))->setData(QUrl("qupzilla:reportbug")); m_menuHelp->addAction(tr("Report &Issue"), this, SLOT(loadActionUrlInNewTab()))->setData(QUrl("qupzilla:reportbug"));
} }
@ -685,8 +716,9 @@ void QupZilla::aboutToShowToolsMenu()
void QupZilla::aboutToShowViewMenu() void QupZilla::aboutToShowViewMenu()
{ {
if (!weView()) if (!weView()) {
return; return;
}
if (weView()->isLoading()) { if (weView()->isLoading()) {
m_actionStop->setEnabled(true); m_actionStop->setEnabled(true);
@ -706,7 +738,8 @@ void QupZilla::aboutToShowViewMenu()
m_actionShowBookmarksSideBar->setChecked(false); m_actionShowBookmarksSideBar->setChecked(false);
m_actionShowHistorySideBar->setChecked(false); m_actionShowHistorySideBar->setChecked(false);
// m_actionShowRssSideBar->setChecked(false); // m_actionShowRssSideBar->setChecked(false);
} else { }
else {
SideBar::SideWidget actWidget = m_sideBar->activeWidget(); SideBar::SideWidget actWidget = m_sideBar->activeWidget();
m_actionShowBookmarksSideBar->setChecked(actWidget == SideBar::Bookmarks); m_actionShowBookmarksSideBar->setChecked(actWidget == SideBar::Bookmarks);
m_actionShowHistorySideBar->setChecked(actWidget == SideBar::History); m_actionShowHistorySideBar->setChecked(actWidget == SideBar::History);
@ -720,9 +753,10 @@ void QupZilla::aboutToHideViewMenu()
m_actionStop->setEnabled(true); m_actionStop->setEnabled(true);
if (m_mainLayout->count() == 4) { if (m_mainLayout->count() == 4) {
SearchToolBar* search = qobject_cast<SearchToolBar*>( m_mainLayout->itemAt(3)->widget() ); SearchToolBar* search = qobject_cast<SearchToolBar*>(m_mainLayout->itemAt(3)->widget());
if (!search) if (!search) {
return; return;
}
m_actionStop->setEnabled(false); m_actionStop->setEnabled(false);
} }
} }
@ -740,41 +774,54 @@ void QupZilla::aboutToShowEncodingMenu()
qSort(available); qSort(available);
QString activeCodec = mApp->webSettings()->defaultTextEncoding(); QString activeCodec = mApp->webSettings()->defaultTextEncoding();
foreach (QByteArray name, available) { foreach(QByteArray name, available) {
if (QTextCodec::codecForName(name)->aliases().contains(name)) if (QTextCodec::codecForName(name)->aliases().contains(name)) {
continue; continue;
QAction* action = new QAction(name=="System" ? tr("Default") : name, this); }
QAction* action = new QAction(name == "System" ? tr("Default") : name, this);
action->setData(name); action->setData(name);
action->setCheckable(true); action->setCheckable(true);
connect(action, SIGNAL(triggered()), this, SLOT(changeEncoding())); connect(action, SIGNAL(triggered()), this, SLOT(changeEncoding()));
if (activeCodec.compare(name, Qt::CaseInsensitive) == 0) if (activeCodec.compare(name, Qt::CaseInsensitive) == 0) {
action->setChecked(true); action->setChecked(true);
}
if (name.startsWith("ISO")) if (name.startsWith("ISO")) {
menuISO->addAction(action); menuISO->addAction(action);
else if (name.startsWith("UTF")) }
else if (name.startsWith("UTF")) {
menuUTF->addAction(action); menuUTF->addAction(action);
else if (name.startsWith("windows")) }
else if (name.startsWith("windows")) {
menuWindows->addAction(action); menuWindows->addAction(action);
else if (name.startsWith("Iscii")) }
else if (name.startsWith("Iscii")) {
menuIscii->addAction(action); menuIscii->addAction(action);
else if (name == "System") }
else if (name == "System") {
m_menuEncoding->addAction(action); m_menuEncoding->addAction(action);
else }
else {
menuOther->addAction(action); menuOther->addAction(action);
}
} }
m_menuEncoding->addSeparator(); m_menuEncoding->addSeparator();
if (!menuISO->isEmpty()) if (!menuISO->isEmpty()) {
m_menuEncoding->addMenu(menuISO); m_menuEncoding->addMenu(menuISO);
if (!menuUTF->isEmpty()) }
if (!menuUTF->isEmpty()) {
m_menuEncoding->addMenu(menuUTF); m_menuEncoding->addMenu(menuUTF);
if (!menuWindows->isEmpty()) }
if (!menuWindows->isEmpty()) {
m_menuEncoding->addMenu(menuWindows); m_menuEncoding->addMenu(menuWindows);
if (!menuIscii->isEmpty()) }
if (!menuIscii->isEmpty()) {
m_menuEncoding->addMenu(menuIscii); m_menuEncoding->addMenu(menuIscii);
if (!menuOther->isEmpty()) }
if (!menuOther->isEmpty()) {
m_menuEncoding->addMenu(menuOther); m_menuEncoding->addMenu(menuOther);
}
} }
void QupZilla::changeEncoding() void QupZilla::changeEncoding()
@ -832,8 +879,9 @@ void QupZilla::loadAddress(const QUrl &url)
void QupZilla::urlEnter() void QupZilla::urlEnter()
{ {
if (locationBar()->text().isEmpty()) if (locationBar()->text().isEmpty()) {
return; return;
}
loadAddress(QUrl(WebView::guessUrlFromString(locationBar()->text()))); loadAddress(QUrl(WebView::guessUrlFromString(locationBar()->text())));
weView()->setFocus(); weView()->setFocus();
} }
@ -896,7 +944,7 @@ void QupZilla::showBookmarksToolbar()
bool status = m_bookmarksToolbar->isVisible(); bool status = m_bookmarksToolbar->isVisible();
m_bookmarksToolbar->setVisible(!status); m_bookmarksToolbar->setVisible(!status);
QSettings settings(activeProfil()+"settings.ini", QSettings::IniFormat); QSettings settings(activeProfil() + "settings.ini", QSettings::IniFormat);
settings.setValue("Browser-View-Settings/showBookmarksToolbar", !status); settings.setValue("Browser-View-Settings/showBookmarksToolbar", !status);
} }
@ -904,8 +952,9 @@ void QupZilla::showBookmarksSideBar()
{ {
addSideBar(); addSideBar();
if (m_sideBar->activeWidget() != SideBar::Bookmarks) if (m_sideBar->activeWidget() != SideBar::Bookmarks) {
m_sideBar->showBookmarks(); m_sideBar->showBookmarks();
}
else { else {
m_sideBar->close(); m_sideBar->close();
} }
@ -915,8 +964,9 @@ void QupZilla::showHistorySideBar()
{ {
addSideBar(); addSideBar();
if (m_sideBar->activeWidget() != SideBar::History) if (m_sideBar->activeWidget() != SideBar::History) {
m_sideBar->showHistory(); m_sideBar->showHistory();
}
else { else {
m_sideBar->close(); m_sideBar->close();
} }
@ -924,8 +974,9 @@ void QupZilla::showHistorySideBar()
void QupZilla::addSideBar() void QupZilla::addSideBar()
{ {
if (m_sideBar) if (m_sideBar) {
return; return;
}
m_sideBar = new SideBar(this); m_sideBar = new SideBar(this);
@ -946,25 +997,27 @@ void QupZilla::saveSideBarWidth()
void QupZilla::showNavigationToolbar() void QupZilla::showNavigationToolbar()
{ {
if (!menuBar()->isVisible() && !m_actionShowToolbar->isChecked()) if (!menuBar()->isVisible() && !m_actionShowToolbar->isChecked()) {
showMenubar(); showMenubar();
}
bool status = m_navigationBar->isVisible(); bool status = m_navigationBar->isVisible();
m_navigationBar->setVisible(!status); m_navigationBar->setVisible(!status);
QSettings settings(activeProfil()+"settings.ini", QSettings::IniFormat); QSettings settings(activeProfil() + "settings.ini", QSettings::IniFormat);
settings.setValue("Browser-View-Settings/showNavigationToolbar", !status); settings.setValue("Browser-View-Settings/showNavigationToolbar", !status);
} }
void QupZilla::showMenubar() void QupZilla::showMenubar()
{ {
if (!m_navigationBar->isVisible() && !m_actionShowMenubar->isChecked()) if (!m_navigationBar->isVisible() && !m_actionShowMenubar->isChecked()) {
showNavigationToolbar(); showNavigationToolbar();
}
menuBar()->setVisible(!menuBar()->isVisible()); menuBar()->setVisible(!menuBar()->isVisible());
m_navigationBar->buttonSuperMenu()->setVisible(!menuBar()->isVisible()); m_navigationBar->buttonSuperMenu()->setVisible(!menuBar()->isVisible());
QSettings settings(activeProfil()+"settings.ini", QSettings::IniFormat); QSettings settings(activeProfil() + "settings.ini", QSettings::IniFormat);
settings.setValue("Browser-View-Settings/showMenubar", menuBar()->isVisible()); settings.setValue("Browser-View-Settings/showMenubar", menuBar()->isVisible());
} }
@ -973,7 +1026,7 @@ void QupZilla::showStatusbar()
bool status = statusBar()->isVisible(); bool status = statusBar()->isVisible();
statusBar()->setVisible(!status); statusBar()->setVisible(!status);
QSettings settings(activeProfil()+"settings.ini", QSettings::IniFormat); QSettings settings(activeProfil() + "settings.ini", QSettings::IniFormat);
settings.setValue("Browser-View-Settings/showStatusbar", !status); settings.setValue("Browser-View-Settings/showStatusbar", !status);
} }
@ -1020,9 +1073,10 @@ void QupZilla::webSearch()
void QupZilla::searchOnPage() void QupZilla::searchOnPage()
{ {
if (m_mainLayout->count() == 4) { if (m_mainLayout->count() == 4) {
SearchToolBar* search = qobject_cast<SearchToolBar*>( m_mainLayout->itemAt(3)->widget() ); SearchToolBar* search = qobject_cast<SearchToolBar*>(m_mainLayout->itemAt(3)->widget());
if (!search) if (!search) {
return; return;
}
search->searchLine()->setFocus(); search->searchLine()->setFocus();
return; return;
@ -1036,25 +1090,30 @@ void QupZilla::searchOnPage()
void QupZilla::openFile() void QupZilla::openFile()
{ {
QString filePath = QFileDialog::getOpenFileName(this, tr("Open file..."), QDir::homePath(), "(*.html *.htm *.jpg *.png)"); QString filePath = QFileDialog::getOpenFileName(this, tr("Open file..."), QDir::homePath(), "(*.html *.htm *.jpg *.png)");
if (!filePath.isEmpty()) if (!filePath.isEmpty()) {
loadAddress(QUrl(filePath)); loadAddress(QUrl(filePath));
}
} }
void QupZilla::showNavigationWithFullscreen() void QupZilla::showNavigationWithFullscreen()
{ {
bool state; bool state;
if (m_navigationVisible) if (m_navigationVisible) {
state = !m_navigationBar->isVisible(); state = !m_navigationBar->isVisible();
else }
else {
state = !m_tabWidget->getTabBar()->isVisible(); state = !m_tabWidget->getTabBar()->isVisible();
}
if (m_navigationVisible) if (m_navigationVisible) {
m_navigationBar->setVisible(state); m_navigationBar->setVisible(state);
}
m_tabWidget->getTabBar()->updateVisibilityWithFullscreen(state); m_tabWidget->getTabBar()->updateVisibilityWithFullscreen(state);
if (m_bookmarksToolBarVisible) if (m_bookmarksToolBarVisible) {
m_bookmarksToolbar->setVisible(state); m_bookmarksToolbar->setVisible(state);
}
} }
void QupZilla::fullScreen(bool make) void QupZilla::fullScreen(bool make)
@ -1122,14 +1181,15 @@ void QupZilla::startPrivate(bool state)
actions.append(tr("Your session is not stored.")); actions.append(tr("Your session is not stored."));
QString text2 = tr("Until you close the window, you can still click the Back and Forward " QString text2 = tr("Until you close the window, you can still click the Back and Forward "
"buttons to return to the webpages you have opened."); "buttons to return to the webpages you have opened.");
QString message = QString(QLatin1String("<b>%1</b><p>%2</p><ul><li>%3</li></ul><p>%4</p>")).arg(title, text1, actions.join(QLatin1String("</li><li>")), text2); QString message = QString(QLatin1String("<b>%1</b><p>%2</p><ul><li>%3</li></ul><p>%4</p>")).arg(title, text1, actions.join(QLatin1String("</li><li>")), text2);
QMessageBox::StandardButton button = QMessageBox::question(this, tr("Start Private Browsing"), QMessageBox::StandardButton button = QMessageBox::question(this, tr("Start Private Browsing"),
message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (button != QMessageBox::Yes) if (button != QMessageBox::Yes) {
return; return;
}
} }
mApp->webSettings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, state); mApp->webSettings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, state);
mApp->history()->setSaving(!state); mApp->history()->setSaving(!state);
@ -1137,7 +1197,7 @@ void QupZilla::startPrivate(bool state)
emit message(MainApplication::CheckPrivateBrowsing, state); emit message(MainApplication::CheckPrivateBrowsing, state);
} }
void QupZilla::keyPressEvent(QKeyEvent *event) void QupZilla::keyPressEvent(QKeyEvent* event)
{ {
switch (event->key()) { switch (event->key()) {
case Qt::Key_Back: case Qt::Key_Back:
@ -1213,8 +1273,9 @@ void QupZilla::mousePressEvent(QMouseEvent* event)
void QupZilla::closeEvent(QCloseEvent* event) void QupZilla::closeEvent(QCloseEvent* event)
{ {
if (mApp->isClosing()) if (mApp->isClosing()) {
return; return;
}
m_isClosing = true; m_isClosing = true;
mApp->saveStateSlot(); mApp->saveStateSlot();
@ -1230,11 +1291,12 @@ void QupZilla::closeEvent(QCloseEvent* event)
bool QupZilla::quitApp() bool QupZilla::quitApp()
{ {
if (m_sideBar) if (m_sideBar) {
saveSideBarWidth(); saveSideBarWidth();
}
QSettings settings(m_activeProfil+"settings.ini", QSettings::IniFormat); QSettings settings(m_activeProfil + "settings.ini", QSettings::IniFormat);
int afterLaunch = settings.value("Web-URL-Settings/afterLaunch",0).toInt(); int afterLaunch = settings.value("Web-URL-Settings/afterLaunch", 0).toInt();
bool askOnClose = settings.value("Browser-Tabs-Settings/AskOnClosing", false).toBool(); bool askOnClose = settings.value("Browser-Tabs-Settings/AskOnClosing", false).toBool();
settings.beginGroup("Browser-View-Settings"); settings.beginGroup("Browser-View-Settings");
@ -1250,10 +1312,12 @@ bool QupZilla::quitApp()
ui->setupUi(dialog); ui->setupUi(dialog);
ui->textLabel->setText(tr("There are still %1 open tabs and your session won't be stored. Are you sure to quit?").arg(m_tabWidget->count())); ui->textLabel->setText(tr("There are still %1 open tabs and your session won't be stored. Are you sure to quit?").arg(m_tabWidget->count()));
ui->iconLabel->setPixmap(style()->standardPixmap(QStyle::SP_MessageBoxWarning)); ui->iconLabel->setPixmap(style()->standardPixmap(QStyle::SP_MessageBoxWarning));
if (dialog->exec() != QDialog::Accepted) if (dialog->exec() != QDialog::Accepted) {
return false; return false;
if (ui->dontAskAgain->isChecked()) }
if (ui->dontAskAgain->isChecked()) {
settings.setValue("Browser-Tabs-Settings/AskOnClosing", false); settings.setValue("Browser-Tabs-Settings/AskOnClosing", false);
}
} }
mApp->quitApplication(); mApp->quitApplication();
@ -1269,6 +1333,7 @@ QupZilla::~QupZilla()
delete m_bookmarksToolbar; delete m_bookmarksToolbar;
delete m_progressBar; delete m_progressBar;
if (m_webInspectorDock) if (m_webInspectorDock) {
delete m_webInspectorDock; delete m_webInspectorDock;
}
} }

View File

@ -98,10 +98,10 @@ public:
inline StatusBarMessage* statusBarMessage() { return m_statusBarMessage; } inline StatusBarMessage* statusBarMessage() { return m_statusBarMessage; }
inline NavigationBar* navigationBar() { return m_navigationBar; } inline NavigationBar* navigationBar() { return m_navigationBar; }
inline ProgressBar* progressBar(){ return m_progressBar; } inline ProgressBar* progressBar() { return m_progressBar; }
inline QString activeProfil(){ return m_activeProfil; } inline QString activeProfil() { return m_activeProfil; }
inline QString activeLanguage(){ return m_activeLanguage; } inline QString activeLanguage() { return m_activeLanguage; }
inline QLabel* ipLabel(){ return m_ipLabel; } inline QLabel* ipLabel() { return m_ipLabel; }
inline QColor menuTextColor() { return m_menuTextColor; } inline QColor menuTextColor() { return m_menuTextColor; }
inline QMenu* menuHelp() { return m_menuHelp; } inline QMenu* menuHelp() { return m_menuHelp; }
inline QAction* actionRestoreTab() { return m_actionRestoreTab; } inline QAction* actionRestoreTab() { return m_actionRestoreTab; }
@ -126,7 +126,7 @@ public slots:
void loadActionUrlInNewTab(); void loadActionUrlInNewTab();
void bookmarkPage(); void bookmarkPage();
void loadAddress(const QUrl &url); void loadAddress(const QUrl &url);
void showSource(const QString& selectedHtml = ""); void showSource(const QString &selectedHtml = "");
void showPageInfo(); void showPageInfo();
void receiveMessage(MainApplication::MessageType mes, bool state); void receiveMessage(MainApplication::MessageType mes, bool state);
@ -177,7 +177,7 @@ private slots:
void openLocation() { locationBar()->setFocus(); locationBar()->selectAll(); } void openLocation() { locationBar()->setFocus(); locationBar()->selectAll(); }
void openFile(); void openFile();
void savePage(); void savePage();
void sendLink() { QDesktopServices::openUrl(QUrl("mailto:?body="+weView()->url().toString())); } void sendLink() { QDesktopServices::openUrl(QUrl("mailto:?body=" + weView()->url().toString())); }
void webSearch(); void webSearch();
void copy() { QApplication::clipboard()->setText(weView()->selectedText()); } void copy() { QApplication::clipboard()->setText(weView()->selectedText()); }
@ -193,7 +193,7 @@ private slots:
bool quitApp(); bool quitApp();
private: private:
void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent* event);
void mousePressEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event);
void closeEvent(QCloseEvent* event); void closeEvent(QCloseEvent* event);

View File

@ -23,15 +23,15 @@
AutoFillModel::AutoFillModel(QupZilla* mainClass, QObject* parent) : AutoFillModel::AutoFillModel(QupZilla* mainClass, QObject* parent) :
QObject(parent) QObject(parent)
,p_QupZilla(mainClass) , p_QupZilla(mainClass)
,m_isStoring(false) , m_isStoring(false)
{ {
QTimer::singleShot(0, this, SLOT(loadSettings())); QTimer::singleShot(0, this, SLOT(loadSettings()));
} }
void AutoFillModel::loadSettings() void AutoFillModel::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
m_isStoring = settings.value("SavePasswordsOnSites", true).toBool(); m_isStoring = settings.value("SavePasswordsOnSites", true).toBool();
settings.endGroup(); settings.endGroup();
@ -39,44 +39,48 @@ void AutoFillModel::loadSettings()
bool AutoFillModel::isStored(const QUrl &url) bool AutoFillModel::isStored(const QUrl &url)
{ {
if (!isStoringEnabled(url)) if (!isStoringEnabled(url)) {
return false; return false;
}
QString server = url.host(); QString server = url.host();
QSqlQuery query; QSqlQuery query;
query.exec("SELECT count(id) FROM autofill WHERE server='"+server+"'"); query.exec("SELECT count(id) FROM autofill WHERE server='" + server + "'");
query.next(); query.next();
if (query.value(0).toInt()>0) if (query.value(0).toInt() > 0) {
return true; return true;
}
return false; return false;
} }
bool AutoFillModel::isStoringEnabled(const QUrl &url) bool AutoFillModel::isStoringEnabled(const QUrl &url)
{ {
if (!m_isStoring) if (!m_isStoring) {
return false; return false;
}
QString server = url.host(); QString server = url.host();
QSqlQuery query; QSqlQuery query;
query.exec("SELECT count(id) FROM autofill_exceptions WHERE server='"+server+"'"); query.exec("SELECT count(id) FROM autofill_exceptions WHERE server='" + server + "'");
query.next(); query.next();
if (query.value(0).toInt()>0) if (query.value(0).toInt() > 0) {
return false; return false;
}
return true; return true;
} }
void AutoFillModel::blockStoringfor (const QUrl &url) void AutoFillModel::blockStoringfor(const QUrl &url)
{ {
QString server = url.host(); QString server = url.host();
QSqlQuery query; QSqlQuery query;
query.exec("INSERT INTO autofill_exceptions (server) VALUES ('"+server+"')"); query.exec("INSERT INTO autofill_exceptions (server) VALUES ('" + server + "')");
} }
QString AutoFillModel::getUsername(const QUrl &url) QString AutoFillModel::getUsername(const QUrl &url)
{ {
QString server = url.host(); QString server = url.host();
QSqlQuery query; QSqlQuery query;
query.exec("SELECT username FROM autofill WHERE server='"+server+"'"); query.exec("SELECT username FROM autofill WHERE server='" + server + "'");
query.next(); query.next();
return query.value(0).toString(); return query.value(0).toString();
} }
@ -85,7 +89,7 @@ QString AutoFillModel::getPassword(const QUrl &url)
{ {
QString server = url.host(); QString server = url.host();
QSqlQuery query; QSqlQuery query;
query.exec("SELECT password FROM autofill WHERE server='"+server+"'"); query.exec("SELECT password FROM autofill WHERE server='" + server + "'");
query.next(); query.next();
return query.value(0).toString(); return query.value(0).toString();
} }
@ -94,9 +98,10 @@ QString AutoFillModel::getPassword(const QUrl &url)
bool AutoFillModel::addEntry(const QUrl &url, const QString &name, const QString &pass) bool AutoFillModel::addEntry(const QUrl &url, const QString &name, const QString &pass)
{ {
QSqlQuery query; QSqlQuery query;
query.exec("SELECT username FROM autofill WHERE server='"+url.host()+"'"); query.exec("SELECT username FROM autofill WHERE server='" + url.host() + "'");
if (query.next()) if (query.next()) {
return false; return false;
}
query.prepare("INSERT INTO autofill (server, username, password) VALUES (?,?,?)"); query.prepare("INSERT INTO autofill (server, username, password) VALUES (?,?,?)");
query.bindValue(0, url.host()); query.bindValue(0, url.host());
query.bindValue(1, name); query.bindValue(1, name);
@ -108,9 +113,10 @@ bool AutoFillModel::addEntry(const QUrl &url, const QString &name, const QString
bool AutoFillModel::addEntry(const QUrl &url, const QByteArray &data, const QString &pass) bool AutoFillModel::addEntry(const QUrl &url, const QByteArray &data, const QString &pass)
{ {
QSqlQuery query; QSqlQuery query;
query.exec("SELECT data FROM autofill WHERE server='"+url.host()+"'"); query.exec("SELECT data FROM autofill WHERE server='" + url.host() + "'");
if (query.next()) if (query.next()) {
return false; return false;
}
query.prepare("INSERT INTO autofill (server, data, password) VALUES (?,?,?)"); query.prepare("INSERT INTO autofill (server, data, password) VALUES (?,?,?)");
query.bindValue(0, url.host()); query.bindValue(0, url.host());
@ -121,8 +127,9 @@ bool AutoFillModel::addEntry(const QUrl &url, const QByteArray &data, const QStr
void AutoFillModel::completePage(WebView* view) void AutoFillModel::completePage(WebView* view)
{ {
if (!isStored(view->url())) if (!isStored(view->url())) {
return; return;
}
QWebElementCollection inputs; QWebElementCollection inputs;
QList<QWebFrame*> frames; QList<QWebFrame*> frames;
@ -134,26 +141,29 @@ void AutoFillModel::completePage(WebView* view)
} }
QSqlQuery query; QSqlQuery query;
query.exec("SELECT data FROM autofill WHERE server='"+view->url().host()+"'"); query.exec("SELECT data FROM autofill WHERE server='" + view->url().host() + "'");
query.next(); query.next();
QByteArray data = query.value(0).toByteArray(); QByteArray data = query.value(0).toByteArray();
if (data.isEmpty()) if (data.isEmpty()) {
return; return;
}
QList<QPair<QString, QString> > arguments = QUrl::fromEncoded(QByteArray("http://bla.com/?"+data)).queryItems(); QList<QPair<QString, QString> > arguments = QUrl::fromEncoded(QByteArray("http://bla.com/?" + data)).queryItems();
for (int i = 0; i<arguments.count(); i++) { for (int i = 0; i < arguments.count(); i++) {
QString key = QUrl::fromEncoded(arguments.at(i).first.toAscii()).toString(); QString key = QUrl::fromEncoded(arguments.at(i).first.toAscii()).toString();
QString value = QUrl::fromEncoded(arguments.at(i).second.toAscii()).toString(); QString value = QUrl::fromEncoded(arguments.at(i).second.toAscii()).toString();
//key.replace("+"," "); //key.replace("+"," ");
//value.replace("+"," "); //value.replace("+"," ");
for (int i = 0; i<inputs.count(); i++) { for (int i = 0; i < inputs.count(); i++) {
QWebElement element = inputs.at(i); QWebElement element = inputs.at(i);
if (element.attribute("type")!="text" && element.attribute("type")!="password" && element.attribute("type")!="") if (element.attribute("type") != "text" && element.attribute("type") != "password" && element.attribute("type") != "") {
continue; continue;
if (key == element.attribute("name")) }
element.setAttribute("value",value); if (key == element.attribute("name")) {
element.setAttribute("value", value);
}
} }
} }
} }
@ -161,8 +171,9 @@ void AutoFillModel::completePage(WebView* view)
void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgoingData) void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgoingData)
{ {
//Dont save in private browsing //Dont save in private browsing
if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
return; return;
}
m_lastOutgoingData = outgoingData; m_lastOutgoingData = outgoingData;
@ -170,14 +181,16 @@ void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgo
QWebPage* webPage = (QWebPage*)(v.value<void*>()); QWebPage* webPage = (QWebPage*)(v.value<void*>());
v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 102)); v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 102));
WebView* webView = (WebView*)(v.value<void*>()); WebView* webView = (WebView*)(v.value<void*>());
if (!webPage || !webView) if (!webPage || !webView) {
return; return;
}
v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101)); v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101));
QWebPage::NavigationType type = (QWebPage::NavigationType)v.toInt(); QWebPage::NavigationType type = (QWebPage::NavigationType)v.toInt();
if (type!=QWebPage::NavigationTypeFormSubmitted) if (type != QWebPage::NavigationTypeFormSubmitted) {
return; return;
}
QString passwordName = ""; QString passwordName = "";
QString passwordValue = ""; QString passwordValue = "";
@ -192,20 +205,23 @@ void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgo
frames += frame->childFrames(); frames += frame->childFrames();
} }
foreach (QWebElement element, inputs) { foreach(QWebElement element, inputs) {
passwordName = element.attribute("name"); passwordName = element.attribute("name");
passwordValue = element.evaluateJavaScript("this.value").toString(); passwordValue = element.evaluateJavaScript("this.value").toString();
if (!passwordValue.isEmpty()) if (!passwordValue.isEmpty()) {
break; break;
}
} }
//Return if storing is not enabled, data for this page is already stored, no password element found in sent data //Return if storing is not enabled, data for this page is already stored, no password element found in sent data
if (passwordName.isEmpty() || !isStoringEnabled(siteUrl) || isStored(siteUrl)) if (passwordName.isEmpty() || !isStoringEnabled(siteUrl) || isStored(siteUrl)) {
return; return;
}
//Return if no password form has been sent //Return if no password form has been sent
if (!outgoingData.contains((QUrl(passwordName).toEncoded() + "=")) || passwordValue.isEmpty()) if (!outgoingData.contains((QUrl(passwordName).toEncoded() + "=")) || passwordValue.isEmpty()) {
return; return;
}
AutoFillNotification* aWidget = new AutoFillNotification(siteUrl, outgoingData, passwordValue); AutoFillNotification* aWidget = new AutoFillNotification(siteUrl, outgoingData, passwordValue);
webView->addNotification(aWidget); webView->addNotification(aWidget);

View File

@ -33,7 +33,7 @@ public:
bool isStored(const QUrl &url); bool isStored(const QUrl &url);
bool isStoringEnabled(const QUrl &url); bool isStoringEnabled(const QUrl &url);
void blockStoringfor (const QUrl &url); void blockStoringfor(const QUrl &url);
QString getUsername(const QUrl &url); QString getUsername(const QUrl &url);
QString getPassword(const QUrl &url); QString getPassword(const QUrl &url);

View File

@ -23,11 +23,11 @@
#include "iconprovider.h" #include "iconprovider.h"
AutoFillNotification::AutoFillNotification(QUrl url, QByteArray data, QString pass, QWidget* parent) AutoFillNotification::AutoFillNotification(QUrl url, QByteArray data, QString pass, QWidget* parent)
:AnimatedWidget(AnimatedWidget::Down, 300, parent) : AnimatedWidget(AnimatedWidget::Down, 300, parent)
,ui(new Ui::AutoFillWidget) , ui(new Ui::AutoFillWidget)
,m_url(url) , m_url(url)
,m_data(data) , m_data(data)
,m_pass(pass) , m_pass(pass)
{ {
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
ui->setupUi(widget()); ui->setupUi(widget());

View File

@ -25,8 +25,9 @@
#include "animatedwidget.h" #include "animatedwidget.h"
namespace Ui { namespace Ui
class AutoFillWidget; {
class AutoFillWidget;
} }
class AnimatedWidget; class AnimatedWidget;
class AutoFillNotification : public AnimatedWidget class AutoFillNotification : public AnimatedWidget

View File

@ -44,33 +44,40 @@ void BookmarkIcon::iconClicked()
if (m_bookmarksModel->isBookmarked(url)) { if (m_bookmarksModel->isBookmarked(url)) {
BookmarksWidget* menu = new BookmarksWidget(m_bookmarksModel->bookmarkId(url), p_QupZilla->locationBar()); BookmarksWidget* menu = new BookmarksWidget(m_bookmarksModel->bookmarkId(url), p_QupZilla->locationBar());
menu->showAt(this); menu->showAt(this);
} else }
else {
m_bookmarksModel->saveBookmark(p_QupZilla->weView()); m_bookmarksModel->saveBookmark(p_QupZilla->weView());
}
} }
void BookmarkIcon::checkBookmark(const QUrl &url) void BookmarkIcon::checkBookmark(const QUrl &url)
{ {
if (m_lastUrl == url) if (m_lastUrl == url) {
return; return;
}
if (m_bookmarksModel->isBookmarked(url)) if (m_bookmarksModel->isBookmarked(url)) {
setBookmarkSaved(); setBookmarkSaved();
else }
else {
setBookmarkDisabled(); setBookmarkDisabled();
}
m_lastUrl = url; m_lastUrl = url;
} }
void BookmarkIcon::bookmarkDeleted(const BookmarksModel::Bookmark &bookmark) void BookmarkIcon::bookmarkDeleted(const BookmarksModel::Bookmark &bookmark)
{ {
if (bookmark.url == m_lastUrl) if (bookmark.url == m_lastUrl) {
setBookmarkDisabled(); setBookmarkDisabled();
}
} }
void BookmarkIcon::bookmarkAdded(const BookmarksModel::Bookmark &bookmark) void BookmarkIcon::bookmarkAdded(const BookmarksModel::Bookmark &bookmark)
{ {
if (bookmark.url == m_lastUrl) if (bookmark.url == m_lastUrl) {
setBookmarkSaved(); setBookmarkSaved();
}
} }
void BookmarkIcon::setBookmarkSaved() void BookmarkIcon::setBookmarkSaved()

View File

@ -40,7 +40,7 @@ BookmarksManager::BookmarksManager(QupZilla* mainClass, QWidget* parent)
ui->deleteB->setShortcut(QKeySequence("Del")); ui->deleteB->setShortcut(QKeySequence("Del"));
connect(ui->deleteB, SIGNAL(clicked()), this, SLOT(deleteItem())); connect(ui->deleteB, SIGNAL(clicked()), this, SLOT(deleteItem()));
connect(ui->bookmarksTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(itemChanged(QTreeWidgetItem*))); connect(ui->bookmarksTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(itemChanged(QTreeWidgetItem*)));
connect(ui->addSubfolder, SIGNAL(clicked()), this, SLOT(addSubfolder())); connect(ui->addSubfolder, SIGNAL(clicked()), this, SLOT(addSubfolder()));
connect(ui->addFolder, SIGNAL(clicked()), this, SLOT(addFolder())); connect(ui->addFolder, SIGNAL(clicked()), this, SLOT(addFolder()));
connect(ui->renameFolder, SIGNAL(clicked()), this, SLOT(renameFolder())); connect(ui->renameFolder, SIGNAL(clicked()), this, SLOT(renameFolder()));
@ -50,11 +50,11 @@ BookmarksManager::BookmarksManager(QupZilla* mainClass, QWidget* parent)
connect(m_bookmarksModel, SIGNAL(bookmarkAdded(BookmarksModel::Bookmark)), this, SLOT(addBookmark(BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkAdded(BookmarksModel::Bookmark)), this, SLOT(addBookmark(BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(bookmarkDeleted(BookmarksModel::Bookmark)), this, SLOT(removeBookmark(BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkDeleted(BookmarksModel::Bookmark)), this, SLOT(removeBookmark(BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(bookmarkEdited(BookmarksModel::Bookmark,BookmarksModel::Bookmark)), this, SLOT(bookmarkEdited(BookmarksModel::Bookmark,BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkEdited(BookmarksModel::Bookmark, BookmarksModel::Bookmark)), this, SLOT(bookmarkEdited(BookmarksModel::Bookmark, BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(subfolderAdded(QString)), this, SLOT(addSubfolder(QString))); connect(m_bookmarksModel, SIGNAL(subfolderAdded(QString)), this, SLOT(addSubfolder(QString)));
connect(m_bookmarksModel, SIGNAL(folderAdded(QString)), this, SLOT(addFolder(QString))); connect(m_bookmarksModel, SIGNAL(folderAdded(QString)), this, SLOT(addFolder(QString)));
connect(m_bookmarksModel, SIGNAL(folderDeleted(QString)), this, SLOT(removeFolder(QString))); connect(m_bookmarksModel, SIGNAL(folderDeleted(QString)), this, SLOT(removeFolder(QString)));
connect(m_bookmarksModel, SIGNAL(folderRenamed(QString,QString)), this, SLOT(renameFolder(QString,QString))); connect(m_bookmarksModel, SIGNAL(folderRenamed(QString, QString)), this, SLOT(renameFolder(QString, QString)));
connect(ui->optimizeDb, SIGNAL(clicked(QPoint)), this, SLOT(optimizeDb())); connect(ui->optimizeDb, SIGNAL(clicked(QPoint)), this, SLOT(optimizeDb()));
@ -70,22 +70,25 @@ void BookmarksManager::search(const QString &string)
QupZilla* BookmarksManager::getQupZilla() QupZilla* BookmarksManager::getQupZilla()
{ {
if (!p_QupZilla) if (!p_QupZilla) {
p_QupZilla = mApp->getWindow(); p_QupZilla = mApp->getWindow();
}
return p_QupZilla; return p_QupZilla;
} }
void BookmarksManager::setMainWindow(QupZilla* window) void BookmarksManager::setMainWindow(QupZilla* window)
{ {
if (window) if (window) {
p_QupZilla = window; p_QupZilla = window;
}
} }
void BookmarksManager::addFolder() void BookmarksManager::addFolder()
{ {
QString text = QInputDialog::getText(this, tr("Add new folder"), tr("Choose name for new bookmark folder: ")); QString text = QInputDialog::getText(this, tr("Add new folder"), tr("Choose name for new bookmark folder: "));
if (text.isEmpty()) if (text.isEmpty()) {
return; return;
}
m_bookmarksModel->createFolder(text); m_bookmarksModel->createFolder(text);
} }
@ -93,8 +96,9 @@ void BookmarksManager::addFolder()
void BookmarksManager::addSubfolder() void BookmarksManager::addSubfolder()
{ {
QString text = QInputDialog::getText(this, tr("Add new subfolder"), tr("Choose name for new subfolder in bookmarks toolbar: ")); QString text = QInputDialog::getText(this, tr("Add new subfolder"), tr("Choose name for new subfolder in bookmarks toolbar: "));
if (text.isEmpty()) if (text.isEmpty()) {
return; return;
}
m_bookmarksModel->createSubfolder(text); m_bookmarksModel->createSubfolder(text);
} }
@ -102,28 +106,33 @@ void BookmarksManager::addSubfolder()
void BookmarksManager::renameFolder() void BookmarksManager::renameFolder()
{ {
QTreeWidgetItem* item = ui->bookmarksTree->currentItem(); QTreeWidgetItem* item = ui->bookmarksTree->currentItem();
if (!item) if (!item) {
return; return;
}
if (!item->text(1).isEmpty()) if (!item->text(1).isEmpty()) {
return; return;
}
QString folder = item->text(0); QString folder = item->text(0);
if (folder == tr("Bookmarks In Menu") || folder == tr("Bookmarks In ToolBar")) if (folder == tr("Bookmarks In Menu") || folder == tr("Bookmarks In ToolBar")) {
return; return;
}
QString text = QInputDialog::getText(this, tr("Rename Folder"), tr("Choose name for folder: "), QLineEdit::Normal, folder); QString text = QInputDialog::getText(this, tr("Rename Folder"), tr("Choose name for folder: "), QLineEdit::Normal, folder);
if (text.isEmpty()) if (text.isEmpty()) {
return; return;
}
m_bookmarksModel->renameFolder(folder, text); m_bookmarksModel->renameFolder(folder, text);
} }
void BookmarksManager::itemChanged(QTreeWidgetItem* item) void BookmarksManager::itemChanged(QTreeWidgetItem* item)
{ {
if (!item || m_isRefreshing || item->text(1).isEmpty()) if (!item || m_isRefreshing || item->text(1).isEmpty()) {
return; return;
}
QString name = item->text(0); QString name = item->text(0);
QUrl url = QUrl(item->text(1)); QUrl url = QUrl(item->text(1));
@ -135,22 +144,25 @@ void BookmarksManager::itemChanged(QTreeWidgetItem* item)
void BookmarksManager::itemControlClicked(QTreeWidgetItem* item) void BookmarksManager::itemControlClicked(QTreeWidgetItem* item)
{ {
if (!item || item->text(1).isEmpty()) if (!item || item->text(1).isEmpty()) {
return; return;
}
getQupZilla()->tabWidget()->addView(QUrl(item->text(1))); getQupZilla()->tabWidget()->addView(QUrl(item->text(1)));
} }
void BookmarksManager::loadInNewTab() void BookmarksManager::loadInNewTab()
{ {
if (QAction* action = qobject_cast<QAction*>(sender())) if (QAction* action = qobject_cast<QAction*>(sender())) {
getQupZilla()->tabWidget()->addView(action->data().toUrl(), tr("New Tab"), TabWidget::NewNotSelectedTab); getQupZilla()->tabWidget()->addView(action->data().toUrl(), tr("New Tab"), TabWidget::NewNotSelectedTab);
}
} }
void BookmarksManager::deleteItem() void BookmarksManager::deleteItem()
{ {
QTreeWidgetItem* item = ui->bookmarksTree->currentItem(); QTreeWidgetItem* item = ui->bookmarksTree->currentItem();
if (!item) if (!item) {
return; return;
}
if (item->text(1).isEmpty()) { // Delete folder if (item->text(1).isEmpty()) { // Delete folder
QString folder = item->text(0); QString folder = item->text(0);
@ -170,8 +182,9 @@ void BookmarksManager::addBookmark(WebView* view)
void BookmarksManager::moveBookmark() void BookmarksManager::moveBookmark()
{ {
QTreeWidgetItem* item = ui->bookmarksTree->currentItem(); QTreeWidgetItem* item = ui->bookmarksTree->currentItem();
if (!item) if (!item) {
return; return;
}
if (QAction* action = qobject_cast<QAction*>(sender())) { if (QAction* action = qobject_cast<QAction*>(sender())) {
m_bookmarksModel->editBookmark(item->whatsThis(1).toInt(), item->text(0), QUrl(), action->data().toString()); m_bookmarksModel->editBookmark(item->whatsThis(1).toInt(), item->text(0), QUrl(), action->data().toString());
} }
@ -179,11 +192,13 @@ void BookmarksManager::moveBookmark()
void BookmarksManager::contextMenuRequested(const QPoint &position) void BookmarksManager::contextMenuRequested(const QPoint &position)
{ {
if (!ui->bookmarksTree->itemAt(position)) if (!ui->bookmarksTree->itemAt(position)) {
return; return;
}
QString link = ui->bookmarksTree->itemAt(position)->text(1); QString link = ui->bookmarksTree->itemAt(position)->text(1);
if (link.isEmpty()) if (link.isEmpty()) {
return; return;
}
QMenu menu; QMenu menu;
menu.addAction(tr("Open link in actual &tab"), getQupZilla(), SLOT(loadActionUrl()))->setData(link); menu.addAction(tr("Open link in actual &tab"), getQupZilla(), SLOT(loadActionUrl()))->setData(link);
@ -197,13 +212,14 @@ void BookmarksManager::contextMenuRequested(const QPoint &position)
moveMenu.addAction(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"), this, SLOT(moveBookmark()))->setData("bookmarksToolbar"); moveMenu.addAction(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"), this, SLOT(moveBookmark()))->setData("bookmarksToolbar");
QSqlQuery query; QSqlQuery query;
query.exec("SELECT name FROM folders"); query.exec("SELECT name FROM folders");
while(query.next()) while (query.next()) {
moveMenu.addAction(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString(), this, SLOT(moveBookmark()))->setData(query.value(0).toString()); moveMenu.addAction(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString(), this, SLOT(moveBookmark()))->setData(query.value(0).toString());
}
menu.addMenu(&moveMenu); menu.addMenu(&moveMenu);
//Prevent choosing first option with double rightclick //Prevent choosing first option with double rightclick
QPoint pos = QCursor::pos(); QPoint pos = QCursor::pos();
QPoint p(pos.x(), pos.y()+1); QPoint p(pos.x(), pos.y() + 1);
menu.exec(p); menu.exec(p);
} }
@ -225,7 +241,7 @@ void BookmarksManager::refreshTable()
ui->bookmarksTree->addTopLevelItem(bookmarksToolbar); ui->bookmarksTree->addTopLevelItem(bookmarksToolbar);
query.exec("SELECT name FROM folders WHERE subfolder!='yes'"); query.exec("SELECT name FROM folders WHERE subfolder!='yes'");
while(query.next()) { while (query.next()) {
newItem = new QTreeWidgetItem(ui->bookmarksTree); newItem = new QTreeWidgetItem(ui->bookmarksTree);
newItem->setText(0, query.value(0).toString()); newItem->setText(0, query.value(0).toString());
newItem->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon)); newItem->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon));
@ -233,22 +249,25 @@ void BookmarksManager::refreshTable()
} }
query.exec("SELECT title, url, id, folder, icon FROM bookmarks"); query.exec("SELECT title, url, id, folder, icon FROM bookmarks");
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
int id = query.value(2).toInt(); int id = query.value(2).toInt();
QString folder = query.value(3).toString(); QString folder = query.value(3).toString();
QIcon icon = IconProvider::iconFromBase64(query.value(4).toByteArray()); QIcon icon = IconProvider::iconFromBase64(query.value(4).toByteArray());
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
if (folder == "bookmarksMenu") if (folder == "bookmarksMenu") {
folder = tr("Bookmarks In Menu"); folder = tr("Bookmarks In Menu");
if (folder == "bookmarksToolbar") }
if (folder == "bookmarksToolbar") {
folder = tr("Bookmarks In ToolBar"); folder = tr("Bookmarks In ToolBar");
}
if (folder != "unsorted") { if (folder != "unsorted") {
QList<QTreeWidgetItem*> findParent = ui->bookmarksTree->findItems(folder, 0); QList<QTreeWidgetItem*> findParent = ui->bookmarksTree->findItems(folder, 0);
if (findParent.count() != 1) if (findParent.count() != 1) {
continue; continue;
}
findParent.at(0)->addChild(item); findParent.at(0)->addChild(item);
} }
@ -264,7 +283,7 @@ void BookmarksManager::refreshTable()
} }
query.exec("SELECT name FROM folders WHERE subfolder='yes'"); query.exec("SELECT name FROM folders WHERE subfolder='yes'");
while(query.next()) { while (query.next()) {
newItem = new QTreeWidgetItem(bookmarksToolbar); newItem = new QTreeWidgetItem(bookmarksToolbar);
newItem->setText(0, query.value(0).toString()); newItem->setText(0, query.value(0).toString());
newItem->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon)); newItem->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon));
@ -273,7 +292,7 @@ void BookmarksManager::refreshTable()
query2.prepare("SELECT title, url, id, icon FROM bookmarks WHERE folder=?"); query2.prepare("SELECT title, url, id, icon FROM bookmarks WHERE folder=?");
query2.addBindValue(query.value(0).toString()); query2.addBindValue(query.value(0).toString());
query2.exec(); query2.exec();
while(query2.next()) { while (query2.next()) {
QString title = query2.value(0).toString(); QString title = query2.value(0).toString();
QUrl url = query2.value(1).toUrl(); QUrl url = query2.value(1).toUrl();
int id = query2.value(2).toInt(); int id = query2.value(2).toInt();
@ -313,7 +332,7 @@ void BookmarksManager::addBookmark(const BookmarksModel::Bookmark &bookmark)
if (bookmark.inSubfolder) { if (bookmark.inSubfolder) {
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.folder, Qt::MatchExactly | Qt::MatchRecursive); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.folder, Qt::MatchExactly | Qt::MatchRecursive);
if (list.count() != 0) { if (list.count() != 0) {
foreach (QTreeWidgetItem* it, list) { foreach(QTreeWidgetItem * it, list) {
if (it->text(1).isEmpty()) { if (it->text(1).isEmpty()) {
it->addChild(item); it->addChild(item);
break; break;
@ -321,10 +340,12 @@ void BookmarksManager::addBookmark(const BookmarksModel::Bookmark &bookmark)
} }
} }
} }
else if (bookmark.folder != "unsorted") else if (bookmark.folder != "unsorted") {
ui->bookmarksTree->appendToParentItem(translatedFolder, item); ui->bookmarksTree->appendToParentItem(translatedFolder, item);
else }
else {
ui->bookmarksTree->addTopLevelItem(item); ui->bookmarksTree->addTopLevelItem(item);
}
m_isRefreshing = false; m_isRefreshing = false;
} }
@ -336,20 +357,22 @@ void BookmarksManager::removeBookmark(const BookmarksModel::Bookmark &bookmark)
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.folder, Qt::MatchExactly | Qt::MatchRecursive); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.folder, Qt::MatchExactly | Qt::MatchRecursive);
QTreeWidgetItem* subfolderItem = 0; QTreeWidgetItem* subfolderItem = 0;
if (list.count() != 0) { if (list.count() != 0) {
foreach (QTreeWidgetItem* it, list) { foreach(QTreeWidgetItem * it, list) {
if (it->text(1).isEmpty()) { if (it->text(1).isEmpty()) {
subfolderItem = it; subfolderItem = it;
break; break;
} }
} }
} }
if (!subfolderItem) if (!subfolderItem) {
return; return;
}
for (int i = 0; i < subfolderItem->childCount(); i++) { for (int i = 0; i < subfolderItem->childCount(); i++) {
QTreeWidgetItem* item = subfolderItem->child(i); QTreeWidgetItem* item = subfolderItem->child(i);
if (!item) if (!item) {
continue; continue;
}
if (item->text(0) == bookmark.title && item->whatsThis(1) == QString::number(bookmark.id)) { if (item->text(0) == bookmark.title && item->whatsThis(1) == QString::number(bookmark.id)) {
ui->bookmarksTree->deleteItem(item); ui->bookmarksTree->deleteItem(item);
return; return;
@ -358,23 +381,28 @@ void BookmarksManager::removeBookmark(const BookmarksModel::Bookmark &bookmark)
} }
else if (bookmark.folder == "unsorted") { else if (bookmark.folder == "unsorted") {
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.title, Qt::MatchExactly); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(bookmark.title, Qt::MatchExactly);
if (list.count() == 0) if (list.count() == 0) {
return; return;
}
QTreeWidgetItem* item = list.at(0); QTreeWidgetItem* item = list.at(0);
if (item && item->whatsThis(1) == QString::number(bookmark.id)) if (item && item->whatsThis(1) == QString::number(bookmark.id)) {
ui->bookmarksTree->deleteItem(item); ui->bookmarksTree->deleteItem(item);
}
} }
else { else {
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(BookmarksModel::toTranslatedFolder(bookmark.folder), Qt::MatchExactly); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(BookmarksModel::toTranslatedFolder(bookmark.folder), Qt::MatchExactly);
if (list.count() == 0) if (list.count() == 0) {
return; return;
}
QTreeWidgetItem* parentItem = list.at(0); QTreeWidgetItem* parentItem = list.at(0);
if (!parentItem) if (!parentItem) {
return; return;
}
for (int i = 0; i < parentItem->childCount(); i++) { for (int i = 0; i < parentItem->childCount(); i++) {
QTreeWidgetItem* item = parentItem->child(i); QTreeWidgetItem* item = parentItem->child(i);
if (!item) if (!item) {
continue; continue;
}
if (item->text(0) == bookmark.title && item->whatsThis(1) == QString::number(bookmark.id)) { if (item->text(0) == bookmark.title && item->whatsThis(1) == QString::number(bookmark.id)) {
ui->bookmarksTree->deleteItem(item); ui->bookmarksTree->deleteItem(item);
return; return;
@ -418,20 +446,22 @@ void BookmarksManager::addSubfolder(const QString &name)
void BookmarksManager::removeFolder(const QString &name) void BookmarksManager::removeFolder(const QString &name)
{ {
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(name, Qt::MatchExactly | Qt::MatchRecursive); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(name, Qt::MatchExactly | Qt::MatchRecursive);
if (list.count() == 0) if (list.count() == 0) {
return; return;
}
QTreeWidgetItem* folderItem = 0; QTreeWidgetItem* folderItem = 0;
if (list.count() != 0) { if (list.count() != 0) {
foreach (QTreeWidgetItem* it, list) { foreach(QTreeWidgetItem * it, list) {
if (it->text(1).isEmpty()) { if (it->text(1).isEmpty()) {
folderItem = it; folderItem = it;
break; break;
} }
} }
} }
if (!folderItem) if (!folderItem) {
return; return;
}
ui->bookmarksTree->deleteItem(folderItem); ui->bookmarksTree->deleteItem(folderItem);
} }
@ -439,28 +469,31 @@ void BookmarksManager::removeFolder(const QString &name)
void BookmarksManager::renameFolder(const QString &before, const QString &after) void BookmarksManager::renameFolder(const QString &before, const QString &after)
{ {
QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(before, Qt::MatchExactly | Qt::MatchRecursive); QList<QTreeWidgetItem*> list = ui->bookmarksTree->findItems(before, Qt::MatchExactly | Qt::MatchRecursive);
if (list.count() == 0) if (list.count() == 0) {
return; return;
}
QTreeWidgetItem* folderItem = 0; QTreeWidgetItem* folderItem = 0;
if (list.count() != 0) { if (list.count() != 0) {
foreach (QTreeWidgetItem* it, list) { foreach(QTreeWidgetItem * it, list) {
if (it->text(0) == before && it->text(1).isEmpty()) { if (it->text(0) == before && it->text(1).isEmpty()) {
folderItem = it; folderItem = it;
break; break;
} }
} }
} }
if (!folderItem) if (!folderItem) {
return; return;
}
folderItem->setText(0, after); folderItem->setText(0, after);
} }
void BookmarksManager::insertBookmark(const QUrl &url, const QString &title, const QIcon &icon) void BookmarksManager::insertBookmark(const QUrl &url, const QString &title, const QIcon &icon)
{ {
if (url.isEmpty() || title.isEmpty()) if (url.isEmpty() || title.isEmpty()) {
return; return;
}
QDialog* dialog = new QDialog(getQupZilla()); QDialog* dialog = new QDialog(getQupZilla());
QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, dialog); QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, dialog);
QLabel* label = new QLabel(dialog); QLabel* label = new QLabel(dialog);
@ -474,8 +507,9 @@ void BookmarksManager::insertBookmark(const QUrl &url, const QString &title, con
layout->addWidget(label); layout->addWidget(label);
layout->addWidget(edit); layout->addWidget(edit);
layout->addWidget(combo); layout->addWidget(combo);
if (m_bookmarksModel->isBookmarked(url)) if (m_bookmarksModel->isBookmarked(url)) {
layout->addWidget(new QLabel(tr("<b>Warning: </b>You already have this page bookmarked!"))); layout->addWidget(new QLabel(tr("<b>Warning: </b>You already have this page bookmarked!")));
}
layout->addWidget(box); layout->addWidget(box);
combo->addItem(QIcon(":icons/other/unsortedbookmarks.png"), tr("Unsorted Bookmarks")); combo->addItem(QIcon(":icons/other/unsortedbookmarks.png"), tr("Unsorted Bookmarks"));
@ -483,8 +517,9 @@ void BookmarksManager::insertBookmark(const QUrl &url, const QString &title, con
combo->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar")); combo->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"));
QSqlQuery query; QSqlQuery query;
query.exec("SELECT name FROM folders"); query.exec("SELECT name FROM folders");
while(query.next()) while (query.next()) {
combo->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString()); combo->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString());
}
label->setText(tr("Choose name and location of bookmark.")); label->setText(tr("Choose name and location of bookmark."));
edit->setText(title); edit->setText(title);
@ -496,10 +531,12 @@ void BookmarksManager::insertBookmark(const QUrl &url, const QString &title, con
size.setWidth(350); size.setWidth(350);
dialog->resize(size); dialog->resize(size);
dialog->exec(); dialog->exec();
if (dialog->result() == QDialog::Rejected) if (dialog->result() == QDialog::Rejected) {
return; return;
if (edit->text().isEmpty()) }
if (edit->text().isEmpty()) {
return; return;
}
m_bookmarksModel->saveBookmark(url, edit->text(), icon, BookmarksModel::fromTranslatedFolder(combo->currentText())); m_bookmarksModel->saveBookmark(url, edit->text(), icon, BookmarksModel::fromTranslatedFolder(combo->currentText()));
delete dialog; delete dialog;
@ -525,8 +562,9 @@ void BookmarksManager::insertAllTabs()
combo->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar")); combo->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"));
QSqlQuery query; QSqlQuery query;
query.exec("SELECT name FROM folders"); query.exec("SELECT name FROM folders");
while(query.next()) while (query.next()) {
combo->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString()); combo->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString());
}
label->setText(tr("Choose folder for bookmarks:")); label->setText(tr("Choose folder for bookmarks:"));
dialog->setWindowTitle(tr("Bookmark All Tabs")); dialog->setWindowTitle(tr("Bookmark All Tabs"));
@ -535,15 +573,17 @@ void BookmarksManager::insertAllTabs()
size.setWidth(350); size.setWidth(350);
dialog->resize(size); dialog->resize(size);
dialog->exec(); dialog->exec();
if (dialog->result() == QDialog::Rejected) if (dialog->result() == QDialog::Rejected) {
return; return;
}
foreach (WebTab* tab, getQupZilla()->tabWidget()->allTabs(false)) { foreach(WebTab * tab, getQupZilla()->tabWidget()->allTabs(false)) {
WebView* view = tab->view(); WebView* view = tab->view();
if (view->url().isEmpty()) if (view->url().isEmpty()) {
continue; continue;
}
m_bookmarksModel->saveBookmark(view->url(), view->title(), view->siteIcon(),BookmarksModel::fromTranslatedFolder(combo->currentText())); m_bookmarksModel->saveBookmark(view->url(), view->title(), view->siteIcon(), BookmarksModel::fromTranslatedFolder(combo->currentText()));
} }
delete dialog; delete dialog;
@ -552,8 +592,9 @@ void BookmarksManager::insertAllTabs()
void BookmarksManager::optimizeDb() void BookmarksManager::optimizeDb()
{ {
BrowsingLibrary* b = qobject_cast<BrowsingLibrary*>(parentWidget()->parentWidget()); BrowsingLibrary* b = qobject_cast<BrowsingLibrary*>(parentWidget()->parentWidget());
if (!b) if (!b) {
return; return;
}
b->optimizeDatabase(); b->optimizeDatabase();
} }

View File

@ -26,8 +26,9 @@
#include "bookmarksmodel.h" #include "bookmarksmodel.h"
namespace Ui { namespace Ui
class BookmarksManager; {
class BookmarksManager;
} }
class WebView; class WebView;

View File

@ -25,7 +25,7 @@
// However from bookmark icon, it is not possible to add more than one bookmark // However from bookmark icon, it is not possible to add more than one bookmark
// Only from Ctrl+D dialog it is possible // Only from Ctrl+D dialog it is possible
BookmarksModel::BookmarksModel(QObject *parent) BookmarksModel::BookmarksModel(QObject* parent)
: QObject(parent) : QObject(parent)
{ {
loadSettings(); loadSettings();
@ -33,17 +33,17 @@ BookmarksModel::BookmarksModel(QObject *parent)
void BookmarksModel::loadSettings() void BookmarksModel::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
m_showMostVisited = settings.value("showMostVisited",true).toBool(); m_showMostVisited = settings.value("showMostVisited", true).toBool();
settings.endGroup(); settings.endGroup();
} }
void BookmarksModel::setShowingMostVisited(bool state) void BookmarksModel::setShowingMostVisited(bool state)
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
settings.setValue("showMostVisited",state); settings.setValue("showMostVisited", state);
settings.endGroup(); settings.endGroup();
m_showMostVisited = state; m_showMostVisited = state;
} }
@ -55,7 +55,7 @@ bool BookmarksModel::isBookmarked(const QUrl &url)
query.bindValue(0, url.toString()); query.bindValue(0, url.toString());
query.exec(); query.exec();
query.next(); query.next();
return query.value(0).toInt()>0; return query.value(0).toInt() > 0;
} }
// Bookmark search priority: // Bookmark search priority:
@ -66,20 +66,23 @@ int BookmarksModel::bookmarkId(const QUrl &url)
query.prepare("SELECT id FROM bookmarks WHERE url=? AND folder='bookmarksMenu' "); query.prepare("SELECT id FROM bookmarks WHERE url=? AND folder='bookmarksMenu' ");
query.bindValue(0, url.toString()); query.bindValue(0, url.toString());
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return query.value(0).toInt(); return query.value(0).toInt();
}
query.prepare("SELECT id FROM bookmarks WHERE url=? AND folder='bookmarksToolbar' "); query.prepare("SELECT id FROM bookmarks WHERE url=? AND folder='bookmarksToolbar' ");
query.bindValue(0, url.toString()); query.bindValue(0, url.toString());
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return query.value(0).toInt(); return query.value(0).toInt();
}
query.prepare("SELECT id FROM bookmarks WHERE url=? "); query.prepare("SELECT id FROM bookmarks WHERE url=? ");
query.bindValue(0, url.toString()); query.bindValue(0, url.toString());
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return query.value(0).toInt(); return query.value(0).toInt();
}
return -1; return -1;
} }
@ -92,8 +95,9 @@ int BookmarksModel::bookmarkId(const QUrl &url, const QString &title, const QStr
query.bindValue(1, title); query.bindValue(1, title);
query.bindValue(2, folder); query.bindValue(2, folder);
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return query.value(0).toInt(); return query.value(0).toInt();
}
return -1; return -1;
} }
@ -117,8 +121,9 @@ BookmarksModel::Bookmark BookmarksModel::getBookmark(int id)
bool BookmarksModel::saveBookmark(const QUrl &url, const QString &title, const QIcon &icon, const QString &folder) bool BookmarksModel::saveBookmark(const QUrl &url, const QString &title, const QIcon &icon, const QString &folder)
{ {
if (url.isEmpty() || title.isEmpty() || folder.isEmpty()) if (url.isEmpty() || title.isEmpty() || folder.isEmpty()) {
return false; return false;
}
QSqlQuery query; QSqlQuery query;
query.prepare("INSERT INTO bookmarks (url, title, folder, icon) VALUES (?,?,?,?)"); query.prepare("INSERT INTO bookmarks (url, title, folder, icon) VALUES (?,?,?,?)");
@ -127,8 +132,9 @@ bool BookmarksModel::saveBookmark(const QUrl &url, const QString &title, const Q
query.bindValue(2, folder); query.bindValue(2, folder);
query.bindValue(3, IconProvider::iconToBase64(icon)); query.bindValue(3, IconProvider::iconToBase64(icon));
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
Bookmark bookmark; Bookmark bookmark;
bookmark.id = query.lastInsertId().toInt(); bookmark.id = query.lastInsertId().toInt();
@ -143,7 +149,7 @@ bool BookmarksModel::saveBookmark(const QUrl &url, const QString &title, const Q
return true; return true;
} }
bool BookmarksModel::saveBookmark(WebView *view, const QString &folder) bool BookmarksModel::saveBookmark(WebView* view, const QString &folder)
{ {
return saveBookmark(view->url(), view->title(), view->siteIcon(), folder); return saveBookmark(view->url(), view->title(), view->siteIcon(), folder);
} }
@ -154,8 +160,9 @@ bool BookmarksModel::removeBookmark(int id)
query.prepare("SELECT url, title, folder FROM bookmarks WHERE id = ?"); query.prepare("SELECT url, title, folder FROM bookmarks WHERE id = ?");
query.bindValue(0, id); query.bindValue(0, id);
query.exec(); query.exec();
if (!query.next()) if (!query.next()) {
return false; return false;
}
Bookmark bookmark; Bookmark bookmark;
bookmark.id = id; bookmark.id = id;
@ -165,8 +172,9 @@ bool BookmarksModel::removeBookmark(int id)
bookmark.icon = IconProvider::iconFromBase64(query.value(3).toByteArray()); bookmark.icon = IconProvider::iconFromBase64(query.value(3).toByteArray());
bookmark.inSubfolder = isSubfolder(bookmark.folder); bookmark.inSubfolder = isSubfolder(bookmark.folder);
if (!query.exec("DELETE FROM bookmarks WHERE id = " + QString::number(id))) if (!query.exec("DELETE FROM bookmarks WHERE id = " + QString::number(id))) {
return false; return false;
}
emit bookmarkDeleted(bookmark); emit bookmarkDeleted(bookmark);
mApp->sendMessages(MainApplication::BookmarksChanged, true); mApp->sendMessages(MainApplication::BookmarksChanged, true);
@ -205,11 +213,13 @@ bool BookmarksModel::removeBookmark(WebView* view)
bool BookmarksModel::editBookmark(int id, const QString &title, const QUrl &url, const QString &folder) bool BookmarksModel::editBookmark(int id, const QString &title, const QUrl &url, const QString &folder)
{ {
if (title.isEmpty() && url.isEmpty() && folder.isEmpty()) if (title.isEmpty() && url.isEmpty() && folder.isEmpty()) {
return false; return false;
}
QSqlQuery query; QSqlQuery query;
if (!query.exec("SELECT title, url, folder, icon FROM bookmarks WHERE id = "+QString::number(id))) if (!query.exec("SELECT title, url, folder, icon FROM bookmarks WHERE id = " + QString::number(id))) {
return false; return false;
}
query.next(); query.next();
@ -235,8 +245,9 @@ bool BookmarksModel::editBookmark(int id, const QString &title, const QUrl &url,
query.bindValue(2, after.folder); query.bindValue(2, after.folder);
query.bindValue(3, id); query.bindValue(3, id);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
emit bookmarkEdited(before, after); emit bookmarkEdited(before, after);
mApp->sendMessages(MainApplication::BookmarksChanged, true); mApp->sendMessages(MainApplication::BookmarksChanged, true);
@ -249,13 +260,15 @@ bool BookmarksModel::createFolder(const QString &name)
query.prepare("SELECT name FROM folders WHERE name = ?"); query.prepare("SELECT name FROM folders WHERE name = ?");
query.bindValue(0, name); query.bindValue(0, name);
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return false; return false;
}
query.prepare("INSERT INTO folders (name, subfolder) VALUES (?, 'no')"); query.prepare("INSERT INTO folders (name, subfolder) VALUES (?, 'no')");
query.bindValue(0, name); query.bindValue(0, name);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
emit folderAdded(name); emit folderAdded(name);
mApp->sendMessages(MainApplication::BookmarksChanged, true); mApp->sendMessages(MainApplication::BookmarksChanged, true);
@ -264,26 +277,31 @@ bool BookmarksModel::createFolder(const QString &name)
bool BookmarksModel::removeFolder(const QString &name) bool BookmarksModel::removeFolder(const QString &name)
{ {
if (name == tr("Bookmarks In Menu") || name == tr("Bookmarks In ToolBar")) if (name == tr("Bookmarks In Menu") || name == tr("Bookmarks In ToolBar")) {
return false; return false;
}
QSqlQuery query; QSqlQuery query;
query.prepare("SELECT id FROM bookmarks WHERE folder = ? "); query.prepare("SELECT id FROM bookmarks WHERE folder = ? ");
query.bindValue(0, name); query.bindValue(0, name);
if (!query.exec()) if (!query.exec()) {
return false; return false;
while (query.next()) }
while (query.next()) {
removeBookmark(query.value(0).toInt()); removeBookmark(query.value(0).toInt());
}
query.prepare("DELETE FROM folders WHERE name=?"); query.prepare("DELETE FROM folders WHERE name=?");
query.bindValue(0, name); query.bindValue(0, name);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
query.prepare("DELETE FROM bookmarks WHERE folder=?"); query.prepare("DELETE FROM bookmarks WHERE folder=?");
query.bindValue(0, name); query.bindValue(0, name);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
emit folderDeleted(name); emit folderDeleted(name);
mApp->sendMessages(MainApplication::BookmarksChanged, true); mApp->sendMessages(MainApplication::BookmarksChanged, true);
@ -296,20 +314,23 @@ bool BookmarksModel::renameFolder(const QString &before, const QString &after)
query.prepare("SELECT name FROM folders WHERE name = ?"); query.prepare("SELECT name FROM folders WHERE name = ?");
query.bindValue(0, after); query.bindValue(0, after);
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return false; return false;
}
query.prepare("UPDATE folders SET name=? WHERE name=?"); query.prepare("UPDATE folders SET name=? WHERE name=?");
query.bindValue(0, after); query.bindValue(0, after);
query.bindValue(1, before); query.bindValue(1, before);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
query.prepare("UPDATE bookmarks SET folder=? WHERE folder=?"); query.prepare("UPDATE bookmarks SET folder=? WHERE folder=?");
query.bindValue(0, after); query.bindValue(0, after);
query.bindValue(1, before); query.bindValue(1, before);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
emit folderRenamed(before, after); emit folderRenamed(before, after);
return true; return true;
@ -321,13 +342,15 @@ bool BookmarksModel::createSubfolder(const QString &name)
query.prepare("SELECT name FROM folders WHERE name = ?"); query.prepare("SELECT name FROM folders WHERE name = ?");
query.bindValue(0, name); query.bindValue(0, name);
query.exec(); query.exec();
if (query.next()) if (query.next()) {
return false; return false;
}
query.prepare("INSERT INTO folders (name, subfolder) VALUES (?, 'yes')"); query.prepare("INSERT INTO folders (name, subfolder) VALUES (?, 'yes')");
query.bindValue(0, name); query.bindValue(0, name);
if (!query.exec()) if (!query.exec()) {
return false; return false;
}
emit subfolderAdded(name); emit subfolderAdded(name);
mApp->sendMessages(MainApplication::BookmarksChanged, true); mApp->sendMessages(MainApplication::BookmarksChanged, true);
@ -340,49 +363,62 @@ bool BookmarksModel::isSubfolder(const QString &name)
query.prepare("SELECT subfolder FROM folders WHERE name = ?"); query.prepare("SELECT subfolder FROM folders WHERE name = ?");
query.bindValue(0, name); query.bindValue(0, name);
query.exec(); query.exec();
if (!query.next()) if (!query.next()) {
return false; return false;
}
return query.value(0).toString() == "yes"; return query.value(0).toString() == "yes";
} }
bool BookmarksModel::bookmarksEqual(const Bookmark &one, const Bookmark &two) bool BookmarksModel::bookmarksEqual(const Bookmark &one, const Bookmark &two)
{ {
if (one.id != two.id) if (one.id != two.id) {
return false; return false;
if (one.title != two.title) }
if (one.title != two.title) {
return false; return false;
if (one.folder != two.folder) }
if (one.folder != two.folder) {
return false; return false;
if (one.url != two.url) }
if (one.url != two.url) {
return false; return false;
}
return true; return true;
} }
QString BookmarksModel::toTranslatedFolder(const QString &name) QString BookmarksModel::toTranslatedFolder(const QString &name)
{ {
QString trFolder; QString trFolder;
if (name == "bookmarksMenu") if (name == "bookmarksMenu") {
trFolder = tr("Bookmarks In Menu"); trFolder = tr("Bookmarks In Menu");
else if (name == "bookmarksToolbar") }
else if (name == "bookmarksToolbar") {
trFolder = tr("Bookmarks In ToolBar"); trFolder = tr("Bookmarks In ToolBar");
else if (name == "unsorted") }
else if (name == "unsorted") {
trFolder = tr("Unsorted Bookmarks"); trFolder = tr("Unsorted Bookmarks");
else }
else {
trFolder = name; trFolder = name;
}
return trFolder; return trFolder;
} }
QString BookmarksModel::fromTranslatedFolder(const QString &name) QString BookmarksModel::fromTranslatedFolder(const QString &name)
{ {
QString folder; QString folder;
if (name == tr("Bookmarks In Menu")) if (name == tr("Bookmarks In Menu")) {
folder = "bookmarksMenu"; folder = "bookmarksMenu";
else if (name == tr("Bookmarks In ToolBar")) }
else if (name == tr("Bookmarks In ToolBar")) {
folder = "bookmarksToolbar"; folder = "bookmarksToolbar";
else if (name == tr("Unsorted Bookmarks")) }
else if (name == tr("Unsorted Bookmarks")) {
folder = "unsorted"; folder = "unsorted";
else }
else {
folder = name; folder = name;
}
return folder; return folder;
} }

View File

@ -39,13 +39,12 @@ public:
QIcon icon; QIcon icon;
bool inSubfolder; bool inSubfolder;
Bookmark() Bookmark() {
{ id = -1;
inSubfolder = false; inSubfolder = false;
} }
bool operator==(const Bookmark &other) bool operator==(const Bookmark &other) const {
{
return (this->title == other.title && return (this->title == other.title &&
this->folder == other.folder && this->folder == other.folder &&
this->url == other.url && this->url == other.url &&

View File

@ -39,10 +39,10 @@ BookmarksToolbar::BookmarksToolbar(QupZilla* mainClass, QWidget* parent)
connect(m_bookmarksModel, SIGNAL(bookmarkAdded(BookmarksModel::Bookmark)), this, SLOT(addBookmark(BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkAdded(BookmarksModel::Bookmark)), this, SLOT(addBookmark(BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(bookmarkDeleted(BookmarksModel::Bookmark)), this, SLOT(removeBookmark(BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkDeleted(BookmarksModel::Bookmark)), this, SLOT(removeBookmark(BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(bookmarkEdited(BookmarksModel::Bookmark,BookmarksModel::Bookmark)), this, SLOT(bookmarkEdited(BookmarksModel::Bookmark,BookmarksModel::Bookmark))); connect(m_bookmarksModel, SIGNAL(bookmarkEdited(BookmarksModel::Bookmark, BookmarksModel::Bookmark)), this, SLOT(bookmarkEdited(BookmarksModel::Bookmark, BookmarksModel::Bookmark)));
connect(m_bookmarksModel, SIGNAL(subfolderAdded(QString)), this, SLOT(subfolderAdded(QString))); connect(m_bookmarksModel, SIGNAL(subfolderAdded(QString)), this, SLOT(subfolderAdded(QString)));
connect(m_bookmarksModel, SIGNAL(folderDeleted(QString)), this, SLOT(folderDeleted(QString))); connect(m_bookmarksModel, SIGNAL(folderDeleted(QString)), this, SLOT(folderDeleted(QString)));
connect(m_bookmarksModel, SIGNAL(folderRenamed(QString,QString)), this, SLOT(folderRenamed(QString,QString))); connect(m_bookmarksModel, SIGNAL(folderRenamed(QString, QString)), this, SLOT(folderRenamed(QString, QString)));
// QTimer::singleShot(0, this, SLOT(refreshBookmarks())); // QTimer::singleShot(0, this, SLOT(refreshBookmarks()));
refreshBookmarks(); refreshBookmarks();
@ -62,7 +62,7 @@ void BookmarksToolbar::customContextMenuRequested(const QPoint &pos)
//Prevent choosing first option with double rightclick //Prevent choosing first option with double rightclick
QPoint position = QCursor::pos(); QPoint position = QCursor::pos();
QPoint p(position.x(), position.y()+1); QPoint p(position.x(), position.y() + 1);
menu.exec(p); menu.exec(p);
} }
@ -71,10 +71,11 @@ void BookmarksToolbar::showBookmarkContextMenu(const QPoint &pos)
Q_UNUSED(pos) Q_UNUSED(pos)
ToolButton* button = qobject_cast<ToolButton*>(sender()); ToolButton* button = qobject_cast<ToolButton*>(sender());
if (!button) if (!button) {
return; return;
}
QVariant buttonPointer = qVariantFromValue((void *) button); QVariant buttonPointer = qVariantFromValue((void*) button);
QMenu menu; QMenu menu;
menu.addAction(IconProvider::fromTheme("go-next"), tr("Move right"), this, SLOT(moveRight()))->setData(buttonPointer); menu.addAction(IconProvider::fromTheme("go-next"), tr("Move right"), this, SLOT(moveRight()))->setData(buttonPointer);
@ -84,25 +85,28 @@ void BookmarksToolbar::showBookmarkContextMenu(const QPoint &pos)
//Prevent choosing first option with double rightclick //Prevent choosing first option with double rightclick
QPoint position = QCursor::pos(); QPoint position = QCursor::pos();
QPoint p(position.x(), position.y()+1); QPoint p(position.x(), position.y() + 1);
menu.exec(p); menu.exec(p);
} }
void BookmarksToolbar::moveRight() void BookmarksToolbar::moveRight()
{ {
QAction* act = qobject_cast<QAction*> (sender()); QAction* act = qobject_cast<QAction*> (sender());
if (!act) if (!act) {
return; return;
}
ToolButton* button = (ToolButton*) act->data().value<void*>(); ToolButton* button = (ToolButton*) act->data().value<void*>();
int index = m_layout->indexOf(button); int index = m_layout->indexOf(button);
if (index == m_layout->count() - 1) if (index == m_layout->count() - 1) {
return; return;
}
ToolButton* buttonRight = qobject_cast<ToolButton*> (m_layout->itemAt(index + 1)->widget()); ToolButton* buttonRight = qobject_cast<ToolButton*> (m_layout->itemAt(index + 1)->widget());
if (!buttonRight || buttonRight->menu()) if (!buttonRight || buttonRight->menu()) {
return; return;
}
Bookmark bookmark = button->data().value<Bookmark>(); Bookmark bookmark = button->data().value<Bookmark>();
Bookmark bookmarkRight = buttonRight->data().value<Bookmark>(); Bookmark bookmarkRight = buttonRight->data().value<Bookmark>();
@ -125,18 +129,21 @@ void BookmarksToolbar::moveRight()
void BookmarksToolbar::moveLeft() void BookmarksToolbar::moveLeft()
{ {
QAction* act = qobject_cast<QAction*> (sender()); QAction* act = qobject_cast<QAction*> (sender());
if (!act) if (!act) {
return; return;
}
ToolButton* button = (ToolButton*) act->data().value<void*>(); ToolButton* button = (ToolButton*) act->data().value<void*>();
int index = m_layout->indexOf(button); int index = m_layout->indexOf(button);
if (index == 0) if (index == 0) {
return; return;
}
ToolButton* buttonLeft = qobject_cast<ToolButton*> (m_layout->itemAt(index - 1)->widget()); ToolButton* buttonLeft = qobject_cast<ToolButton*> (m_layout->itemAt(index - 1)->widget());
if (!buttonLeft) if (!buttonLeft) {
return; return;
}
Bookmark bookmark = button->data().value<Bookmark>(); Bookmark bookmark = button->data().value<Bookmark>();
Bookmark bookmarkLeft = buttonLeft->data().value<Bookmark>(); Bookmark bookmarkLeft = buttonLeft->data().value<Bookmark>();
@ -159,12 +166,14 @@ void BookmarksToolbar::moveLeft()
void BookmarksToolbar::removeButton() void BookmarksToolbar::removeButton()
{ {
QAction* act = qobject_cast<QAction*> (sender()); QAction* act = qobject_cast<QAction*> (sender());
if (!act) if (!act) {
return; return;
}
ToolButton* button = (ToolButton*) act->data().value<void*>(); ToolButton* button = (ToolButton*) act->data().value<void*>();
if (!button) if (!button) {
return; return;
}
Bookmark bookmark = button->data().value<Bookmark>(); Bookmark bookmark = button->data().value<Bookmark>();
m_bookmarksModel->removeBookmark(bookmark.id); m_bookmarksModel->removeBookmark(bookmark.id);
@ -178,8 +187,9 @@ void BookmarksToolbar::hidePanel()
void BookmarksToolbar::loadClickedBookmark() void BookmarksToolbar::loadClickedBookmark()
{ {
ToolButton* button = qobject_cast<ToolButton*>(sender()); ToolButton* button = qobject_cast<ToolButton*>(sender());
if (!button) if (!button) {
return; return;
}
Bookmark bookmark = button->data().value<Bookmark>(); Bookmark bookmark = button->data().value<Bookmark>();
@ -189,8 +199,9 @@ void BookmarksToolbar::loadClickedBookmark()
void BookmarksToolbar::loadClickedBookmarkInNewTab() void BookmarksToolbar::loadClickedBookmarkInNewTab()
{ {
ToolButton* button = qobject_cast<ToolButton*>(sender()); ToolButton* button = qobject_cast<ToolButton*>(sender());
if (!button) if (!button) {
return; return;
}
Bookmark bookmark = button->data().value<Bookmark>(); Bookmark bookmark = button->data().value<Bookmark>();
@ -207,11 +218,13 @@ int BookmarksToolbar::indexOfLastBookmark()
{ {
for (int i = m_layout->count() - 1; i >= 0; i--) { for (int i = m_layout->count() - 1; i >= 0; i--) {
ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget()); ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget());
if (!button) if (!button) {
continue; continue;
}
if (!button->menu()) if (!button->menu()) {
return i + 1; return i + 1;
}
} }
return 0; return 0;
@ -238,8 +251,9 @@ void BookmarksToolbar::folderDeleted(const QString &name)
for (int i = index; i < m_layout->count(); i++) { for (int i = index; i < m_layout->count(); i++) {
ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget()); ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget());
if (!button) if (!button) {
continue; continue;
}
if (button->text() == name) { if (button->text() == name) {
delete button; delete button;
@ -254,8 +268,9 @@ void BookmarksToolbar::folderRenamed(const QString &before, const QString &after
for (int i = index; i < m_layout->count(); i++) { for (int i = index; i < m_layout->count(); i++) {
ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget()); ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget());
if (!button) if (!button) {
continue; continue;
}
if (button->text() == before) { if (button->text() == before) {
button->setText(after); button->setText(after);
@ -267,12 +282,13 @@ void BookmarksToolbar::folderRenamed(const QString &before, const QString &after
void BookmarksToolbar::addBookmark(const BookmarksModel::Bookmark &bookmark) void BookmarksToolbar::addBookmark(const BookmarksModel::Bookmark &bookmark)
{ {
if (bookmark.folder != "bookmarksToolbar") if (bookmark.folder != "bookmarksToolbar") {
return; return;
}
QString title = bookmark.title; QString title = bookmark.title;
if (title.length()>15) { if (title.length() > 15) {
title.truncate(13); title.truncate(13);
title+=".."; title += "..";
} }
QVariant v; QVariant v;
@ -306,8 +322,9 @@ void BookmarksToolbar::removeBookmark(const BookmarksModel::Bookmark &bookmark)
{ {
for (int i = 0; i < m_layout->count(); i++) { for (int i = 0; i < m_layout->count(); i++) {
ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget()); ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget());
if (!button) if (!button) {
continue; continue;
}
Bookmark book = button->data().value<Bookmark>(); Bookmark book = button->data().value<Bookmark>();
@ -320,23 +337,26 @@ void BookmarksToolbar::removeBookmark(const BookmarksModel::Bookmark &bookmark)
void BookmarksToolbar::bookmarkEdited(const BookmarksModel::Bookmark &before, const BookmarksModel::Bookmark &after) void BookmarksToolbar::bookmarkEdited(const BookmarksModel::Bookmark &before, const BookmarksModel::Bookmark &after)
{ {
if (before.folder == "bookmarksToolbar" && after.folder != "bookmarksToolbar") //Editing from toolbar folder to other folder -> Remove bookmark if (before.folder == "bookmarksToolbar" && after.folder != "bookmarksToolbar") { //Editing from toolbar folder to other folder -> Remove bookmark
removeBookmark(before); removeBookmark(before);
else if (before.folder != "bookmarksToolbar" && after.folder == "bookmarksToolbar") //Editing from other folder to toolbar folder -> Add bookmark }
else if (before.folder != "bookmarksToolbar" && after.folder == "bookmarksToolbar") { //Editing from other folder to toolbar folder -> Add bookmark
addBookmark(after); addBookmark(after);
else { //Editing bookmark already in toolbar }
else { //Editing bookmark already in toolbar
for (int i = 0; i < m_layout->count(); i++) { for (int i = 0; i < m_layout->count(); i++) {
ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget()); ToolButton* button = qobject_cast<ToolButton*>(m_layout->itemAt(i)->widget());
if (!button) if (!button) {
continue; continue;
}
Bookmark book = button->data().value<Bookmark>(); Bookmark book = button->data().value<Bookmark>();
if (book == before) { if (book == before) {
QString title = after.title; QString title = after.title;
if (title.length()>15) { if (title.length() > 15) {
title.truncate(13); title.truncate(13);
title+=".."; title += "..";
} }
QVariant v; QVariant v;
@ -357,7 +377,7 @@ void BookmarksToolbar::refreshBookmarks()
{ {
QSqlQuery query; QSqlQuery query;
query.exec("SELECT id, title, url, icon FROM bookmarks WHERE folder='bookmarksToolbar' ORDER BY toolbar_position"); query.exec("SELECT id, title, url, icon FROM bookmarks WHERE folder='bookmarksToolbar' ORDER BY toolbar_position");
while(query.next()) { while (query.next()) {
Bookmark bookmark; Bookmark bookmark;
bookmark.id = query.value(0).toInt(); bookmark.id = query.value(0).toInt();
bookmark.title = query.value(1).toString(); bookmark.title = query.value(1).toString();
@ -365,9 +385,9 @@ void BookmarksToolbar::refreshBookmarks()
bookmark.icon = IconProvider::iconFromBase64(query.value(3).toByteArray()); bookmark.icon = IconProvider::iconFromBase64(query.value(3).toByteArray());
bookmark.folder = "bookmarksToolbar"; bookmark.folder = "bookmarksToolbar";
QString title = bookmark.title; QString title = bookmark.title;
if (title.length()>15) { if (title.length() > 15) {
title.truncate(13); title.truncate(13);
title+=".."; title += "..";
} }
QVariant v; QVariant v;
@ -390,7 +410,7 @@ void BookmarksToolbar::refreshBookmarks()
} }
query.exec("SELECT name FROM folders WHERE subfolder='yes'"); query.exec("SELECT name FROM folders WHERE subfolder='yes'");
while(query.next()) { while (query.next()) {
ToolButton* b = new ToolButton(this); ToolButton* b = new ToolButton(this);
b->setPopupMode(QToolButton::InstantPopup); b->setPopupMode(QToolButton::InstantPopup);
b->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); b->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
@ -424,8 +444,9 @@ void BookmarksToolbar::refreshBookmarks()
void BookmarksToolbar::aboutToShowFolderMenu() void BookmarksToolbar::aboutToShowFolderMenu()
{ {
QMenu* menu = qobject_cast<QMenu*> (sender()); QMenu* menu = qobject_cast<QMenu*> (sender());
if (!menu) if (!menu) {
return; return;
}
menu->clear(); menu->clear();
QString folder = menu->title(); QString folder = menu->title();
@ -434,7 +455,7 @@ void BookmarksToolbar::aboutToShowFolderMenu()
query.prepare("SELECT title, url, icon FROM bookmarks WHERE folder=?"); query.prepare("SELECT title, url, icon FROM bookmarks WHERE folder=?");
query.addBindValue(folder); query.addBindValue(folder);
query.exec(); query.exec();
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray()); QIcon icon = IconProvider::iconFromBase64(query.value(2).toByteArray());
@ -445,8 +466,9 @@ void BookmarksToolbar::aboutToShowFolderMenu()
menu->addAction(icon, title, p_QupZilla, SLOT(loadActionUrl()))->setData(url); menu->addAction(icon, title, p_QupZilla, SLOT(loadActionUrl()))->setData(url);
} }
if (menu->isEmpty()) if (menu->isEmpty()) {
menu->addAction(tr("Empty")); menu->addAction(tr("Empty"));
}
} }
void BookmarksToolbar::refreshMostVisited() void BookmarksToolbar::refreshMostVisited()
@ -454,14 +476,15 @@ void BookmarksToolbar::refreshMostVisited()
m_menuMostVisited->clear(); m_menuMostVisited->clear();
QList<HistoryModel::HistoryEntry> mostList = m_historyModel->mostVisited(10); QList<HistoryModel::HistoryEntry> mostList = m_historyModel->mostVisited(10);
foreach (HistoryModel::HistoryEntry entry, mostList) { foreach(HistoryModel::HistoryEntry entry, mostList) {
if (entry.title.length()>40) { if (entry.title.length() > 40) {
entry.title.truncate(40); entry.title.truncate(40);
entry.title+=".."; entry.title += "..";
} }
m_menuMostVisited->addAction(_iconForUrl(entry.url), entry.title, p_QupZilla, SLOT(loadActionUrl()))->setData(entry.url); m_menuMostVisited->addAction(_iconForUrl(entry.url), entry.title, p_QupZilla, SLOT(loadActionUrl()))->setData(entry.url);
} }
if (m_menuMostVisited->isEmpty()) if (m_menuMostVisited->isEmpty()) {
m_menuMostVisited->addAction(tr("Empty")); m_menuMostVisited->addAction(tr("Empty"));
}
} }

View File

@ -22,9 +22,9 @@
BookmarksWidget::BookmarksWidget(int bookmarkId, QWidget* parent) : BookmarksWidget::BookmarksWidget(int bookmarkId, QWidget* parent) :
QMenu(parent) QMenu(parent)
,ui(new Ui::BookmarksWidget) , ui(new Ui::BookmarksWidget)
,m_bookmarkId(bookmarkId) , m_bookmarkId(bookmarkId)
,m_bookmarksModel(0) , m_bookmarksModel(0)
{ {
ui->setupUi(this); ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
@ -39,7 +39,7 @@ BookmarksWidget::BookmarksWidget(int bookmarkId, QWidget* parent) :
void BookmarksWidget::loadBookmark() void BookmarksWidget::loadBookmark()
{ {
BookmarksModel::Bookmark bookmark = m_bookmarksModel->getBookmark(m_bookmarkId); BookmarksModel::Bookmark bookmark = m_bookmarksModel->getBookmark(m_bookmarkId);
ui->name->setText( bookmark.title ); ui->name->setText(bookmark.title);
// Bookmark folders // Bookmark folders
ui->folder->addItem(QIcon(":icons/other/unsortedbookmarks.png"), tr("Unsorted Bookmarks"), "unsorted"); ui->folder->addItem(QIcon(":icons/other/unsortedbookmarks.png"), tr("Unsorted Bookmarks"), "unsorted");
@ -47,10 +47,11 @@ void BookmarksWidget::loadBookmark()
ui->folder->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"), "bookmarksToolbar"); ui->folder->addItem(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Bookmarks In ToolBar"), "bookmarksToolbar");
QSqlQuery query; QSqlQuery query;
query.exec("SELECT name FROM folders"); query.exec("SELECT name FROM folders");
while(query.next()) while (query.next()) {
ui->folder->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString(), query.value(0).toString()); ui->folder->addItem(style()->standardIcon(QStyle::SP_DirIcon), query.value(0).toString(), query.value(0).toString());
}
ui->folder->setCurrentIndex( ui->folder->findData(bookmark.folder) ); ui->folder->setCurrentIndex(ui->folder->findData(bookmark.folder));
ui->name->setCursorPosition(0); ui->name->setCursorPosition(0);
} }
@ -63,14 +64,14 @@ void BookmarksWidget::removeBookmark()
void BookmarksWidget::saveBookmark() void BookmarksWidget::saveBookmark()
{ {
m_bookmarksModel->editBookmark(m_bookmarkId, ui->name->text(), QUrl(), ui->folder->itemData(ui->folder->currentIndex()).toString() ); m_bookmarksModel->editBookmark(m_bookmarkId, ui->name->text(), QUrl(), ui->folder->itemData(ui->folder->currentIndex()).toString());
close(); close();
} }
void BookmarksWidget::showAt(QWidget* _parent) void BookmarksWidget::showAt(QWidget* _parent)
{ {
QPoint p = _parent->mapToGlobal(QPoint(0, 0)); QPoint p = _parent->mapToGlobal(QPoint(0, 0));
move( (p.x()+_parent->width() ) - width(), p.y() + _parent->height()); move((p.x() + _parent->width()) - width(), p.y() + _parent->height());
show(); show();
} }

View File

@ -29,8 +29,9 @@
#include <QSqlQuery> #include <QSqlQuery>
#include <QSqlError> #include <QSqlError>
namespace Ui { namespace Ui
class BookmarksWidget; {
class BookmarksWidget;
} }
class BookmarksModel; class BookmarksModel;

View File

@ -44,10 +44,11 @@ void BookmarksImportDialog::nextPage()
{ {
switch (m_currentPage) { switch (m_currentPage) {
case 0: case 0:
if (!ui->browserList->currentItem()) if (!ui->browserList->currentItem()) {
return; return;
}
m_browser = (Browser) (ui->browserList->currentRow()); m_browser = (Browser)(ui->browserList->currentRow());
setupBrowser(m_browser); setupBrowser(m_browser);
ui->iconLabel->setPixmap(m_browserPixmap); ui->iconLabel->setPixmap(m_browserPixmap);
ui->importingFromLabel->setText(tr("<b>Importing from %1</b>").arg(m_browserName)); ui->importingFromLabel->setText(tr("<b>Importing from %1</b>").arg(m_browserName));
@ -61,8 +62,9 @@ void BookmarksImportDialog::nextPage()
break; break;
case 1: case 1:
if (ui->fileLine->text().isEmpty()) if (ui->fileLine->text().isEmpty()) {
return; return;
}
if (exportedOK()) { if (exportedOK()) {
m_currentPage++; m_currentPage++;
@ -89,7 +91,7 @@ void BookmarksImportDialog::startFetchingIcons()
ui->progressBar->setMaximum(m_exportedBookmarks.count()); ui->progressBar->setMaximum(m_exportedBookmarks.count());
int i = 0; int i = 0;
foreach (BookmarksModel::Bookmark b, m_exportedBookmarks) { foreach(BookmarksModel::Bookmark b, m_exportedBookmarks) {
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
item->setText(0, b.title); item->setText(0, b.title);
item->setIcon(0, QWebSettings::globalSettings()->webGraphic(QWebSettings::DefaultFrameIconGraphic)); item->setIcon(0, QWebSettings::globalSettings()->webGraphic(QWebSettings::DefaultFrameIconGraphic));
@ -132,8 +134,9 @@ void BookmarksImportDialog::loadFinished()
void BookmarksImportDialog::iconFetched(const QIcon &icon) void BookmarksImportDialog::iconFetched(const QIcon &icon)
{ {
IconFetcher* fetcher = qobject_cast<IconFetcher*>(sender()); IconFetcher* fetcher = qobject_cast<IconFetcher*>(sender());
if (!fetcher) if (!fetcher) {
return; return;
}
QUrl url; QUrl url;
for (int i = 0; i < m_fetchers.count(); i++) { for (int i = 0; i < m_fetchers.count(); i++) {
@ -144,17 +147,19 @@ void BookmarksImportDialog::iconFetched(const QIcon &icon)
} }
} }
if (url.isEmpty()) if (url.isEmpty()) {
return; return;
}
QList<QTreeWidgetItem*> items = ui->treeWidget->findItems(url.toString(), Qt::MatchExactly, 1); QList<QTreeWidgetItem*> items = ui->treeWidget->findItems(url.toString(), Qt::MatchExactly, 1);
if (items.count() == 0) if (items.count() == 0) {
return; return;
}
foreach (QTreeWidgetItem* item, items) { foreach(QTreeWidgetItem * item, items) {
item->setIcon(0, icon); item->setIcon(0, icon);
foreach (BookmarksModel::Bookmark b, m_exportedBookmarks) { foreach(BookmarksModel::Bookmark b, m_exportedBookmarks) {
if (b.url == url) { if (b.url == url) {
m_exportedBookmarks.removeOne(b); m_exportedBookmarks.removeOne(b);
b.icon = icon; b.icon = icon;
@ -170,30 +175,35 @@ bool BookmarksImportDialog::exportedOK()
if (m_browser == Firefox) { if (m_browser == Firefox) {
FirefoxImporter firefox(this); FirefoxImporter firefox(this);
firefox.setFile(ui->fileLine->text()); firefox.setFile(ui->fileLine->text());
if (firefox.openDatabase()) if (firefox.openDatabase()) {
m_exportedBookmarks = firefox.exportBookmarks(); m_exportedBookmarks = firefox.exportBookmarks();
}
if (firefox.error()) { if (firefox.error()) {
QMessageBox::critical(this, tr("Error!"), firefox.errorString()); QMessageBox::critical(this, tr("Error!"), firefox.errorString());
return false; return false;
} }
return true; return true;
} else if (m_browser == Chrome) { }
else if (m_browser == Chrome) {
ChromeImporter chrome(this); ChromeImporter chrome(this);
chrome.setFile(ui->fileLine->text()); chrome.setFile(ui->fileLine->text());
if (chrome.openFile()) if (chrome.openFile()) {
m_exportedBookmarks = chrome.exportBookmarks(); m_exportedBookmarks = chrome.exportBookmarks();
}
if (chrome.error()) { if (chrome.error()) {
QMessageBox::critical(this, tr("Error!"), chrome.errorString()); QMessageBox::critical(this, tr("Error!"), chrome.errorString());
return false; return false;
} }
return true; return true;
} else if (m_browser == Opera) { }
else if (m_browser == Opera) {
OperaImporter opera(this); OperaImporter opera(this);
opera.setFile(ui->fileLine->text()); opera.setFile(ui->fileLine->text());
if (opera.openFile()) if (opera.openFile()) {
m_exportedBookmarks = opera.exportBookmarks(); m_exportedBookmarks = opera.exportBookmarks();
}
if (opera.error()) { if (opera.error()) {
QMessageBox::critical(this, tr("Error!"), opera.errorString()); QMessageBox::critical(this, tr("Error!"), opera.errorString());
@ -210,14 +220,17 @@ void BookmarksImportDialog::setFile()
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if (m_browser == IE) { if (m_browser == IE) {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose directory...")); QString path = QFileDialog::getExistingDirectory(this, tr("Choose directory..."));
if (!path.isEmpty()) if (!path.isEmpty()) {
ui->fileLine->setText(path); ui->fileLine->setText(path);
} else }
}
else
#endif #endif
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose file..."), QDir::homePath(), m_browserBookmarkFile); QString path = QFileDialog::getOpenFileName(this, tr("Choose file..."), QDir::homePath(), m_browserBookmarkFile);
if (!path.isEmpty()) if (!path.isEmpty()) {
ui->fileLine->setText(path); ui->fileLine->setText(path);
}
} }
ui->nextButton->setEnabled(!ui->fileLine->text().isEmpty()); ui->nextButton->setEnabled(!ui->fileLine->text().isEmpty());
@ -229,11 +242,12 @@ void BookmarksImportDialog::addExportedBookmarks()
BookmarksModel* model = mApp->bookmarksModel(); BookmarksModel* model = mApp->bookmarksModel();
if (m_exportedBookmarks.count() > 0) if (m_exportedBookmarks.count() > 0) {
model->createFolder(m_exportedBookmarks.at(0).folder); model->createFolder(m_exportedBookmarks.at(0).folder);
}
foreach (BookmarksModel::Bookmark b, m_exportedBookmarks) foreach(BookmarksModel::Bookmark b, m_exportedBookmarks)
model->saveBookmark(b.url, b.title, b.icon, b.folder); model->saveBookmark(b.url, b.title, b.icon, b.folder);
qApp->restoreOverrideCursor(); qApp->restoreOverrideCursor();
} }
@ -250,9 +264,9 @@ void BookmarksImportDialog::setupBrowser(Browser browser)
m_browserFileText2 = tr("Please choose this file to begin importing bookmarks."); m_browserFileText2 = tr("Please choose this file to begin importing bookmarks.");
m_standardDir = m_standardDir =
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
"%APPDATA%/Mozilla/"; "%APPDATA%/Mozilla/";
#else #else
"/home/user/.mozilla/firefox/profilename/"; "/home/user/.mozilla/firefox/profilename/";
#endif #endif
break; break;
@ -281,9 +295,9 @@ void BookmarksImportDialog::setupBrowser(Browser browser)
m_browserFileText2 = tr("Please choose this file to begin importing bookmarks."); m_browserFileText2 = tr("Please choose this file to begin importing bookmarks.");
m_standardDir = m_standardDir =
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
"%APPDATA%/Chrome/Default/"; "%APPDATA%/Chrome/Default/";
#else #else
"/home/user/.opera/"; "/home/user/.opera/";
#endif #endif
break; break;
@ -304,7 +318,8 @@ void BookmarksImportDialog::setupBrowser(Browser browser)
BookmarksImportDialog::~BookmarksImportDialog() BookmarksImportDialog::~BookmarksImportDialog()
{ {
if (m_fetchers.count() > 0) { if (m_fetchers.count() > 0) {
for (int i = 0; i < m_fetchers.count(); i++) {tr(""); for (int i = 0; i < m_fetchers.count(); i++) {
tr("");
IconFetcher* fetcher = m_fetchers.at(i).first; IconFetcher* fetcher = m_fetchers.at(i).first;
delete fetcher; delete fetcher;
} }

View File

@ -28,8 +28,9 @@
#include "bookmarksmodel.h" #include "bookmarksmodel.h"
namespace Ui { namespace Ui
class BookmarksImportDialog; {
class BookmarksImportDialog;
} }
class IconFetcher; class IconFetcher;
@ -57,7 +58,7 @@ private:
void startFetchingIcons(); void startFetchingIcons();
void addExportedBookmarks(); void addExportedBookmarks();
Ui::BookmarksImportDialog *ui; Ui::BookmarksImportDialog* ui;
int m_currentPage; int m_currentPage;
Browser m_browser; Browser m_browser;

View File

@ -61,15 +61,16 @@ QList<BookmarksModel::Bookmark> ChromeImporter::exportBookmarks()
} }
QScriptEngine* scriptEngine = new QScriptEngine(); QScriptEngine* scriptEngine = new QScriptEngine();
foreach (QString parsedString, parsedBookmarks) { foreach(QString parsedString, parsedBookmarks) {
parsedString = "(" + parsedString + ")"; parsedString = "(" + parsedString + ")";
if (scriptEngine->canEvaluate(parsedString)) { if (scriptEngine->canEvaluate(parsedString)) {
QScriptValue object = scriptEngine->evaluate(parsedString); QScriptValue object = scriptEngine->evaluate(parsedString);
QString name = object.property("name").toString(); QString name = object.property("name").toString();
QString url = object.property("url").toString(); QString url = object.property("url").toString();
if (name.isEmpty() || url.isEmpty()) if (name.isEmpty() || url.isEmpty()) {
continue; continue;
}
BookmarksModel::Bookmark b; BookmarksModel::Bookmark b;
b.folder = "Chrome Import"; b.folder = "Chrome Import";
@ -77,7 +78,8 @@ QList<BookmarksModel::Bookmark> ChromeImporter::exportBookmarks()
b.url = url; b.url = url;
list.append(b); list.append(b);
} else { }
else {
m_error = true; m_error = true;
m_errorString = tr("Cannot evaluate JSON code."); m_errorString = tr("Cannot evaluate JSON code.");
} }

View File

@ -17,7 +17,7 @@
* ============================================================ */ * ============================================================ */
#include "firefoximporter.h" #include "firefoximporter.h"
FirefoxImporter::FirefoxImporter(QObject *parent) FirefoxImporter::FirefoxImporter(QObject* parent)
: QObject(parent) : QObject(parent)
, m_error(false) , m_error(false)
, m_errorString(tr("No Error")) , m_errorString(tr("No Error"))
@ -56,20 +56,22 @@ QList<BookmarksModel::Bookmark> FirefoxImporter::exportBookmarks()
QSqlQuery query(db); QSqlQuery query(db);
query.exec("SELECT title, fk FROM moz_bookmarks WHERE title != ''"); query.exec("SELECT title, fk FROM moz_bookmarks WHERE title != ''");
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
int placesId = query.value(1).toInt(); int placesId = query.value(1).toInt();
QSqlQuery query2(db); QSqlQuery query2(db);
query2.exec("SELECT url FROM moz_places WHERE id=" + QString::number(placesId)); query2.exec("SELECT url FROM moz_places WHERE id=" + QString::number(placesId));
if (!query2.next()) if (!query2.next()) {
continue; continue;
}
QString url = query2.value(0).toString(); QString url = query2.value(0).toString();
if (title.isEmpty() || url.isEmpty() || url.startsWith("place:")) if (title.isEmpty() || url.isEmpty() || url.startsWith("place:")) {
continue; continue;
}
BookmarksModel::Bookmark b; BookmarksModel::Bookmark b;
b.folder = "Firefox Import"; b.folder = "Firefox Import";

View File

@ -66,8 +66,9 @@ QList<BookmarksModel::Bookmark> OperaImporter::exportBookmarks()
rx2.indexIn(string); rx2.indexIn(string);
QString url = rx2.cap(1); QString url = rx2.cap(1);
if (name.isEmpty() || url.isEmpty()) if (name.isEmpty() || url.isEmpty()) {
continue; continue;
}
BookmarksModel::Bookmark b; BookmarksModel::Bookmark b;
b.folder = "Opera Import"; b.folder = "Opera Import";

View File

@ -45,12 +45,13 @@ void CookieJar::setAllowCookies(bool allow)
bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url) bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{ {
if (!m_allowCookies) if (!m_allowCookies) {
return QNetworkCookieJar::setCookiesFromUrl(QList<QNetworkCookie>(), url); return QNetworkCookieJar::setCookiesFromUrl(QList<QNetworkCookie>(), url);
}
QList<QNetworkCookie> newList = cookieList; QList<QNetworkCookie> newList = cookieList;
foreach (QNetworkCookie cok, newList) { foreach(QNetworkCookie cok, newList) {
if (m_allowCookiesFromDomain && !QString("." + url.host()).contains(cok.domain().remove("www."))) { if (m_allowCookiesFromDomain && !QString("." + url.host()).contains(cok.domain().remove("www."))) {
#ifdef COOKIE_DEBUG #ifdef COOKIE_DEBUG
qDebug() << "purged for domain mismatch" << cok; qDebug() << "purged for domain mismatch" << cok;
@ -72,17 +73,18 @@ bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const
void CookieJar::saveCookies() void CookieJar::saveCookies()
{ {
if (m_deleteOnClose) if (m_deleteOnClose) {
return; return;
}
QList<QNetworkCookie> allCookies = getAllCookies(); QList<QNetworkCookie> allCookies = getAllCookies();
QFile file(m_activeProfil+"cookies.dat"); QFile file(m_activeProfil + "cookies.dat");
file.open(QIODevice::WriteOnly); file.open(QIODevice::WriteOnly);
QDataStream stream(&file); QDataStream stream(&file);
int count = allCookies.count(); int count = allCookies.count();
stream << count; stream << count;
for (int i = 0; i<count; i++) { for (int i = 0; i < count; i++) {
stream << allCookies.at(i).toRawForm(); stream << allCookies.at(i).toRawForm();
} }
@ -91,25 +93,28 @@ void CookieJar::saveCookies()
void CookieJar::restoreCookies() void CookieJar::restoreCookies()
{ {
if (!QFile::exists(m_activeProfil+"cookies.dat")) if (!QFile::exists(m_activeProfil + "cookies.dat")) {
return; return;
}
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> restoredCookies; QList<QNetworkCookie> restoredCookies;
QFile file(m_activeProfil+"cookies.dat"); QFile file(m_activeProfil + "cookies.dat");
file.open(QIODevice::ReadOnly); file.open(QIODevice::ReadOnly);
QDataStream stream(&file); QDataStream stream(&file);
int count; int count;
stream >> count; stream >> count;
for (int i = 0; i<count; i++) { for (int i = 0; i < count; i++) {
QByteArray rawForm; QByteArray rawForm;
stream >> rawForm; stream >> rawForm;
QNetworkCookie cok = QNetworkCookie::parseCookies(rawForm).at(0); QNetworkCookie cok = QNetworkCookie::parseCookies(rawForm).at(0);
if (cok.expirationDate() < now) if (cok.expirationDate() < now) {
continue; continue;
if (cok.isSessionCookie()) }
if (cok.isSessionCookie()) {
continue; continue;
}
restoredCookies.append(cok); restoredCookies.append(cok);
} }
@ -132,7 +137,8 @@ void CookieJar::turnPrivateJar(bool state)
if (state) { if (state) {
m_tempList = QNetworkCookieJar::allCookies(); m_tempList = QNetworkCookieJar::allCookies();
QNetworkCookieJar::setAllCookies(QList<QNetworkCookie>()); QNetworkCookieJar::setAllCookies(QList<QNetworkCookie>());
} else { }
else {
QNetworkCookieJar::setAllCookies(m_tempList); QNetworkCookieJar::setAllCookies(m_tempList);
m_tempList.clear(); m_tempList.clear();
} }

View File

@ -33,7 +33,7 @@ CookieManager::CookieManager(QWidget* parent)
ui->setupUi(this); ui->setupUi(this);
qz_centerWidgetOnScreen(this); qz_centerWidgetOnScreen(this);
connect(ui->cookieTree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),this, SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*))); connect(ui->cookieTree, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
connect(ui->removeAll, SIGNAL(clicked()), this, SLOT(removeAll())); connect(ui->removeAll, SIGNAL(clicked()), this, SLOT(removeAll()));
connect(ui->removeOne, SIGNAL(clicked()), this, SLOT(removeCookie())); connect(ui->removeOne, SIGNAL(clicked()), this, SLOT(removeCookie()));
connect(ui->close, SIGNAL(clicked(QAbstractButton*)), this, SLOT(hide())); connect(ui->close, SIGNAL(clicked(QAbstractButton*)), this, SLOT(hide()));
@ -50,9 +50,10 @@ CookieManager::CookieManager(QWidget* parent)
void CookieManager::removeAll() void CookieManager::removeAll()
{ {
QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"), QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"),
tr("Are you sure to delete all cookies on your computer?"), QMessageBox::Yes | QMessageBox::No); tr("Are you sure to delete all cookies on your computer?"), QMessageBox::Yes | QMessageBox::No);
if (button != QMessageBox::Yes) if (button != QMessageBox::Yes) {
return; return;
}
m_cookies.clear(); m_cookies.clear();
mApp->cookieJar()->setAllCookies(m_cookies); mApp->cookieJar()->setAllCookies(m_cookies);
@ -62,16 +63,18 @@ void CookieManager::removeAll()
void CookieManager::removeCookie() void CookieManager::removeCookie()
{ {
QTreeWidgetItem* current = ui->cookieTree->currentItem(); QTreeWidgetItem* current = ui->cookieTree->currentItem();
if (!current) if (!current) {
return; return;
}
int indexToNavigate = -1; int indexToNavigate = -1;
if (current->text(1).isEmpty()) { //Remove whole cookie group if (current->text(1).isEmpty()) { //Remove whole cookie group
QString domain = current->whatsThis(0); QString domain = current->whatsThis(0);
foreach(QNetworkCookie cok, m_cookies) { foreach(QNetworkCookie cok, m_cookies) {
if (cok.domain() == domain || cok.domain() == domain.mid(1)) if (cok.domain() == domain || cok.domain() == domain.mid(1)) {
m_cookies.removeOne(cok); m_cookies.removeOne(cok);
}
} }
indexToNavigate = ui->cookieTree->indexOfTopLevelItem(current) - 1; indexToNavigate = ui->cookieTree->indexOfTopLevelItem(current) - 1;
@ -91,15 +94,17 @@ void CookieManager::removeCookie()
ui->cookieTree->scrollToItem(scrollItem); ui->cookieTree->scrollToItem(scrollItem);
} }
if (!ui->search->text().isEmpty()) if (!ui->search->text().isEmpty()) {
search(); search();
}
} }
void CookieManager::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* parent) void CookieManager::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* parent)
{ {
Q_UNUSED(parent); Q_UNUSED(parent);
if (!current) if (!current) {
return; return;
}
if (current->text(1).isEmpty()) { if (current->text(1).isEmpty()) {
ui->name->setText(tr("<cookie not selected>")); ui->name->setText(tr("<cookie not selected>"));
@ -133,25 +138,28 @@ void CookieManager::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem
void CookieManager::refreshTable(bool refreshCookieJar) void CookieManager::refreshTable(bool refreshCookieJar)
{ {
if (refreshCookieJar) if (refreshCookieJar) {
m_cookies = mApp->cookieJar()->getAllCookies(); m_cookies = mApp->cookieJar()->getAllCookies();
}
ui->cookieTree->setUpdatesEnabled(false); ui->cookieTree->setUpdatesEnabled(false);
ui->cookieTree->clear(); ui->cookieTree->clear();
QString cookServer; QString cookServer;
for (int i = 0; i<m_cookies.count(); i++) { for (int i = 0; i < m_cookies.count(); i++) {
QNetworkCookie cok = m_cookies.at(i); QNetworkCookie cok = m_cookies.at(i);
QTreeWidgetItem* item; QTreeWidgetItem* item;
cookServer = cok.domain(); cookServer = cok.domain();
if (cookServer.startsWith(".")) if (cookServer.startsWith(".")) {
cookServer = cookServer.mid(1); cookServer = cookServer.mid(1);
}
QList<QTreeWidgetItem*> findParent = ui->cookieTree->findItems(cookServer, 0); QList<QTreeWidgetItem*> findParent = ui->cookieTree->findItems(cookServer, 0);
if (findParent.count() == 1) { if (findParent.count() == 1) {
item = new QTreeWidgetItem(findParent.at(0)); item = new QTreeWidgetItem(findParent.at(0));
}else{ }
else {
QTreeWidgetItem* newParent = new QTreeWidgetItem(ui->cookieTree); QTreeWidgetItem* newParent = new QTreeWidgetItem(ui->cookieTree);
newParent->setText(0, cookServer); newParent->setText(0, cookServer);
newParent->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon)); newParent->setIcon(0, style()->standardIcon(QStyle::SP_DirIcon));
@ -160,7 +168,7 @@ void CookieManager::refreshTable(bool refreshCookieJar)
item = new QTreeWidgetItem(newParent); item = new QTreeWidgetItem(newParent);
} }
item->setText(0,"."+cookServer); item->setText(0, "." + cookServer);
item->setText(1, cok.name()); item->setText(1, cok.name());
item->setWhatsThis(1, QString::number(i)); item->setWhatsThis(1, QString::number(i));
ui->cookieTree->addTopLevelItem(item); ui->cookieTree->addTopLevelItem(item);

View File

@ -23,8 +23,9 @@
#include <QNetworkCookie> #include <QNetworkCookie>
#include <QTreeWidgetItem> #include <QTreeWidgetItem>
namespace Ui { namespace Ui
class CookieManager; {
class CookieManager;
} }
class QupZilla; class QupZilla;

View File

@ -19,27 +19,28 @@
#include "ui_desktopnotification.h" #include "ui_desktopnotification.h"
DesktopNotification::DesktopNotification(bool setPosition) DesktopNotification::DesktopNotification(bool setPosition)
: QWidget(0) : QWidget(0)
, ui(new Ui::DesktopNotification) , ui(new Ui::DesktopNotification)
, m_settingPosition(setPosition) , m_settingPosition(setPosition)
, m_timeout(6000) , m_timeout(6000)
, m_timer(new QTimer(this)) , m_timer(new QTimer(this))
{ {
ui->setupUi(this); ui->setupUi(this);
setAttribute(Qt::WA_TranslucentBackground); setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
Qt::WindowFlags flags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint; Qt::WindowFlags flags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint;
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
flags |= Qt::ToolTip; flags |= Qt::ToolTip;
#endif #endif
setWindowFlags(flags); setWindowFlags(flags);
setWindowOpacity(0.9); setWindowOpacity(0.9);
m_timer->setSingleShot(true); m_timer->setSingleShot(true);
connect(m_timer, SIGNAL(timeout()), this, SLOT(close())); connect(m_timer, SIGNAL(timeout()), this, SLOT(close()));
if (m_settingPosition) if (m_settingPosition) {
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
}
} }
void DesktopNotification::show() void DesktopNotification::show()
@ -59,17 +60,19 @@ void DesktopNotification::show()
void DesktopNotification::enterEvent(QEvent*) void DesktopNotification::enterEvent(QEvent*)
{ {
if (!m_settingPosition) if (!m_settingPosition) {
setWindowOpacity(0.5); setWindowOpacity(0.5);
}
} }
void DesktopNotification::leaveEvent(QEvent*) void DesktopNotification::leaveEvent(QEvent*)
{ {
if (!m_settingPosition) if (!m_settingPosition) {
setWindowOpacity(0.9); setWindowOpacity(0.9);
}
} }
void DesktopNotification::mousePressEvent(QMouseEvent *e) void DesktopNotification::mousePressEvent(QMouseEvent* e)
{ {
if (!m_settingPosition) { if (!m_settingPosition) {
close(); close();
@ -82,7 +85,7 @@ void DesktopNotification::mousePressEvent(QMouseEvent *e)
} }
} }
void DesktopNotification::mouseMoveEvent(QMouseEvent *e) void DesktopNotification::mouseMoveEvent(QMouseEvent* e)
{ {
if (e->buttons() & Qt::LeftButton) { if (e->buttons() & Qt::LeftButton) {
move(e->globalPos() - m_dragPosition); move(e->globalPos() - m_dragPosition);

View File

@ -22,8 +22,9 @@
#include <QTimer> #include <QTimer>
#include <QMouseEvent> #include <QMouseEvent>
namespace Ui { namespace Ui
class DesktopNotification; {
class DesktopNotification;
} }
class DesktopNotification : public QWidget class DesktopNotification : public QWidget

View File

@ -28,7 +28,7 @@ DesktopNotificationsFactory::DesktopNotificationsFactory(QObject* parent)
void DesktopNotificationsFactory::loadSettings() void DesktopNotificationsFactory::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Notifications"); settings.beginGroup("Notifications");
m_enabled = settings.value("Enabled", true).toBool(); m_enabled = settings.value("Enabled", true).toBool();
m_timeout = settings.value("Timeout", 6000).toInt(); m_timeout = settings.value("Timeout", 6000).toInt();
@ -43,13 +43,15 @@ void DesktopNotificationsFactory::loadSettings()
void DesktopNotificationsFactory::notify(const QPixmap &icon, const QString &heading, const QString &text) void DesktopNotificationsFactory::notify(const QPixmap &icon, const QString &heading, const QString &text)
{ {
if (!m_enabled) if (!m_enabled) {
return; return;
}
switch (m_notifType) { switch (m_notifType) {
case PopupWidget: case PopupWidget:
if (!m_desktopNotif) if (!m_desktopNotif) {
m_desktopNotif = new DesktopNotification(); m_desktopNotif = new DesktopNotification();
}
m_desktopNotif->setPixmap(icon); m_desktopNotif->setPixmap(icon);
m_desktopNotif->setHeading(heading); m_desktopNotif->setHeading(heading);
m_desktopNotif->setText(text); m_desktopNotif->setText(text);
@ -75,8 +77,9 @@ void DesktopNotificationsFactory::notify(const QPixmap &icon, const QString &hea
args.append(m_timeout); args.append(m_timeout);
QDBusMessage message = dbus.callWithArgumentList(QDBus::Block, "Notify", args); QDBusMessage message = dbus.callWithArgumentList(QDBus::Block, "Notify", args);
QVariantList list = message.arguments(); QVariantList list = message.arguments();
if (list.count() > 0) if (list.count() > 0) {
m_uint = list.at(0).toInt(); m_uint = list.at(0).toInt();
}
#endif #endif
break; break;
} }

View File

@ -30,8 +30,10 @@ DownloadFileHelper::DownloadFileHelper(const QString &lastDownloadPath, const QS
, m_lastDownloadPath(lastDownloadPath) , m_lastDownloadPath(lastDownloadPath)
, m_downloadPath(downloadPath) , m_downloadPath(downloadPath)
, m_useNativeDialog(useNativeDialog) , m_useNativeDialog(useNativeDialog)
, m_timer(0)
, m_reply(0) , m_reply(0)
, m_openFileChoosed(false) , m_openFileChoosed(false)
, m_listWidget(0)
, m_iconProvider(new QFileIconProvider) , m_iconProvider(new QFileIconProvider)
, m_manager(0) , m_manager(0)
{ {
@ -55,7 +57,7 @@ void DownloadFileHelper::handleUnsupportedContent(QNetworkReply* reply, bool ask
QTemporaryFile tempFile("XXXXXX." + info.suffix()); QTemporaryFile tempFile("XXXXXX." + info.suffix());
tempFile.open(); tempFile.open();
QFileInfo tempInfo(tempFile.fileName()); QFileInfo tempInfo(tempFile.fileName());
m_fileIcon = m_iconProvider->icon(tempInfo).pixmap(30,30); m_fileIcon = m_iconProvider->icon(tempInfo).pixmap(30, 30);
QString mimeType = m_iconProvider->type(tempInfo); QString mimeType = m_iconProvider->type(tempInfo);
//Get Download Page and Close Empty Tab //Get Download Page and Close Empty Tab
@ -63,20 +65,25 @@ void DownloadFileHelper::handleUnsupportedContent(QNetworkReply* reply, bool ask
QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
WebPage* webPage = (WebPage*)(v.value<void*>()); WebPage* webPage = (WebPage*)(v.value<void*>());
if (webPage) { if (webPage) {
if (!webPage->mainFrame()->url().isEmpty()) if (!webPage->mainFrame()->url().isEmpty()) {
m_downloadPage = webPage->mainFrame()->url(); m_downloadPage = webPage->mainFrame()->url();
else if (webPage->history()->canGoBack()) }
else if (webPage->history()->canGoBack()) {
m_downloadPage = webPage->history()->backItem().url(); m_downloadPage = webPage->history()->backItem().url();
else if (webPage->history()->count() == 0) }
else if (webPage->history()->count() == 0) {
webPage->getView()->closeTab(); webPage->getView()->closeTab();
}
} }
if (askWhatToDo) { if (askWhatToDo) {
DownloadOptionsDialog* dialog = new DownloadOptionsDialog(m_h_fileName, m_fileIcon, mimeType, reply->url(), mApp->activeWindow()); DownloadOptionsDialog* dialog = new DownloadOptionsDialog(m_h_fileName, m_fileIcon, mimeType, reply->url(), mApp->activeWindow());
dialog->show(); dialog->show();
connect(dialog, SIGNAL(dialogFinished(int)), this, SLOT(optionsDialogAccepted(int))); connect(dialog, SIGNAL(dialogFinished(int)), this, SLOT(optionsDialogAccepted(int)));
} else }
else {
optionsDialogAccepted(2); optionsDialogAccepted(2);
}
} }
void DownloadFileHelper::optionsDialogAccepted(int finish) void DownloadFileHelper::optionsDialogAccepted(int finish)
@ -84,8 +91,9 @@ void DownloadFileHelper::optionsDialogAccepted(int finish)
m_openFileChoosed = false; m_openFileChoosed = false;
switch (finish) { switch (finish) {
case 0: //Cancelled case 0: //Cancelled
if (m_timer) if (m_timer) {
delete m_timer; delete m_timer;
}
return; return;
break; break;
case 1: //Open case 1: //Open
@ -99,7 +107,8 @@ void DownloadFileHelper::optionsDialogAccepted(int finish)
if (m_downloadPath.isEmpty()) { if (m_downloadPath.isEmpty()) {
if (m_useNativeDialog) { if (m_useNativeDialog) {
fileNameChoosed(QFileDialog::getSaveFileName(mApp->getWindow(), tr("Save file as..."), m_lastDownloadPath + m_h_fileName)); fileNameChoosed(QFileDialog::getSaveFileName(mApp->getWindow(), tr("Save file as..."), m_lastDownloadPath + m_h_fileName));
} else { }
else {
QFileDialog* dialog = new QFileDialog(mApp->getWindow()); QFileDialog* dialog = new QFileDialog(mApp->getWindow());
dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setWindowTitle(tr("Save file as...")); dialog->setWindowTitle(tr("Save file as..."));
@ -109,10 +118,13 @@ void DownloadFileHelper::optionsDialogAccepted(int finish)
connect(dialog, SIGNAL(fileSelected(QString)), this, SLOT(fileNameChoosed(QString))); connect(dialog, SIGNAL(fileSelected(QString)), this, SLOT(fileNameChoosed(QString)));
} }
} }
else else {
fileNameChoosed(m_downloadPath + m_h_fileName, true); fileNameChoosed(m_downloadPath + m_h_fileName, true);
} else }
}
else {
fileNameChoosed(QDir::tempPath() + "/" + m_h_fileName, true); fileNameChoosed(QDir::tempPath() + "/" + m_h_fileName, true);
}
} }
void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoGenerated) void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoGenerated)
@ -121,8 +133,9 @@ void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoG
if (m_userFileName.isEmpty()) { if (m_userFileName.isEmpty()) {
m_reply->abort(); m_reply->abort();
if (m_timer) if (m_timer) {
delete m_timer; delete m_timer;
}
return; return;
} }
@ -130,8 +143,8 @@ void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoG
int pos = m_userFileName.lastIndexOf("/"); int pos = m_userFileName.lastIndexOf("/");
if (pos != -1) { if (pos != -1) {
int size = m_userFileName.size(); int size = m_userFileName.size();
m_path = m_userFileName.left(pos+1); m_path = m_userFileName.left(pos + 1);
m_fileName = m_userFileName.right(size-pos-1); m_fileName = m_userFileName.right(size - pos - 1);
} }
if (fileNameAutoGenerated && QFile::exists(m_userFileName)) { if (fileNameAutoGenerated && QFile::exists(m_userFileName)) {
@ -142,17 +155,19 @@ void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoG
int index = _tmpFileName.lastIndexOf("."); int index = _tmpFileName.lastIndexOf(".");
if (index == -1) { if (index == -1) {
_tmpFileName.append("("+QString::number(i)+")"); _tmpFileName.append("(" + QString::number(i) + ")");
} else { }
_tmpFileName = _tmpFileName.mid(0, index) + "("+QString::number(i)+")" + _tmpFileName.mid(index); else {
_tmpFileName = _tmpFileName.mid(0, index) + "(" + QString::number(i) + ")" + _tmpFileName.mid(index);
} }
i++; i++;
} }
m_fileName = _tmpFileName; m_fileName = _tmpFileName;
} }
if (!m_path.contains(QDir::tempPath())) if (!m_path.contains(QDir::tempPath())) {
m_lastDownloadPath = m_path; m_lastDownloadPath = m_path;
}
QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("DownloadManager"); settings.beginGroup("DownloadManager");
@ -176,15 +191,17 @@ QString DownloadFileHelper::getFileName(QNetworkReply* reply)
if (reply->hasRawHeader("Content-Disposition")) { if (reply->hasRawHeader("Content-Disposition")) {
QString value = reply->rawHeader("Content-Disposition"); QString value = reply->rawHeader("Content-Disposition");
int pos = value.indexOf("filename="); int pos = value.indexOf("filename=");
if (pos!=-1) { if (pos != -1) {
QString name = value.mid(pos + 9); QString name = value.mid(pos + 9);
if (name.startsWith('"') && name.endsWith('"')) if (name.startsWith('"') && name.endsWith('"')) {
name = name.mid(1, name.size() - 2); name = name.mid(1, name.size() - 2);
}
path = name; path = name;
} }
} }
if (path.isEmpty()) if (path.isEmpty()) {
path = reply->url().path(); path = reply->url().path();
}
QFileInfo info(path); QFileInfo info(path);
QString baseName = info.completeBaseName(); QString baseName = info.completeBaseName();
@ -194,14 +211,17 @@ QString DownloadFileHelper::getFileName(QNetworkReply* reply)
baseName = tr("NoNameDownload"); baseName = tr("NoNameDownload");
} }
if (!endName.isEmpty()) if (!endName.isEmpty()) {
endName="."+endName; endName = "." + endName;
}
QString name = baseName+endName; QString name = baseName + endName;
if (name.startsWith("\"")) if (name.startsWith("\"")) {
name = name.mid(1); name = name.mid(1);
if (name.endsWith("\";")) }
if (name.endsWith("\";")) {
name.remove("\";"); name.remove("\";");
}
return name; return name;
} }

View File

@ -44,15 +44,16 @@ DownloadItem::DownloadItem(QListWidgetItem* item, QNetworkReply* reply, const QS
qDebug() << __FUNCTION__ << item << reply << path << fileName; qDebug() << __FUNCTION__ << item << reply << path << fileName;
#endif #endif
QString fullPath = path + fileName; QString fullPath = path + fileName;
if (QFile::exists(fullPath)) if (QFile::exists(fullPath)) {
QFile::remove(fullPath); QFile::remove(fullPath);
}
m_outputFile.setFileName(fullPath); m_outputFile.setFileName(fullPath);
ui->setupUi(this); ui->setupUi(this);
setMaximumWidth(525); setMaximumWidth(525);
ui->button->setPixmap(IconProvider::standardIcon(QStyle::SP_BrowserStop).pixmap(20,20)); ui->button->setPixmap(IconProvider::standardIcon(QStyle::SP_BrowserStop).pixmap(20, 20));
ui->fileName->setText(m_fileName); ui->fileName->setText(m_fileName);
ui->downloadInfo->setText(tr("Remaining time unavailable")); ui->downloadInfo->setText(tr("Remaining time unavailable"));
ui->fileIcon->setPixmap(fileIcon); ui->fileIcon->setPixmap(fileIcon);
@ -82,8 +83,9 @@ DownloadItem::DownloadItem(QListWidgetItem* item, QNetworkReply* reply, const QS
void DownloadItem::parentResized(const QSize &size) void DownloadItem::parentResized(const QSize &size)
{ {
if (size.width() < 200) if (size.width() < 200) {
return; return;
}
setMaximumWidth(size.width()); setMaximumWidth(size.width());
} }
@ -93,8 +95,9 @@ void DownloadItem::metaDataChanged()
// << download this picture emits metaDataChanged signal, but image is downloaded correctly // << download this picture emits metaDataChanged signal, but image is downloaded correctly
QVariant locationHeader = m_reply->header(QNetworkRequest::LocationHeader); QVariant locationHeader = m_reply->header(QNetworkRequest::LocationHeader);
if (!locationHeader.toUrl().isEmpty()) if (!locationHeader.toUrl().isEmpty()) {
qWarning("DownloadManager: metaDataChanged << URL: %s", qPrintable(locationHeader.toString())); qWarning("DownloadManager: metaDataChanged << URL: %s", qPrintable(locationHeader.toString()));
}
// QMessageBox::information(m_item->listWidget()->parentWidget(), "Meta Data Changed", QString("Meta data changed feature unimplemented yet, sorry.\n URL: '%̈́'").arg(locationHeader.toUrl().toString())); // QMessageBox::information(m_item->listWidget()->parentWidget(), "Meta Data Changed", QString("Meta data changed feature unimplemented yet, sorry.\n URL: '%̈́'").arg(locationHeader.toUrl().toString()));
} }
@ -118,8 +121,9 @@ void DownloadItem::finished()
#endif #endif
m_downloading = false; m_downloading = false;
if (m_openAfterFinish) if (m_openAfterFinish) {
openFile(); openFile();
}
emit downloadFinished(true); emit downloadFinished(true);
} }
@ -146,8 +150,10 @@ void DownloadItem::timerEvent(QTimerEvent* event)
{ {
if (event->timerId() == m_timer.timerId()) { if (event->timerId() == m_timer.timerId()) {
updateDownloadInfo(m_currSpeed, m_received, m_total); updateDownloadInfo(m_currSpeed, m_received, m_total);
} else }
else {
QWidget::timerEvent(event); QWidget::timerEvent(event);
}
} }
int DownloadItem::progress() int DownloadItem::progress()
@ -162,49 +168,59 @@ bool DownloadItem::isCancelled()
QString DownloadItem::remaingTimeToString(QTime time) QString DownloadItem::remaingTimeToString(QTime time)
{ {
if (time<QTime(0, 0, 10)) if (time < QTime(0, 0, 10)) {
return tr("few seconds"); return tr("few seconds");
else if (time<QTime(0, 1)) }
return time.toString("s")+" "+tr("seconds"); else if (time < QTime(0, 1)) {
else if (time<QTime(1, 0)) return time.toString("s") + " " + tr("seconds");
return time.toString("m")+" "+tr("minutes"); }
else else if (time < QTime(1, 0)) {
return time.toString("h")+" "+tr("hours"); return time.toString("m") + " " + tr("minutes");
}
else {
return time.toString("h") + " " + tr("hours");
}
} }
QString DownloadItem::currentSpeedToString(double speed) QString DownloadItem::currentSpeedToString(double speed)
{ {
if (speed < 0) if (speed < 0) {
return tr("Unknown speed"); return tr("Unknown speed");
}
speed /= 1024; // kB speed /= 1024; // kB
if (speed < 1000) if (speed < 1000) {
return QString::number(speed, 'f', 0)+" kB/s"; return QString::number(speed, 'f', 0) + " kB/s";
}
speed /= 1024; //MB speed /= 1024; //MB
if (speed < 1000) if (speed < 1000) {
return QString::number(speed, 'f', 2)+" MB/s"; return QString::number(speed, 'f', 2) + " MB/s";
}
speed /= 1024; //GB speed /= 1024; //GB
return QString::number(speed, 'f', 2)+" GB/s"; return QString::number(speed, 'f', 2) + " GB/s";
} }
QString DownloadItem::fileSizeToString(qint64 size) QString DownloadItem::fileSizeToString(qint64 size)
{ {
if (size < 0) if (size < 0) {
return tr("Unknown size"); return tr("Unknown size");
}
double _size = (double)size; double _size = (double)size;
_size /= 1024; //kB _size /= 1024; //kB
if (_size < 1000) if (_size < 1000) {
return QString::number(_size, 'f', 0)+" kB"; return QString::number(_size, 'f', 0) + " kB";
}
_size /= 1024; //MB _size /= 1024; //MB
if (_size < 1000) if (_size < 1000) {
return QString::number(_size, 'f', 1)+" MB"; return QString::number(_size, 'f', 1) + " MB";
}
_size /= 1024; //GB _size /= 1024; //GB
return QString::number(_size, 'f', 2)+" GB"; return QString::number(_size, 'f', 2) + " GB";
} }
void DownloadItem::updateDownloadInfo(double currSpeed, qint64 received, qint64 total) void DownloadItem::updateDownloadInfo(double currSpeed, qint64 received, qint64 total)
@ -216,7 +232,7 @@ void DownloadItem::updateDownloadInfo(double currSpeed, qint64 received, qint64
// | m_remTime | |m_currSize| |m_fileSize| |m_speed| // | m_remTime | |m_currSize| |m_fileSize| |m_speed|
// Remaining 26 minutes - 339MB of 693 MB (350kB/s) // Remaining 26 minutes - 339MB of 693 MB (350kB/s)
int estimatedTime=((total-received)/1024) / (currSpeed/1024); int estimatedTime = ((total - received) / 1024) / (currSpeed / 1024);
QString speed = currentSpeedToString(currSpeed); QString speed = currentSpeedToString(currSpeed);
// We have QString speed now // We have QString speed now
@ -228,10 +244,12 @@ void DownloadItem::updateDownloadInfo(double currSpeed, qint64 received, qint64
QString currSize = fileSizeToString(received); QString currSize = fileSizeToString(received);
QString fileSize = fileSizeToString(total); QString fileSize = fileSizeToString(total);
if (fileSize == tr("Unknown size")) if (fileSize == tr("Unknown size")) {
ui->downloadInfo->setText(tr("%2 - unknown size (%3)").arg(currSize, speed)); ui->downloadInfo->setText(tr("%2 - unknown size (%3)").arg(currSize, speed));
else }
else {
ui->downloadInfo->setText(tr("Remaining %1 - %2 of %3 (%4)").arg(remTime, currSize, fileSize, speed)); ui->downloadInfo->setText(tr("Remaining %1 - %2 of %3 (%4)").arg(remTime, currSize, fileSize, speed));
}
} }
void DownloadItem::stop(bool askForDeleteFile) void DownloadItem::stop(bool askForDeleteFile)
@ -240,8 +258,9 @@ void DownloadItem::stop(bool askForDeleteFile)
qDebug() << __FUNCTION__; qDebug() << __FUNCTION__;
#endif #endif
if (m_downloadStopped) if (m_downloadStopped) {
return; return;
}
m_downloadStopped = true; m_downloadStopped = true;
m_openAfterFinish = false; m_openAfterFinish = false;
@ -264,8 +283,9 @@ void DownloadItem::stop(bool askForDeleteFile)
if (askForDeleteFile) { if (askForDeleteFile) {
QMessageBox::StandardButton button = QMessageBox::question(m_item->listWidget()->parentWidget(), tr("Delete file"), tr("Do you want to also delete dowloaded file?"), QMessageBox::Yes | QMessageBox::No); QMessageBox::StandardButton button = QMessageBox::question(m_item->listWidget()->parentWidget(), tr("Delete file"), tr("Do you want to also delete dowloaded file?"), QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) if (button == QMessageBox::Yes) {
QFile::remove(outputfile); QFile::remove(outputfile);
}
} }
} }
@ -288,8 +308,9 @@ void DownloadItem::customContextMenuRequested(const QPoint &pos)
menu.addAction(IconProvider::standardIcon(QStyle::SP_BrowserStop), tr("Cancel downloading"), this, SLOT(stop()))->setEnabled(m_downloading); menu.addAction(IconProvider::standardIcon(QStyle::SP_BrowserStop), tr("Cancel downloading"), this, SLOT(stop()))->setEnabled(m_downloading);
menu.addAction(QIcon::fromTheme("list-remove"), tr("Clear"), this, SLOT(clear()))->setEnabled(!m_downloading); menu.addAction(QIcon::fromTheme("list-remove"), tr("Clear"), this, SLOT(clear()))->setEnabled(!m_downloading);
if (m_downloading || ui->downloadInfo->text().startsWith(tr("Cancelled")) || ui->downloadInfo->text().startsWith(tr("Error"))) if (m_downloading || ui->downloadInfo->text().startsWith(tr("Cancelled")) || ui->downloadInfo->text().startsWith(tr("Error"))) {
menu.actions().at(0)->setEnabled(false); menu.actions().at(0)->setEnabled(false);
}
menu.exec(mapToGlobal(pos)); menu.exec(mapToGlobal(pos));
} }
@ -310,13 +331,16 @@ void DownloadItem::clear()
void DownloadItem::openFile() void DownloadItem::openFile()
{ {
if (m_downloading) if (m_downloading) {
return; return;
QFileInfo info(m_path+m_fileName); }
if (info.exists()) QFileInfo info(m_path + m_fileName);
if (info.exists()) {
QDesktopServices::openUrl(QUrl::fromLocalFile(info.absoluteFilePath())); QDesktopServices::openUrl(QUrl::fromLocalFile(info.absoluteFilePath()));
else }
else {
QMessageBox::warning(m_item->listWidget()->parentWidget(), tr("Not found"), tr("Sorry, the file \n %1 \n was not found!").arg(info.absoluteFilePath())); QMessageBox::warning(m_item->listWidget()->parentWidget(), tr("Not found"), tr("Sorry, the file \n %1 \n was not found!").arg(info.absoluteFilePath()));
}
} }
void DownloadItem::openFolder() void DownloadItem::openFolder()
@ -342,8 +366,9 @@ void DownloadItem::error(QNetworkReply::NetworkError error)
#ifdef DOWNMANAGER_DEBUG #ifdef DOWNMANAGER_DEBUG
qDebug() << __FUNCTION__ << error; qDebug() << __FUNCTION__ << error;
#endif #endif
if (error != QNetworkReply::NoError) if (error != QNetworkReply::NoError) {
ui->downloadInfo->setText(tr("Error: ") + m_reply->errorString()); ui->downloadInfo->setText(tr("Error: ") + m_reply->errorString());
}
} }
void DownloadItem::updateDownload() void DownloadItem::updateDownload()
@ -352,7 +377,7 @@ void DownloadItem::updateDownload()
qDebug() << __FUNCTION__ ; qDebug() << __FUNCTION__ ;
#endif #endif
if (ui->progressBar->maximum() == 0 && m_outputFile.isOpen() && m_reply->isFinished()) { if (ui->progressBar->maximum() == 0 && m_outputFile.isOpen() && m_reply->isFinished()) {
downloadProgress(0,0); downloadProgress(0, 0);
finished(); finished();
} }
} }

View File

@ -33,8 +33,9 @@
#include <QMenu> #include <QMenu>
#include <QMessageBox> #include <QMessageBox>
namespace Ui { namespace Ui
class DownloadItem; {
class DownloadItem;
} }
class DownloadManager; class DownloadManager;

View File

@ -36,8 +36,9 @@ DownloadManager::DownloadManager(QWidget* parent)
setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint); setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
ui->setupUi(this); ui->setupUi(this);
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if (QtWin::isCompositionEnabled()) if (QtWin::isCompositionEnabled()) {
QtWin::extendFrameIntoClientArea(this); QtWin::extendFrameIntoClientArea(this);
}
#endif #endif
ui->clearButton->setIcon(QIcon::fromTheme("edit-clear")); ui->clearButton->setIcon(QIcon::fromTheme("edit-clear"));
qz_centerWidgetOnScreen(this); qz_centerWidgetOnScreen(this);
@ -49,36 +50,37 @@ DownloadManager::DownloadManager(QWidget* parent)
loadSettings(); loadSettings();
#ifdef W7API #ifdef W7API
if (QtWin::isRunningWindows7()) if (QtWin::isRunningWindows7()) {
win7.init(this->winId()); win7.init(this->winId());
}
#endif #endif
} }
void DownloadManager::loadSettings() void DownloadManager::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("DownloadManager"); settings.beginGroup("DownloadManager");
m_downloadPath = settings.value("defaultDownloadPath", "").toString(); m_downloadPath = settings.value("defaultDownloadPath", "").toString();
m_lastDownloadPath = settings.value("lastDownloadPath", QDir::homePath() + "/").toString(); m_lastDownloadPath = settings.value("lastDownloadPath", QDir::homePath() + "/").toString();
m_closeOnFinish = settings.value("CloseManagerOnFinish", false).toBool(); m_closeOnFinish = settings.value("CloseManagerOnFinish", false).toBool();
m_useNativeDialog = settings.value("useNativeDialog", m_useNativeDialog = settings.value("useNativeDialog",
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
false false
#else #else
true true
#endif #endif
).toBool(); ).toBool();
settings.endGroup(); settings.endGroup();
} }
void DownloadManager::show() void DownloadManager::show()
{ {
m_timer.start(1000*2, this); m_timer.start(1000 * 2, this);
QWidget::show(); QWidget::show();
} }
void DownloadManager::resizeEvent(QResizeEvent *e) void DownloadManager::resizeEvent(QResizeEvent* e)
{ {
QWidget::resizeEvent(e); QWidget::resizeEvent(e);
emit resized(size()); emit resized(size());
@ -105,33 +107,36 @@ void DownloadManager::timerEvent(QTimerEvent* event)
} }
for (int i = 0; i < ui->list->count(); i++) { for (int i = 0; i < ui->list->count(); i++) {
DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
if (!downItem || (downItem && downItem->isCancelled()) || !downItem->isDownloading()) if (!downItem || (downItem && downItem->isCancelled()) || !downItem->isDownloading()) {
continue; continue;
}
progresses.append(downItem->progress()); progresses.append(downItem->progress());
remTimes.append(downItem->remainingTime()); remTimes.append(downItem->remainingTime());
speeds.append(downItem->currentSpeed()); speeds.append(downItem->currentSpeed());
} }
if (remTimes.isEmpty()) if (remTimes.isEmpty()) {
return; return;
}
QTime remaining; QTime remaining;
foreach (QTime time, remTimes) { foreach(QTime time, remTimes) {
if (time > remaining) if (time > remaining) {
remaining = time; remaining = time;
}
} }
int progress = 0; int progress = 0;
foreach (int prog, progresses) foreach(int prog, progresses)
progress+=prog; progress += prog;
progress = progress / progresses.count(); progress = progress / progresses.count();
double speed = 0.00; double speed = 0.00;
foreach (double spee, speeds) foreach(double spee, speeds)
speed+=spee; speed += spee;
ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress),QString::number(progresses.count()), ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()),
DownloadItem::currentSpeedToString(speed), DownloadItem::currentSpeedToString(speed),
DownloadItem::remaingTimeToString(remaining))); DownloadItem::remaingTimeToString(remaining)));
setWindowTitle(QString::number(progress) + tr("% - Download Manager")); setWindowTitle(QString::number(progress) + tr("% - Download Manager"));
#ifdef W7API #ifdef W7API
if (QtWin::isRunningWindows7()) { if (QtWin::isRunningWindows7()) {
@ -139,8 +144,10 @@ void DownloadManager::timerEvent(QTimerEvent* event)
win7.setProgressState(win7.Normal); win7.setProgressState(win7.Normal);
} }
#endif #endif
} else }
else {
QWidget::timerEvent(event); QWidget::timerEvent(event);
}
} }
void DownloadManager::clearList() void DownloadManager::clearList()
@ -148,10 +155,12 @@ void DownloadManager::clearList()
QList<DownloadItem*> items; QList<DownloadItem*> items;
for (int i = 0; i < ui->list->count(); i++) { for (int i = 0; i < ui->list->count(); i++) {
DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
if (!downItem) if (!downItem) {
continue; continue;
if (downItem->isDownloading()) }
if (downItem->isDownloading()) {
continue; continue;
}
items.append(downItem); items.append(downItem);
} }
qDeleteAll(items); qDeleteAll(items);
@ -164,18 +173,19 @@ void DownloadManager::download(const QNetworkRequest &request, bool askWhatToDo)
void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, bool askWhatToDo) void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, bool askWhatToDo)
{ {
if (reply->url().scheme() == "qupzilla") if (reply->url().scheme() == "qupzilla") {
return; return;
}
DownloadFileHelper* h = new DownloadFileHelper(m_lastDownloadPath, m_downloadPath, m_useNativeDialog); DownloadFileHelper* h = new DownloadFileHelper(m_lastDownloadPath, m_downloadPath, m_useNativeDialog);
connect(h, SIGNAL(itemCreated(QListWidgetItem*,DownloadItem*)), this, SLOT(itemCreated(QListWidgetItem*,DownloadItem*))); connect(h, SIGNAL(itemCreated(QListWidgetItem*, DownloadItem*)), this, SLOT(itemCreated(QListWidgetItem*, DownloadItem*)));
h->setDownloadManager(this); h->setDownloadManager(this);
h->setListWidget(ui->list); h->setListWidget(ui->list);
h->handleUnsupportedContent(reply, askWhatToDo); h->handleUnsupportedContent(reply, askWhatToDo);
} }
void DownloadManager::itemCreated(QListWidgetItem *item, DownloadItem *downItem) void DownloadManager::itemCreated(QListWidgetItem* item, DownloadItem* downItem)
{ {
connect(downItem, SIGNAL(deleteItem(DownloadItem*)), this, SLOT(deleteItem(DownloadItem*))); connect(downItem, SIGNAL(deleteItem(DownloadItem*)), this, SLOT(deleteItem(DownloadItem*)));
connect(downItem, SIGNAL(downloadFinished(bool)), this, SLOT(downloadFinished(bool))); connect(downItem, SIGNAL(downloadFinished(bool)), this, SLOT(downloadFinished(bool)));
@ -193,8 +203,9 @@ void DownloadManager::downloadFinished(bool success)
bool downloadingAllFilesFinished = true; bool downloadingAllFilesFinished = true;
for (int i = 0; i < ui->list->count(); i++) { for (int i = 0; i < ui->list->count(); i++) {
DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
if (!downItem || (downItem && downItem->isCancelled()) || !downItem->isDownloading()) if (!downItem || (downItem && downItem->isCancelled()) || !downItem->isDownloading()) {
continue; continue;
}
downloadingAllFilesFinished = false; downloadingAllFilesFinished = false;
} }
@ -214,27 +225,31 @@ void DownloadManager::downloadFinished(bool success)
win7.setProgressState(win7.NoProgress); win7.setProgressState(win7.NoProgress);
} }
#endif #endif
if (m_closeOnFinish) if (m_closeOnFinish) {
close(); close();
}
} }
} }
void DownloadManager::deleteItem(DownloadItem* item) void DownloadManager::deleteItem(DownloadItem* item)
{ {
if (item && !item->isDownloading()) if (item && !item->isDownloading()) {
delete item; delete item;
}
} }
bool DownloadManager::canClose() bool DownloadManager::canClose()
{ {
if (m_isClosing) if (m_isClosing) {
return true; return true;
}
bool isDownloading = false; bool isDownloading = false;
for (int i = 0; i < ui->list->count(); i++) { for (int i = 0; i < ui->list->count(); i++) {
DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
if (!downItem) if (!downItem) {
continue; continue;
}
if (downItem->isDownloading()) { if (downItem->isDownloading()) {
isDownloading = true; isDownloading = true;
break; break;
@ -247,9 +262,9 @@ bool DownloadManager::canClose()
void DownloadManager::closeEvent(QCloseEvent* e) void DownloadManager::closeEvent(QCloseEvent* e)
{ {
if (mApp->windowCount() == 0) { // No main windows -> we are going to quit if (mApp->windowCount() == 0) { // No main windows -> we are going to quit
if (!canClose()){ if (!canClose()) {
QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Warning"), QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Warning"),
tr("Are you sure to quit? All uncompleted downloads will be cancelled!"), QMessageBox::Yes | QMessageBox::No); tr("Are you sure to quit? All uncompleted downloads will be cancelled!"), QMessageBox::Yes | QMessageBox::No);
if (button != QMessageBox::Yes) { if (button != QMessageBox::Yes) {
e->ignore(); e->ignore();
return; return;

View File

@ -35,8 +35,9 @@
#include "ecwin7.h" #include "ecwin7.h"
namespace Ui { namespace Ui
class DownloadManager; {
class DownloadManager;
} }
class DownloadItem; class DownloadItem;
@ -81,7 +82,7 @@ private:
#endif #endif
void timerEvent(QTimerEvent* event); void timerEvent(QTimerEvent* event);
void closeEvent(QCloseEvent* e); void closeEvent(QCloseEvent* e);
void resizeEvent(QResizeEvent *e); void resizeEvent(QResizeEvent* e);
Ui::DownloadManager* ui; Ui::DownloadManager* ui;
NetworkManager* m_networkManager; NetworkManager* m_networkManager;

View File

@ -23,7 +23,7 @@ DownloadOptionsDialog::DownloadOptionsDialog(const QString &fileName, const QPix
, ui(new Ui::DownloadOptionsDialog) , ui(new Ui::DownloadOptionsDialog)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->fileName->setText("<b>"+fileName+"</b>"); ui->fileName->setText("<b>" + fileName + "</b>");
ui->fileIcon->setPixmap(fileIcon); ui->fileIcon->setPixmap(fileIcon);
ui->fileType->setText(mimeType); ui->fileType->setText(mimeType);
ui->fromServer->setText(url.host()); ui->fromServer->setText(url.host());
@ -37,10 +37,12 @@ DownloadOptionsDialog::DownloadOptionsDialog(const QString &fileName, const QPix
void DownloadOptionsDialog::emitDialogFinished(int status) void DownloadOptionsDialog::emitDialogFinished(int status)
{ {
if (status != 0) { if (status != 0) {
if (ui->radioOpen->isChecked()) if (ui->radioOpen->isChecked()) {
status = 1; status = 1;
else if (ui->radioSave->isChecked()) }
else if (ui->radioSave->isChecked()) {
status = 2; status = 2;
}
} }
emit dialogFinished(status); emit dialogFinished(status);
} }

View File

@ -22,8 +22,9 @@
#include <QUrl> #include <QUrl>
#include <QCloseEvent> #include <QCloseEvent>
namespace Ui { namespace Ui
class DownloadOptionsDialog; {
class DownloadOptionsDialog;
} }
class DownloadOptionsDialog : public QDialog class DownloadOptionsDialog : public QDialog

View File

@ -35,8 +35,8 @@ HistoryManager::HistoryManager(QupZilla* mainClass, QWidget* parent)
qz_centerWidgetOnScreen(this); qz_centerWidgetOnScreen(this);
ui->deleteB->setShortcut(QKeySequence("Del")); ui->deleteB->setShortcut(QKeySequence("Del"));
connect(ui->historyTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this, SLOT(itemDoubleClicked(QTreeWidgetItem*))); connect(ui->historyTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(itemDoubleClicked(QTreeWidgetItem*)));
connect(ui->historyTree, SIGNAL(itemMiddleButtonClicked(QTreeWidgetItem*)),this, SLOT(itemDoubleClicked(QTreeWidgetItem*))); connect(ui->historyTree, SIGNAL(itemMiddleButtonClicked(QTreeWidgetItem*)), this, SLOT(itemDoubleClicked(QTreeWidgetItem*)));
connect(ui->deleteB, SIGNAL(clicked()), this, SLOT(deleteItem())); connect(ui->deleteB, SIGNAL(clicked()), this, SLOT(deleteItem()));
connect(ui->clearAll, SIGNAL(clicked()), this, SLOT(clearHistory())); connect(ui->clearAll, SIGNAL(clicked()), this, SLOT(clearHistory()));
@ -44,7 +44,7 @@ HistoryManager::HistoryManager(QupZilla* mainClass, QWidget* parent)
connect(m_historyModel, SIGNAL(historyEntryAdded(HistoryModel::HistoryEntry)), this, SLOT(historyEntryAdded(HistoryModel::HistoryEntry))); connect(m_historyModel, SIGNAL(historyEntryAdded(HistoryModel::HistoryEntry)), this, SLOT(historyEntryAdded(HistoryModel::HistoryEntry)));
connect(m_historyModel, SIGNAL(historyEntryDeleted(HistoryModel::HistoryEntry)), this, SLOT(historyEntryDeleted(HistoryModel::HistoryEntry))); connect(m_historyModel, SIGNAL(historyEntryDeleted(HistoryModel::HistoryEntry)), this, SLOT(historyEntryDeleted(HistoryModel::HistoryEntry)));
connect(m_historyModel, SIGNAL(historyEntryEdited(HistoryModel::HistoryEntry,HistoryModel::HistoryEntry)), this, SLOT(historyEntryEdited(HistoryModel::HistoryEntry,HistoryModel::HistoryEntry))); connect(m_historyModel, SIGNAL(historyEntryEdited(HistoryModel::HistoryEntry, HistoryModel::HistoryEntry)), this, SLOT(historyEntryEdited(HistoryModel::HistoryEntry, HistoryModel::HistoryEntry)));
connect(m_historyModel, SIGNAL(historyClear()), ui->historyTree, SLOT(clear())); connect(m_historyModel, SIGNAL(historyClear()), ui->historyTree, SLOT(clear()));
connect(ui->optimizeDb, SIGNAL(clicked(QPoint)), this, SLOT(optimizeDb())); connect(ui->optimizeDb, SIGNAL(clicked(QPoint)), this, SLOT(optimizeDb()));
@ -56,37 +56,43 @@ HistoryManager::HistoryManager(QupZilla* mainClass, QWidget* parent)
QupZilla* HistoryManager::getQupZilla() QupZilla* HistoryManager::getQupZilla()
{ {
if (!p_QupZilla) if (!p_QupZilla) {
p_QupZilla = mApp->getWindow(); p_QupZilla = mApp->getWindow();
}
return p_QupZilla; return p_QupZilla;
} }
void HistoryManager::setMainWindow(QupZilla* window) void HistoryManager::setMainWindow(QupZilla* window)
{ {
if (window) if (window) {
p_QupZilla = window; p_QupZilla = window;
}
} }
void HistoryManager::itemDoubleClicked(QTreeWidgetItem* item) void HistoryManager::itemDoubleClicked(QTreeWidgetItem* item)
{ {
if (!item || item->text(1).isEmpty()) if (!item || item->text(1).isEmpty()) {
return; return;
}
getQupZilla()->tabWidget()->addView(QUrl(item->text(1))); getQupZilla()->tabWidget()->addView(QUrl(item->text(1)));
} }
void HistoryManager::loadInNewTab() void HistoryManager::loadInNewTab()
{ {
if (QAction* action = qobject_cast<QAction*>(sender())) if (QAction* action = qobject_cast<QAction*>(sender())) {
getQupZilla()->tabWidget()->addView(action->data().toUrl(), tr("New Tab"), TabWidget::NewNotSelectedTab); getQupZilla()->tabWidget()->addView(action->data().toUrl(), tr("New Tab"), TabWidget::NewNotSelectedTab);
}
} }
void HistoryManager::contextMenuRequested(const QPoint &position) void HistoryManager::contextMenuRequested(const QPoint &position)
{ {
if (!ui->historyTree->itemAt(position)) if (!ui->historyTree->itemAt(position)) {
return; return;
}
QString link = ui->historyTree->itemAt(position)->text(1); QString link = ui->historyTree->itemAt(position)->text(1);
if (link.isEmpty()) if (link.isEmpty()) {
return; return;
}
QMenu menu; QMenu menu;
menu.addAction(tr("Open link in actual tab"), getQupZilla(), SLOT(loadActionUrl()))->setData(link); menu.addAction(tr("Open link in actual tab"), getQupZilla(), SLOT(loadActionUrl()))->setData(link);
@ -95,16 +101,17 @@ void HistoryManager::contextMenuRequested(const QPoint &position)
//Prevent choosing first option with double rightclick //Prevent choosing first option with double rightclick
QPoint pos = QCursor::pos(); QPoint pos = QCursor::pos();
QPoint p(pos.x(), pos.y()+1); QPoint p(pos.x(), pos.y() + 1);
menu.exec(p); menu.exec(p);
} }
void HistoryManager::deleteItem() void HistoryManager::deleteItem()
{ {
QApplication::setOverrideCursor(Qt::WaitCursor); QApplication::setOverrideCursor(Qt::WaitCursor);
foreach (QTreeWidgetItem* item, ui->historyTree->selectedItems()) { foreach(QTreeWidgetItem * item, ui->historyTree->selectedItems()) {
if (!item) if (!item) {
return; return;
}
if (!item->parent()) { if (!item->parent()) {
for (int i = 0; i < item->childCount(); i++) { for (int i = 0; i < item->childCount(); i++) {
@ -113,7 +120,8 @@ void HistoryManager::deleteItem()
m_historyModel->deleteHistoryEntry(id); m_historyModel->deleteHistoryEntry(id);
} }
ui->historyTree->deleteItem(item); ui->historyTree->deleteItem(item);
} else { }
else {
int id = item->whatsThis(1).toInt(); int id = item->whatsThis(1).toInt();
m_historyModel->deleteHistoryEntry(id); m_historyModel->deleteHistoryEntry(id);
} }
@ -129,21 +137,26 @@ void HistoryManager::historyEntryAdded(const HistoryModel::HistoryEntry &entry)
QDate date = entry.date.date(); QDate date = entry.date.date();
QString localDate; QString localDate;
if (date == todayDate) if (date == todayDate) {
localDate = tr("Today"); localDate = tr("Today");
else if (date >= startOfWeekDate) }
else if (date >= startOfWeekDate) {
localDate = tr("This Week"); localDate = tr("This Week");
else if (date.month() == todayDate.month()) }
else if (date.month() == todayDate.month()) {
localDate = tr("This Month"); localDate = tr("This Month");
else }
else {
localDate = QString("%1 %2").arg(HistoryModel::titleCaseLocalizedMonth(date.month()), QString::number(date.year())); localDate = QString("%1 %2").arg(HistoryModel::titleCaseLocalizedMonth(date.month()), QString::number(date.year()));
}
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
QTreeWidgetItem* parentItem; QTreeWidgetItem* parentItem;
QList<QTreeWidgetItem*> findParent = ui->historyTree->findItems(localDate, 0); QList<QTreeWidgetItem*> findParent = ui->historyTree->findItems(localDate, 0);
if (findParent.count() == 1) { if (findParent.count() == 1) {
parentItem = findParent.at(0); parentItem = findParent.at(0);
} else { }
else {
parentItem = new QTreeWidgetItem(); parentItem = new QTreeWidgetItem();
parentItem->setText(0, localDate); parentItem->setText(0, localDate);
parentItem->setIcon(0, QIcon(":/icons/menu/history_entry.png")); parentItem->setIcon(0, QIcon(":/icons/menu/history_entry.png"));
@ -163,11 +176,13 @@ void HistoryManager::historyEntryAdded(const HistoryModel::HistoryEntry &entry)
void HistoryManager::historyEntryDeleted(const HistoryModel::HistoryEntry &entry) void HistoryManager::historyEntryDeleted(const HistoryModel::HistoryEntry &entry)
{ {
QList<QTreeWidgetItem*> list = ui->historyTree->allItems(); QList<QTreeWidgetItem*> list = ui->historyTree->allItems();
foreach (QTreeWidgetItem* item, list) { foreach(QTreeWidgetItem * item, list) {
if (!item) if (!item) {
continue; continue;
if (item->whatsThis(1).toInt() != entry.id) }
if (item->whatsThis(1).toInt() != entry.id) {
continue; continue;
}
ui->historyTree->deleteItem(item); ui->historyTree->deleteItem(item);
return; return;
} }
@ -182,9 +197,10 @@ void HistoryManager::historyEntryEdited(const HistoryModel::HistoryEntry &before
void HistoryManager::clearHistory() void HistoryManager::clearHistory()
{ {
QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"), QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"),
tr("Are you sure to delete all history?"), QMessageBox::Yes | QMessageBox::No); tr("Are you sure to delete all history?"), QMessageBox::Yes | QMessageBox::No);
if (button != QMessageBox::Yes) if (button != QMessageBox::Yes) {
return; return;
}
m_historyModel->clearHistory(); m_historyModel->clearHistory();
m_historyModel->optimizeHistory(); m_historyModel->optimizeHistory();
@ -200,27 +216,32 @@ void HistoryManager::refreshTable()
QSqlQuery query; QSqlQuery query;
query.exec("SELECT title, url, id, date FROM history ORDER BY date DESC"); query.exec("SELECT title, url, id, date FROM history ORDER BY date DESC");
while(query.next()) { while (query.next()) {
QString title = query.value(0).toString(); QString title = query.value(0).toString();
QUrl url = query.value(1).toUrl(); QUrl url = query.value(1).toUrl();
int id = query.value(2).toInt(); int id = query.value(2).toInt();
QDate date = QDateTime::fromMSecsSinceEpoch(query.value(3).toLongLong()).date(); QDate date = QDateTime::fromMSecsSinceEpoch(query.value(3).toLongLong()).date();
QString localDate; QString localDate;
if (date == todayDate) if (date == todayDate) {
localDate = tr("Today"); localDate = tr("Today");
else if (date >= startOfWeekDate) }
else if (date >= startOfWeekDate) {
localDate = tr("This Week"); localDate = tr("This Week");
else if (date.month() == todayDate.month()) }
else if (date.month() == todayDate.month()) {
localDate = tr("This Month"); localDate = tr("This Month");
else }
else {
localDate = QString("%1 %2").arg(HistoryModel::titleCaseLocalizedMonth(date.month()), QString::number(date.year())); localDate = QString("%1 %2").arg(HistoryModel::titleCaseLocalizedMonth(date.month()), QString::number(date.year()));
}
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
QList<QTreeWidgetItem*> findParent = ui->historyTree->findItems(localDate, 0); QList<QTreeWidgetItem*> findParent = ui->historyTree->findItems(localDate, 0);
if (findParent.count() == 1) { if (findParent.count() == 1) {
item = new QTreeWidgetItem(findParent.at(0)); item = new QTreeWidgetItem(findParent.at(0));
}else{ }
else {
QTreeWidgetItem* newParent = new QTreeWidgetItem(ui->historyTree); QTreeWidgetItem* newParent = new QTreeWidgetItem(ui->historyTree);
newParent->setText(0, localDate); newParent->setText(0, localDate);
newParent->setIcon(0, QIcon(":/icons/menu/history_entry.png")); newParent->setIcon(0, QIcon(":/icons/menu/history_entry.png"));
@ -253,12 +274,13 @@ void HistoryManager::search(const QString &searchText)
refreshTable(); refreshTable();
ui->historyTree->setUpdatesEnabled(false); ui->historyTree->setUpdatesEnabled(false);
QList<QTreeWidgetItem*> items = ui->historyTree->findItems("*"+searchText+"*", Qt::MatchRecursive | Qt::MatchWildcard); QList<QTreeWidgetItem*> items = ui->historyTree->findItems("*" + searchText + "*", Qt::MatchRecursive | Qt::MatchWildcard);
QList<QTreeWidgetItem*> foundItems; QList<QTreeWidgetItem*> foundItems;
foreach(QTreeWidgetItem* fitem, items) { foreach(QTreeWidgetItem * fitem, items) {
if (fitem->text(1).isEmpty()) if (fitem->text(1).isEmpty()) {
continue; continue;
}
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
item->setText(0, fitem->text(0)); item->setText(0, fitem->text(0));
item->setText(1, fitem->text(1)); item->setText(1, fitem->text(1));
@ -274,8 +296,9 @@ void HistoryManager::search(const QString &searchText)
void HistoryManager::optimizeDb() void HistoryManager::optimizeDb()
{ {
BrowsingLibrary* b = qobject_cast<BrowsingLibrary*>(parentWidget()->parentWidget()); BrowsingLibrary* b = qobject_cast<BrowsingLibrary*>(parentWidget()->parentWidget());
if (!b) if (!b) {
return; return;
}
b->optimizeDatabase(); b->optimizeDatabase();
} }

View File

@ -24,8 +24,9 @@
#include "historymodel.h" #include "historymodel.h"
namespace Ui { namespace Ui
class HistoryManager; {
class HistoryManager;
} }
class QupZilla; class QupZilla;

View File

@ -30,20 +30,23 @@ HistoryModel::HistoryModel(QupZilla* mainClass, QObject* parent)
void HistoryModel::loadSettings() void HistoryModel::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
m_isSaving = settings.value("allowHistory",true).toBool(); m_isSaving = settings.value("allowHistory", true).toBool();
settings.endGroup(); settings.endGroup();
} }
int HistoryModel::addHistoryEntry(const QString &url, QString &title) int HistoryModel::addHistoryEntry(const QString &url, QString &title)
{ {
if (!m_isSaving) if (!m_isSaving) {
return -2; return -2;
if (url.startsWith("file://") || url.startsWith("qupzilla:") || title.contains(tr("Failed loading page")) || url.isEmpty() || url.contains("about:blank") ) }
if (url.startsWith("file://") || url.startsWith("qupzilla:") || title.contains(tr("Failed loading page")) || url.isEmpty() || url.contains("about:blank")) {
return -1; return -1;
if (title == "") }
title=tr("No Named Page"); if (title == "") {
title = tr("No Named Page");
}
QSqlQuery query; QSqlQuery query;
query.prepare("SELECT id FROM history WHERE url=?"); query.prepare("SELECT id FROM history WHERE url=?");
@ -64,7 +67,8 @@ int HistoryModel::addHistoryEntry(const QString &url, QString &title)
entry.url = url; entry.url = url;
entry.title = title; entry.title = title;
emit historyEntryAdded(entry); emit historyEntryAdded(entry);
} else { }
else {
int id = query.value(0).toInt(); int id = query.value(0).toInt();
query.prepare("UPDATE history SET count = count + 1, date=?, title=? WHERE url=?"); query.prepare("UPDATE history SET count = count + 1, date=?, title=? WHERE url=?");
query.bindValue(0, QDateTime::currentMSecsSinceEpoch()); query.bindValue(0, QDateTime::currentMSecsSinceEpoch());
@ -87,8 +91,9 @@ int HistoryModel::addHistoryEntry(const QString &url, QString &title)
int HistoryModel::addHistoryEntry(WebView* view) int HistoryModel::addHistoryEntry(WebView* view)
{ {
if (!m_isSaving) if (!m_isSaving) {
return -2; return -2;
}
QString url = view->url().toEncoded(); QString url = view->url().toEncoded();
QString title = view->title(); QString title = view->title();
@ -101,8 +106,9 @@ bool HistoryModel::deleteHistoryEntry(int index)
query.prepare("SELECT id, count, date, url, title FROM history WHERE id=?"); query.prepare("SELECT id, count, date, url, title FROM history WHERE id=?");
query.bindValue(0, index); query.bindValue(0, index);
query.exec(); query.exec();
if (!query.next()) if (!query.next()) {
return false; return false;
}
HistoryEntry entry; HistoryEntry entry;
entry.id = query.value(0).toInt(); entry.id = query.value(0).toInt();
entry.count = query.value(1).toInt(); entry.count = query.value(1).toInt();
@ -151,7 +157,7 @@ QList<HistoryModel::HistoryEntry> HistoryModel::mostVisited(int count)
QList<HistoryEntry> list; QList<HistoryEntry> list;
QSqlQuery query; QSqlQuery query;
query.exec(QString("SELECT count, date, id, title, url FROM history ORDER BY count DESC LIMIT %1").arg(count)); query.exec(QString("SELECT count, date, id, title, url FROM history ORDER BY count DESC LIMIT %1").arg(count));
while(query.next()) { while (query.next()) {
HistoryEntry entry; HistoryEntry entry;
entry.count = query.value(0).toInt(); entry.count = query.value(0).toInt();
entry.date = query.value(1).toDateTime(); entry.date = query.value(1).toDateTime();

View File

@ -19,7 +19,7 @@
#include "mainapplication.h" #include "mainapplication.h"
#include "historymodel.h" #include "historymodel.h"
WebHistoryInterface::WebHistoryInterface(QObject *parent) : WebHistoryInterface::WebHistoryInterface(QObject* parent) :
QWebHistoryInterface(parent) QWebHistoryInterface(parent)
{ {
} }

View File

@ -25,7 +25,7 @@ class WebHistoryInterface : public QWebHistoryInterface
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit WebHistoryInterface(QObject *parent = 0); explicit WebHistoryInterface(QObject* parent = 0);
void addHistoryEntry(const QString &url); void addHistoryEntry(const QString &url);
bool historyContains(const QString &url) const; bool historyContains(const QString &url) const;

View File

@ -23,7 +23,7 @@
#include "commandlineoptions.h" #include "commandlineoptions.h"
#include "mainapplication.h" #include "mainapplication.h"
int main(int argc, char *argv[]) int main(int argc, char* argv[])
{ {
Q_INIT_RESOURCE(icons); Q_INIT_RESOURCE(icons);
Q_INIT_RESOURCE(html); Q_INIT_RESOURCE(html);
@ -38,7 +38,7 @@ int main(int argc, char *argv[])
if (argc > 1) { if (argc > 1) {
CommandLineOptions cmd(argc, argv); CommandLineOptions cmd(argc, argv);
cmdActions = cmd.getActions(); cmdActions = cmd.getActions();
foreach (CommandLineOptions::ActionPair pair, cmdActions) { foreach(CommandLineOptions::ActionPair pair, cmdActions) {
switch (pair.action) { switch (pair.action) {
case CommandLineOptions::ExitAction: case CommandLineOptions::ExitAction:
return 1; return 1;
@ -51,8 +51,9 @@ int main(int argc, char *argv[])
MainApplication app(cmdActions, argc, argv); MainApplication app(cmdActions, argc, argv);
if (app.isExited()) { if (app.isExited()) {
if (argc == 1) if (argc == 1) {
std::cout << "QupZilla already running - activating existing window" << std::endl; std::cout << "QupZilla already running - activating existing window" << std::endl;
}
return 1; return 1;
} }

View File

@ -113,10 +113,12 @@ void LocationBar::urlEnter()
if (urlToLoad.isEmpty()) { if (urlToLoad.isEmpty()) {
QUrl guessedUrl = WebView::guessUrlFromString(text()); QUrl guessedUrl = WebView::guessUrlFromString(text());
if (!guessedUrl.isEmpty()) if (!guessedUrl.isEmpty()) {
urlToLoad = guessedUrl; urlToLoad = guessedUrl;
else }
else {
urlToLoad = text(); urlToLoad = text();
}
} }
m_webView->load(urlToLoad); m_webView->load(urlToLoad);
@ -132,8 +134,9 @@ void LocationBar::textEdit()
void LocationBar::showGoButton() void LocationBar::showGoButton()
{ {
if (m_goButton->isVisible()) if (m_goButton->isVisible()) {
return; return;
}
m_rssIconVisible = m_rssIcon->isVisible(); m_rssIconVisible = m_rssIcon->isVisible();
@ -144,8 +147,9 @@ void LocationBar::showGoButton()
void LocationBar::hideGoButton() void LocationBar::hideGoButton()
{ {
if (!m_goButton->isVisible()) if (!m_goButton->isVisible()) {
return; return;
}
m_rssIcon->setVisible(m_rssIconVisible); m_rssIcon->setVisible(m_rssIconVisible);
m_bookmarkIcon->show(); m_bookmarkIcon->show();
@ -179,10 +183,11 @@ void LocationBar::showRSSIcon(bool state)
void LocationBar::showUrl(const QUrl &url, bool empty) void LocationBar::showUrl(const QUrl &url, bool empty)
{ {
if (hasFocus() || (url.isEmpty() && empty)) if (hasFocus() || (url.isEmpty() && empty)) {
return; return;
}
if (url.toEncoded()!=text()) { if (url.toEncoded() != text()) {
setText(url.toEncoded()); setText(url.toEncoded());
setCursorPosition(0); setCursorPosition(0);
} }
@ -199,8 +204,9 @@ void LocationBar::siteIconChanged()
if (icon_.isNull()) { if (icon_.isNull()) {
clearIcon(); clearIcon();
} else { }
m_siteIcon->setIcon(QIcon(icon_.pixmap(16,16))); else {
m_siteIcon->setIcon(QIcon(icon_.pixmap(16, 16)));
} }
} }
@ -219,8 +225,9 @@ void LocationBar::setPrivacy(bool state)
void LocationBar::focusOutEvent(QFocusEvent* e) void LocationBar::focusOutEvent(QFocusEvent* e)
{ {
QLineEdit::focusOutEvent(e); QLineEdit::focusOutEvent(e);
if (!selectedText().isEmpty() && e->reason() != Qt::TabFocusReason) if (!selectedText().isEmpty() && e->reason() != Qt::TabFocusReason) {
return; return;
}
setCursorPosition(0); setCursorPosition(0);
hideGoButton(); hideGoButton();
} }
@ -251,13 +258,15 @@ void LocationBar::dropEvent(QDropEvent* event)
void LocationBar::mouseDoubleClickEvent(QMouseEvent* event) void LocationBar::mouseDoubleClickEvent(QMouseEvent* event)
{ {
if (event->button() == Qt::LeftButton && m_locationBarSettings->selectAllOnDoubleClick) if (event->button() == Qt::LeftButton && m_locationBarSettings->selectAllOnDoubleClick) {
selectAll(); selectAll();
else }
else {
QLineEdit::mouseDoubleClickEvent(event); QLineEdit::mouseDoubleClickEvent(event);
}
} }
void LocationBar::keyPressEvent(QKeyEvent *event) void LocationBar::keyPressEvent(QKeyEvent* event)
{ {
if (event->key() == Qt::Key_Escape) { if (event->key() == Qt::Key_Escape) {
setText(m_webView->url().toEncoded()); setText(m_webView->url().toEncoded());
@ -265,11 +274,13 @@ void LocationBar::keyPressEvent(QKeyEvent *event)
return; return;
} }
QString localDomain = tr(".co.uk","Append domain name on ALT key = Should be different for every country"); QString localDomain = tr(".co.uk", "Append domain name on ALT key = Should be different for every country");
if (event->key() == Qt::Key_Control && m_locationBarSettings->addComWithCtrl && !text().endsWith(".com")) //Disabled for a while if (event->key() == Qt::Key_Control && m_locationBarSettings->addComWithCtrl && !text().endsWith(".com")) { //Disabled for a while
setText(text().append(".com")); setText(text().append(".com"));
if (event->key() == Qt::Key_Alt && m_locationBarSettings->addCountryWithAlt && !text().endsWith(localDomain) && !text().endsWith("/")) }
if (event->key() == Qt::Key_Alt && m_locationBarSettings->addCountryWithAlt && !text().endsWith(localDomain) && !text().endsWith("/")) {
setText(text().append(localDomain)); setText(text().append(localDomain));
}
QLineEdit::keyPressEvent(event); QLineEdit::keyPressEvent(event);
} }

View File

@ -30,16 +30,17 @@ LocationBarSettings::LocationBarSettings()
LocationBarSettings* LocationBarSettings::instance() LocationBarSettings* LocationBarSettings::instance()
{ {
if (!s_instance) if (!s_instance) {
s_instance = new LocationBarSettings(); s_instance = new LocationBarSettings();
}
return s_instance; return s_instance;
} }
void LocationBarSettings::loadSettings() void LocationBarSettings::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("AddressBar"); settings.beginGroup("AddressBar");
selectAllOnDoubleClick = settings.value("SelectAllTextOnDoubleClick",true).toBool(); selectAllOnDoubleClick = settings.value("SelectAllTextOnDoubleClick", true).toBool();
addComWithCtrl = settings.value("AddComDomainWithCtrlKey",false).toBool(); addComWithCtrl = settings.value("AddComDomainWithCtrlKey", false).toBool();
addCountryWithAlt = settings.value("AddCountryDomainWithAltKey",true).toBool(); addCountryWithAlt = settings.value("AddCountryDomainWithAltKey", true).toBool();
} }

View File

@ -34,7 +34,7 @@ LocationCompleter::LocationCompleter(QObject* parent) :
treeView->header()->hide(); treeView->header()->hide();
treeView->header()->setStretchLastSection(false); treeView->header()->setStretchLastSection(false);
treeView->header()->setResizeMode(0, QHeaderView::Stretch); treeView->header()->setResizeMode(0, QHeaderView::Stretch);
treeView->header()->resizeSection(1,0); treeView->header()->resizeSection(1, 0);
setCompletionMode(QCompleter::PopupCompletion); setCompletionMode(QCompleter::PopupCompletion);
setCaseSensitivity(Qt::CaseInsensitive); setCaseSensitivity(Qt::CaseInsensitive);
@ -56,50 +56,56 @@ QStringList LocationCompleter::splitPath(const QString &path) const
QStringList returned = QCompleter::splitPath(path); QStringList returned = QCompleter::splitPath(path);
QStringList returned2; QStringList returned2;
QSqlQuery query; QSqlQuery query;
query.exec("SELECT url FROM history WHERE title LIKE '%"+path+"%' OR url LIKE '%"+path+"%' ORDER BY count DESC LIMIT 1"); query.exec("SELECT url FROM history WHERE title LIKE '%" + path + "%' OR url LIKE '%" + path + "%' ORDER BY count DESC LIMIT 1");
if (query.next()) { if (query.next()) {
QString url = query.value(0).toString(); QString url = query.value(0).toString();
bool titleSearching = false; bool titleSearching = false;
if (!url.contains(path)) if (!url.contains(path)) {
titleSearching = true; titleSearching = true;
QString prefix = url.mid(0,url.indexOf(path)); }
foreach (QString string, returned) { QString prefix = url.mid(0, url.indexOf(path));
if (titleSearching) foreach(QString string, returned) {
if (titleSearching) {
returned2.append(url); returned2.append(url);
else }
returned2.append(prefix+string); else {
returned2.append(prefix + string);
}
} }
return returned2; return returned2;
} else { }
foreach (QString string, returned) else {
returned2.append("http://www.google.com/search?client=qupzilla&q=" + string); foreach(QString string, returned)
returned2.append("http://www.google.com/search?client=qupzilla&q=" + string);
return returned2; return returned2;
} }
#endif #endif
} }
void LocationCompleter::refreshCompleter(QString string) void LocationCompleter::refreshCompleter(const QString &string)
{ {
int limit; int limit;
if (string.size() < 3) if (string.size() < 3) {
limit = 25; limit = 25;
else }
else {
limit = 15; limit = 15;
}
QSqlQuery query; QSqlQuery query;
query.exec("SELECT title, url FROM history WHERE title LIKE '%"+string+"%' OR url LIKE '%"+string+"%' ORDER BY count DESC LIMIT "+QString::number(limit)); query.exec("SELECT title, url FROM history WHERE title LIKE '%" + string + "%' OR url LIKE '%" + string + "%' ORDER BY count DESC LIMIT " + QString::number(limit));
int i = 0; int i = 0;
QStandardItemModel* cModel = qobject_cast<QStandardItemModel*>(model()); QStandardItemModel* cModel = qobject_cast<QStandardItemModel*>(model());
QTreeView* treeView = qobject_cast<QTreeView*>(popup()); QTreeView* treeView = qobject_cast<QTreeView*>(popup());
cModel->clear(); cModel->clear();
while(query.next()) { while (query.next()) {
QStandardItem* iconText = new QStandardItem(); QStandardItem* iconText = new QStandardItem();
QStandardItem* findUrl = new QStandardItem(); QStandardItem* findUrl = new QStandardItem();
QString url = query.value(1).toUrl().toEncoded(); QString url = query.value(1).toUrl().toEncoded();
iconText->setIcon(_iconForUrl(query.value(1).toUrl()).pixmap(16,16)); iconText->setIcon(_iconForUrl(query.value(1).toUrl()).pixmap(16, 16));
iconText->setText(query.value(0).toString().replace("\n","").append("\n"+url)); iconText->setText(query.value(0).toString().replace("\n", "").append("\n" + url));
findUrl->setText(url); findUrl->setText(url);
QList<QStandardItem*> items; QList<QStandardItem*> items;
@ -124,12 +130,14 @@ void LocationCompleter::refreshCompleter(QString string)
// } // }
treeView->header()->setResizeMode(0, QHeaderView::Stretch); treeView->header()->setResizeMode(0, QHeaderView::Stretch);
treeView->header()->resizeSection(1,0); treeView->header()->resizeSection(1, 0);
if (i>6) if (i > 6) {
popup()->setMinimumHeight(190); popup()->setMinimumHeight(190);
else }
else {
popup()->setMinimumHeight(0); popup()->setMinimumHeight(0);
}
popup()->setUpdatesEnabled(true); popup()->setUpdatesEnabled(true);
} }

View File

@ -40,7 +40,7 @@ public:
signals: signals:
public slots: public slots:
void refreshCompleter(QString string); void refreshCompleter(const QString &string);
}; };

View File

@ -17,8 +17,8 @@
* ============================================================ */ * ============================================================ */
#include "locationpopup.h" #include "locationpopup.h"
LocationPopup::LocationPopup(QWidget* parent) LocationPopup::LocationPopup(QWidget* parent)
:QAbstractItemView() : QAbstractItemView()
,m_parent(parent) , m_parent(parent)
{ {
setWindowFlags(Qt::Popup); setWindowFlags(Qt::Popup);
} }
@ -26,7 +26,7 @@ LocationPopup::LocationPopup(QWidget* parent)
void LocationPopup::show() void LocationPopup::show()
{ {
QPoint p = m_parent->mapToGlobal(QPoint(0, 0)); QPoint p = m_parent->mapToGlobal(QPoint(0, 0));
move( (p.x() ), (p.y() + m_parent->height())); move((p.x()), (p.y() + m_parent->height()));
resize(m_parent->width(), 100); resize(m_parent->width(), 100);
QAbstractItemView::show(); QAbstractItemView::show();
} }

View File

@ -23,7 +23,7 @@
#include "reloadstopbutton.h" #include "reloadstopbutton.h"
#include "webhistorywrapper.h" #include "webhistorywrapper.h"
NavigationBar::NavigationBar(QupZilla *mainClass, QWidget *parent) NavigationBar::NavigationBar(QupZilla* mainClass, QWidget* parent)
: QWidget(parent) : QWidget(parent)
, p_QupZilla(mainClass) , p_QupZilla(mainClass)
{ {
@ -120,7 +120,8 @@ void NavigationBar::setSplitterSizes(int locationBar, int websearchBar)
if (locationBar == 0) { if (locationBar == 0) {
int splitterWidth = m_navigationSplitter->width(); int splitterWidth = m_navigationSplitter->width();
sizes << (int)((double)splitterWidth * .80) << (int)((double)splitterWidth * .20); sizes << (int)((double)splitterWidth * .80) << (int)((double)splitterWidth * .20);
} else { }
else {
sizes << locationBar << websearchBar; sizes << locationBar << websearchBar;
} }
@ -139,8 +140,9 @@ void NavigationBar::showStopButton()
void NavigationBar::aboutToShowHistoryBackMenu() void NavigationBar::aboutToShowHistoryBackMenu()
{ {
if (!m_menuBack || !p_QupZilla->weView()) if (!m_menuBack || !p_QupZilla->weView()) {
return; return;
}
m_menuBack->clear(); m_menuBack->clear();
QWebHistory* history = p_QupZilla->weView()->history(); QWebHistory* history = p_QupZilla->weView()->history();
@ -148,7 +150,7 @@ void NavigationBar::aboutToShowHistoryBackMenu()
int count = 0; int count = 0;
QUrl lastUrl = history->currentItem().url(); QUrl lastUrl = history->currentItem().url();
for (int i = curindex-1; i >= 0; i--) { for (int i = curindex - 1; i >= 0; i--) {
QWebHistoryItem item = history->itemAt(i); QWebHistoryItem item = history->itemAt(i);
if (item.isValid() && lastUrl != item.url()) { if (item.isValid() && lastUrl != item.url()) {
QString title = item.title(); QString title = item.title();
@ -156,14 +158,15 @@ void NavigationBar::aboutToShowHistoryBackMenu()
title.truncate(40); title.truncate(40);
title += ".."; title += "..";
} }
QAction* action = m_menuBack->addAction(_iconForUrl(item.url()),title, this, SLOT(goAtHistoryIndex())); QAction* action = m_menuBack->addAction(_iconForUrl(item.url()), title, this, SLOT(goAtHistoryIndex()));
action->setData(i); action->setData(i);
lastUrl = item.url(); lastUrl = item.url();
} }
count++; count++;
if (count == 20) if (count == 20) {
break; break;
}
} }
m_menuBack->addSeparator(); m_menuBack->addSeparator();
@ -172,8 +175,9 @@ void NavigationBar::aboutToShowHistoryBackMenu()
void NavigationBar::aboutToShowHistoryNextMenu() void NavigationBar::aboutToShowHistoryNextMenu()
{ {
if (!m_menuForward || !p_QupZilla->weView()) if (!m_menuForward || !p_QupZilla->weView()) {
return; return;
}
m_menuForward->clear(); m_menuForward->clear();
QWebHistory* history = p_QupZilla->weView()->history(); QWebHistory* history = p_QupZilla->weView()->history();
@ -181,7 +185,7 @@ void NavigationBar::aboutToShowHistoryNextMenu()
int count = 0; int count = 0;
QUrl lastUrl = history->currentItem().url(); QUrl lastUrl = history->currentItem().url();
for (int i = curindex+1; i < history->count(); i++) { for (int i = curindex + 1; i < history->count(); i++) {
QWebHistoryItem item = history->itemAt(i); QWebHistoryItem item = history->itemAt(i);
if (item.isValid() && lastUrl != item.url()) { if (item.isValid() && lastUrl != item.url()) {
QString title = item.title(); QString title = item.title();
@ -189,14 +193,15 @@ void NavigationBar::aboutToShowHistoryNextMenu()
title.truncate(40); title.truncate(40);
title += ".."; title += "..";
} }
QAction* action = m_menuForward->addAction(_iconForUrl(item.url()),title, this, SLOT(goAtHistoryIndex())); QAction* action = m_menuForward->addAction(_iconForUrl(item.url()), title, this, SLOT(goAtHistoryIndex()));
action->setData(i); action->setData(i);
lastUrl = item.url(); lastUrl = item.url();
} }
count++; count++;
if (count == 20) if (count == 20) {
break; break;
}
} }
m_menuForward->addSeparator(); m_menuForward->addSeparator();
@ -221,8 +226,9 @@ void NavigationBar::goAtHistoryIndex()
void NavigationBar::refreshHistory() void NavigationBar::refreshHistory()
{ {
if (mApp->isClosing() || p_QupZilla->isClosing()) if (mApp->isClosing() || p_QupZilla->isClosing()) {
return; return;
}
QWebHistory* history = p_QupZilla->weView()->page()->history(); QWebHistory* history = p_QupZilla->weView()->page()->history();
m_buttonBack->setEnabled(WebHistoryWrapper::canGoBack(history)); m_buttonBack->setEnabled(WebHistoryWrapper::canGoBack(history));

View File

@ -31,7 +31,7 @@ class NavigationBar : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit NavigationBar(QupZilla* mainClass, QWidget *parent = 0); explicit NavigationBar(QupZilla* mainClass, QWidget* parent = 0);
~NavigationBar(); ~NavigationBar();
void setSplitterSizes(int locationBar, int websearchBar); void setSplitterSizes(int locationBar, int websearchBar);

View File

@ -17,7 +17,7 @@
* ============================================================ */ * ============================================================ */
#include "reloadstopbutton.h" #include "reloadstopbutton.h"
ReloadStopButton::ReloadStopButton(QWidget *parent) : ReloadStopButton::ReloadStopButton(QWidget* parent) :
QWidget(parent) QWidget(parent)
{ {
QHBoxLayout* lay = new QHBoxLayout(this); QHBoxLayout* lay = new QHBoxLayout(this);

View File

@ -26,7 +26,7 @@ class ReloadStopButton : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ReloadStopButton(QWidget *parent = 0); explicit ReloadStopButton(QWidget* parent = 0);
~ReloadStopButton(); ~ReloadStopButton();
void showStopButton(); void showStopButton();

View File

@ -99,12 +99,13 @@ void WebSearchBar::setupEngines()
QString activeEngine = m_searchManager->startingEngineName(); QString activeEngine = m_searchManager->startingEngineName();
if (m_boxSearchType->allItems().count() != 0) if (m_boxSearchType->allItems().count() != 0) {
activeEngine = m_activeEngine.name; activeEngine = m_activeEngine.name;
}
m_boxSearchType->clearItems(); m_boxSearchType->clearItems();
foreach (SearchEngine en, m_searchManager->allEngines()) { foreach(SearchEngine en, m_searchManager->allEngines()) {
ButtonWithMenu::Item item; ButtonWithMenu::Item item;
item.icon = en.icon; item.icon = en.icon;
item.text = en.name; item.text = en.name;
@ -114,8 +115,9 @@ void WebSearchBar::setupEngines()
m_boxSearchType->addItem(item); m_boxSearchType->addItem(item);
if (item.text == activeEngine) if (item.text == activeEngine) {
m_boxSearchType->setCurrentItem(item); m_boxSearchType->setCurrentItem(item);
}
} }
connect(m_searchManager, SIGNAL(enginesChanged()), this, SLOT(setupEngines())); connect(m_searchManager, SIGNAL(enginesChanged()), this, SLOT(setupEngines()));
@ -140,22 +142,25 @@ void WebSearchBar::search()
p_QupZilla->weView()->setFocus(); p_QupZilla->weView()->setFocus();
} }
void WebSearchBar::completeMenuWithAvailableEngines(QMenu *menu) void WebSearchBar::completeMenuWithAvailableEngines(QMenu* menu)
{ {
WebView* view = p_QupZilla->weView(); WebView* view = p_QupZilla->weView();
QWebFrame* frame = view->webPage()->mainFrame(); QWebFrame* frame = view->webPage()->mainFrame();
QWebElementCollection elements = frame->documentElement().findAll(QLatin1String("link[rel=search]")); QWebElementCollection elements = frame->documentElement().findAll(QLatin1String("link[rel=search]"));
foreach (QWebElement element, elements) { foreach(QWebElement element, elements) {
if (element.attribute("type") != "application/opensearchdescription+xml") if (element.attribute("type") != "application/opensearchdescription+xml") {
continue; continue;
}
QString url = view->url().resolved(element.attribute("href")).toString(); QString url = view->url().resolved(element.attribute("href")).toString();
QString title = element.attribute("title"); QString title = element.attribute("title");
if (url.isEmpty()) if (url.isEmpty()) {
continue; continue;
if (title.isEmpty()) }
if (title.isEmpty()) {
title = view->title(); title = view->title();
}
menu->addAction(view->icon(), tr("Add %1 ...").arg(title), this, SLOT(addEngineFromAction()))->setData(url); menu->addAction(view->icon(), tr("Add %1 ...").arg(title), this, SLOT(addEngineFromAction()))->setData(url);
} }

View File

@ -37,9 +37,9 @@ NetworkManager::NetworkManager(QupZilla* mainClass, QObject* parent)
, m_qupzillaSchemeHandler(new QupZillaSchemeHandler) , m_qupzillaSchemeHandler(new QupZillaSchemeHandler)
, m_ignoreAllWarnings(false) , m_ignoreAllWarnings(false)
{ {
connect(this, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this, SLOT(authentication(QNetworkReply*, QAuthenticator* ))); connect(this, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), this, SLOT(authentication(QNetworkReply*, QAuthenticator*)));
connect(this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), this, SLOT(proxyAuthentication(QNetworkProxy,QAuthenticator*))); connect(this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)), this, SLOT(proxyAuthentication(QNetworkProxy, QAuthenticator*)));
connect(this, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(sslError(QNetworkReply*,QList<QSslError>))); connect(this, SIGNAL(sslErrors(QNetworkReply*, QList<QSslError>)), this, SLOT(sslError(QNetworkReply*, QList<QSslError>)));
connect(this, SIGNAL(finished(QNetworkReply*)), this, SLOT(setSSLConfiguration(QNetworkReply*))); connect(this, SIGNAL(finished(QNetworkReply*)), this, SLOT(setSSLConfiguration(QNetworkReply*)));
m_proxyFactory = new NetworkProxyFactory(); m_proxyFactory = new NetworkProxyFactory();
@ -49,13 +49,13 @@ NetworkManager::NetworkManager(QupZilla* mainClass, QObject* parent)
void NetworkManager::loadSettings() void NetworkManager::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Browser-Settings"); settings.beginGroup("Web-Browser-Settings");
if (settings.value("AllowLocalCache", true).toBool()) { if (settings.value("AllowLocalCache", true).toBool()) {
m_diskCache = mApp->networkCache(); m_diskCache = mApp->networkCache();
m_diskCache->setCacheDirectory(mApp->getActiveProfilPath()+"/networkcache"); m_diskCache->setCacheDirectory(mApp->getActiveProfilPath() + "/networkcache");
m_diskCache->setMaximumCacheSize(settings.value("MaximumCacheSize",50).toInt() * 1024*1024); //MegaBytes m_diskCache->setMaximumCacheSize(settings.value("MaximumCacheSize", 50).toInt() * 1024 * 1024); //MegaBytes
setCache(m_diskCache); setCache(m_diskCache);
} }
m_doNotTrack = settings.value("DoNotTrack", false).toBool(); m_doNotTrack = settings.value("DoNotTrack", false).toBool();
@ -75,23 +75,26 @@ void NetworkManager::loadSettings()
m_proxyFactory->loadSettings(); m_proxyFactory->loadSettings();
} }
void NetworkManager::setSSLConfiguration(QNetworkReply *reply) void NetworkManager::setSSLConfiguration(QNetworkReply* reply)
{ {
if (!reply->sslConfiguration().isNull()) { if (!reply->sslConfiguration().isNull()) {
QSslCertificate cert = reply->sslConfiguration().peerCertificate(); QSslCertificate cert = reply->sslConfiguration().peerCertificate();
if (!cert.isValid()) if (!cert.isValid()) {
return; return;
}
QNetworkRequest request = reply->request(); QNetworkRequest request = reply->request();
QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
WebPage* webPage = (WebPage*)(v.value<void*>()); WebPage* webPage = (WebPage*)(v.value<void*>());
v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 102)); v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 102));
WebView* webView = (WebView*)(v.value<void*>()); WebView* webView = (WebView*)(v.value<void*>());
if (!webPage || !webView) if (!webPage || !webView) {
return; return;
}
if (webView->url().host() == reply->url().host()) if (webView->url().host() == reply->url().host()) {
webPage->setSSLCertificate( cert ); webPage->setSSLCertificate(cert);
}
} }
} }
@ -105,19 +108,22 @@ void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
QNetworkRequest request = reply->request(); QNetworkRequest request = reply->request();
QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100)); QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
WebPage* webPage = (WebPage*)(v.value<void*>()); WebPage* webPage = (WebPage*)(v.value<void*>());
if (!webPage) if (!webPage) {
return; return;
}
QString title = tr("SSL Certificate Error!"); QString title = tr("SSL Certificate Error!");
QString text1 = tr("The page you trying to access has following errors in SSL Certificate:"); QString text1 = tr("The page you trying to access has following errors in SSL Certificate:");
QStringList actions; QStringList actions;
foreach (QSslError error, errors) { foreach(QSslError error, errors) {
if (m_localCerts.contains(error.certificate())) if (m_localCerts.contains(error.certificate())) {
continue; continue;
if (error.error() == QSslError::NoError) //Weird behavior on Windows }
if (error.error() == QSslError::NoError) { //Weird behavior on Windows
continue; continue;
}
QSslCertificate cert = error.certificate(); QSslCertificate cert = error.certificate();
actions.append(tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization))); actions.append(tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization)));
@ -134,13 +140,15 @@ void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
// message, QMessageBox::Yes | QMessageBox::No); // message, QMessageBox::Yes | QMessageBox::No);
// if (button != QMessageBox::Yes) // if (button != QMessageBox::Yes)
// return; // return;
if (!webPage->javaScriptConfirm(webPage->mainFrame(), message)) if (!webPage->javaScriptConfirm(webPage->mainFrame(), message)) {
return; return;
}
} }
foreach (QSslError error, errors) { foreach(QSslError error, errors) {
if (m_localCerts.contains(error.certificate())) if (m_localCerts.contains(error.certificate())) {
continue; continue;
}
addLocalCertificate(error.certificate()); addLocalCertificate(error.certificate());
} }
@ -190,19 +198,22 @@ void NetworkManager::authentication(QNetworkReply* reply, QAuthenticator* auth)
emit wantsFocus(reply->url()); emit wantsFocus(reply->url());
//Do not save when private browsing is enabled //Do not save when private browsing is enabled
if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
save->setVisible(false); save->setVisible(false);
}
if (!dialog->exec() == QDialog::Accepted) if (!dialog->exec() == QDialog::Accepted) {
return; return;
}
auth->setUser(user->text()); auth->setUser(user->text());
auth->setPassword(pass->text()); auth->setPassword(pass->text());
if (save->isChecked()) if (save->isChecked()) {
fill->addEntry(reply->url(), user->text(), pass->text()); fill->addEntry(reply->url(), user->text(), pass->text());
}
} }
void NetworkManager::proxyAuthentication(const QNetworkProxy &proxy, QAuthenticator *auth) void NetworkManager::proxyAuthentication(const QNetworkProxy &proxy, QAuthenticator* auth)
{ {
QDialog* dialog = new QDialog(p_QupZilla); QDialog* dialog = new QDialog(p_QupZilla);
dialog->setWindowTitle(tr("Proxy authorization required")); dialog->setWindowTitle(tr("Proxy authorization required"));
@ -231,8 +242,9 @@ void NetworkManager::proxyAuthentication(const QNetworkProxy &proxy, QAuthentica
formLa->addRow(passLab, pass); formLa->addRow(passLab, pass);
formLa->addWidget(box); formLa->addWidget(box);
if (!dialog->exec() == QDialog::Accepted) if (!dialog->exec() == QDialog::Accepted) {
return; return;
}
auth->setUser(user->text()); auth->setUser(user->text());
auth->setPassword(pass->text()); auth->setPassword(pass->text());
} }
@ -240,35 +252,41 @@ void NetworkManager::proxyAuthentication(const QNetworkProxy &proxy, QAuthentica
QNetworkReply* NetworkManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice* outgoingData) QNetworkReply* NetworkManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice* outgoingData)
{ {
if (op == PostOperation && outgoingData) { if (op == PostOperation && outgoingData) {
QByteArray outgoingDataByteArray = outgoingData->peek(1024 * 1024); QByteArray outgoingDataByteArray = outgoingData->peek(1024 * 1024);
mApp->autoFill()->post(request, outgoingDataByteArray); mApp->autoFill()->post(request, outgoingDataByteArray);
} }
QNetworkRequest req = request; QNetworkRequest req = request;
QNetworkReply* reply = 0; QNetworkReply* reply = 0;
if (m_doNotTrack) if (m_doNotTrack) {
req.setRawHeader("DNT", "1"); req.setRawHeader("DNT", "1");
}
req.setRawHeader("Accept-Language", m_acceptLanguage); req.setRawHeader("Accept-Language", m_acceptLanguage);
//SchemeHandlers //SchemeHandlers
if (req.url().scheme() == "qupzilla") if (req.url().scheme() == "qupzilla") {
reply = m_qupzillaSchemeHandler->createRequest(op, req, outgoingData); reply = m_qupzillaSchemeHandler->createRequest(op, req, outgoingData);
if (reply) }
if (reply) {
return reply; return reply;
}
req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
if (req.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() == QNetworkRequest::PreferNetwork) if (req.attribute(QNetworkRequest::CacheLoadControlAttribute).toInt() == QNetworkRequest::PreferNetwork) {
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
}
// Adblock // Adblock
if (op == QNetworkAccessManager::GetOperation) { if (op == QNetworkAccessManager::GetOperation) {
if (!m_adblockNetwork) if (!m_adblockNetwork) {
m_adblockNetwork = AdBlockManager::instance()->network(); m_adblockNetwork = AdBlockManager::instance()->network();
}
reply = m_adblockNetwork->block(req); reply = m_adblockNetwork->block(req);
if (reply) if (reply) {
return reply; return reply;
}
} }
reply = QNetworkAccessManager::createRequest(op, req, outgoingData); reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
@ -288,8 +306,9 @@ void NetworkManager::removeLocalCertificate(const QSslCertificate &cert)
QDirIterator it(mApp->getActiveProfilPath() + "certificates", QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories); QDirIterator it(mApp->getActiveProfilPath() + "certificates", QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
while (it.hasNext()) { while (it.hasNext()) {
QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex); QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex);
if (!filePath.contains(certFileName)) if (!filePath.contains(certFileName)) {
continue; continue;
}
QFile file(filePath); QFile file(filePath);
file.remove(); file.remove();
@ -299,15 +318,17 @@ void NetworkManager::removeLocalCertificate(const QSslCertificate &cert)
void NetworkManager::addLocalCertificate(const QSslCertificate &cert) void NetworkManager::addLocalCertificate(const QSslCertificate &cert)
{ {
if (!cert.isValid()) if (!cert.isValid()) {
return; return;
}
m_localCerts.append(cert); m_localCerts.append(cert);
QSslSocket::addDefaultCaCertificate(cert); QSslSocket::addDefaultCaCertificate(cert);
QDir dir(mApp->getActiveProfilPath()); QDir dir(mApp->getActiveProfilPath());
if (!dir.exists("certificates")) if (!dir.exists("certificates")) {
dir.mkdir("certificates"); dir.mkdir("certificates");
}
QString fileName = qz_ensureUniqueFilename(mApp->getActiveProfilPath() + "certificates/" + CertificateInfoWidget::certificateItemText(cert).remove(" ") + ".crt"); QString fileName = qz_ensureUniqueFilename(mApp->getActiveProfilPath() + "certificates/" + CertificateInfoWidget::certificateItemText(cert).remove(" ") + ".crt");
QFile file(fileName); QFile file(fileName);
@ -336,7 +357,7 @@ void NetworkManager::loadCertificates()
//CA Certificates //CA Certificates
m_caCerts = QSslSocket::defaultCaCertificates(); m_caCerts = QSslSocket::defaultCaCertificates();
foreach (QString path, m_certPaths) { foreach(QString path, m_certPaths) {
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
// Used from Qt 4.7.4 qsslcertificate.cpp and modified because QSslCertificate::fromPath // Used from Qt 4.7.4 qsslcertificate.cpp and modified because QSslCertificate::fromPath
// is kind of a bugged on Windows, it does work only with full path to cert file // is kind of a bugged on Windows, it does work only with full path to cert file
@ -344,12 +365,14 @@ void NetworkManager::loadCertificates()
QDirIterator it(path, QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories); QDirIterator it(path, QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
while (it.hasNext()) { while (it.hasNext()) {
QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex); QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex);
if (!filePath.endsWith(".crt")) if (!filePath.endsWith(".crt")) {
continue; continue;
}
QFile file(filePath); QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_caCerts += QSslCertificate::fromData(file.readAll(), QSsl::Pem); m_caCerts += QSslCertificate::fromData(file.readAll(), QSsl::Pem);
}
} }
#else #else
m_caCerts += QSslCertificate::fromPath(path + "/*.crt", QSsl::Pem, QRegExp::Wildcard); m_caCerts += QSslCertificate::fromPath(path + "/*.crt", QSsl::Pem, QRegExp::Wildcard);
@ -357,19 +380,21 @@ void NetworkManager::loadCertificates()
} }
//Local Certificates //Local Certificates
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
int startIndex = 0; int startIndex = 0;
QDirIterator it_(mApp->getActiveProfilPath() + "certificates", QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories); QDirIterator it_(mApp->getActiveProfilPath() + "certificates", QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
while (it_.hasNext()) { while (it_.hasNext()) {
QString filePath = startIndex == 0 ? it_.next() : it_.next().mid(startIndex); QString filePath = startIndex == 0 ? it_.next() : it_.next().mid(startIndex);
if (!filePath.endsWith(".crt")) if (!filePath.endsWith(".crt")) {
continue; continue;
QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
m_localCerts += QSslCertificate::fromData(file.readAll(), QSsl::Pem);
} }
QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_localCerts += QSslCertificate::fromData(file.readAll(), QSsl::Pem);
}
}
#else #else
m_localCerts += QSslCertificate::fromPath(mApp->getActiveProfilPath() + "certificates/*.crt", QSsl::Pem, QRegExp::Wildcard); m_localCerts += QSslCertificate::fromPath(mApp->getActiveProfilPath() + "certificates/*.crt", QSsl::Pem, QRegExp::Wildcard);
#endif #endif
QSslSocket::setDefaultCaCertificates(m_caCerts + m_localCerts); QSslSocket::setDefaultCaCertificates(m_caCerts + m_localCerts);

View File

@ -69,7 +69,7 @@ signals:
private slots: private slots:
void authentication(QNetworkReply* reply, QAuthenticator* auth); void authentication(QNetworkReply* reply, QAuthenticator* auth);
void proxyAuthentication(const QNetworkProxy& proxy,QAuthenticator* auth); void proxyAuthentication(const QNetworkProxy &proxy, QAuthenticator* auth);
void sslError(QNetworkReply* reply, QList<QSslError> errors); void sslError(QNetworkReply* reply, QList<QSslError> errors);
void setSSLConfiguration(QNetworkReply* reply); void setSSLConfiguration(QNetworkReply* reply);

View File

@ -22,11 +22,12 @@
#include "cookiejar.h" #include "cookiejar.h"
#include "mainapplication.h" #include "mainapplication.h"
NetworkManagerProxy::NetworkManagerProxy(QupZilla* mainClass, QObject* parent) : NetworkManagerProxy::NetworkManagerProxy(QupZilla* mainClass, QObject* parent)
QNetworkAccessManager(parent) : QNetworkAccessManager(parent)
,p_QupZilla(mainClass) , p_QupZilla(mainClass)
,m_view(0) , m_view(0)
,m_page(0) , m_page(0)
, m_manager(0)
{ {
setCookieJar(mApp->cookieJar()); setCookieJar(mApp->cookieJar());
} }
@ -34,7 +35,7 @@ NetworkManagerProxy::NetworkManagerProxy(QupZilla* mainClass, QObject* parent) :
void NetworkManagerProxy::populateNetworkRequest(QNetworkRequest &request) void NetworkManagerProxy::populateNetworkRequest(QNetworkRequest &request)
{ {
qDebug() << __FUNCTION__ << "called"; qDebug() << __FUNCTION__ << "called";
QVariant variant = qVariantFromValue((void *) m_page); QVariant variant = qVariantFromValue((void*) m_page);
request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100), variant); request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100), variant);
} }
@ -44,7 +45,7 @@ void NetworkManagerProxy::setPrimaryNetworkAccessManager(NetworkManager* manager
m_manager = manager; m_manager = manager;
connect(this, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*))); connect(this, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)));
connect(this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); connect(this, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)), manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)));
connect(this, SIGNAL(finished(QNetworkReply*)), manager, SIGNAL(finished(QNetworkReply*))); connect(this, SIGNAL(finished(QNetworkReply*)), manager, SIGNAL(finished(QNetworkReply*)));
connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)), manager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&))); connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)), manager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)));
} }

View File

@ -18,14 +18,15 @@
#include "networkproxyfactory.h" #include "networkproxyfactory.h"
#include "mainapplication.h" #include "mainapplication.h"
NetworkProxyFactory::NetworkProxyFactory() : NetworkProxyFactory::NetworkProxyFactory()
QNetworkProxyFactory() : QNetworkProxyFactory()
, m_proxyPreference(SystemProxy)
{ {
} }
void NetworkProxyFactory::loadSettings() void NetworkProxyFactory::loadSettings()
{ {
QSettings settings(mApp->getActiveProfilPath()+"settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Web-Proxy"); settings.beginGroup("Web-Proxy");
m_proxyPreference = ProxyPreference(settings.value("UseProxy", SystemProxy).toInt()); m_proxyPreference = ProxyPreference(settings.value("UseProxy", SystemProxy).toInt());
m_proxyType = QNetworkProxy::ProxyType(settings.value("ProxyType", QNetworkProxy::HttpProxy).toInt()); m_proxyType = QNetworkProxy::ProxyType(settings.value("ProxyType", QNetworkProxy::HttpProxy).toInt());
@ -41,8 +42,9 @@ QList<QNetworkProxy> NetworkProxyFactory::queryProxy(const QNetworkProxyQuery &q
{ {
QNetworkProxy proxy; QNetworkProxy proxy;
if (m_proxyExceptions.contains(query.url().host(), Qt::CaseInsensitive)) if (m_proxyExceptions.contains(query.url().host(), Qt::CaseInsensitive)) {
proxy.setType(QNetworkProxy::NoProxy); proxy.setType(QNetworkProxy::NoProxy);
}
switch (m_proxyPreference) { switch (m_proxyPreference) {
case SystemProxy: case SystemProxy:

View File

@ -35,14 +35,15 @@ QNetworkReply* QupZillaSchemeHandler::createRequest(QNetworkAccessManager::Opera
{ {
Q_UNUSED(outgoingData) Q_UNUSED(outgoingData)
if (op != QNetworkAccessManager::GetOperation) if (op != QNetworkAccessManager::GetOperation) {
return 0; return 0;
}
QupZillaSchemeReply* reply = new QupZillaSchemeReply(request); QupZillaSchemeReply* reply = new QupZillaSchemeReply(request);
return reply; return reply;
} }
QupZillaSchemeReply::QupZillaSchemeReply(const QNetworkRequest &req, QObject *parent) QupZillaSchemeReply::QupZillaSchemeReply(const QNetworkRequest &req, QObject* parent)
: QNetworkReply(parent) : QNetworkReply(parent)
{ {
setOperation(QNetworkAccessManager::GetOperation); setOperation(QNetworkAccessManager::GetOperation);
@ -56,7 +57,8 @@ QupZillaSchemeReply::QupZillaSchemeReply(const QNetworkRequest &req, QObject *pa
QTimer::singleShot(0, this, SLOT(loadPage())); QTimer::singleShot(0, this, SLOT(loadPage()));
open(QIODevice::ReadOnly); open(QIODevice::ReadOnly);
} else { }
else {
setError(QNetworkReply::HostNotFoundError, tr("Not Found")); setError(QNetworkReply::HostNotFoundError, tr("Not Found"));
QTimer::singleShot(0, this, SLOT(delayedFinish())); QTimer::singleShot(0, this, SLOT(delayedFinish()));
} }
@ -65,12 +67,15 @@ QupZillaSchemeReply::QupZillaSchemeReply(const QNetworkRequest &req, QObject *pa
void QupZillaSchemeReply::loadPage() void QupZillaSchemeReply::loadPage()
{ {
QTextStream stream(&m_buffer); QTextStream stream(&m_buffer);
if (m_pageName == "about") if (m_pageName == "about") {
stream << aboutPage(); stream << aboutPage();
else if (m_pageName == "reportbug") }
else if (m_pageName == "reportbug") {
stream << reportbugPage(); stream << reportbugPage();
else if (m_pageName == "start") }
else if (m_pageName == "start") {
stream << startPage(); stream << startPage();
}
stream.flush(); stream.flush();
m_buffer.reset(); m_buffer.reset();
@ -97,7 +102,7 @@ qint64 QupZillaSchemeReply::bytesAvailable() const
return m_buffer.bytesAvailable() + QNetworkReply::bytesAvailable(); return m_buffer.bytesAvailable() + QNetworkReply::bytesAvailable();
} }
qint64 QupZillaSchemeReply::readData(char *data, qint64 maxSize) qint64 QupZillaSchemeReply::readData(char* data, qint64 maxSize)
{ {
return m_buffer.read(data, maxSize); return m_buffer.read(data, maxSize);
} }
@ -178,17 +183,17 @@ QString QupZillaSchemeReply::aboutPage()
page.replace("%MAIN-DEVELOPER-TEXT%", authorString(QupZilla::AUTHOR, "nowrep@gmail.com")); page.replace("%MAIN-DEVELOPER-TEXT%", authorString(QupZilla::AUTHOR, "nowrep@gmail.com"));
page.replace("%CONTRIBUTORS%", tr("Contributors")); page.replace("%CONTRIBUTORS%", tr("Contributors"));
page.replace("%CONTRIBUTORS-TEXT%", authorString("Daniele Cocca", "jmc@chakra-project.org") + "<br/>" + page.replace("%CONTRIBUTORS-TEXT%", authorString("Daniele Cocca", "jmc@chakra-project.org") + "<br/>" +
authorString("Jan Rajnoha", "honza.rajny@hotmail.com") authorString("Jan Rajnoha", "honza.rajny@hotmail.com")
); );
page.replace("%TRANSLATORS%", tr("Translators")); page.replace("%TRANSLATORS%", tr("Translators"));
page.replace("%TRANSLATORS-TEXT%", authorString("Heimen Stoffels", "vistausss@gmail.com") + " (Dutch)<br/>" + page.replace("%TRANSLATORS-TEXT%", authorString("Heimen Stoffels", "vistausss@gmail.com") + " (Dutch)<br/>" +
authorString("Peter Vacula", "pvacula1989@gmail.com") + " (Slovak)<br/>" + authorString("Peter Vacula", "pvacula1989@gmail.com") + " (Slovak)<br/>" +
authorString("Ján Ďanovský", "dagsoftware@yahoo.com") + " (Slovak)<br/>" + authorString("Ján Ďanovský", "dagsoftware@yahoo.com") + " (Slovak)<br/>" +
authorString("Jonathan Hooverman", "jonathan.hooverman@gmail.com") + " (German)<br/>" + authorString("Jonathan Hooverman", "jonathan.hooverman@gmail.com") + " (German)<br/>" +
authorString("Unink-Lio", "unink4451@163.com") + " (Chinese)<br/>" + authorString("Unink-Lio", "unink4451@163.com") + " (Chinese)<br/>" +
authorString("Federico Fabiani", "federico.fabiani85@gmail.com") + " (Italy)<br/>" + authorString("Federico Fabiani", "federico.fabiani85@gmail.com") + " (Italy)<br/>" +
authorString("Francesco Marinucci", "framarinucci@gmail.com") + " (Italy)" authorString("Francesco Marinucci", "framarinucci@gmail.com") + " (Italy)"
); );
return page; return page;
} }

View File

@ -48,7 +48,7 @@ public:
virtual qint64 bytesAvailable() const; virtual qint64 bytesAvailable() const;
protected: protected:
virtual qint64 readData(char *data, qint64 maxSize); virtual qint64 readData(char* data, qint64 maxSize);
virtual void abort() { } virtual void abort() { }
private slots: private slots:

View File

@ -82,8 +82,9 @@ void EditSearchEngine::hideIconLabels()
void EditSearchEngine::chooseIcon() void EditSearchEngine::chooseIcon()
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose icon...")); QString path = QFileDialog::getOpenFileName(this, tr("Choose icon..."));
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
setIcon(QIcon(path)); setIcon(QIcon(path));
} }

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