1
mirror of https://invent.kde.org/network/falkon.git synced 2024-12-20 10:46:35 +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

@ -26,6 +26,7 @@ DEFINE_GUID(IID_ITaskbarList3,0xea1afb91,0x9e28,0x4b86,0x90,0xE9,0x9e,0x9f,0x8a,
// Constructor: variabiles initialization // Constructor: variabiles initialization
EcWin7::EcWin7() EcWin7::EcWin7()
, mTaskBar(NULL)
{ {
mOverlayIcon = NULL; mOverlayIcon = NULL;
} }
@ -41,8 +42,7 @@ void EcWin7::init(WId wid)
// (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,
@ -72,14 +72,14 @@ 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,
@ -88,8 +88,7 @@ void EcWin7::setOverlayIcon(QString iconName, QString description)
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);
} }
} }

View File

@ -56,7 +56,8 @@ 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);
@ -100,7 +101,8 @@ void FancyTabProxyStyle::drawControl(
if (vertical_tabs) { if (vertical_tabs) {
m = QTransform::fromTranslate(rect.left(), rect.bottom()); m = QTransform::fromTranslate(rect.left(), rect.bottom());
m.rotate(-90); m.rotate(-90);
} else { }
else {
m = QTransform::fromTranslate(rect.left(), rect.top()); m = QTransform::fromTranslate(rect.left(), rect.top());
} }
@ -147,7 +149,8 @@ void FancyTabProxyStyle::drawControl(
animation->setEndValue(40); animation->setEndValue(40);
animation->start(); animation->start();
} }
} else { }
else {
if (animation->state() != QAbstractAnimation::Running && fader != 0) { if (animation->state() != QAbstractAnimation::Running && fader != 0) {
animation->stop(); animation->stop();
animation->setDuration(160); animation->setDuration(160);
@ -178,7 +181,8 @@ void FancyTabProxyStyle::drawControl(
p->restore(); p->restore();
} }
void FancyTabProxyStyle::polish(QWidget* widget) { void FancyTabProxyStyle::polish(QWidget* widget)
{
if (QString(widget->metaObject()->className()) == "QTabBar") { if (QString(widget->metaObject()->className()) == "QTabBar") {
widget->setMouseTracking(true); widget->setMouseTracking(true);
widget->installEventFilter(this); widget->installEventFilter(this);
@ -186,15 +190,18 @@ void FancyTabProxyStyle::polish(QWidget* widget) {
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); QTabBar* bar = qobject_cast<QTabBar*>(o);
if (bar && (e->type() == QEvent::MouseMove || e->type() == QEvent::Leave)) { if (bar && (e->type() == QEvent::MouseMove || e->type() == QEvent::Leave)) {
QMouseEvent* event = static_cast<QMouseEvent*>(e); QMouseEvent* event = static_cast<QMouseEvent*>(e);
@ -202,9 +209,10 @@ bool FancyTabProxyStyle::eventFilter(QObject* o, QEvent* e) {
const QString hovered_tab = e->type() == QEvent::Leave ? QString() : bar->tabText(bar->tabAt(event->pos())); const QString hovered_tab = e->type() == QEvent::Leave ? QString() : bar->tabText(bar->tabAt(event->pos()));
bar->setProperty("tab_hover", hovered_tab); 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;
} }
@ -265,7 +273,8 @@ FancyTabBar::~FancyTabBar()
delete style(); delete style();
} }
QSize FancyTab::sizeHint() const { QSize FancyTab::sizeHint() const
{
QFont boldFont(font()); QFont boldFont(font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true); boldFont.setBold(true);
@ -295,13 +304,15 @@ void FancyTabBar::paintEvent(QPaintEvent *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,11 +341,13 @@ 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);
} }
@ -359,7 +372,8 @@ 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); FancyTab* tab = new FancyTab(this);
tab->icon = icon; tab->icon = icon;
tab->text = label; tab->text = label;
@ -367,7 +381,8 @@ void FancyTabBar::addTab(const QIcon& icon, const QString& label) {
qobject_cast<QVBoxLayout*>(layout())->insertWidget(layout()->count() - 1, 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, qobject_cast<QVBoxLayout*>(layout())->insertSpacerItem(layout()->count() - 1,
new QSpacerItem(0, size, QSizePolicy::Fixed, QSizePolicy::Maximum)); new QSpacerItem(0, size, QSizePolicy::Fixed, QSizePolicy::Maximum));
} }
@ -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);
@ -462,16 +478,15 @@ 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;
}; };
@ -511,23 +526,28 @@ FancyTabWidget::FancyTabWidget(QWidget* parent)
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); stack_->addWidget(tab);
items_ << Item(icon, label); 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; background_pixmap_ = pixmap;
update(); update();
} }
void FancyTabWidget::paintEvent(QPaintEvent*) { void FancyTabWidget::paintEvent(QPaintEvent*)
if (!use_background_) {
if (!use_background_) {
return; return;
}
QPainter painter(this); QPainter painter(this);
@ -555,30 +575,37 @@ void FancyTabWidget::paintEvent(QPaintEvent*) {
painter.drawLine(rect.bottomLeft(), rect.bottomRight()); 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_)) { if (FancyTabBar* bar = qobject_cast<FancyTabBar*>(tab_bar_)) {
bar->setCurrentIndex(index); bar->setCurrentIndex(index);
} else if (QTabBar* bar = qobject_cast<QTabBar*>(tab_bar_)) { }
else if (QTabBar* bar = qobject_cast<QTabBar*>(tab_bar_)) {
bar->setCurrentIndex(index); bar->setCurrentIndex(index);
} else { }
else {
stack_->setCurrentIndex(index); stack_->setCurrentIndex(index);
} }
} }
void FancyTabWidget::ShowWidget(int index) { void FancyTabWidget::ShowWidget(int index)
{
stack_->setCurrentIndex(index); stack_->setCurrentIndex(index);
emit CurrentChanged(index); emit CurrentChanged(index);
} }
void FancyTabWidget::AddBottomWidget(QWidget* widget) { void FancyTabWidget::AddBottomWidget(QWidget* widget)
{
top_layout_->addWidget(widget); top_layout_->addWidget(widget);
} }
void FancyTabWidget::SetMode(Mode mode) { void FancyTabWidget::SetMode(Mode mode)
{
// Remove previous tab bar // Remove previous tab bar
delete tab_bar_; delete tab_bar_;
tab_bar_ = NULL; tab_bar_ = NULL;
@ -598,11 +625,13 @@ void FancyTabWidget::SetMode(Mode mode) {
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 }
else {
bar->addTab(item.tab_icon_, item.tab_label_); 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)));
@ -637,7 +666,8 @@ void FancyTabWidget::SetMode(Mode 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,18 +688,21 @@ 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); QAction* action = group->addAction(text);
action->setCheckable(true); action->setCheckable(true);
mapper->setMapping(action, mode); mapper->setMapping(action, mode);
connect(action, SIGNAL(triggered()), mapper, SLOT(map())); 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); QTabBar* bar = new QTabBar(this);
bar->setShape(shape); bar->setShape(shape);
bar->setDocumentMode(true); bar->setDocumentMode(true);
@ -683,14 +716,17 @@ void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons,
bar->setStyle(proxy_style_); bar->setStyle(proxy_style_);
} }
if (shape == QTabBar::RoundedNorth) if (shape == QTabBar::RoundedNorth) {
top_layout_->insertWidget(0, bar); top_layout_->insertWidget(0, bar);
else }
else {
side_layout_->insertWidget(0, bar); side_layout_->insertWidget(0, bar);
}
foreach(const Item & item, items_) { foreach(const Item & item, items_) {
if (item.type_ != Item::Type_Tab) if (item.type_ != Item::Type_Tab) {
continue; continue;
}
QString label = item.tab_label_; QString label = item.tab_label_;
if (shape == QTabBar::RoundedWest) { if (shape == QTabBar::RoundedWest) {
@ -698,12 +734,15 @@ void FancyTabWidget::MakeTabBar(QTabBar::Shape shape, bool text, bool icons,
} }
int tab_id = -1; int tab_id = -1;
if (icons && text) if (icons && text) {
tab_id = bar->addTab(item.tab_icon_, label); tab_id = bar->addTab(item.tab_icon_, label);
else if (icons) }
else if (icons) {
tab_id = bar->addTab(item.tab_icon_, QString()); tab_id = bar->addTab(item.tab_icon_, QString());
else if (text) }
else if (text) {
tab_id = bar->addTab(label); tab_id = bar->addTab(label);
}
bar->setTabToolTip(tab_id, item.tab_label_); bar->setTabToolTip(tab_id, item.tab_label_);
} }

View File

@ -45,10 +45,13 @@ 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:
@ -62,7 +65,8 @@ 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)
@ -138,7 +142,8 @@ 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)

View File

@ -14,8 +14,9 @@ SideWidget::SideWidget(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);
} }
@ -51,19 +52,23 @@ 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);
@ -82,7 +87,8 @@ bool LineEdit::event(QEvent *event)
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);
} }
@ -92,23 +98,27 @@ bool LineEdit::event(QEvent *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);

View File

@ -55,8 +55,7 @@ extern "C"{
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;
@ -80,8 +79,7 @@ IObjectArray : public IUnknown
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;
@ -119,8 +117,8 @@ 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;
@ -128,8 +126,7 @@ enum 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;
@ -206,8 +203,8 @@ 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,
@ -217,8 +214,8 @@ enum 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
@ -226,8 +223,7 @@ enum 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;
@ -249,8 +245,8 @@ 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,
@ -263,8 +259,7 @@ 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,

View File

@ -59,7 +59,8 @@ static PProcessIdToSessionId pProcessIdToSessionId = 0;
#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,11 +116,13 @@ 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))
@ -129,8 +132,9 @@ bool QtLocalPeer::isClient()
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,8 +142,9 @@ 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;
@ -147,8 +152,9 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
// 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

@ -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"
} }

View File

@ -58,14 +58,17 @@ 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();
}
struct flock fl; struct flock fl;
fl.l_whence = SEEK_SET; fl.l_whence = SEEK_SET;
@ -76,8 +79,9 @@ bool QtLockedFile::lock(LockMode mode, bool block)
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;
} }
@ -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;
@ -115,7 +120,8 @@ bool QtLockedFile::unlock()
QtLockedFile::~QtLockedFile() QtLockedFile::~QtLockedFile()
{ {
if (isOpen()) if (isOpen()) {
unlock(); unlock();
} }
}

View File

@ -60,8 +60,9 @@ 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) {
@ -76,8 +77,9 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
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

@ -291,11 +291,13 @@ 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 }
else {
disconnect(peer, SIGNAL(messageReceived(const QString &)), this, SLOT(activateWindow())); disconnect(peer, SIGNAL(messageReceived(const QString &)), this, SLOT(activateWindow()));
} }
}
/*! /*!

View File

@ -42,21 +42,20 @@
#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);
@ -77,9 +76,15 @@ 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); } }
void addWidget(QWidget* widget) {
widgets.append(widget);
}
void removeWidget(QWidget* widget) {
widgets.removeAll(widget);
}
bool winEvent(MSG* message, long* result); bool winEvent(MSG* message, long* result);
private: private:
@ -133,9 +138,10 @@ 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;
} }
@ -225,9 +231,10 @@ 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;
} }
@ -236,8 +243,9 @@ QColor QtWin::colorizationColor()
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;
} }
@ -260,7 +268,8 @@ 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());
@ -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)) {
@ -320,7 +330,8 @@ void QtWin::populateFrequentSites(IObjectCollection* collection, const QString &
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;
@ -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;

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,11 +59,13 @@ 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
QColor StyleHelper::m_baseColor; QColor StyleHelper::m_baseColor;
@ -70,11 +73,13 @@ 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)
{ {
@ -164,7 +169,8 @@ 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);
} }
} }

View File

@ -44,7 +44,8 @@ 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:

View File

@ -55,7 +55,7 @@ class AdBlockBlockedNetworkReply : public QNetworkReply
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);

View File

@ -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);
@ -137,22 +139,24 @@ 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;
@ -160,8 +164,9 @@ void AdBlockDialog::refresh()
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

@ -39,8 +39,9 @@ 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) {
@ -61,11 +62,13 @@ 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,22 +85,25 @@ 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);
@ -112,8 +118,9 @@ 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);
@ -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

@ -58,28 +58,33 @@ 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;

View File

@ -49,13 +49,15 @@ AdBlockPage::AdBlockPage(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) {
@ -68,27 +70,32 @@ void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QStri
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"));
@ -100,11 +107,13 @@ void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QStri
void AdBlockPage::applyRulesToPage(QWebPage* page) void AdBlockPage::applyRulesToPage(QWebPage* page)
{ {
if (!page || !page->mainFrame()) if (!page || !page->mainFrame()) {
return; return;
}
AdBlockManager* manager = AdBlockManager::instance(); AdBlockManager* manager = AdBlockManager::instance();
if (!manager->isEnabled()) 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();

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("@@"))) {
@ -136,17 +138,20 @@ bool AdBlockRule::networkMatch(const QString &encodedUrl) const
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;
} }
} }
} }
} }
}
#if defined(ADBLOCKRULE_DEBUG) #if defined(ADBLOCKRULE_DEBUG)
qDebug() << "AdBlockRule::" << __FUNCTION__ << "options are currently not supported" << m_options; qDebug() << "AdBlockRule::" << __FUNCTION__ << "options are currently not supported" << m_options;
@ -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,7 +196,8 @@ 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

View File

@ -62,14 +62,16 @@ void AdBlockSubscription::loadRules()
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,14 +125,15 @@ 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");
} }
@ -156,18 +163,20 @@ void AdBlockSubscription::saveRules()
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

@ -26,8 +26,10 @@ AutoSaver::AutoSaver(QObject* parent) :
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

@ -131,12 +131,16 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
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 }
else {
m_activeProfil = homePath + "profiles/" + settings.value("Profiles/startProfile", "default").toString() + "/"; m_activeProfil = homePath + "profiles/" + settings.value("Profiles/startProfile", "default").toString() + "/";
} else }
}
else {
m_activeProfil = homePath + "profiles/" + startProfile + "/"; m_activeProfil = homePath + "profiles/" + startProfile + "/";
}
ProfileUpdater u(m_activeProfil, DATADIR); ProfileUpdater u(m_activeProfil, DATADIR);
u.checkProfile(); u.checkProfile();
@ -144,8 +148,9 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
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();
@ -162,8 +167,9 @@ MainApplication::MainApplication(const QList<CommandLineOptions::ActionPair> &cm
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());
@ -271,14 +277,17 @@ void MainApplication::loadSettings()
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()
{ {
@ -293,8 +302,9 @@ 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,15 +335,19 @@ 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();
if (!actWin && !isClosing()) { // It can only occur if download manager window was still open if (!actWin && !isClosing()) { // It can only occur if download manager window was still open
@ -348,18 +362,21 @@ 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)));
@ -369,8 +386,9 @@ void MainApplication::makeNewWindow(bool tryRestore, const QUrl &startUrl)
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;
} }
@ -393,15 +412,17 @@ void MainApplication::translateApp()
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,8 +437,9 @@ 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");
@ -428,10 +450,12 @@ void MainApplication::quitApplication()
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,8 +588,9 @@ 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");
@ -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;
} }
@ -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

@ -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

@ -138,24 +138,31 @@ void QupZilla::postLaunch()
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();
@ -193,7 +202,8 @@ void QupZilla::setupUi()
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());
} }
@ -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"));
@ -375,8 +386,9 @@ 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);
} }
@ -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,11 +479,13 @@ 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();
@ -544,8 +564,9 @@ void QupZilla::aboutToShowBookmarksMenu()
} }
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");
@ -566,8 +587,9 @@ void QupZilla::aboutToShowBookmarksMenu()
} }
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,7 +623,7 @@ 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) {
@ -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);
@ -641,8 +667,9 @@ void QupZilla::aboutToShowClosedTabsMenu()
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);
@ -721,8 +754,9 @@ void QupZilla::aboutToHideViewMenu()
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);
} }
} }
@ -741,41 +775,54 @@ void QupZilla::aboutToShowEncodingMenu()
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();
} }
@ -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,8 +997,9 @@ 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);
@ -958,8 +1010,9 @@ void QupZilla::showNavigationToolbar()
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());
@ -1021,8 +1074,9 @@ 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,26 +1090,31 @@ 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)
{ {
@ -1128,9 +1187,10 @@ void QupZilla::startPrivate(bool state)
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);
mApp->cookieJar()->turnPrivateJar(state); mApp->cookieJar()->turnPrivateJar(state);
@ -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,8 +1291,9 @@ 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();
@ -1250,11 +1312,13 @@ 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();
return true; return true;
@ -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

@ -39,29 +39,33 @@ 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;
} }
@ -95,8 +99,9 @@ bool AutoFillModel::addEntry(const QUrl &url, const QString &name, const QString
{ {
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);
@ -109,8 +114,9 @@ bool AutoFillModel::addEntry(const QUrl &url, const QByteArray &data, const QStr
{ {
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;
@ -137,8 +144,9 @@ void AutoFillModel::completePage(WebView* view)
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++) {
@ -150,19 +158,22 @@ void AutoFillModel::completePage(WebView* view)
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")) }
if (key == element.attribute("name")) {
element.setAttribute("value", value); element.setAttribute("value", value);
} }
} }
} }
}
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 = "";
@ -195,17 +208,20 @@ void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgo
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

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

View File

@ -44,34 +44,41 @@ 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

@ -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,8 +212,9 @@ 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
@ -240,15 +256,18 @@ void BookmarksManager::refreshTable()
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);
} }
@ -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;
} }
@ -343,13 +364,15 @@ void BookmarksManager::removeBookmark(const BookmarksModel::Bookmark &bookmark)
} }
} }
} }
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,8 +446,9 @@ 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) {
@ -430,8 +459,9 @@ void BookmarksManager::removeFolder(const QString &name)
} }
} }
} }
if (!folderItem) if (!folderItem) {
return; return;
}
ui->bookmarksTree->deleteItem(folderItem); ui->bookmarksTree->deleteItem(folderItem);
} }
@ -439,8 +469,9 @@ 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) {
@ -451,16 +482,18 @@ void BookmarksManager::renameFolder(const QString &before, const QString &after)
} }
} }
} }
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,13 +573,15 @@ 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()));
} }
@ -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,7 +26,8 @@
#include "bookmarksmodel.h" #include "bookmarksmodel.h"
namespace Ui { namespace Ui
{
class BookmarksManager; class BookmarksManager;
} }

View File

@ -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();
@ -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

@ -71,8 +71,9 @@ 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);
@ -91,18 +92,21 @@ void BookmarksToolbar::showBookmarkContextMenu(const QPoint &pos)
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,12 +218,14 @@ 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,8 +282,9 @@ 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);
@ -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,15 +337,18 @@ 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>();
@ -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();
@ -445,9 +466,10 @@ 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()
{ {
@ -462,6 +484,7 @@ void BookmarksToolbar::refreshMostVisited()
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

@ -47,8 +47,9 @@ 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);

View File

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

View File

@ -44,8 +44,9 @@ 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);
@ -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++;
@ -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,12 +147,14 @@ 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);
@ -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,15 +220,18 @@ 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,8 +242,9 @@ 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);
@ -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,7 +28,8 @@
#include "bookmarksmodel.h" #include "bookmarksmodel.h"
namespace Ui { namespace Ui
{
class BookmarksImportDialog; class BookmarksImportDialog;
} }

View File

@ -68,8 +68,9 @@ QList<BookmarksModel::Bookmark> ChromeImporter::exportBookmarks()
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

@ -63,13 +63,15 @@ QList<BookmarksModel::Bookmark> FirefoxImporter::exportBookmarks()
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,8 +45,9 @@ 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;
@ -72,8 +73,9 @@ 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");
@ -91,8 +93,9 @@ 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;
@ -106,10 +109,12 @@ void CookieJar::restoreCookies()
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

@ -51,8 +51,9 @@ 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,17 +63,19 @@ 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,8 +138,9 @@ 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();
@ -145,13 +151,15 @@ void CookieManager::refreshTable(bool refreshCookieJar)
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));

View File

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

View File

@ -38,9 +38,10 @@ DesktopNotification::DesktopNotification(bool setPosition)
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,15 +60,17 @@ 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)
{ {

View File

@ -22,7 +22,8 @@
#include <QTimer> #include <QTimer>
#include <QMouseEvent> #include <QMouseEvent>
namespace Ui { namespace Ui
{
class DesktopNotification; class DesktopNotification;
} }

View File

@ -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)
{ {
@ -63,29 +65,35 @@ 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)
{ {
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,11 +118,14 @@ 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;
} }
@ -143,7 +156,8 @@ void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoG
if (index == -1) { if (index == -1) {
_tmpFileName.append("(" + QString::number(i) + ")"); _tmpFileName.append("(" + QString::number(i) + ")");
} else { }
else {
_tmpFileName = _tmpFileName.mid(0, index) + "(" + QString::number(i) + ")" + _tmpFileName.mid(index); _tmpFileName = _tmpFileName.mid(0, index) + "(" + QString::number(i) + ")" + _tmpFileName.mid(index);
} }
i++; i++;
@ -151,8 +165,9 @@ void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoG
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");
@ -178,13 +193,15 @@ QString DownloadFileHelper::getFileName(QNetworkReply* reply)
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,8 +44,9 @@ 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);
@ -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,9 +150,11 @@ 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,28 +168,35 @@ 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)) }
else if (time < QTime(0, 1)) {
return time.toString("s") + " " + tr("seconds"); return time.toString("s") + " " + tr("seconds");
else if (time<QTime(1, 0)) }
else if (time < QTime(1, 0)) {
return time.toString("m") + " " + tr("minutes"); return time.toString("m") + " " + tr("minutes");
else }
else {
return time.toString("h") + " " + tr("hours"); 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";
@ -191,17 +204,20 @@ QString DownloadItem::currentSpeedToString(double speed)
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";
@ -228,11 +244,13 @@ 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,10 +283,11 @@ 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);
} }
} }
}
void DownloadItem::mouseDoubleClickEvent(QMouseEvent* e) void DownloadItem::mouseDoubleClickEvent(QMouseEvent* e)
{ {
@ -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,14 +331,17 @@ void DownloadItem::clear()
void DownloadItem::openFile() void DownloadItem::openFile()
{ {
if (m_downloading) if (m_downloading) {
return; return;
}
QFileInfo info(m_path + m_fileName); QFileInfo info(m_path + m_fileName);
if (info.exists()) 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,9 +366,10 @@ 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()
{ {

View File

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

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,8 +50,9 @@ 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
} }
@ -105,20 +107,23 @@ 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)
@ -139,19 +144,23 @@ 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()
{ {
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,8 +173,9 @@ 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*)));
@ -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;

View File

@ -35,7 +35,8 @@
#include "ecwin7.h" #include "ecwin7.h"
namespace Ui { namespace Ui
{
class DownloadManager; class DownloadManager;
} }

View File

@ -37,11 +37,13 @@ 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,7 +22,8 @@
#include <QUrl> #include <QUrl>
#include <QCloseEvent> #include <QCloseEvent>
namespace Ui { namespace Ui
{
class DownloadOptionsDialog; class DownloadOptionsDialog;
} }

View File

@ -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);
@ -103,8 +109,9 @@ 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"));
@ -164,10 +177,12 @@ 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;
} }
@ -183,8 +198,9 @@ 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();
@ -207,20 +223,25 @@ void HistoryManager::refreshTable()
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"));
@ -257,8 +278,9 @@ void HistoryManager::search(const QString &searchText)
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,7 +24,8 @@
#include "historymodel.h" #include "historymodel.h"
namespace Ui { namespace Ui
{
class HistoryManager; class HistoryManager;
} }

View File

@ -38,12 +38,15 @@ void HistoryModel::loadSettings()
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 == "") }
if (title == "") {
title = tr("No Named Page"); 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();

View File

@ -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,11 +113,13 @@ 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);
setText(urlToLoad.toEncoded()); setText(urlToLoad.toEncoded());
@ -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,8 +183,9 @@ 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());
@ -199,7 +204,8 @@ void LocationBar::siteIconChanged()
if (icon_.isNull()) { if (icon_.isNull()) {
clearIcon(); clearIcon();
} else { }
else {
m_siteIcon->setIcon(QIcon(icon_.pixmap(16, 16))); 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,11 +258,13 @@ 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)
{ {
@ -266,10 +275,12 @@ void LocationBar::keyPressEvent(QKeyEvent *event)
} }
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,8 +30,9 @@ 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;
} }

View File

@ -60,17 +60,21 @@ QStringList LocationCompleter::splitPath(const QString &path) const
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)); QString prefix = url.mid(0, url.indexOf(path));
foreach(QString string, returned) { foreach(QString string, returned) {
if (titleSearching) if (titleSearching) {
returned2.append(url); returned2.append(url);
else }
else {
returned2.append(prefix + string); returned2.append(prefix + string);
} }
}
return returned2; return returned2;
} else { }
else {
foreach(QString string, returned) foreach(QString string, returned)
returned2.append("http://www.google.com/search?client=qupzilla&q=" + string); returned2.append("http://www.google.com/search?client=qupzilla&q=" + string);
return returned2; return returned2;
@ -78,13 +82,15 @@ QStringList LocationCompleter::splitPath(const QString &path) const
#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));
@ -126,10 +132,12 @@ 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

@ -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();
@ -162,9 +164,10 @@ void NavigationBar::aboutToShowHistoryBackMenu()
} }
count++; count++;
if (count == 20) if (count == 20) {
break; break;
} }
}
m_menuBack->addSeparator(); m_menuBack->addSeparator();
m_menuBack->addAction(tr("Clear history"), this, SLOT(clearHistory())); m_menuBack->addAction(tr("Clear history"), this, SLOT(clearHistory()));
@ -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();
@ -195,9 +199,10 @@ void NavigationBar::aboutToShowHistoryNextMenu()
} }
count++; count++;
if (count == 20) if (count == 20) {
break; break;
} }
}
m_menuForward->addSeparator(); m_menuForward->addSeparator();
m_menuForward->addAction(tr("Clear history"), this, SLOT(clearHistory())); m_menuForward->addAction(tr("Clear history"), this, SLOT(clearHistory()));
@ -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

@ -99,8 +99,9 @@ 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();
@ -114,9 +115,10 @@ 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()));
} }
@ -147,15 +149,18 @@ void WebSearchBar::completeMenuWithAvailableEngines(QMenu *menu)
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

@ -79,21 +79,24 @@ 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);
} }
} }
}
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors) void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
{ {
@ -105,8 +108,9 @@ 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:");
@ -114,10 +118,12 @@ void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
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,17 +198,20 @@ 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)
{ {
@ -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());
} }
@ -247,29 +259,35 @@ QNetworkReply* NetworkManager::createRequest(QNetworkAccessManager::Operation op
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);
return reply; return reply;
@ -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);
@ -344,13 +365,15 @@ 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);
#endif #endif
@ -361,13 +384,15 @@ void NetworkManager::loadCertificates()
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); QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_localCerts += QSslCertificate::fromData(file.readAll(), QSsl::Pem); 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

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());
} }

View File

@ -18,8 +18,9 @@
#include "networkproxyfactory.h" #include "networkproxyfactory.h"
#include "mainapplication.h" #include "mainapplication.h"
NetworkProxyFactory::NetworkProxyFactory() : NetworkProxyFactory::NetworkProxyFactory()
QNetworkProxyFactory() : QNetworkProxyFactory()
, m_proxyPreference(SystemProxy)
{ {
} }
@ -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,8 +35,9 @@ 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;
@ -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();

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));
} }

View File

@ -21,7 +21,8 @@
#include <QDialog> #include <QDialog>
#include <QFileDialog> #include <QFileDialog>
namespace Ui { namespace Ui
{
class EditSearchEngine; class EditSearchEngine;
} }

View File

@ -116,9 +116,10 @@ OpenSearchEngine::OpenSearchEngine(QObject *parent)
*/ */
OpenSearchEngine::~OpenSearchEngine() OpenSearchEngine::~OpenSearchEngine()
{ {
if (m_scriptEngine) if (m_scriptEngine) {
m_scriptEngine->deleteLater(); m_scriptEngine->deleteLater();
} }
}
QString OpenSearchEngine::parseTemplate(const QString &searchTerm, const QString &searchTemplate) QString OpenSearchEngine::parseTemplate(const QString &searchTerm, const QString &searchTemplate)
{ {
@ -219,17 +220,19 @@ void OpenSearchEngine::setSearchUrlTemplate(const QString &searchUrlTemplate)
*/ */
QUrl OpenSearchEngine::searchUrl(const QString &searchTerm) const QUrl OpenSearchEngine::searchUrl(const QString &searchTerm) const
{ {
if (m_searchUrlTemplate.isEmpty()) if (m_searchUrlTemplate.isEmpty()) {
return QUrl(); return QUrl();
}
QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_searchUrlTemplate).toUtf8()); QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_searchUrlTemplate).toUtf8());
if (m_searchMethod != QLatin1String("post")) { if (m_searchMethod != QLatin1String("post")) {
Parameters::const_iterator end = m_searchParameters.constEnd(); Parameters::const_iterator end = m_searchParameters.constEnd();
Parameters::const_iterator i = m_searchParameters.constBegin(); Parameters::const_iterator i = m_searchParameters.constBegin();
for (; i != end; ++i) for (; i != end; ++i) {
retVal.addQueryItem(i->first, parseTemplate(searchTerm, i->second)); retVal.addQueryItem(i->first, parseTemplate(searchTerm, i->second));
} }
}
return retVal; return retVal;
} }
@ -277,17 +280,19 @@ QUrl OpenSearchEngine::suggestionsUrl(const QString &searchTerm) const
return QUrl(s); return QUrl(s);
} }
if (m_suggestionsUrlTemplate.isEmpty()) if (m_suggestionsUrlTemplate.isEmpty()) {
return QUrl(); return QUrl();
}
QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_suggestionsUrlTemplate).toUtf8()); QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_suggestionsUrlTemplate).toUtf8());
if (m_suggestionsMethod != QLatin1String("post")) { if (m_suggestionsMethod != QLatin1String("post")) {
Parameters::const_iterator end = m_suggestionsParameters.constEnd(); Parameters::const_iterator end = m_suggestionsParameters.constEnd();
Parameters::const_iterator i = m_suggestionsParameters.constBegin(); Parameters::const_iterator i = m_suggestionsParameters.constBegin();
for (; i != end; ++i) for (; i != end; ++i) {
retVal.addQueryItem(i->first, parseTemplate(searchTerm, i->second)); retVal.addQueryItem(i->first, parseTemplate(searchTerm, i->second));
} }
}
return retVal; return retVal;
} }
@ -338,8 +343,9 @@ QString OpenSearchEngine::searchMethod() const
void OpenSearchEngine::setSearchMethod(const QString &method) void OpenSearchEngine::setSearchMethod(const QString &method)
{ {
QString requestMethod = method.toLower(); QString requestMethod = method.toLower();
if (!m_requestMethods.contains(requestMethod)) if (!m_requestMethods.contains(requestMethod)) {
return; return;
}
m_searchMethod = requestMethod; m_searchMethod = requestMethod;
} }
@ -356,8 +362,9 @@ QString OpenSearchEngine::suggestionsMethod() const
void OpenSearchEngine::setSuggestionsMethod(const QString &method) void OpenSearchEngine::setSuggestionsMethod(const QString &method)
{ {
QString requestMethod = method.toLower(); QString requestMethod = method.toLower();
if (!m_requestMethods.contains(requestMethod)) if (!m_requestMethods.contains(requestMethod)) {
return; return;
}
m_suggestionsMethod = requestMethod; m_suggestionsMethod = requestMethod;
} }
@ -386,8 +393,9 @@ void OpenSearchEngine::setImageUrl(const QString &imageUrl)
void OpenSearchEngine::loadImage() const void OpenSearchEngine::loadImage() const
{ {
if (!m_networkAccessManager || m_imageUrl.isEmpty()) if (!m_networkAccessManager || m_imageUrl.isEmpty()) {
return; return;
}
QNetworkReply* reply = m_networkAccessManager->get(QNetworkRequest(QUrl::fromEncoded(m_imageUrl.toUtf8()))); QNetworkReply* reply = m_networkAccessManager->get(QNetworkRequest(QUrl::fromEncoded(m_imageUrl.toUtf8())));
connect(reply, SIGNAL(finished()), this, SLOT(imageObtained())); connect(reply, SIGNAL(finished()), this, SLOT(imageObtained()));
@ -397,16 +405,18 @@ void OpenSearchEngine::imageObtained()
{ {
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 (response.isEmpty()) if (response.isEmpty()) {
return; return;
}
m_image.loadFromData(response); m_image.loadFromData(response);
emit imageChanged(); emit imageChanged();
@ -423,8 +433,9 @@ void OpenSearchEngine::imageObtained()
*/ */
QImage OpenSearchEngine::image() const QImage OpenSearchEngine::image() const
{ {
if (m_image.isNull()) if (m_image.isNull()) {
loadImage(); loadImage();
}
return m_image; return m_image;
} }
@ -499,8 +510,9 @@ QByteArray OpenSearchEngine::getSuggestionsParameters()
QStringList parameters; QStringList parameters;
Parameters::const_iterator end = m_suggestionsParameters.constEnd(); Parameters::const_iterator end = m_suggestionsParameters.constEnd();
Parameters::const_iterator i = m_suggestionsParameters.constBegin(); Parameters::const_iterator i = m_suggestionsParameters.constBegin();
for (; i != end; ++i) for (; i != end; ++i) {
parameters.append(i->first + QLatin1String("=") + i->second); parameters.append(i->first + QLatin1String("=") + i->second);
}
QByteArray data = parameters.join(QLatin1String("&")).toUtf8(); QByteArray data = parameters.join(QLatin1String("&")).toUtf8();
@ -509,13 +521,15 @@ QByteArray OpenSearchEngine::getSuggestionsParameters()
void OpenSearchEngine::requestSuggestions(const QString &searchTerm) void OpenSearchEngine::requestSuggestions(const QString &searchTerm)
{ {
if (searchTerm.isEmpty() || !providesSuggestions()) if (searchTerm.isEmpty() || !providesSuggestions()) {
return; return;
}
Q_ASSERT(m_networkAccessManager); Q_ASSERT(m_networkAccessManager);
if (!m_networkAccessManager) if (!m_networkAccessManager) {
return; return;
}
if (m_suggestionsReply) { if (m_suggestionsReply) {
m_suggestionsReply->disconnect(this); m_suggestionsReply->disconnect(this);
@ -527,12 +541,14 @@ void OpenSearchEngine::requestSuggestions(const QString &searchTerm)
Q_ASSERT(m_requestMethods.contains(m_suggestionsMethod)); Q_ASSERT(m_requestMethods.contains(m_suggestionsMethod));
if (m_suggestionsMethod == QLatin1String("get")) { if (m_suggestionsMethod == QLatin1String("get")) {
m_suggestionsReply = m_networkAccessManager->get(QNetworkRequest(suggestionsUrl(searchTerm))); m_suggestionsReply = m_networkAccessManager->get(QNetworkRequest(suggestionsUrl(searchTerm)));
} else { }
else {
QStringList parameters; QStringList parameters;
Parameters::const_iterator end = m_suggestionsParameters.constEnd(); Parameters::const_iterator end = m_suggestionsParameters.constEnd();
Parameters::const_iterator i = m_suggestionsParameters.constBegin(); Parameters::const_iterator i = m_suggestionsParameters.constBegin();
for (; i != end; ++i) for (; i != end; ++i) {
parameters.append(i->first + QLatin1String("=") + i->second); parameters.append(i->first + QLatin1String("=") + i->second);
}
QByteArray data = parameters.join(QLatin1String("&")).toUtf8(); QByteArray data = parameters.join(QLatin1String("&")).toUtf8();
m_suggestionsReply = m_networkAccessManager->post(QNetworkRequest(suggestionsUrl(searchTerm)), data); m_suggestionsReply = m_networkAccessManager->post(QNetworkRequest(suggestionsUrl(searchTerm)), data);
@ -553,8 +569,9 @@ void OpenSearchEngine::requestSuggestions(const QString &searchTerm)
*/ */
void OpenSearchEngine::requestSearchResults(const QString &searchTerm) void OpenSearchEngine::requestSearchResults(const QString &searchTerm)
{ {
if (!m_delegate || searchTerm.isEmpty()) if (!m_delegate || searchTerm.isEmpty()) {
return; return;
}
Q_ASSERT(m_requestMethods.contains(m_searchMethod)); Q_ASSERT(m_requestMethods.contains(m_searchMethod));
@ -566,8 +583,9 @@ void OpenSearchEngine::requestSearchResults(const QString &searchTerm)
QStringList parameters; QStringList parameters;
Parameters::const_iterator end = m_searchParameters.constEnd(); Parameters::const_iterator end = m_searchParameters.constEnd();
Parameters::const_iterator i = m_searchParameters.constBegin(); Parameters::const_iterator i = m_searchParameters.constBegin();
for (; i != end; ++i) for (; i != end; ++i) {
parameters.append(i->first + QLatin1String("=") + i->second); parameters.append(i->first + QLatin1String("=") + i->second);
}
data = parameters.join(QLatin1String("&")).toUtf8(); data = parameters.join(QLatin1String("&")).toUtf8();
} }
@ -584,23 +602,28 @@ void OpenSearchEngine::suggestionsObtained()
m_suggestionsReply->deleteLater(); m_suggestionsReply->deleteLater();
m_suggestionsReply = 0; m_suggestionsReply = 0;
if (response.isEmpty()) if (response.isEmpty()) {
return; return;
}
if (!response.startsWith(QLatin1Char('[')) || !response.endsWith(QLatin1Char(']'))) if (!response.startsWith(QLatin1Char('[')) || !response.endsWith(QLatin1Char(']'))) {
return; return;
}
if (!m_scriptEngine) if (!m_scriptEngine) {
m_scriptEngine = new QScriptEngine(); m_scriptEngine = new QScriptEngine();
}
// Evaluate the JSON response using QtScript. // Evaluate the JSON response using QtScript.
if (!m_scriptEngine->canEvaluate(response)) if (!m_scriptEngine->canEvaluate(response)) {
return; return;
}
QScriptValue responseParts = m_scriptEngine->evaluate(response); QScriptValue responseParts = m_scriptEngine->evaluate(response);
if (!responseParts.property(1).isArray()) if (!responseParts.property(1).isArray()) {
return; return;
}
QStringList suggestionsList; QStringList suggestionsList;
qScriptValueToSequence(responseParts.property(1), suggestionsList); qScriptValueToSequence(responseParts.property(1), suggestionsList);

View File

@ -86,8 +86,9 @@ OpenSearchEngine *OpenSearchReader::read(QIODevice *device)
{ {
clear(); clear();
if (!device->isOpen()) if (!device->isOpen()) {
device->open(QIODevice::ReadOnly); device->open(QIODevice::ReadOnly);
}
setDevice(device); setDevice(device);
return read(); return read();
@ -98,8 +99,9 @@ OpenSearchEngine *OpenSearchReader::read()
OpenSearchEngine* engine = new OpenSearchEngine(); OpenSearchEngine* engine = new OpenSearchEngine();
m_searchXml = device()->peek(1024 * 5); m_searchXml = device()->peek(1024 * 5);
while (!isStartElement() && !atEnd()) while (!isStartElement() && !atEnd()) {
readNext(); readNext();
}
if (!m_searchXml.contains(QLatin1String("http://a9.com/-/spec/opensearch/1.1/"))) { if (!m_searchXml.contains(QLatin1String("http://a9.com/-/spec/opensearch/1.1/"))) {
raiseError(QObject::tr("The file is not an OpenSearch 1.1 file.")); raiseError(QObject::tr("The file is not an OpenSearch 1.1 file."));
@ -109,30 +111,36 @@ OpenSearchEngine *OpenSearchReader::read()
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (!isStartElement()) if (!isStartElement()) {
continue; continue;
}
if (name() == QLatin1String("ShortName") || name() == QLatin1String("os:ShortName")) { if (name() == QLatin1String("ShortName") || name() == QLatin1String("os:ShortName")) {
engine->setName(readElementText()); engine->setName(readElementText());
} else if (name() == QLatin1String("Description") || name() == QLatin1String("os:Description")) { }
else if (name() == QLatin1String("Description") || name() == QLatin1String("os:Description")) {
engine->setDescription(readElementText()); engine->setDescription(readElementText());
} else if (name() == QLatin1String("Url") || name() == QLatin1String("os:Url")) { }
else if (name() == QLatin1String("Url") || name() == QLatin1String("os:Url")) {
QString type = attributes().value(QLatin1String("type")).toString(); QString type = attributes().value(QLatin1String("type")).toString();
QString url = attributes().value(QLatin1String("template")).toString(); QString url = attributes().value(QLatin1String("template")).toString();
QString method = attributes().value(QLatin1String("method")).toString(); QString method = attributes().value(QLatin1String("method")).toString();
if (type == QLatin1String("application/x-suggestions+json") if (type == QLatin1String("application/x-suggestions+json")
&& !engine->suggestionsUrlTemplate().isEmpty()) && !engine->suggestionsUrlTemplate().isEmpty()) {
continue; continue;
}
if ((type.isEmpty() if ((type.isEmpty()
|| type == QLatin1String("text/html") || type == QLatin1String("text/html")
|| type == QLatin1String("application/xhtml+xml")) || type == QLatin1String("application/xhtml+xml"))
&& !engine->searchUrlTemplate().isEmpty()) && !engine->searchUrlTemplate().isEmpty()) {
continue; continue;
}
if (url.isEmpty()) if (url.isEmpty()) {
continue; continue;
}
QList<OpenSearchEngine::Parameter> parameters; QList<OpenSearchEngine::Parameter> parameters;
@ -148,24 +156,28 @@ OpenSearchEngine *OpenSearchReader::read()
QString key = attributes().value(QLatin1String("name")).toString(); QString key = attributes().value(QLatin1String("name")).toString();
QString value = attributes().value(QLatin1String("value")).toString(); QString value = attributes().value(QLatin1String("value")).toString();
if (!key.isEmpty() && !value.isEmpty()) if (!key.isEmpty() && !value.isEmpty()) {
parameters.append(OpenSearchEngine::Parameter(key, value)); parameters.append(OpenSearchEngine::Parameter(key, value));
}
while (!isEndElement()) while (!isEndElement()) {
readNext(); readNext();
} }
}
if (type == QLatin1String("application/x-suggestions+json")) { if (type == QLatin1String("application/x-suggestions+json")) {
engine->setSuggestionsUrlTemplate(url); engine->setSuggestionsUrlTemplate(url);
engine->setSuggestionsParameters(parameters); engine->setSuggestionsParameters(parameters);
engine->setSuggestionsMethod(method); engine->setSuggestionsMethod(method);
} else if (type.isEmpty() || type == QLatin1String("text/html") || type == QLatin1String("application/xhtml+xml")) { }
else if (type.isEmpty() || type == QLatin1String("text/html") || type == QLatin1String("application/xhtml+xml")) {
engine->setSearchUrlTemplate(url); engine->setSearchUrlTemplate(url);
engine->setSearchParameters(parameters); engine->setSearchParameters(parameters);
engine->setSearchMethod(method); engine->setSearchMethod(method);
} }
} else if (name() == QLatin1String("Image") || name() == QLatin1String("os:Image")) { }
else if (name() == QLatin1String("Image") || name() == QLatin1String("os:Image")) {
engine->setImageUrl(readElementText()); engine->setImageUrl(readElementText());
} }
@ -173,9 +185,10 @@ OpenSearchEngine *OpenSearchReader::read()
&& !engine->description().isEmpty() && !engine->description().isEmpty()
&& !engine->suggestionsUrlTemplate().isEmpty() && !engine->suggestionsUrlTemplate().isEmpty()
&& !engine->searchUrlTemplate().isEmpty() && !engine->searchUrlTemplate().isEmpty()
&& !engine->imageUrl().isEmpty()) && !engine->imageUrl().isEmpty()) {
break; break;
} }
}
return engine; return engine;
} }

View File

@ -44,8 +44,9 @@ void SearchEnginesDialog::addEngine()
EditSearchEngine dialog(tr("Add Search Engine"), this); EditSearchEngine dialog(tr("Add Search Engine"), this);
dialog.hideIconLabels(); dialog.hideIconLabels();
if (dialog.exec() != QDialog::Accepted) if (dialog.exec() != QDialog::Accepted) {
return; return;
}
SearchEngine engine; SearchEngine engine;
engine.name = dialog.name(); engine.name = dialog.name();
@ -53,8 +54,9 @@ void SearchEnginesDialog::addEngine()
engine.shortcut = dialog.shortcut(); engine.shortcut = dialog.shortcut();
engine.icon = SearchEnginesManager::iconForSearchEngine(dialog.url()); engine.icon = SearchEnginesManager::iconForSearchEngine(dialog.url());
if (engine.name.isEmpty() || engine.url.isEmpty()) if (engine.name.isEmpty() || engine.url.isEmpty()) {
return; return;
}
QTreeWidgetItem* item = new QTreeWidgetItem(); QTreeWidgetItem* item = new QTreeWidgetItem();
QVariant v; QVariant v;
@ -71,8 +73,9 @@ void SearchEnginesDialog::addEngine()
void SearchEnginesDialog::removeEngine() void SearchEnginesDialog::removeEngine()
{ {
QTreeWidgetItem* item = ui->treeWidget->currentItem(); QTreeWidgetItem* item = ui->treeWidget->currentItem();
if (!item || ui->treeWidget->topLevelItemCount() == 1) if (!item || ui->treeWidget->topLevelItemCount() == 1) {
return; return;
}
delete item; delete item;
} }
@ -80,8 +83,9 @@ void SearchEnginesDialog::removeEngine()
void SearchEnginesDialog::editEngine() void SearchEnginesDialog::editEngine()
{ {
QTreeWidgetItem* item = ui->treeWidget->currentItem(); QTreeWidgetItem* item = ui->treeWidget->currentItem();
if (!item) if (!item) {
return; return;
}
SearchEngine engine = item->data(0, Qt::UserRole).value<SearchEngine>(); SearchEngine engine = item->data(0, Qt::UserRole).value<SearchEngine>();
@ -92,16 +96,18 @@ void SearchEnginesDialog::editEngine()
dialog.setShortcut(engine.shortcut); dialog.setShortcut(engine.shortcut);
dialog.setIcon(engine.icon); dialog.setIcon(engine.icon);
if (dialog.exec() != QDialog::Accepted) if (dialog.exec() != QDialog::Accepted) {
return; return;
}
engine.name = dialog.name(); engine.name = dialog.name();
engine.url = dialog.url(); engine.url = dialog.url();
engine.shortcut = dialog.shortcut(); engine.shortcut = dialog.shortcut();
engine.icon = dialog.icon(); engine.icon = dialog.icon();
if (engine.name.isEmpty() || engine.url.isEmpty()) if (engine.name.isEmpty() || engine.url.isEmpty()) {
return; return;
}
QVariant v; QVariant v;
v.setValue<SearchEngine>(engine); v.setValue<SearchEngine>(engine);
@ -137,15 +143,17 @@ void SearchEnginesDialog::reloadEngines()
void SearchEnginesDialog::accept() void SearchEnginesDialog::accept()
{ {
if (ui->treeWidget->topLevelItemCount() < 1) if (ui->treeWidget->topLevelItemCount() < 1) {
return; return;
}
QList<SearchEngine> allEngines; QList<SearchEngine> allEngines;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem* item = ui->treeWidget->topLevelItem(i); QTreeWidgetItem* item = ui->treeWidget->topLevelItem(i);
if (!item) if (!item) {
continue; continue;
}
SearchEngine engine = item->data(0, Qt::UserRole).value<SearchEngine>(); SearchEngine engine = item->data(0, Qt::UserRole).value<SearchEngine>();
allEngines.append(engine); allEngines.append(engine);

View File

@ -20,7 +20,8 @@
#include <QDialog> #include <QDialog>
namespace Ui { namespace Ui
{
class SearchEnginesDialog; class SearchEnginesDialog;
} }

View File

@ -27,8 +27,9 @@
QIcon SearchEnginesManager::iconForSearchEngine(const QUrl &url) QIcon SearchEnginesManager::iconForSearchEngine(const QUrl &url)
{ {
QIcon ic = mApp->iconProvider()->iconForDomain(url); QIcon ic = mApp->iconProvider()->iconForDomain(url);
if (ic.isNull()) if (ic.isNull()) {
ic = QIcon(":icons/menu/search-icon.png"); ic = QIcon(":icons/menu/search-icon.png");
}
return ic; return ic;
} }
@ -63,16 +64,18 @@ void SearchEnginesManager::loadSettings()
m_allEngines.append(en); m_allEngines.append(en);
} }
if (m_allEngines.isEmpty()) if (m_allEngines.isEmpty()) {
restoreDefaults(); restoreDefaults();
} }
}
SearchEngine SearchEnginesManager::engineForShortcut(const QString &shortcut) SearchEngine SearchEnginesManager::engineForShortcut(const QString &shortcut)
{ {
foreach(Engine en, m_allEngines) { foreach(Engine en, m_allEngines) {
if (en.shortcut == shortcut) if (en.shortcut == shortcut) {
return en; return en;
} }
}
return Engine(); return Engine();
} }
@ -136,8 +139,9 @@ void SearchEnginesManager::engineChangedImage()
{ {
OpenSearchEngine* engine = qobject_cast<OpenSearchEngine*>(sender()); OpenSearchEngine* engine = qobject_cast<OpenSearchEngine*>(sender());
if (!engine) if (!engine) {
return; return;
}
foreach(Engine e, m_allEngines) { foreach(Engine e, m_allEngines) {
if (e.name == engine->name() && e.url.contains(engine->searchUrl("%s").toString()) if (e.name == engine->name() && e.url.contains(engine->searchUrl("%s").toString())
@ -165,14 +169,16 @@ void SearchEnginesManager::addEngine(const Engine &engine, bool emitSignal)
{ {
ENSURE_LOADED; ENSURE_LOADED;
if (m_allEngines.contains(engine)) if (m_allEngines.contains(engine)) {
return; return;
}
m_allEngines.append(engine); m_allEngines.append(engine);
if (emitSignal) if (emitSignal) {
emit enginesChanged(); emit enginesChanged();
} }
}
void SearchEnginesManager::addEngine(OpenSearchEngine* engine) void SearchEnginesManager::addEngine(OpenSearchEngine* engine)
{ {
@ -181,10 +187,12 @@ void SearchEnginesManager::addEngine(OpenSearchEngine* engine)
Engine en; Engine en;
en.name = engine->name(); en.name = engine->name();
en.url = engine->searchUrl("searchstring").toString().replace("searchstring", "%s"); en.url = engine->searchUrl("searchstring").toString().replace("searchstring", "%s");
if (engine->image().isNull()) if (engine->image().isNull()) {
en.icon = iconForSearchEngine(engine->searchUrl("")); en.icon = iconForSearchEngine(engine->searchUrl(""));
else }
else {
en.icon = QIcon(QPixmap::fromImage(engine->image())); en.icon = QIcon(QPixmap::fromImage(engine->image()));
}
en.suggestionsUrl = engine->getSuggestionsUrl(); en.suggestionsUrl = engine->getSuggestionsUrl();
en.suggestionsParameters = engine->getSuggestionsParameters(); en.suggestionsParameters = engine->getSuggestionsParameters();
@ -197,8 +205,9 @@ void SearchEnginesManager::addEngine(const QUrl &url)
{ {
ENSURE_LOADED; ENSURE_LOADED;
if (!url.isValid()) if (!url.isValid()) {
return; return;
}
qApp->setOverrideCursor(Qt::WaitCursor); qApp->setOverrideCursor(Qt::WaitCursor);
@ -212,8 +221,9 @@ void SearchEnginesManager::replyFinished()
qApp->restoreOverrideCursor(); qApp->restoreOverrideCursor();
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) if (!reply) {
return; return;
}
if (reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::NoError) {
reply->close(); reply->close();
@ -250,8 +260,9 @@ void SearchEnginesManager::setActiveEngine(const Engine &engine)
{ {
ENSURE_LOADED; ENSURE_LOADED;
if (!m_allEngines.contains(engine)) if (!m_allEngines.contains(engine)) {
return; return;
}
m_activeEngine = engine; m_activeEngine = engine;
emit activeEngineChanged(); emit activeEngineChanged();
@ -261,8 +272,9 @@ void SearchEnginesManager::removeEngine(const Engine &engine)
{ {
ENSURE_LOADED; ENSURE_LOADED;
if (!m_allEngines.contains(engine)) if (!m_allEngines.contains(engine)) {
return; return;
}
QSqlQuery query; QSqlQuery query;
query.prepare("DELETE FROM search_engines WHERE name=? AND url=?"); query.prepare("DELETE FROM search_engines WHERE name=? AND url=?");
@ -296,8 +308,9 @@ void SearchEnginesManager::saveSettings()
settings.setValue("activeEngine", m_activeEngine.name); settings.setValue("activeEngine", m_activeEngine.name);
settings.endGroup(); settings.endGroup();
if (!m_saveScheduled) if (!m_saveScheduled) {
return; return;
}
// Well, this is not the best implementation to do as this is taking some time. // Well, this is not the best implementation to do as this is taking some time.
// Actually, it is delaying the quit of app for about a 1 sec on my machine with only // Actually, it is delaying the quit of app for about a 1 sec on my machine with only

View File

@ -46,8 +46,7 @@ public:
QByteArray suggestionsParameters; QByteArray suggestionsParameters;
bool operator==(const Engine &other) bool operator==(const Engine &other) const {
{
return (this->name == other.name && return (this->name == other.name &&
this->url == other.url); this->url == other.url);
} }

View File

@ -42,11 +42,13 @@ AboutDialog::AboutDialog(QWidget* parent) :
void AboutDialog::buttonClicked() void AboutDialog::buttonClicked()
{ {
if (ui->authorsButton->text() == tr("Authors and Contributors")) if (ui->authorsButton->text() == tr("Authors and Contributors")) {
showAuthors(); showAuthors();
else if (ui->authorsButton->text() == tr("< About QupZilla")) }
else if (ui->authorsButton->text() == tr("< About QupZilla")) {
showAbout(); showAbout();
} }
}
void AboutDialog::showAbout() void AboutDialog::showAbout()
{ {

View File

@ -20,7 +20,8 @@
#include <QDialog> #include <QDialog>
namespace Ui { namespace Ui
{
class AboutDialog; class AboutDialog;
} }

View File

@ -89,11 +89,13 @@ void BrowsingLibrary::currentIndexChanged(int index)
void BrowsingLibrary::search() void BrowsingLibrary::search()
{ {
if (ui->tabs->current_index() == 0) if (ui->tabs->current_index() == 0) {
m_historyManager->search(ui->searchLine->text()); m_historyManager->search(ui->searchLine->text());
else }
else {
m_bookmarksManager->search(ui->searchLine->text()); m_bookmarksManager->search(ui->searchLine->text());
} }
}
void BrowsingLibrary::showHistory(QupZilla* mainClass) void BrowsingLibrary::showHistory(QupZilla* mainClass)
{ {

View File

@ -22,7 +22,8 @@
#include <QFileInfo> #include <QFileInfo>
#include <QCloseEvent> #include <QCloseEvent>
namespace Ui { namespace Ui
{
class BrowsingLibrary; class BrowsingLibrary;
} }

View File

@ -24,7 +24,8 @@
#include <QCheckBox> #include <QCheckBox>
#include <QLabel> #include <QLabel>
namespace Ui { namespace Ui
{
class ClearPrivateData; class ClearPrivateData;
} }

View File

@ -24,7 +24,8 @@
#include <QAbstractButton> #include <QAbstractButton>
#include <QFileDialog> #include <QFileDialog>
namespace Ui { namespace Ui
{
class PageScreen; class PageScreen;
} }

View File

@ -89,15 +89,17 @@ SourceViewer::SourceViewer(QWebPage* page, const QString &selectedHtml) :
qz_centerWidgetOnScreen(this); qz_centerWidgetOnScreen(this);
//Highlight selectedHtml //Highlight selectedHtml
if (!selectedHtml.isEmpty()) if (!selectedHtml.isEmpty()) {
m_sourceEdit->find(selectedHtml, QTextDocument::FindWholeWords); m_sourceEdit->find(selectedHtml, QTextDocument::FindWholeWords);
} }
}
void SourceViewer::save() void SourceViewer::save()
{ {
QString filePath = QFileDialog::getSaveFileName(this, tr("Save file..."), QDir::homePath() + "/source_code.html"); QString filePath = QFileDialog::getSaveFileName(this, tr("Save file..."), QDir::homePath() + "/source_code.html");
if (filePath.isEmpty()) if (filePath.isEmpty()) {
return; return;
}
QFile file(filePath); QFile file(filePath);
if (!file.open(QFile::WriteOnly)) { if (!file.open(QFile::WriteOnly)) {
@ -149,12 +151,14 @@ void SourceViewer::setTextWordWrap()
void SourceViewer::goToLine() void SourceViewer::goToLine()
{ {
int line = QInputDialog::getInt(this, tr("Go to Line..."), tr("Enter line number"), 0, 1, 5000); int line = QInputDialog::getInt(this, tr("Go to Line..."), tr("Enter line number"), 0, 1, 5000);
if (line == 0) if (line == 0) {
return; return;
}
m_sourceEdit->setUpdatesEnabled(false); m_sourceEdit->setUpdatesEnabled(false);
m_sourceEdit->moveCursor(QTextCursor::Start); m_sourceEdit->moveCursor(QTextCursor::Start);
for (int i = 0; i < line; i++) for (int i = 0; i < line; i++) {
m_sourceEdit->moveCursor(QTextCursor::Down); m_sourceEdit->moveCursor(QTextCursor::Down);
}
m_sourceEdit->setUpdatesEnabled(true); m_sourceEdit->setUpdatesEnabled(true);
} }

View File

@ -51,8 +51,9 @@ void SourceViewerSearch::activateLineEdit()
void SourceViewerSearch::next() void SourceViewerSearch::next()
{ {
bool found = find(0); bool found = find(0);
if (!found) if (!found) {
m_sourceViewer->sourceEdit()->moveCursor(QTextCursor::Start); m_sourceViewer->sourceEdit()->moveCursor(QTextCursor::Start);
}
ui->lineEdit->setProperty("notfound", !found); ui->lineEdit->setProperty("notfound", !found);
@ -63,8 +64,9 @@ void SourceViewerSearch::next()
void SourceViewerSearch::previous() void SourceViewerSearch::previous()
{ {
bool found = find(QTextDocument::FindBackward); bool found = find(QTextDocument::FindBackward);
if (!found) if (!found) {
m_sourceViewer->sourceEdit()->moveCursor(QTextCursor::Start); m_sourceViewer->sourceEdit()->moveCursor(QTextCursor::Start);
}
ui->lineEdit->setProperty("notfound", !found); ui->lineEdit->setProperty("notfound", !found);
@ -75,8 +77,9 @@ void SourceViewerSearch::previous()
bool SourceViewerSearch::find(QTextDocument::FindFlags flags) bool SourceViewerSearch::find(QTextDocument::FindFlags flags)
{ {
QString string = ui->lineEdit->text(); QString string = ui->lineEdit->text();
if (string.isEmpty()) if (string.isEmpty()) {
return true; return true;
}
if (string != m_lastSearchedString) { if (string != m_lastSearchedString) {
QTextCursor cursor = m_sourceViewer->sourceEdit()->textCursor(); QTextCursor cursor = m_sourceViewer->sourceEdit()->textCursor();
cursor.setPosition(cursor.selectionStart()); cursor.setPosition(cursor.selectionStart());

View File

@ -23,7 +23,8 @@
#include "animatedwidget.h" #include "animatedwidget.h"
namespace Ui { namespace Ui
{
class SourceViewerSearch; class SourceViewerSearch;
} }

View File

@ -89,8 +89,9 @@ StatusBarMessage::StatusBarMessage(QupZilla* mainClass)
void StatusBarMessage::showMessage(const QString &message) void StatusBarMessage::showMessage(const QString &message)
{ {
if (p_QupZilla->statusBar()->isVisible()) if (p_QupZilla->statusBar()->isVisible()) {
p_QupZilla->statusBar()->showMessage(message); p_QupZilla->statusBar()->showMessage(message);
}
else { else {
WebView* view = p_QupZilla->weView(); WebView* view = p_QupZilla->weView();
QWebFrame* mainFrame = view->page()->mainFrame(); QWebFrame* mainFrame = view->page()->mainFrame();
@ -99,10 +100,12 @@ void StatusBarMessage::showMessage(const QString &message)
int verticalScrollSize = 0; int verticalScrollSize = 0;
const int scrollbarSize = p_QupZilla->style()->pixelMetric(QStyle::PM_ScrollBarExtent); const int scrollbarSize = p_QupZilla->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
if (mainFrame->scrollBarMaximum(Qt::Horizontal)) if (mainFrame->scrollBarMaximum(Qt::Horizontal)) {
horizontalScrollSize = scrollbarSize; horizontalScrollSize = scrollbarSize;
if (mainFrame->scrollBarMaximum(Qt::Vertical)) }
if (mainFrame->scrollBarMaximum(Qt::Vertical)) {
verticalScrollSize = scrollbarSize; verticalScrollSize = scrollbarSize;
}
m_statusBarText->setText(message); m_statusBarText->setText(message);
m_statusBarText->resize(m_statusBarText->sizeHint()); m_statusBarText->resize(m_statusBarText->sizeHint());
@ -113,8 +116,9 @@ void StatusBarMessage::showMessage(const QString &message)
QRect statusRect = QRect(view->mapToGlobal(QPoint(0, position.y())), m_statusBarText->size()); QRect statusRect = QRect(view->mapToGlobal(QPoint(0, position.y())), m_statusBarText->size());
if (statusRect.contains(QCursor::pos())) if (statusRect.contains(QCursor::pos())) {
position.setY(position.y() - m_statusBarText->height()); position.setY(position.y() - m_statusBarText->height());
}
m_statusBarText->move(view->mapToGlobal(position)); m_statusBarText->move(view->mapToGlobal(position));
m_statusBarText->show(); m_statusBarText->show();
@ -123,8 +127,10 @@ void StatusBarMessage::showMessage(const QString &message)
void StatusBarMessage::clearMessage() void StatusBarMessage::clearMessage()
{ {
if (p_QupZilla->statusBar()->isVisible()) if (p_QupZilla->statusBar()->isVisible()) {
p_QupZilla->statusBar()->showMessage(""); p_QupZilla->statusBar()->showMessage("");
else }
else {
m_statusBarText->hide(); m_statusBarText->hide();
} }
}

View File

@ -26,7 +26,8 @@
class QupZilla; class QupZilla;
class TipLabel; class TipLabel;
class TipLabel : public SqueezeLabelV1 { class TipLabel : public SqueezeLabelV1
{
Q_OBJECT Q_OBJECT
public: public:

View File

@ -34,16 +34,18 @@ Updater::Version Updater::parseVersionFromString(const QString &string)
ver.isValid = false; ver.isValid = false;
QStringList v = string.split("."); QStringList v = string.split(".");
if (v.count() != 3) if (v.count() != 3) {
return ver; return ver;
}
QStringList r = v.at(2).split("-"); QStringList r = v.at(2).split("-");
ver.majorVersion = v.at(0).toInt(); ver.majorVersion = v.at(0).toInt();
ver.minorVersion = v.at(1).toInt(); ver.minorVersion = v.at(1).toInt();
ver.revisionNumber = r.at(0).toInt(); ver.revisionNumber = r.at(0).toInt();
if (r.count() == 2) if (r.count() == 2) {
ver.specialSymbol = r.at(1); ver.specialSymbol = r.at(1);
}
ver.isValid = true; ver.isValid = true;
return ver; return ver;
@ -51,17 +53,21 @@ Updater::Version Updater::parseVersionFromString(const QString &string)
bool Updater::isBiggerThan_SpecialSymbol(QString one, QString two) bool Updater::isBiggerThan_SpecialSymbol(QString one, QString two)
{ {
if (one.contains("rc") && two.contains("b")) if (one.contains("rc") && two.contains("b")) {
return true; return true;
}
if (one.contains("b") && two.contains("rc")) if (one.contains("b") && two.contains("rc")) {
return false; return false;
}
if (one.isEmpty()) if (one.isEmpty()) {
return true; return true;
}
if (two.isEmpty()) if (two.isEmpty()) {
return false; return false;
}
if (one.contains("b")) { if (one.contains("b")) {
int o = one.remove("b").toInt(); int o = one.remove("b").toInt();

View File

@ -38,8 +38,7 @@ public:
int revisionNumber; int revisionNumber;
QString specialSymbol; QString specialSymbol;
bool operator<(const Version &other) const bool operator<(const Version &other) const {
{
if (!this->isValid || !other.isValid) if (!this->isValid || !other.isValid)
return false; return false;
if (this->majorVersion < other.majorVersion) if (this->majorVersion < other.majorVersion)
@ -54,13 +53,11 @@ public:
return false; return false;
} }
bool operator>(const Version &other) const bool operator>(const Version &other) const {
{
return !operator<(other); return !operator<(other);
} }
bool operator==(const Version &other) const bool operator==(const Version &other) const {
{
if (!this->isValid || !other.isValid) if (!this->isValid || !other.isValid)
return false; return false;
@ -70,15 +67,13 @@ public:
this->specialSymbol == other.specialSymbol); this->specialSymbol == other.specialSymbol);
} }
bool operator>=(const Version &other) const bool operator>=(const Version &other) const {
{
if (*this == other) if (*this == other)
return true; return true;
return *this > other; return *this > other;
} }
bool operator<=(const Version &other) const bool operator<=(const Version &other) const {
{
if (*this == other) if (*this == other)
return true; return true;
return *this < other; return *this < other;

View File

@ -129,8 +129,9 @@ void ClickToFlash::toWhitelist()
void ClickToFlash::hideAdBlocked() void ClickToFlash::hideAdBlocked()
{ {
findElement(); findElement();
if (!m_element.isNull()) if (!m_element.isNull()) {
m_element.setAttribute("style", "display:none;"); m_element.setAttribute("style", "display:none;");
}
else { else {
hide(); hide();
} }
@ -140,8 +141,9 @@ void ClickToFlash::hideAdBlocked()
void ClickToFlash::findElement() void ClickToFlash::findElement()
{ {
if (!m_toolButton) if (!m_toolButton) {
return; return;
}
QWidget* parent = parentWidget(); QWidget* parent = parentWidget();
QWebView* view = 0; QWebView* view = 0;
@ -152,8 +154,9 @@ void ClickToFlash::findElement()
} }
parent = parent->parentWidget(); parent = parent->parentWidget();
} }
if (!view) if (!view) {
return; return;
}
QList<QWebFrame*> frames; QList<QWebFrame*> frames;
frames.append(view->page()->frameAt(view->mapFromGlobal(m_toolButton->mapToGlobal(m_toolButton->pos())))); frames.append(view->page()->frameAt(view->mapFromGlobal(m_toolButton->mapToGlobal(m_toolButton->pos()))));
@ -162,8 +165,9 @@ void ClickToFlash::findElement()
while (!frames.isEmpty()) { while (!frames.isEmpty()) {
QWebFrame* frame = frames.takeFirst(); QWebFrame* frame = frames.takeFirst();
if (!frame) if (!frame) {
continue; continue;
}
QWebElement docElement = frame->documentElement(); QWebElement docElement = frame->documentElement();
QWebElementCollection elements; QWebElementCollection elements;
@ -172,8 +176,9 @@ void ClickToFlash::findElement()
QWebElement element; QWebElement element;
foreach(element, elements) { foreach(element, elements) {
if (!checkElement(element) && !checkUrlOnElement(element)) if (!checkElement(element) && !checkUrlOnElement(element)) {
continue; continue;
}
m_element = element; m_element = element;
return; return;
} }
@ -186,7 +191,8 @@ void ClickToFlash::load()
findElement(); findElement();
if (m_element.isNull()) { if (m_element.isNull()) {
qWarning("Click2Flash: Cannot find Flash object."); qWarning("Click2Flash: Cannot find Flash object.");
} else { }
else {
QWebElement substitute = m_element.clone(); QWebElement substitute = m_element.clone();
substitute.setAttribute(QLatin1String("type"), "application/futuresplash"); substitute.setAttribute(QLatin1String("type"), "application/futuresplash");
m_element.replace(substitute); m_element.replace(substitute);
@ -196,10 +202,12 @@ void ClickToFlash::load()
bool ClickToFlash::checkUrlOnElement(QWebElement el) bool ClickToFlash::checkUrlOnElement(QWebElement el)
{ {
QString checkString = el.attribute("src"); QString checkString = el.attribute("src");
if (checkString.isEmpty()) if (checkString.isEmpty()) {
checkString = el.attribute("data"); checkString = el.attribute("data");
if (checkString.isEmpty()) }
if (checkString.isEmpty()) {
checkString = el.attribute("value"); checkString = el.attribute("value");
}
checkString = m_page->getView()->url().resolved(QUrl(checkString)).toString(QUrl::RemoveQuery); checkString = m_page->getView()->url().resolved(QUrl(checkString)).toString(QUrl::RemoveQuery);
@ -210,9 +218,10 @@ bool ClickToFlash::checkElement(QWebElement el)
{ {
if (m_argumentNames == el.attributeNames()) { if (m_argumentNames == el.attributeNames()) {
foreach(QString name, m_argumentNames) { foreach(QString name, m_argumentNames) {
if (m_argumentValues.indexOf(el.attribute(name)) == -1) if (m_argumentValues.indexOf(el.attribute(name)) == -1) {
return false; return false;
} }
}
return true; return true;
} }
return false; return false;
@ -235,8 +244,9 @@ void ClickToFlash::showInfo()
i++; i++;
} }
if (i == 0) if (i == 0) {
lay->addRow(new QLabel(tr("No more informations available."))); lay->addRow(new QLabel(tr("No more informations available.")));
}
widg->setMaximumHeight(500); widg->setMaximumHeight(500);
qz_centerWidgetToParent(widg, m_page->qupzilla()); qz_centerWidgetToParent(widg, m_page->qupzilla());
@ -245,12 +255,16 @@ void ClickToFlash::showInfo()
ClickToFlash::~ClickToFlash() ClickToFlash::~ClickToFlash()
{ {
if (m_toolButton) if (m_toolButton) {
delete m_toolButton; delete m_toolButton;
if (m_layout1) }
if (m_layout1) {
delete m_layout1; delete m_layout1;
if (m_layout2) }
if (m_layout2) {
delete m_layout2; delete m_layout2;
if (m_frame) }
if (m_frame) {
delete m_frame; delete m_frame;
} }
}

View File

@ -27,8 +27,9 @@ PluginProxy::PluginProxy() :
void PluginProxy::populateWebViewMenu(QMenu* menu, QWebView* view, QWebHitTestResult r) void PluginProxy::populateWebViewMenu(QMenu* menu, QWebView* view, QWebHitTestResult r)
{ {
if (!menu || !view || loadedPlugins.count() == 0) if (!menu || !view || loadedPlugins.count() == 0) {
return; return;
}
menu->addSeparator(); menu->addSeparator();
int count = menu->actions().count(); int count = menu->actions().count();
@ -36,46 +37,52 @@ void PluginProxy::populateWebViewMenu(QMenu* menu, QWebView* view, QWebHitTestRe
foreach(PluginInterface * iPlugin, loadedPlugins) foreach(PluginInterface * iPlugin, loadedPlugins)
iPlugin->populateWebViewMenu(menu, view, r); iPlugin->populateWebViewMenu(menu, view, r);
if (menu->actions().count() == count) if (menu->actions().count() == count) {
menu->removeAction(menu->actions().at(count - 1)); menu->removeAction(menu->actions().at(count - 1));
} }
}
void PluginProxy::populateToolsMenu(QMenu* menu) void PluginProxy::populateToolsMenu(QMenu* menu)
{ {
if (!menu || loadedPlugins.count() == 0) if (!menu || loadedPlugins.count() == 0) {
return; return;
}
int count = menu->actions().count(); int count = menu->actions().count();
foreach(PluginInterface * iPlugin, loadedPlugins) foreach(PluginInterface * iPlugin, loadedPlugins)
iPlugin->populateToolsMenu(menu); iPlugin->populateToolsMenu(menu);
if (menu->actions().count() != count) if (menu->actions().count() != count) {
menu->addSeparator(); menu->addSeparator();
} }
}
void PluginProxy::populateHelpMenu(QMenu* menu) void PluginProxy::populateHelpMenu(QMenu* menu)
{ {
if (!menu || loadedPlugins.count() == 0) if (!menu || loadedPlugins.count() == 0) {
return; return;
}
int count = menu->actions().count(); int count = menu->actions().count();
foreach(PluginInterface * iPlugin, loadedPlugins) foreach(PluginInterface * iPlugin, loadedPlugins)
iPlugin->populateHelpMenu(menu); iPlugin->populateHelpMenu(menu);
if (menu->actions().count() != count) if (menu->actions().count() != count) {
menu->addSeparator(); menu->addSeparator();
} }
}
QNetworkReply* PluginProxy::createNetworkRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice* outgoingData) QNetworkReply* PluginProxy::createNetworkRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice* outgoingData)
{ {
QNetworkReply* reply = 0; QNetworkReply* reply = 0;
foreach(PluginInterface * iPlugin, loadedPlugins) { foreach(PluginInterface * iPlugin, loadedPlugins) {
reply = iPlugin->createNetworkRequest(op, request, outgoingData); reply = iPlugin->createNetworkRequest(op, request, outgoingData);
if (reply) if (reply) {
break; break;
} }
}
return reply; return reply;
} }

View File

@ -38,8 +38,9 @@ void Plugins::loadSettings()
void Plugins::loadPlugins() void Plugins::loadPlugins()
{ {
if (!m_pluginsEnabled) if (!m_pluginsEnabled) {
return; return;
}
m_availablePluginFileNames.clear(); m_availablePluginFileNames.clear();
loadedPlugins.clear(); loadedPlugins.clear();
@ -49,8 +50,9 @@ void Plugins::loadPlugins()
foreach(QString fileName, pluginsDir.entryList(QDir::Files)) { foreach(QString fileName, pluginsDir.entryList(QDir::Files)) {
m_availablePluginFileNames.append(fileName); m_availablePluginFileNames.append(fileName);
if (!m_allowedPluginFileNames.contains(fileName)) if (!m_allowedPluginFileNames.contains(fileName)) {
continue; continue;
}
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject* plugin = loader.instance(); QObject* plugin = loader.instance();
@ -74,14 +76,17 @@ void Plugins::loadPlugins()
PluginInterface* Plugins::getPlugin(QString pluginFileName) PluginInterface* Plugins::getPlugin(QString pluginFileName)
{ {
QString path = mApp->PLUGINSDIR + pluginFileName; QString path = mApp->PLUGINSDIR + pluginFileName;
if (!QFile::exists(path)) if (!QFile::exists(path)) {
return 0; return 0;
}
QPluginLoader loader(path); QPluginLoader loader(path);
QObject* plugin = loader.instance(); QObject* plugin = loader.instance();
if (plugin) { if (plugin) {
PluginInterface* iPlugin = qobject_cast<PluginInterface*>(plugin); PluginInterface* iPlugin = qobject_cast<PluginInterface*>(plugin);
return iPlugin; return iPlugin;
} else }
else {
return 0; return 0;
} }
}

View File

@ -30,30 +30,36 @@ WebPluginFactory::WebPluginFactory(QObject* parent)
QObject* WebPluginFactory::create(const QString &mimeType, const QUrl &url, const QStringList &argumentNames, const QStringList &argumentValues) const QObject* WebPluginFactory::create(const QString &mimeType, const QUrl &url, const QStringList &argumentNames, const QStringList &argumentValues) const
{ {
QString mime = mimeType.trimmed(); //Fixing bad behaviour when mimeType contains spaces QString mime = mimeType.trimmed(); //Fixing bad behaviour when mimeType contains spaces
if (mime.isEmpty()) if (mime.isEmpty()) {
return 0;
if (mime != "application/x-shockwave-flash") {
if (mime != "application/futuresplash")
qDebug() << "missing mimeType handler for: " << mime;
return 0; return 0;
} }
if (!mApp->plugins()->c2f_isEnabled()) if (mime != "application/x-shockwave-flash") {
if (mime != "application/futuresplash") {
qDebug() << "missing mimeType handler for: " << mime;
}
return 0; return 0;
}
if (!mApp->plugins()->c2f_isEnabled()) {
return 0;
}
//Click2Flash whitelist //Click2Flash whitelist
QStringList whitelist = mApp->plugins()->c2f_getWhiteList(); QStringList whitelist = mApp->plugins()->c2f_getWhiteList();
if (whitelist.contains(url.host()) || whitelist.contains("www."+url.host()) || whitelist.contains(url.host().remove("www."))) if (whitelist.contains(url.host()) || whitelist.contains("www." + url.host()) || whitelist.contains(url.host().remove("www."))) {
return 0; return 0;
}
WebPluginFactory* factory = const_cast<WebPluginFactory*>(this); WebPluginFactory* factory = const_cast<WebPluginFactory*>(this);
if (!factory) if (!factory) {
return 0; return 0;
}
WebPage* page = factory->parentPage(); WebPage* page = factory->parentPage();
if (!page) if (!page) {
return 0; return 0;
}
ClickToFlash* ctf = new ClickToFlash(url, argumentNames, argumentValues, page); ClickToFlash* ctf = new ClickToFlash(url, argumentNames, argumentValues, page);
@ -62,8 +68,9 @@ QObject* WebPluginFactory::create(const QString &mimeType, const QUrl &url, cons
WebPage* WebPluginFactory::parentPage() WebPage* WebPluginFactory::parentPage()
{ {
if (m_page) if (m_page) {
return m_page; return m_page;
}
WebPage* page = qobject_cast<WebPage*> (parent()); WebPage* page = qobject_cast<WebPage*> (parent());
return page; return page;

View File

@ -46,8 +46,9 @@ QStringList AcceptLanguage::defaultLanguage()
QByteArray AcceptLanguage::generateHeader(const QStringList &langs) QByteArray AcceptLanguage::generateHeader(const QStringList &langs)
{ {
if (langs.count() == 0) if (langs.count() == 0) {
return QByteArray(); return QByteArray();
}
QByteArray header; QByteArray header;
header.append(langs.at(0)); header.append(langs.at(0));
@ -56,8 +57,9 @@ QByteArray AcceptLanguage::generateHeader(const QStringList &langs)
for (int i = 1; i < langs.count(); i++) { for (int i = 1; i < langs.count(); i++) {
QString s = ", " + langs.at(i) + ";q=0,"; QString s = ", " + langs.at(i) + ";q=0,";
s.append(QString::number(counter)); s.append(QString::number(counter));
if (counter != 2) if (counter != 2) {
counter -= 2; counter -= 2;
}
header.append(s); header.append(s);
} }
@ -81,10 +83,12 @@ AcceptLanguage::AcceptLanguage(QWidget* parent)
QLocale loc = QLocale(code_.replace("-", "_")); QLocale loc = QLocale(code_.replace("-", "_"));
QString label; QString label;
if (loc.language() == QLocale::C) if (loc.language() == QLocale::C) {
label = tr("Personal [%1]").arg(code); label = tr("Personal [%1]").arg(code);
else }
else {
label = QString("%1/%2 [%3]").arg(loc.languageToString(loc.language()), loc.countryToString(loc.country()), code); label = QString("%1/%2 [%3]").arg(loc.languageToString(loc.language()), loc.countryToString(loc.country()), code);
}
ui->listWidget->addItem(label); ui->listWidget->addItem(label);
} }
@ -105,16 +109,18 @@ QStringList AcceptLanguage::expand(const QLocale::Language &language)
languageString = QString(QLatin1String("%1 [%2]")) languageString = QString(QLatin1String("%1 [%2]"))
.arg(QLocale::languageToString(language)) .arg(QLocale::languageToString(language))
.arg(QLocale(language).name().split(QLatin1Char('_')).at(0)); .arg(QLocale(language).name().split(QLatin1Char('_')).at(0));
} else { }
else {
languageString = QString(QLatin1String("%1/%2 [%3]")) languageString = QString(QLatin1String("%1/%2 [%3]"))
.arg(QLocale::languageToString(language)) .arg(QLocale::languageToString(language))
.arg(QLocale::countryToString(countries.at(j))) .arg(QLocale::countryToString(countries.at(j)))
.arg(QLocale(language, countries.at(j)).name().split(QLatin1Char('_')).join(QLatin1String("-")).toLower()); .arg(QLocale(language, countries.at(j)).name().split(QLatin1Char('_')).join(QLatin1String("-")).toLower());
} }
if (!allLanguages.contains(languageString)) if (!allLanguages.contains(languageString)) {
allLanguages.append(languageString); allLanguages.append(languageString);
} }
}
return allLanguages; return allLanguages;
} }
@ -125,23 +131,27 @@ void AcceptLanguage::addLanguage()
_ui.setupUi(&dialog); _ui.setupUi(&dialog);
QStringList allLanguages; QStringList allLanguages;
for (int i = 1 + (int)QLocale::C; i <= (int)QLocale::LastLanguage; ++i) for (int i = 1 + (int)QLocale::C; i <= (int)QLocale::LastLanguage; ++i) {
allLanguages += expand(QLocale::Language(i)); allLanguages += expand(QLocale::Language(i));
}
_ui.listWidget->addItems(allLanguages); _ui.listWidget->addItems(allLanguages);
connect(_ui.listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), &dialog, SLOT(accept())); connect(_ui.listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), &dialog, SLOT(accept()));
if (dialog.exec() == QDialog::Rejected) if (dialog.exec() == QDialog::Rejected) {
return; return;
}
if (!_ui.ownDefinition->text().isEmpty()) { if (!_ui.ownDefinition->text().isEmpty()) {
QString title = tr("Personal [%1]").arg(_ui.ownDefinition->text()); QString title = tr("Personal [%1]").arg(_ui.ownDefinition->text());
ui->listWidget->addItem(title); ui->listWidget->addItem(title);
} else { }
else {
QListWidgetItem* c = _ui.listWidget->currentItem(); QListWidgetItem* c = _ui.listWidget->currentItem();
if (!c) if (!c) {
return; return;
}
ui->listWidget->addItem(c->text()); ui->listWidget->addItem(c->text());
} }
@ -151,17 +161,19 @@ void AcceptLanguage::addLanguage()
void AcceptLanguage::removeLanguage() void AcceptLanguage::removeLanguage()
{ {
QListWidgetItem* currentItem = ui->listWidget->currentItem(); QListWidgetItem* currentItem = ui->listWidget->currentItem();
if (currentItem) if (currentItem) {
delete currentItem; delete currentItem;
} }
}
void AcceptLanguage::upLanguage() void AcceptLanguage::upLanguage()
{ {
int index = ui->listWidget->currentRow(); int index = ui->listWidget->currentRow();
QListWidgetItem* currentItem = ui->listWidget->currentItem(); QListWidgetItem* currentItem = ui->listWidget->currentItem();
if (!currentItem || index == 0) if (!currentItem || index == 0) {
return; return;
}
ui->listWidget->takeItem(index); ui->listWidget->takeItem(index);
ui->listWidget->insertItem(index - 1, currentItem); ui->listWidget->insertItem(index - 1, currentItem);
@ -173,8 +185,9 @@ void AcceptLanguage::downLanguage()
int index = ui->listWidget->currentRow(); int index = ui->listWidget->currentRow();
QListWidgetItem* currentItem = ui->listWidget->currentItem(); QListWidgetItem* currentItem = ui->listWidget->currentItem();
if (!currentItem || index == ui->listWidget->count() - 1) if (!currentItem || index == ui->listWidget->count() - 1) {
return; return;
}
ui->listWidget->takeItem(index); ui->listWidget->takeItem(index);
ui->listWidget->insertItem(index + 1, currentItem); ui->listWidget->insertItem(index + 1, currentItem);

View File

@ -22,7 +22,8 @@
#include <QLocale> #include <QLocale>
#include <QSettings> #include <QSettings>
namespace Ui { namespace Ui
{
class AcceptLanguage; class AcceptLanguage;
} }

View File

@ -63,19 +63,22 @@ void AutoFillManager::loadPasswords()
void AutoFillManager::showPasswords() void AutoFillManager::showPasswords()
{ {
if (m_passwordsShown) if (m_passwordsShown) {
return; return;
}
m_passwordsShown = true; m_passwordsShown = true;
int result = QMessageBox::question(this, tr("Show Passwords"), tr("Are you sure that you want to show all passwords?"), int result = QMessageBox::question(this, tr("Show Passwords"), tr("Are you sure that you want to show all passwords?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (result != QMessageBox::Yes) if (result != QMessageBox::Yes) {
return; return;
}
for (int i = 0; i < ui->treePass->topLevelItemCount(); i++) { for (int i = 0; i < ui->treePass->topLevelItemCount(); i++) {
QTreeWidgetItem* item = ui->treePass->topLevelItem(i); QTreeWidgetItem* item = ui->treePass->topLevelItem(i);
if (!item) if (!item) {
continue; continue;
}
item->setText(1, item->whatsThis(1)); item->setText(1, item->whatsThis(1));
} }
@ -86,8 +89,9 @@ void AutoFillManager::showPasswords()
void AutoFillManager::removePass() void AutoFillManager::removePass()
{ {
QTreeWidgetItem* curItem = ui->treePass->currentItem(); QTreeWidgetItem* curItem = ui->treePass->currentItem();
if (!curItem) if (!curItem) {
return; return;
}
QString id = curItem->whatsThis(0); QString id = curItem->whatsThis(0);
QSqlQuery query; QSqlQuery query;
query.exec("DELETE FROM autofill WHERE id=" + id); query.exec("DELETE FROM autofill WHERE id=" + id);
@ -99,8 +103,9 @@ void AutoFillManager::removeAllPass()
{ {
QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"), QMessageBox::StandardButton button = QMessageBox::warning(this, tr("Confirmation"),
tr("Are you sure to delete all passwords on your computer?"), QMessageBox::Yes | QMessageBox::No); tr("Are you sure to delete all passwords on your computer?"), QMessageBox::Yes | QMessageBox::No);
if (button != QMessageBox::Yes) if (button != QMessageBox::Yes) {
return; return;
}
QSqlQuery query; QSqlQuery query;
query.exec("DELETE FROM autofill"); query.exec("DELETE FROM autofill");
@ -111,8 +116,9 @@ void AutoFillManager::removeAllPass()
void AutoFillManager::editPass() void AutoFillManager::editPass()
{ {
QTreeWidgetItem* curItem = ui->treePass->currentItem(); QTreeWidgetItem* curItem = ui->treePass->currentItem();
if (!curItem) if (!curItem) {
return; return;
}
bool ok; bool ok;
QString text = QInputDialog::getText(this, tr("Edit password"), tr("Change password:"), QLineEdit::Normal, curItem->whatsThis(1), &ok); QString text = QInputDialog::getText(this, tr("Edit password"), tr("Change password:"), QLineEdit::Normal, curItem->whatsThis(1), &ok);
@ -133,8 +139,9 @@ void AutoFillManager::editPass()
query.bindValue(2, curItem->whatsThis(0)); query.bindValue(2, curItem->whatsThis(0));
query.exec(); query.exec();
if (m_passwordsShown) if (m_passwordsShown) {
curItem->setText(1, text); curItem->setText(1, text);
}
curItem->setWhatsThis(1, text); curItem->setWhatsThis(1, text);
} }
} }
@ -142,8 +149,9 @@ void AutoFillManager::editPass()
void AutoFillManager::removeExcept() void AutoFillManager::removeExcept()
{ {
QTreeWidgetItem* curItem = ui->treeExcept->currentItem(); QTreeWidgetItem* curItem = ui->treeExcept->currentItem();
if (!curItem) if (!curItem) {
return; return;
}
QString id = curItem->whatsThis(0); QString id = curItem->whatsThis(0);
QSqlQuery query; QSqlQuery query;
query.exec("DELETE FROM autofill_exceptions WHERE id=" + id); query.exec("DELETE FROM autofill_exceptions WHERE id=" + id);

View File

@ -27,7 +27,8 @@
#include <QMessageBox> #include <QMessageBox>
#include <QInputDialog> #include <QInputDialog>
namespace Ui { namespace Ui
{
class AutoFillManager; class AutoFillManager;
} }

View File

@ -59,8 +59,9 @@ PluginsList::PluginsList(QWidget* parent) :
void PluginsList::addWhitelist() void PluginsList::addWhitelist()
{ {
QString site = QInputDialog::getText(this, tr("Add site to whitelist"), tr("Server without http:// (ex. youtube.com)")); QString site = QInputDialog::getText(this, tr("Add site to whitelist"), tr("Server without http:// (ex. youtube.com)"));
if (site.isEmpty()) if (site.isEmpty()) {
return; return;
}
mApp->plugins()->c2f_addWhitelist(site); mApp->plugins()->c2f_addWhitelist(site);
ui->whitelist->insertTopLevelItem(0, new QTreeWidgetItem(QStringList(site))); ui->whitelist->insertTopLevelItem(0, new QTreeWidgetItem(QStringList(site)));
@ -69,8 +70,9 @@ void PluginsList::addWhitelist()
void PluginsList::removeWhitelist() void PluginsList::removeWhitelist()
{ {
QTreeWidgetItem* item = ui->whitelist->currentItem(); QTreeWidgetItem* item = ui->whitelist->currentItem();
if (!item) if (!item) {
return; return;
}
mApp->plugins()->c2f_removeWhitelist(item->text(0)); mApp->plugins()->c2f_removeWhitelist(item->text(0));
delete item; delete item;
@ -119,16 +121,18 @@ void PluginsList::refresh()
QStringList allowedPlugins = mApp->plugins()->getAllowedPlugins(); QStringList allowedPlugins = mApp->plugins()->getAllowedPlugins();
foreach(QString fileName, availablePlugins) { foreach(QString fileName, availablePlugins) {
PluginInterface* plugin = mApp->plugins()->getPlugin(fileName); PluginInterface* plugin = mApp->plugins()->getPlugin(fileName);
if (!plugin) if (!plugin) {
continue; continue;
}
QListWidgetItem* item = new QListWidgetItem(ui->list); QListWidgetItem* item = new QListWidgetItem(ui->list);
item->setText("" + plugin->pluginName() + " (" + plugin->pluginVersion() + ") by " + plugin->pluginAuthor() + "\n" item->setText("" + plugin->pluginName() + " (" + plugin->pluginVersion() + ") by " + plugin->pluginAuthor() + "\n"
+ plugin->pluginInfo() + "\n" + plugin->pluginDescription()); + plugin->pluginInfo() + "\n" + plugin->pluginDescription());
QIcon icon = plugin->pluginIcon(); QIcon icon = plugin->pluginIcon();
if (icon.isNull()) if (icon.isNull()) {
icon = QIcon(":/icons/preferences/extension.png"); icon = QIcon(":/icons/preferences/extension.png");
}
item->setIcon(icon); item->setIcon(icon);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
@ -142,26 +146,31 @@ void PluginsList::refresh()
void PluginsList::currentChanged(QListWidgetItem* item) void PluginsList::currentChanged(QListWidgetItem* item)
{ {
if (!item) if (!item) {
return; return;
}
QString has = item->whatsThis(); QString has = item->whatsThis();
bool show; bool show;
if (has == "1") if (has == "1") {
show = true; show = true;
else }
else {
show = false; show = false;
}
if(item->checkState() == Qt::Unchecked) if (item->checkState() == Qt::Unchecked) {
show = false; show = false;
}
ui->butSettings->setEnabled(show); ui->butSettings->setEnabled(show);
} }
void PluginsList::settingsClicked() void PluginsList::settingsClicked()
{ {
if (!ui->list->currentItem()) if (!ui->list->currentItem()) {
return; return;
}
QString name = ui->list->currentItem()->toolTip(); QString name = ui->list->currentItem()->toolTip();
PluginInterface* plugin = mApp->plugins()->getPlugin(name); PluginInterface* plugin = mApp->plugins()->getPlugin(name);
@ -172,9 +181,10 @@ void PluginsList::reloadPlugins()
{ {
QStringList allowedPlugins; QStringList allowedPlugins;
for (int i = 0; i < ui->list->count(); i++) { for (int i = 0; i < ui->list->count(); i++) {
if (ui->list->item(i)->checkState() == Qt::Checked) if (ui->list->item(i)->checkState() == Qt::Checked) {
allowedPlugins.append(ui->list->item(i)->toolTip()); allowedPlugins.append(ui->list->item(i)->toolTip());
} }
}
QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat); QSettings settings(mApp->getActiveProfilPath() + "settings.ini", QSettings::IniFormat);
settings.beginGroup("Plugin-Settings"); settings.beginGroup("Plugin-Settings");
settings.setValue("AllowedPlugins", allowedPlugins); settings.setValue("AllowedPlugins", allowedPlugins);

View File

@ -22,7 +22,8 @@
#include <QListWidgetItem> #include <QListWidgetItem>
#include <QInputDialog> #include <QInputDialog>
namespace Ui { namespace Ui
{
class PluginsList; class PluginsList;
} }

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