generic: purge Qt support with fire

this includes QtWebKit support removal since it is not going to be
maintained, fancy headers removal, CMake modules rewrite/removal
and removing conditionals from the build system. Pre-processor
definitions checks are still in place on purpose

Signed-off-by: Ivailo Monev <xakepa10@laimg.moc>
This commit is contained in:
Ivailo Monev 2020-02-07 00:14:00 +00:00
parent 1e73152682
commit 8d3ea2c1bc
85 changed files with 71 additions and 14039 deletions

View file

@ -262,9 +262,6 @@ add_subdirectory( kdeclarative )
add_subdirectory( kdecore )
add_subdirectory( kded )
add_subdirectory( kdeui )
if(QT_QTWEBKIT_FOUND)
add_subdirectory( kdewebkit )
endif()
add_subdirectory( kdewidgets )
add_subdirectory( kexiv2 )
add_subdirectory( kfile )

View file

@ -79,8 +79,6 @@ set(cmakeFiles
FindPulseAudio.cmake
FindQalculate.cmake
FindQCA2.cmake
FindQImageBlitz.cmake
FindQJSON.cmake
FindRAW1394.cmake
FindSamba.cmake
FindSane.cmake

View file

@ -1,100 +1,42 @@
# - Try to find dbusmenu-qt
# This module helps finding an installation of the DBusMenuQt library (see https://launchpad.net/libdbusmenu-qt/)
# - Try to find DBusMenuQt library
# Once done this will define
#
# DBUSMENUQT_FOUND - system has dbusmenu-qt
# DBUSMENUQT_INCLUDE_DIR - the dbusmenu-qt include directory
# DBUSMENUQT_LIBRARIES - the libraries needed to use dbusmenu-qt
# DBUSMENUQT_DEFINITIONS - Compiler switches required for using dbusmenu-qt
# DBUSMENUQT_FOUND - system has DBusMenuQt
# DBUSMENUQT_INCLUDE_DIR - the DBusMenuQt include directory
# DBUSMENUQT_LIBRARIES - the libraries needed to use DBusMenuQt
# DBUSMENUQT_DEFINITIONS - Compiler switches required for using DBusMenuQt
#
# The minimum required version of DBusMenuQt can be specified using the
# standard syntax, e.g. find_package(DBusMenuQt 0.6)
#
# WARNING: versions below 0.4.0 cannot be checked for.
# So if you want to have a version check, require at least 0.4.0 of dbusmenuqt.
# Copyright (c) 2009, Canonical Ltd.
# - Author: Aurélien Gâteau <aurelien.gateau@canonical.com>
#
# Based on FindQCA2.cmake
# Copyright (c) 2006, Michael Larouche, <michael.larouche@kdemail.net>
# Copyright (c) 2020, Ivailo Monev, <xakepa10@gmail.com>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
include(FindPackageHandleStandardArgs)
set(DBUSMENU_QT_NAMES dbusmenu-katie dbusmenu-qt dbusmenu-qtd)
find_package(PkgConfig)
set(DBUSMENU_QT_NAMES dbusmenu-qt dbusmenu-qtd)
if(WITH_KATIE)
pkg_check_modules(PC_DBUSMENUQT QUIET dbusmenu-katie)
set(DBUSMENU_QT_NAMES dbusmenu-katie ${DBUSMENU_QT_NAMES})
endif()
if(NOT PC_DBUSMENUQT_FOUND)
pkg_check_modules(PC_DBUSMENUQT QUIET dbusmenu-qt)
endif()
foreach(name ${DBUSMENU_QT_NAMES})
if(NOT PC_DBUSMENUQT_FOUND)
pkg_check_modules(PC_DBUSMENUQT QUIET ${name})
endif()
endforeach()
set(DBUSMENUQT_DEFINITIONS ${PC_DBUSMENUQT_CFLAGS_OTHER})
find_path(DBUSMENUQT_INCLUDE_DIR
NAMES dbusmenuexporter.h
HINTS ${PC_DBUSMENUQT_INCLUDEDIR}
PATH_SUFFIXES ${DBUSMENU_QT_NAMES}
)
find_library(DBUSMENUQT_LIBRARIES
NAMES ${DBUSMENU_QT_NAMES}
HINTS ${PC_DBUSMENUQT_LIBDIR} ${PC_DBUSMENUQT_LIBRARY_DIRS}
)
HINTS ${PC_DBUSMENUQT_LIBDIR}
)
find_path(DBUSMENUQT_INCLUDE_DIR dbusmenuexporter.h
HINTS ${PC_DBUSMENUQT_INCLUDEDIR} ${PC_DBUSMENUQT_INCLUDE_DIRS}
PATH_SUFFIXES ${DBUSMENU_QT_NAMES}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(DBusMenuQt
REQUIRED_VARS DBUSMENUQT_LIBRARIES DBUSMENUQT_INCLUDE_DIR
VERSION_VAR PC_DBUSMENUQT_VERSION
)
# dbusmenu_version.h is installed since 0.4.0, fail if a version below this is required:
if ((DBusMenuQt_FIND_VERSION) AND ("${DBusMenuQt_FIND_VERSION}" VERSION_LESS "0.4.0"))
message(FATAL_ERROR "Cannot check reliably for a DBusMenuQt version below 0.4.0 (${DBusMenuQt_FIND_VERSION} was requested)")
endif ((DBusMenuQt_FIND_VERSION) AND ("${DBusMenuQt_FIND_VERSION}" VERSION_LESS "0.4.0"))
# find the version number from dbusmenu_version.h and store it in the cache
if(DBUSMENUQT_INCLUDE_DIR AND NOT DBUSMENUQT_VERSION)
# parse the version number out from dbusmenu_version:
if(EXISTS ${DBUSMENUQT_INCLUDE_DIR}/dbusmenu_version.h)
file(READ "${DBUSMENUQT_INCLUDE_DIR}/dbusmenu_version.h" DBUSMENUQT_VERSION_CONTENT)
if ("${DBUSMENUQT_VERSION_CONTENT}" MATCHES "DBUSMENUQT_VERSION_MAJOR") # introduced after 0.6.4, makes this code here more robust
string(REGEX MATCH "#define +DBUSMENUQT_VERSION_MAJOR +([0-9]+)" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_MAJOR "${CMAKE_MATCH_1}")
string(REGEX MATCH "#define +DBUSMENUQT_VERSION_MINOR +([0-9]+)" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_MINOR "${CMAKE_MATCH_1}")
string(REGEX MATCH "#define +DBUSMENUQT_VERSION_PATCH +([0-9]+)" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_PATCH "${CMAKE_MATCH_1}")
else("${DBUSMENUQT_VERSION_CONTENT}" MATCHES "DBUSMENUQT_VERSION_MAJOR")
# In versions up to 0.6.4, the code for setting the version number in the header looked like
# shopw below. This made version checking quite un-obvious:
# #define DBUSMENUQT_VERSION \
# ((0 << 16) \
# |(6 << 8) \
# |4)
string(REGEX MATCH "\\(\\( *([0-9]+) *<<" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_MAJOR "${CMAKE_MATCH_1}")
string(REGEX MATCH "\\|\\( *([0-9]+) *<<" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_MINOR "${CMAKE_MATCH_1}")
string(REGEX MATCH "\\| *([0-9]+) *\\)" _dummy "${DBUSMENUQT_VERSION_CONTENT}")
set(DBUSMENUQT_VERSION_PATCH "${CMAKE_MATCH_1}")
endif("${DBUSMENUQT_VERSION_CONTENT}" MATCHES "DBUSMENUQT_VERSION_MAJOR")
endif(EXISTS ${DBUSMENUQT_INCLUDE_DIR}/dbusmenu_version.h)
set(DBUSMENUQT_VERSION "${DBUSMENUQT_VERSION_MAJOR}.${DBUSMENUQT_VERSION_MINOR}.${DBUSMENUQT_VERSION_PATCH}" CACHE STRING "Version number of DBusMenuQt" FORCE)
endif(DBUSMENUQT_INCLUDE_DIR AND NOT DBUSMENUQT_VERSION)
find_package_handle_standard_args(DBusMenuQt REQUIRED_VARS DBUSMENUQT_LIBRARIES DBUSMENUQT_INCLUDE_DIR
VERSION_VAR DBUSMENUQT_VERSION)
#"Could not find dbusmenu-qt; available at https://launchpad.net/libdbusmenu-qt/" DBUSMENUQT_LIBRARIES DBUSMENUQT_INCLUDE_DIR)
mark_as_advanced(DBUSMENUQT_INCLUDE_DIR DBUSMENUQT_LIBRARIES DBUSMENUQT_VERSION)
mark_as_advanced(DBUSMENUQT_INCLUDE_DIR DBUSMENUQT_LIBRARIES)

View file

@ -59,7 +59,6 @@
# KDE4_KTEXTEDITOR_LIBRARY - the ktexteditor library
# KDE4_PLASMA_LIBRARY - the plasma library
# KDE4_KUNITCONVERSION_LIBRARY - the kunitconversion library
# KDE4_KDEWEBKIT_LIBRARY - the kdewebkit library
# KDE4_KCDDB_LIBRARY - the kcddb library
# KDE4_KDCRAW_LIBRARY - the kdcraw library
# KDE4_KEXIV2_LIBRARY - the kexiv2 library
@ -88,7 +87,6 @@
# KDE4_KTEXTEDITOR_LIBS - the ktexteditor library and all depending libraries
# KDE4_PLASMA_LIBS - the plasma library and all depending librairies
# KDE4_KUNITCONVERSION_LIBS - the kunitconversion library and all depending libraries
# KDE4_KDEWEBKIT_LIBS - the kdewebkit library and all depending libraries
# KDE4_KCDDB_LIBS - the kcddb library and all depending libraries
# KDE4_KDCRAW_LIBS - the kdcraw library and all depending libraries
# KDE4_KEXIV2_LIBS - the kexiv2 library and all depending libraries
@ -273,22 +271,7 @@ if(KDE4_FIND_REQUIRED OR KDE4Internal_FIND_REQUIRED)
set(_REQ_STRING_KDE4 REQUIRED)
endif()
#this line includes FindQt4.cmake, which searches the Qt library and headers
# TODO: we should check here that all necessary modules of Qt have been found, e.g. QtDBus
option(WITH_KATIE "Build against Katie instead of Qt4" ON)
# TODO: once Katie goes stable make it required from const in KDEConfig if
# kdelibs is build against it, this file may go away due to order issues
# and be merged into KDEConfig.
if(WITH_KATIE)
find_package(Katie)
endif()
if(NOT KATIE_FOUND)
# avoid the need to check WITH_KATIE in addition to KATIE_FOUND
set(KATIE_FOUND FALSE)
find_package(Qt4 ${_REQ_STRING_KDE4})
endif()
find_package(Katie ${_REQ_STRING_KDE4})
# restore the original CMAKE_MODULE_PATH
set(CMAKE_MODULE_PATH ${_kde_cmake_module_path_back})
@ -412,7 +395,6 @@ set(_kde_libraries
kdeclarative
kdecore
kdeui
kdewebkit
kdnssd
kemoticons
kexiv2

View file

@ -7,35 +7,40 @@
# POPPLER_QT4_DEFINITIONS - Compiler switches required for using poppler-qt4
#
# use pkg-config to get the directories and then use these values
# in the FIND_PATH() and FIND_LIBRARY() calls
# Copyright (c) 2006, Wilfried Huss, <wilfried.huss@gmx.at>
# Copyright (c) 2020, Ivailo Monev, <xakepa10@gmail.com>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
set(POPPLER_QT4_NAMES poppler-katie poppler-qt4)
find_package(PkgConfig)
pkg_check_modules(PC_POPPLERQT4 QUIET poppler-qt4)
foreach(name ${POPPLER_QT4_NAMES})
if(NOT PC_POPPLER_QT4_FOUND)
pkg_check_modules(PC_POPPLER_QT4 QUIET ${name})
endif()
endforeach()
set(POPPLER_QT4_DEFINITIONS ${PC_POPPLERQT4_CFLAGS_OTHER})
set(POPPLER_QT4_DEFINITIONS ${PC_POPPLER_QT4_CFLAGS_OTHER})
find_path(POPPLER_QT4_INCLUDE_DIR
NAMES poppler-qt4.h
HINTS ${PC_POPPLERQT4_INCLUDEDIR}
PATH_SUFFIXES poppler/qt4 poppler
NAMES poppler-katie.h poppler-qt4.h
HINTS ${PC_POPPLER_QT4_INCLUDEDIR}
PATH_SUFFIXES poppler/katie poppler/qt4 poppler
)
find_library(POPPLER_QT4_LIBRARY
NAMES poppler-qt4
HINTS ${PC_POPPLERQT4_LIBDIR}
find_library(POPPLER_QT4_LIBRARIES
NAMES ${POPPLER_QT4_NAMES}
HINTS ${PC_POPPLER_QT4_LIBDIR}
)
set(POPPLER_QT4_LIBRARIES ${POPPLER_QT4_LIBRARY})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PopplerQt4 REQUIRED_VARS POPPLER_QT4_INCLUDE_DIR POPPLER_QT4_LIBRARIES)
find_package_handle_standard_args(PopplerQt4
REQUIRED_VARS POPPLER_QT4_INCLUDE_DIR POPPLER_QT4_LIBRARIES
VERSION_VAR PC_POPPLER_QT4_VERSION
)
# for compatibility:
set(POPPLER_QT4_FOUND ${POPPLERQT4_FOUND})

View file

@ -10,35 +10,37 @@
# in the FIND_PATH() and FIND_LIBRARY() calls
# Copyright (c) 2006, Michael Larouche, <michael.larouche@kdemail.net>
# Copyright (c) 2020, Ivailo Monev, <xakepa10@gmail.com>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
if (QCA2_INCLUDE_DIR AND QCA2_LIBRARIES)
set(QCA2_NAMES qca2-katie qca2)
# in cache already
set(QCA2_FOUND TRUE)
find_package(PkgConfig)
foreach(name ${QCA2_NAMES})
if(NOT PC_QCA2_FOUND)
pkg_check_modules(PC_QCA2 QUIET ${name})
endif()
endforeach()
else (QCA2_INCLUDE_DIR AND QCA2_LIBRARIES)
set(QCA2_DEFINITIONS ${PC_QCA2_CFLAGS_OTHER})
if (NOT WIN32)
find_package(PkgConfig)
pkg_check_modules(PC_QCA2 QUIET qca2 qca2-katie)
set(QCA2_DEFINITIONS ${PC_QCA2_qca2_CFLAGS_OTHER} ${PC_QCA2_qca2-katie_CFLAGS_OTHER})
endif (NOT WIN32)
find_path(QCA2_INCLUDE_DIR
NAMES QtCrypto
HINTS ${PC_QCA2_INCLUDEDIR}
PATH_SUFFIXES Qca-katie/QtCrypto Qca/QtCrypto QtCrypto
)
find_library(QCA2_LIBRARIES
NAMES qca qca-katie
HINTS ${PC_QCA2_qca2_LIBDIR} ${PC_QCA2_qca2-katie_LIBRARY_DIRS}
)
find_library(QCA2_LIBRARIES
NAMES qca-katie qca
HINTS ${PC_QCA2_LIBDIR}
)
find_path(QCA2_INCLUDE_DIR QtCrypto
HINTS ${PC_QCA2_qca2_INCLUDEDIR} ${PC_QCA2_qca2-katie_INCLUDE_DIRS}
PATH_SUFFIXES QtCrypto Qca-katie/QtCrypto)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QCA2
REQUIRED_VARS QCA2_LIBRARIES QCA2_INCLUDE_DIR
VERSION_VAR PC_QCA2_VERSION
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QCA2 DEFAULT_MSG QCA2_LIBRARIES QCA2_INCLUDE_DIR)
mark_as_advanced(QCA2_INCLUDE_DIR QCA2_LIBRARIES)
endif (QCA2_INCLUDE_DIR AND QCA2_LIBRARIES)
mark_as_advanced(QCA2_INCLUDE_DIR QCA2_LIBRARIES)

View file

@ -1,48 +0,0 @@
# - Try to find the qimageblitz lib
# Once done this will define
#
# QIMAGEBLITZ_FOUND - system has qimageblitz lib
# QIMAGEBLITZ_INCLUDES - the qimageblitz include directory
# QIMAGEBLITZ_LIBRARIES - The libraries needed to use qimageblitz
# Copyright (c) 2006, Montel Laurent, <montel@kde.org>
# Copyright (c) 2007, Allen Winter, <winter@kde.org>
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
if (QIMAGEBLITZ_INCLUDES AND QIMAGEBLITZ_LIBRARIES)
set(QImageBlitz_FIND_QUIETLY TRUE)
endif (QIMAGEBLITZ_INCLUDES AND QIMAGEBLITZ_LIBRARIES)
if (NOT WIN32)
# use pkg-config to get the directories and then use these values
# in the FIND_PATH() and FIND_LIBRARY() calls
find_package(PkgConfig)
pkg_check_modules(PC_QIMAGEBLITZ QUIET qimageblitz)
endif (NOT WIN32)
find_path(QIMAGEBLITZ_INCLUDES
NAMES
qimageblitz.h
PATH_SUFFIXES qimageblitz
HINTS
$ENV{QIMAGEBLITZDIR}/include
${PC_QIMAGEBLITZ_INCLUDEDIR}
${KDE4_INCLUDE_DIR}
${INCLUDE_INSTALL_DIR}
)
find_library(QIMAGEBLITZ_LIBRARIES
qimageblitz
HINTS
$ENV{QIMAGEBLITZDIR}/lib
${PC_QIMAGEBLITZ_LIBDIR}
${KDE4_LIB_DIR}
${LIB_INSTALL_DIR}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QImageBlitz DEFAULT_MSG
QIMAGEBLITZ_INCLUDES QIMAGEBLITZ_LIBRARIES)
mark_as_advanced(QIMAGEBLITZ_INCLUDES QIMAGEBLITZ_LIBRARIES)

View file

@ -1,44 +0,0 @@
# Find QJSON - JSON handling library for Qt
#
# This module defines
# QJSON_FOUND - whether the qsjon library was found
# QJSON_LIBRARIES - the qjson library
# QJSON_INCLUDE_DIR - the include path of the qjson library
#
if (QJSON_INCLUDE_DIR AND QJSON_LIBRARIES)
# Already in cache
set (QJSON_FOUND TRUE)
else (QJSON_INCLUDE_DIR AND QJSON_LIBRARIES)
if (NOT WIN32)
# use pkg-config to get the values of QJSON_INCLUDE_DIRS
# and QJSON_LIBRARY_DIRS to add as hints to the find commands.
include (FindPkgConfig)
pkg_check_modules (PC_QJSON QJson>=0.5)
endif (NOT WIN32)
find_library (QJSON_LIBRARIES
NAMES
qjson
PATHS
${PC_QJSON_LIBRARY_DIRS}
${LIB_INSTALL_DIR}
${KDE4_LIB_DIR}
)
find_path (QJSON_INCLUDE_DIR
NAMES
qjson/parser.h
PATHS
${PC_QJSON_INCLUDE_DIRS}
${INCLUDE_INSTALL_DIR}
${KDE4_INCLUDE_DIR}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QJSON DEFAULT_MSG QJSON_LIBRARIES QJSON_INCLUDE_DIR)
endif (QJSON_INCLUDE_DIR AND QJSON_LIBRARIES)

View file

@ -407,14 +407,9 @@ install(
KPixmapSequence
KPixmapSequenceWidget
KPixmapSequenceOverlayPainter
KGraphicsWebView
KAudioPlayer
KMediaPlayer
KMediaWidget
KWebPage
KWebView
KWebPluginFactory
KWebWallet
KPty
KPtyDevice
KPtyProcess
@ -772,7 +767,6 @@ install(
Plasma/View
Plasma/Wallpaper
Plasma/WallpaperScript
Plasma/WebView
Plasma/WindowEffects
DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Plasma
COMPONENT Devel

View file

@ -1,2 +0,0 @@
#include "../kwebpage.h"

View file

@ -1,2 +0,0 @@
#include "../kwebpluginfactory.h"

View file

@ -1,2 +0,0 @@
#include "../kwebview.h"

View file

@ -1,2 +0,0 @@
#include "../kwebwallet.h"

View file

@ -1 +0,0 @@
#include "../../plasma/widgets/webview.h"

View file

@ -40,13 +40,10 @@ target_link_libraries(kdeclarative
${KDE4_KDECORE_LIBS}
${KDE4_KDEUI_LIBS}
${QT_QTSCRIPT_LIBRARY}
${QT_QTSCRIPTTOOLS_LIBRARY}
${QT_QTDECLARATIVE_LIBRARY}
)
if(KATIE_FOUND)
target_link_libraries(kdeclarative ${QT_QTSCRIPTTOOLS_LIBRARY})
endif()
if(ENABLE_TESTING)
add_subdirectory(tests)
endif()

View file

@ -1,67 +0,0 @@
project(kdewebkit)
add_feature_info(QtWebkit QT_QTWEBKIT_FOUND "Needed for building kdelibs" "http://trac.webkit.org/wiki/QtWebKit")
if(NOT QT_QTWEBKIT_FOUND)
message(FATAL_ERROR "The QtWebkit module is required.")
endif()
include_directories(
${KDE4_KDECORE_INCLUDES}
${KDE4_KDEUI_INCLUDES}
${KDE4_KPARTS_INCLUDES}
${KDE4_KIO_INCLUDES}
# for the export headers
${CMAKE_BINARY_DIR}/kutils
)
add_subdirectory(kwebkitpart)
set(kdewebkit_LIB_SRCS
kwebwallet.cpp
kgraphicswebview.cpp
kwebpage.cpp
kwebview.cpp
kwebpluginfactory.cpp
)
add_library(kdewebkit ${LIBRARY_TYPE} ${kdewebkit_LIB_SRCS})
target_link_libraries(kdewebkit
${KDE4_KDEUI_LIBS}
${KDE4_KPARTS_LIBS}
${KDE4_KIO_LIBS}
${QT_QTWEBKIT_LIBRARY}
${QT_QTNETWORK_LIBRARY}
)
set_target_properties(kdewebkit PROPERTIES
VERSION ${GENERIC_LIB_VERSION}
SOVERSION ${GENERIC_LIB_SOVERSION}
)
generate_export_header(kdewebkit)
install(
TARGETS kdewebkit
EXPORT kdelibsLibraryTargets
${INSTALL_TARGETS_DEFAULT_ARGS}
)
install(
FILES
${CMAKE_CURRENT_BINARY_DIR}/kdewebkit_export.h
kwebwallet.h
kgraphicswebview.h
kwebpluginfactory.h
kwebpage.h
kwebview.h
DESTINATION ${INCLUDE_INSTALL_DIR}
COMPONENT Devel
)
# it is required for adblock
install(
FILES khtmlrc
DESTINATION ${CONFIG_INSTALL_DIR}
)

View file

@ -1,51 +0,0 @@
Known Issues [PENDING]:
=======================
* [QtWebKit] Form completion like the one available in native Qt widgets such
as QLineEdit is missing due to lack of access to form elements.
See http://webkit.org/b/36668.
Known Issues [PARTIALLY FIXED]:
===============================
* [QtWebKit] Spell checking support. See https://webkit.org/b/44114 [ QtWebKit > 2.2 ]
Some support was implemented but did not quite make it into QtWebKit 2.2.
It will probably be in future releases. However, what is implemented in QtWebKit is
the continuous spell check or spell-check-as-you-type functionality. The ability to
passively spell check (by selecting option from a context menu) is something that
can be implemented in the specific browser implementation. kwebkitpart already
provides such support.
Known Issues [FIXED]:
=====================
* [kdewebkit] Proper support for putting ioslaves on hold. [KDE 4.6]
Handling unsupported content always requires more than one connection to the
same server to download a single request. The upstream change requested,
http://webkit.org/b/37880, turned out to be the wrong solution. The issue has
now been correctly addressed within KDE itself. You can find the details of
the fix at http://reviewboard.kde.org/r/6182/ & http://reviewboard.kde.org/r/6183/
* [QtWebKit] Missing Java applet support. [QtWebKit 2.1*]
See http://webkit.org/b/33044.
* [QtWebKit] Crash while browsing facebook. [QtWebKit 2.0**]
See http://webkit.org/b/35204.
* [QtWebKit] Does not have support "Content-Disposition". [QtWebKit 2.0**]
Specifically when it contains the keyword "attachment" the content returned
is not supposed to be rendered. Test case site: http://greenbytes.de/tech/tc2231/
See http://webkit.org/b/36395.
* [QtWebKit] No way to stop <meta> tag based page refresh. [QtWebKit 2.0**]
See http://webkit.org/b/29899
* [QtWebKit] HTML 5 <video> tag will not properly work for most users depending
on how their distro created their Qt library package. [QtWebKit >= 2.2]
With QtWebKit 2.2, HTML 5 <video> support is internally handled by QtWebKit using
WebKit's gstreamer integration. For the details on how and why that was done see
https://lists.webkit.org/pipermail/webkit-qt/2011-June/001633.html.
NOTES:
======
** Qt 4.7.x comes with QtWebkit 2.0.x
** Qt 4.8.x comes with QtWebKit 2.2.x

View file

@ -1,85 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "kgraphicswebview.h"
#include "kwebpage.h"
#include "kwebview_p.h"
#include <QtGui/qgraphicssceneevent.h>
#include <QtGui/qgraphicssceneevent.h>
KGraphicsWebView::KGraphicsWebView(QGraphicsItem *parent, bool createCustomPage)
:QGraphicsWebView(parent),
d(new KWebViewPrivate<KGraphicsWebView>(this))
{
if (createCustomPage)
setPage(new KWebPage(this));
}
KGraphicsWebView::~KGraphicsWebView()
{
delete d;
}
bool KGraphicsWebView::isExternalContentAllowed() const
{
return d->isExternalContentAllowed();
}
void KGraphicsWebView::setAllowExternalContent(bool allow)
{
d->setAllowExternalContent(allow);
}
void KGraphicsWebView::wheelEvent(QGraphicsSceneWheelEvent *event)
{
if (d->wheelEvent(event->delta())) {
event->accept();
} else {
QGraphicsWebView::wheelEvent(event);
}
}
void KGraphicsWebView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
d->pressedButtons = event->buttons();
d->keyboardModifiers = event->modifiers();
QGraphicsWebView::mousePressEvent(event);
}
void KGraphicsWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (d->mouseReleased(event->pos().toPoint()) || d->handleUrlPasteFromClipboard(event)) {
event->accept();
return;
}
QGraphicsWebView::mouseReleaseEvent(event);
}
#include "moc_kgraphicswebview.cpp"

View file

@ -1,184 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KGRAPHICSWEBVIEW_H
#define KGRAPHICSWEBVIEW_H
#include <kdewebkit_export.h>
#include <QtWebKit/QGraphicsWebView>
class KUrl;
template<class T> class KWebViewPrivate;
/**
* @short A re-implementation of QGraphicsWebView that provides KDE integration.
*
* This is a drop-in replacement for QGraphicsWebView that provides full KDE
* integration through the use of @ref KWebPage. It also provides signals that
* capture middle, shift and ctrl mouse clicks on links and URL pasting from the
* selection clipboard.
*
* The specific functionality provided by this class (over and above what
* would be acheived by using KWebPage with a QGraphicsWebView) is that
* scrolling * with the mouse wheel while holding down CTRL zooms the page (see
* QGraphicsWebView::setZoomFactor) and several useful signals are emitted when
* the user performs certain actions.
*
* @author Urs Wolfer <uwolfer @ kde.org>
* @author Dawit Alemayehu <adawit @ kde.org>
*
* @since 4.4
*/
class KDEWEBKIT_EXPORT KGraphicsWebView : public QGraphicsWebView
{
Q_OBJECT
public:
/**
* Constructs a KGraphicsWebView object with parent @p parent.
*
* Set @p createCustomPage to false to prevent the creation of a
* @ref KWebPage object for KDE integration. Doing so allows you to
* avoid unnecessary object creation and deletion if you are going to
* use a subclass of KWebPage.
*
* @param parent the parent object
* @param createCustomPage if @c true, the view's page is set to an
* instance of KWebPage
*/
explicit KGraphicsWebView(QGraphicsItem *parent = 0, bool createCustomPage = true);
/**
* Destroys the KGraphicsWebView.
*/
~KGraphicsWebView();
/**
* Returns true if access to remote content is allowed.
*
* By default access to remote content is allowed.
*
* @see setAllowExternalContent()
* @see KWebPage::isExternalContentAllowed()
*/
bool isExternalContentAllowed() const;
/**
* Set @p allow to false if you want to prevent access to remote content.
*
* If this function is set to false only resources on the local system
* can be accessed through this class. By default fetching external content
* is allowed.
*
* @see isExternalContentAllowed()
* @see KWebPage::setAllowExternalContent(bool)
*/
void setAllowExternalContent(bool allow);
Q_SIGNALS:
/**
* Emitted when a URL from the selection clipboard is pasted on this view.
*
* This is triggered when the user clicks on the page with the middle
* mouse button when there is something in the global mouse selection
* clipboard. This is typically only possible on X11.
*
* Uri filters are applied to the selection clipboard to generate @p url.
*
* If the content in the selection clipboard is not a valid URL and a
* default search engine is configured, @p searchText will be set to the
* content of the clipboard (250 characters maximum) and @p url will be
* set to a query to the default search engine.
*
* @param url the URL generated from the selection clipboard content
* @param searchText content of the selection clipboard if it is not a
* valid URL
*
* @see KUriFilter
* @see QClipboard
* @since 4.6
*/
void selectionClipboardUrlPasted(const KUrl &url, const QString& searchText);
/**
* Emitted when a link is clicked with the left mouse button while SHIFT is
* held down.
*
* A KDE user would typically expect this to result in the triggering of a
* "save link as" action.
*
* @param url the URL of the clicked link
*/
void linkShiftClicked(const KUrl &url);
/**
* Emitted when a link is clicked with the middle mouse button or clicked
* with the left mouse button while CTRL is held down.
*
* Typically, the user would expect this to result in the URL being opened
* in a new tab or window.
*
* @param url the URL of the clicked link
*/
void linkMiddleOrCtrlClicked(const KUrl &url);
protected:
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::wheelEvent
* @internal
*/
void wheelEvent(QGraphicsSceneWheelEvent *event);
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::mousePressEvent
* @internal
*/
virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::mouseReleaseEvent
* @internal
*/
virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
private:
friend class KWebViewPrivate<KGraphicsWebView>;
KWebViewPrivate<KGraphicsWebView> * const d;
};
#endif // KWEBVIEW_H

View file

@ -1,200 +0,0 @@
[Filter Settings]
Count=0
Enabled=true
HTMLFilterListMaxAgeDays=7
Shrink=falseHTMLFilterList-Enabled-1=false
HTMLFilterListLocalFilename-1=adblockfilter1.txt
HTMLFilterListName-1=ABP Japanese Filters
HTMLFilterListURL-1=http://bit.ly/11QrCfx
HTMLFilterList-Enabled-2=false
HTMLFilterListLocalFilename-2=adblockfilter2.txt
HTMLFilterListName-2=Czech List
HTMLFilterListURL-2=http://adblock.dajbych.net/adblock.txt
HTMLFilterList-Enabled-3=false
HTMLFilterListLocalFilename-3=adblockfilter3.txt
HTMLFilterListName-3=EasyList
HTMLFilterListURL-3=https://easylist-downloads.adblockplus.org/easylist.txt
HTMLFilterList-Enabled-4=false
HTMLFilterListLocalFilename-4=adblockfilter4.txt
HTMLFilterListName-4=Estonian filters by Gurud.ee
HTMLFilterListURL-4=http://gurud.ee/ab.txt
HTMLFilterList-Enabled-5=false
HTMLFilterListLocalFilename-5=adblockfilter5.txt
HTMLFilterListName-5=Filtros Nauscopicos
HTMLFilterListURL-5=http://abp.mozilla-hispano.org/nauscopio/filtros.txt
HTMLFilterList-Enabled-6=false
HTMLFilterListLocalFilename-6=adblockfilter6.txt
HTMLFilterListName-6=hufilter
HTMLFilterListURL-6=https://raw.githubusercontent.com/szpeter80/hufilter/master/hufilter.txt
HTMLFilterList-Enabled-7=false
HTMLFilterListLocalFilename-7=adblockfilter7.txt
HTMLFilterListName-7=Peter Lowe's list
HTMLFilterListURL-7=http://pgl.yoyo.org/adservers/serverlist.php?hostformat=adblockplus&mimetype=plaintext
HTMLFilterList-Enabled-8=false
HTMLFilterListLocalFilename-8=adblockfilter8.txt
HTMLFilterListName-8=Schacks Adblock Plus liste
HTMLFilterListURL-8=https://adblock.dk/block.csv
HTMLFilterList-Enabled-9=false
HTMLFilterListLocalFilename-9=adblockfilter9.txt
HTMLFilterListName-9=Xfiles
HTMLFilterListURL-9=http://noads.it/filtri.txt
HTMLFilterList-Enabled-10=false
HTMLFilterListLocalFilename-10=adblockfilter10.txt
HTMLFilterListName-10=YousList
HTMLFilterListURL-10=https://raw.githubusercontent.com/yous/YousList/master/youslist.txt
HTMLFilterList-Enabled-11=false
HTMLFilterListLocalFilename-11=adblockfilter11.txt
HTMLFilterListName-11=Adblock Warning Removal List
HTMLFilterListURL-11=https://easylist-downloads.adblockplus.org/antiadblockfilters.txt
HTMLFilterList-Enabled-12=false
HTMLFilterListLocalFilename-12=adblockfilter12.txt
HTMLFilterListName-12=Adware filters
HTMLFilterListURL-12=https://easylist-downloads.adblockplus.org/adwarefilters.txt
HTMLFilterList-Enabled-13=false
HTMLFilterListLocalFilename-13=adblockfilter13.txt
HTMLFilterListName-13=I don't care about cookies
HTMLFilterListURL-13=http://www.kiboke-studio.hr/i-dont-care-about-cookies/abp/
HTMLFilterList-Enabled-14=false
HTMLFilterListLocalFilename-14=adblockfilter14.txt
HTMLFilterListName-14=Malware Domains
HTMLFilterListURL-14=https://easylist-downloads.adblockplus.org/malwaredomains_full.txt
HTMLFilterList-Enabled-15=false
HTMLFilterListLocalFilename-15=adblockfilter15.txt
HTMLFilterListName-15=Prebake
HTMLFilterListURL-15=https://raw.github.com/liamja/Prebake/master/obtrusive.txt
HTMLFilterList-Enabled-16=false
HTMLFilterListLocalFilename-16=adblockfilter16.txt
HTMLFilterListName-16=Spam404
HTMLFilterListURL-16=https://raw.githubusercontent.com/Dawsey21/Lists/master/adblock-list.txt
HTMLFilterList-Enabled-17=false
HTMLFilterListLocalFilename-17=adblockfilter17.txt
HTMLFilterListName-17=ABPindo+EasyList
HTMLFilterListURL-17=https://easylist-downloads.adblockplus.org/abpindo+easylist.txt
HTMLFilterList-Enabled-18=false
HTMLFilterListLocalFilename-18=adblockfilter18.txt
HTMLFilterListName-18=ABPindo
HTMLFilterListURL-18=https://raw.githubusercontent.com/ABPindo/indonesianadblockrules/master/subscriptions/abpindo.txt
HTMLFilterList-Enabled-19=false
HTMLFilterListLocalFilename-19=adblockfilter19.txt
HTMLFilterListName-19=Bulgarian list+EasyList
HTMLFilterListURL-19=https://easylist-downloads.adblockplus.org/bulgarian_list+easylist.txt
HTMLFilterList-Enabled-20=false
HTMLFilterListLocalFilename-20=adblockfilter20.txt
HTMLFilterListName-20=Bulgarian list
HTMLFilterListURL-20=http://stanev.org/abp/adblock_bg.txt
HTMLFilterList-Enabled-21=false
HTMLFilterListLocalFilename-21=adblockfilter21.txt
HTMLFilterListName-21=EasyList China+EasyList
HTMLFilterListURL-21=https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt
HTMLFilterList-Enabled-22=false
HTMLFilterListLocalFilename-22=adblockfilter22.txt
HTMLFilterListName-22=EasyList China
HTMLFilterListURL-22=https://easylist-downloads.adblockplus.org/easylistchina.txt
HTMLFilterList-Enabled-23=false
HTMLFilterListLocalFilename-23=adblockfilter23.txt
HTMLFilterListName-23=EasyList Czech and Slovak+EasyList
HTMLFilterListURL-23=https://easylist-downloads.adblockplus.org/easylistczechslovak+easylist.txt
HTMLFilterList-Enabled-24=false
HTMLFilterListLocalFilename-24=adblockfilter24.txt
HTMLFilterListName-24=EasyList Czech and Slovak
HTMLFilterListURL-24=https://raw.github.com/tomasko126/easylistczechandslovak/master/filters.txt
HTMLFilterList-Enabled-25=false
HTMLFilterListLocalFilename-25=adblockfilter25.txt
HTMLFilterListName-25=EasyList Dutch+EasyList
HTMLFilterListURL-25=https://easylist-downloads.adblockplus.org/easylistdutch+easylist.txt
HTMLFilterList-Enabled-26=false
HTMLFilterListLocalFilename-26=adblockfilter26.txt
HTMLFilterListName-26=EasyList Dutch
HTMLFilterListURL-26=https://easylist-downloads.adblockplus.org/easylistdutch.txt
HTMLFilterList-Enabled-27=false
HTMLFilterListLocalFilename-27=adblockfilter27.txt
HTMLFilterListName-27=EasyList Germany+EasyList
HTMLFilterListURL-27=https://easylist-downloads.adblockplus.org/easylistgermany+easylist.txt
HTMLFilterList-Enabled-28=false
HTMLFilterListLocalFilename-28=adblockfilter28.txt
HTMLFilterListName-28=EasyList Germany
HTMLFilterListURL-28=https://easylist-downloads.adblockplus.org/easylistgermany.txt
HTMLFilterList-Enabled-29=false
HTMLFilterListLocalFilename-29=adblockfilter29.txt
HTMLFilterListName-29=EasyList Hebrew+EasyList
HTMLFilterListURL-29=https://easylist-downloads.adblockplus.org/israellist+easylist.txt
HTMLFilterList-Enabled-30=false
HTMLFilterListLocalFilename-30=adblockfilter30.txt
HTMLFilterListName-30=EasyList Hebrew
HTMLFilterListURL-30=https://raw.githubusercontent.com/ABPIsrael/EasyListHebrew/master/EasyListHebrew.txt
HTMLFilterList-Enabled-31=false
HTMLFilterListLocalFilename-31=adblockfilter31.txt
HTMLFilterListName-31=EasyList Italy+EasyList
HTMLFilterListURL-31=https://easylist-downloads.adblockplus.org/easylistitaly+easylist.txt
HTMLFilterList-Enabled-32=false
HTMLFilterListLocalFilename-32=adblockfilter32.txt
HTMLFilterListName-32=EasyList Italy
HTMLFilterListURL-32=https://easylist-downloads.adblockplus.org/easylistitaly.txt
HTMLFilterList-Enabled-33=false
HTMLFilterListLocalFilename-33=adblockfilter33.txt
HTMLFilterListName-33=EasyList Lithuania+EasyList
HTMLFilterListURL-33=https://easylist-downloads.adblockplus.org/easylistlithuania+easylist.txt
HTMLFilterList-Enabled-34=false
HTMLFilterListLocalFilename-34=adblockfilter34.txt
HTMLFilterListName-34=EasyList Lithuania
HTMLFilterListURL-34=http://margevicius.lt/easylistlithuania.txt
HTMLFilterList-Enabled-35=false
HTMLFilterListLocalFilename-35=adblockfilter35.txt
HTMLFilterListName-35=EasyList Spanish
HTMLFilterListURL-35=https://easylist-downloads.adblockplus.org/easylistspanish.txt
HTMLFilterList-Enabled-36=false
HTMLFilterListLocalFilename-36=adblockfilter36.txt
HTMLFilterListName-36=EasyPrivacy+EasyList
HTMLFilterListURL-36=https://easylist-downloads.adblockplus.org/easyprivacy+easylist.txt
HTMLFilterList-Enabled-37=false
HTMLFilterListLocalFilename-37=adblockfilter37.txt
HTMLFilterListName-37=EasyPrivacy
HTMLFilterListURL-37=https://easylist-downloads.adblockplus.org/easyprivacy.txt
HTMLFilterList-Enabled-38=false
HTMLFilterListLocalFilename-38=adblockfilter38.txt
HTMLFilterListName-38=Icelandic ABP List
HTMLFilterListURL-38=http://adblock.gardar.net/is.abp.txt
HTMLFilterList-Enabled-39=false
HTMLFilterListLocalFilename-39=adblockfilter39.txt
HTMLFilterListName-39=Latvian List+EasyList
HTMLFilterListURL-39=https://easylist-downloads.adblockplus.org/latvianlist+easylist.txt
HTMLFilterList-Enabled-40=false
HTMLFilterListLocalFilename-40=adblockfilter40.txt
HTMLFilterListName-40=Latvian List
HTMLFilterListURL-40=https://notabug.org/latvian-list/adblock-latvian/raw/master/lists/latvian-list.txt
HTMLFilterList-Enabled-41=false
HTMLFilterListLocalFilename-41=adblockfilter41.txt
HTMLFilterListName-41=Liste AR+Liste FR+EasyList
HTMLFilterListURL-41=https://easylist-downloads.adblockplus.org/liste_ar+liste_fr+easylist.txt
HTMLFilterList-Enabled-42=false
HTMLFilterListLocalFilename-42=adblockfilter42.txt
HTMLFilterListName-42=Liste AR
HTMLFilterListURL-42=https://easylist-downloads.adblockplus.org/Liste_AR.txt
HTMLFilterList-Enabled-43=false
HTMLFilterListLocalFilename-43=adblockfilter43.txt
HTMLFilterListName-43=Liste FR+EasyList
HTMLFilterListURL-43=https://easylist-downloads.adblockplus.org/liste_fr+easylist.txt
HTMLFilterList-Enabled-44=false
HTMLFilterListLocalFilename-44=adblockfilter44.txt
HTMLFilterListName-44=Liste FR
HTMLFilterListURL-44=https://easylist-downloads.adblockplus.org/liste_fr.txt
HTMLFilterList-Enabled-45=false
HTMLFilterListLocalFilename-45=adblockfilter45.txt
HTMLFilterListName-45=ROList+EasyList
HTMLFilterListURL-45=https://easylist-downloads.adblockplus.org/rolist+easylist.txt
HTMLFilterList-Enabled-46=false
HTMLFilterListLocalFilename-46=adblockfilter46.txt
HTMLFilterListName-46=ROList
HTMLFilterListURL-46=http://www.zoso.ro/pages/rolist.txt
HTMLFilterList-Enabled-47=false
HTMLFilterListLocalFilename-47=adblockfilter47.txt
HTMLFilterListName-47=RuAdList+EasyList
HTMLFilterListURL-47=https://easylist-downloads.adblockplus.org/ruadlist+easylist.txt
HTMLFilterList-Enabled-48=false
HTMLFilterListLocalFilename-48=adblockfilter48.txt
HTMLFilterListName-48=RU AdList
HTMLFilterListURL-48=https://easylist-downloads.adblockplus.org/advblock.txt
HTMLFilterList-Enabled-49=false
HTMLFilterListLocalFilename-49=adblockfilter49.txt
HTMLFilterListName-49=void.gr
HTMLFilterListURL-49=http://www.void.gr/kargig/void-gr-filters.txt

View file

@ -1,4 +0,0 @@
/tests export-ignore
/scripts export-ignore
.gitattributes export-ignore
.gitignore export-ignore

View file

@ -1,5 +0,0 @@
project(kwebkitpart)
add_subdirectory(icons)
add_subdirectory(src)
# add_subdirectory(kdelauncher)

View file

@ -1,486 +0,0 @@
NOTE! The LGPL below is copyrighted by the Free Software Foundation, but
the instance of code that it refers to (the kde libraries) are copyrighted
by the authors who actually wrote it.
---------------------------------------------------------------------------
GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301, USA.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -1,4 +0,0 @@
#! /usr/bin/env bash
$EXTRACTRC `find . -name '*.rc' -or -name '*.ui'` >> rc.cpp || exit 11
$XGETTEXT `find . -name '*.cpp'` -o $podir/kwebkitpart.pot
rm -f rc.cpp

View file

@ -1,40 +0,0 @@
KWebKitPart
===========
KWebKitPart is a KDE component (KPart) wrapper for QtWebKit. It is intended to
allow KPart based KDE applications such as Konqueror to use it in place of other
browser engine, such as KHTML, to browse the web in Konqueror.
Known limitations and unimplemented features are listed in the following
documents:
* https://projects.kde.org/projects/kde/kdelibs/repository/revisions/master/entry/kdewebkit/ISSUES
* https://projects.kde.org/projects/extragear/base/kwebkitpart/repository/revisions/master/entry/TODO
Please report any issues to: https://bugs.kde.org
IMPORTANT NOTE: Do not select "konqueror" as product, but "kwebkitpart"!
There is also a public mailing list available for support:
webkit-devel @ kde.org
How to use KWebKitPart in Konqueror
===================================
You can switch between the different rendering engines:
View -> View Mode -> {KHTML, WebKit} (website needs to be open)
If WebKit does not show up in Konqueror, run 'kbuildsycoca4' and
restart Konqueror. Note that this change does not persist. If you
press the reload button or open a new website, it will fall back
to the default rendering engine.
If you want to set KWebKitPart as default for any website, run:
'keditfiletype text/html'
and move "WebKit (kwebkitpart)" in the "Embedding" tab to the top.
In KDE 4.6 and higher you can choose the default rendering engine
in Konqueror's configuration dialog under the "General" section.
For more information about this project please see also:
http://techbase.kde.org/Projects/WebKit

View file

@ -1,23 +0,0 @@
* Proper support for KWebKitPart in the following Konqueror plugins:
- adblock This plugin's GUI needs to be changed to use the KPart plugin
extensions so that it is not khtml specific. Other than that
kwebkitpart supports the ad filtering functionalities supported
by khtml.
* Add KPartStatusBarExtension support for the following plugins/features:
- Popup blocker (non-plugin)
* Implement some means of showing information about the webkit rendering engine:
- KWebKitPart's version #
- QtWebKit's version #
- UserAgent string ???
* Look through all of Konqueror's web configuration options and make sure we
honor all those we possibly can. Here is a non-complete list of features
that are either partially implemented or not implemented at all:
- Change cursor over links (TODO, QtWebKit ???).
- Smooth scrolling support (TODO, QtWebKit ???).
- Underline links support (Partial, does not work as intended).
- Enable access key navigation with Ctrl key (TODO, QtWebKit ???).
- Animations (TODO, QtWebKit ???).
- Draw frames around not completely loaded images (TODO, QtWebKit ???).

View file

@ -1 +0,0 @@
kde4_install_icons(${ICON_INSTALL_DIR})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 759 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

View file

@ -1,21 +0,0 @@
project(kdelauncher)
find_package(KDE4 REQUIRED)
include(KDE4Defaults)
include_directories(
${KDE4_INCLUDES}
${KDE4_KDECORE_INCLUDES}
${KDE4_KDEUI_INCLUDES}
${KDE4_KIO_INCLUDES}
)
add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS})
add_executable(kdelauncher main.cpp)
target_link_libraries(kdelauncher
${KDE4_KDECORE_LIBS}
${KDE4_KDEUI_LIBS}
${KDE4_KIO_LIBS}
${KDE4_KDEWEBKIT_LIBS}
)

View file

@ -1,426 +0,0 @@
/*
* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2006 George Staikos <staikos@kde.org>
* Copyright (C) 2006 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006 Simon Hausmann <hausmann@kde.org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <kwebview.h>
#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KIO/AccessManager>
#include <KUriFilter>
#include <KInputDialog>
#include <KLineEdit>
#include <QUiLoader>
#include <QWebPage>
#include <QWebView>
#include <QWebFrame>
#include <QWebSettings>
#include <QWebElement>
#include <QWebElementCollection>
#if !defined(QT_NO_PRINTER)
#include <QPrintPreviewDialog>
#endif
#include <QAction>
#include <QCompleter>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QProgressBar>
#include <QStatusBar>
#include <QStringListModel>
#include <QToolBar>
#include <QToolTip>
#include <QDir>
#include <QFile>
#include <QVector>
#include <QTextStream>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(const QString& url = QString()): currentZoom(100) {
view = new KWebView(this);
setCentralWidget(view);
connect(view, SIGNAL(loadFinished(bool)),
this, SLOT(loadFinished()));
connect(view, SIGNAL(titleChanged(QString)),
this, SLOT(setWindowTitle(QString)));
connect(view->page(), SIGNAL(linkHovered(QString,QString,QString)),
this, SLOT(showLinkHover(QString,QString)));
connect(view->page(), SIGNAL(windowCloseRequested()), this, SLOT(deleteLater()));
setupUI();
QUrl qurl(KUriFilter::self()->filteredUri(url, QStringList() << "kshorturifilter"));
if (qurl.isValid()) {
urlEdit->setText(qurl.toEncoded());
view->load(qurl);
// the zoom values are chosen to be like in Mozilla Firefox 3
zoomLevels << 30 << 50 << 67 << 80 << 90;
zoomLevels << 100;
zoomLevels << 110 << 120 << 133 << 150 << 170 << 200 << 240 << 300;
}
}
QWebPage* webPage() const {
return view->page();
}
QWebView* webView() const {
return view;
}
protected slots:
void changeLocation() {
QUrl url (KUriFilter::self()->filteredUri(urlEdit->text(), QStringList() << "kshorturifilter"));
view->load(url);
view->setFocus(Qt::OtherFocusReason);
}
void loadFinished() {
urlEdit->setText(view->url().toString());
QUrl::FormattingOptions opts;
opts |= QUrl::RemoveScheme;
opts |= QUrl::RemoveUserInfo;
opts |= QUrl::StripTrailingSlash;
QString s = view->url().toString(opts);
s = s.mid(2);
if (s.isEmpty())
return;
if (!urlList.contains(s))
urlList += s;
urlModel.setStringList(urlList);
}
void showLinkHover(const QString &link, const QString &toolTip) {
statusBar()->showMessage(link);
#ifndef QT_NO_TOOLTIP
if (!toolTip.isEmpty())
QToolTip::showText(QCursor::pos(), toolTip);
#endif
}
void zoomIn() {
int i = zoomLevels.indexOf(currentZoom);
Q_ASSERT(i >= 0);
if (i < zoomLevels.count() - 1)
currentZoom = zoomLevels[i + 1];
view->setZoomFactor(qreal(currentZoom)/100.0);
}
void zoomOut() {
int i = zoomLevels.indexOf(currentZoom);
Q_ASSERT(i >= 0);
if (i > 0)
currentZoom = zoomLevels[i - 1];
view->setZoomFactor(qreal(currentZoom)/100.0);
}
void resetZoom()
{
currentZoom = 100;
view->setZoomFactor(1.0);
}
void toggleZoomTextOnly(bool b)
{
view->page()->settings()->setAttribute(QWebSettings::ZoomTextOnly, b);
}
void print() {
#ifndef QT_NO_PRINTER
QScopedPointer<QPrintPreviewDialog> dlg (new QPrintPreviewDialog(this));
connect(dlg.data(), SIGNAL(paintRequested(QPrinter*)),
view, SLOT(print(QPrinter*)));
dlg->exec();
#endif
}
void setEditable(bool on) {
view->page()->setContentEditable(on);
formatMenuAction->setVisible(on);
}
void dumpHtml() {
kDebug() << "HTML: " << view->page()->mainFrame()->toHtml();
}
void selectElements() {
bool ok;
QString str = KInputDialog::getText(i18nc("input dialog window title for selecting html elements", "Select elements"),
i18nc("input dialog text for selecting html elements", "Choose elements"),
QLatin1String("a"), &ok, this);
if (ok && !str.isEmpty()) {
QWebElementCollection collection = view->page()->mainFrame()->findAllElements(str);
const int count = collection.count();
for (int i=0; i < count; i++)
collection.at(i).setStyleProperty("background-color", "yellow");
statusBar()->showMessage(i18np("%1 element selected", "%1 elements selected", count), 5000);
}
}
public slots:
void newWindow(const QString &url = QString()) {
MainWindow *mw = new MainWindow(url);
mw->show();
}
private:
QVector<int> zoomLevels;
int currentZoom;
// create the status bar, tool bar & menu
void setupUI() {
progress = new QProgressBar(this);
progress->setRange(0, 100);
progress->setMinimumSize(100, 20);
progress->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
progress->hide();
statusBar()->addPermanentWidget(progress);
connect(view, SIGNAL(loadProgress(int)), progress, SLOT(show()));
connect(view, SIGNAL(loadProgress(int)), progress, SLOT(setValue(int)));
connect(view, SIGNAL(loadFinished(bool)), progress, SLOT(hide()));
urlEdit = new KLineEdit(this);
urlEdit->setSizePolicy(QSizePolicy::Expanding, urlEdit->sizePolicy().verticalPolicy());
connect(urlEdit, SIGNAL(returnPressed()),
SLOT(changeLocation()));
QCompleter *completer = new QCompleter(this);
urlEdit->setCompleter(completer);
completer->setModel(&urlModel);
QToolBar *bar = addToolBar("Navigation");
bar->addAction(view->pageAction(QWebPage::Back));
bar->addAction(view->pageAction(QWebPage::Forward));
bar->addAction(view->pageAction(QWebPage::Reload));
bar->addAction(view->pageAction(QWebPage::Stop));
bar->addWidget(urlEdit);
QMenu *fileMenu = menuBar()->addMenu(i18n("&File"));
QAction *newWindow = fileMenu->addAction(i18n("New Window"), this, SLOT(newWindow()));
fileMenu->addAction(i18n("Print"), this, SLOT(print()));
fileMenu->addAction(i18n("Close"), this, SLOT(close()));
QMenu *editMenu = menuBar()->addMenu(i18n("&Edit"));
editMenu->addAction(view->pageAction(QWebPage::Undo));
editMenu->addAction(view->pageAction(QWebPage::Redo));
editMenu->addSeparator();
editMenu->addAction(view->pageAction(QWebPage::Cut));
editMenu->addAction(view->pageAction(QWebPage::Copy));
editMenu->addAction(view->pageAction(QWebPage::Paste));
editMenu->addSeparator();
QAction *setEditable = editMenu->addAction(i18n("Set Editable"), this, SLOT(setEditable(bool)));
setEditable->setCheckable(true);
QMenu *viewMenu = menuBar()->addMenu(i18n("&View"));
viewMenu->addAction(view->pageAction(QWebPage::Stop));
viewMenu->addAction(view->pageAction(QWebPage::Reload));
viewMenu->addSeparator();
QAction *zoomIn = viewMenu->addAction(i18n("Zoom &In"), this, SLOT(zoomIn()));
QAction *zoomOut = viewMenu->addAction(i18n("Zoom &Out"), this, SLOT(zoomOut()));
QAction *resetZoom = viewMenu->addAction(i18n("Reset Zoom"), this, SLOT(resetZoom()));
QAction *zoomTextOnly = viewMenu->addAction(i18n("Zoom Text Only"), this, SLOT(toggleZoomTextOnly(bool)));
zoomTextOnly->setCheckable(true);
zoomTextOnly->setChecked(false);
viewMenu->addSeparator();
viewMenu->addAction(i18n("Dump HTML"), this, SLOT(dumpHtml()));
QMenu *formatMenu = new QMenu(i18n("F&ormat"));
formatMenuAction = menuBar()->addMenu(formatMenu);
formatMenuAction->setVisible(false);
formatMenu->addAction(view->pageAction(QWebPage::ToggleBold));
formatMenu->addAction(view->pageAction(QWebPage::ToggleItalic));
formatMenu->addAction(view->pageAction(QWebPage::ToggleUnderline));
QMenu *writingMenu = formatMenu->addMenu(i18n("Writing Direction"));
writingMenu->addAction(view->pageAction(QWebPage::SetTextDirectionDefault));
writingMenu->addAction(view->pageAction(QWebPage::SetTextDirectionLeftToRight));
writingMenu->addAction(view->pageAction(QWebPage::SetTextDirectionRightToLeft));
newWindow->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N));
view->pageAction(QWebPage::Back)->setShortcut(QKeySequence::Back);
view->pageAction(QWebPage::Stop)->setShortcut(Qt::Key_Escape);
view->pageAction(QWebPage::Forward)->setShortcut(QKeySequence::Forward);
view->pageAction(QWebPage::Reload)->setShortcut(QKeySequence::Refresh);
view->pageAction(QWebPage::Undo)->setShortcut(QKeySequence::Undo);
view->pageAction(QWebPage::Redo)->setShortcut(QKeySequence::Redo);
view->pageAction(QWebPage::Cut)->setShortcut(QKeySequence::Cut);
view->pageAction(QWebPage::Copy)->setShortcut(QKeySequence::Copy);
view->pageAction(QWebPage::Paste)->setShortcut(QKeySequence::Paste);
zoomIn->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Plus));
zoomOut->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Minus));
resetZoom->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0));
view->pageAction(QWebPage::ToggleBold)->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_B));
view->pageAction(QWebPage::ToggleItalic)->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_I));
view->pageAction(QWebPage::ToggleUnderline)->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_U));
QMenu *toolsMenu = menuBar()->addMenu(i18n("&Tools"));
toolsMenu->addAction(i18n("Select elements..."), this, SLOT(selectElements()));
}
QWebView *view;
KLineEdit *urlEdit;
QProgressBar *progress;
QAction *formatMenuAction;
QStringList urlList;
QStringListModel urlModel;
};
class URLLoader : public QObject
{
Q_OBJECT
public:
URLLoader(QWebView* view, const QString& inputFileName)
: m_view(view)
, m_stdOut(stdout)
{
init(inputFileName);
}
public slots:
void loadNext()
{
QString qstr;
if (getUrl(qstr)) {
QUrl url(qstr, QUrl::StrictMode);
if (url.isValid()) {
m_stdOut << "Loading " << qstr << " ......" << endl;
m_view->load(url);
} else
loadNext();
} else
disconnect(m_view, 0, this, 0);
}
private:
void init(const QString& inputFileName)
{
QFile inputFile(inputFileName);
if (inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&inputFile);
QString line;
while (true) {
line = stream.readLine();
if (line.isNull())
break;
m_urls.append(line);
}
} else {
kDebug() << "Can't open list file";
exit(0);
}
m_index = 0;
inputFile.close();
}
bool getUrl(QString& qstr)
{
if (m_index == m_urls.size())
return false;
qstr = m_urls[m_index++];
return true;
}
private:
QVector<QString> m_urls;
int m_index;
QWebView* m_view;
QTextStream m_stdOut;
};
int main(int argc, char **argv)
{
KAboutData about("KDELauncher", 0, ki18n("KDELauncher"), "0.0000013");
KCmdLineArgs::init(argc, argv, &about);
KApplication app;
QString url = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html"));
QWebSettings::setMaximumPagesInCache(4);
QWebSettings::setObjectCacheCapacities((16*1024*1024) / 8, (16*1024*1024) / 8, 16*1024*1024);
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
const QStringList args = app.arguments();
if (args.contains(QLatin1String("-r"))) {
// robotized
QString listFile = args.at(2);
if (!(args.count() == 3) && QFile::exists(listFile)) {
kDebug() << "Usage: KDELauncher -r listfile";
exit(0);
}
MainWindow window;
QWebView *view = window.webView();
URLLoader loader(view, listFile);
QObject::connect(view, SIGNAL(loadFinished(bool)), &loader, SLOT(loadNext()));
loader.loadNext();
window.show();
return app.exec();
} else {
if (args.count() > 1)
url = args.at(1);
MainWindow window(url);
// Opens every given urls in new windows
for (int i = 2; i < args.count(); i++)
window.newWindow(args.at(i));
window.show();
return app.exec();
}
}
#include "main.moc"

View file

@ -1,54 +0,0 @@
include_directories(
${KDE4_INCLUDES}
${KDE4_KDECORE_INCLUDES}
${KDE4_KDEUI_INCLUDES}
${KDE4_KIO_INCLUDES}
${CMAKE_SOURCE_DIR}/kdewebkit
${CMAKE_SOURCE_DIR}/kutils
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}/kdewebkit
)
set(kwebkit_LIB_SRCS
kwebkitpart.cpp
kwebkitpart_ext.cpp
kwebkitpartfactory.cpp
webview.cpp
webpage.cpp
websslinfo.cpp
webhistoryinterface.cpp
networkaccessmanager.cpp
webpluginfactory.cpp
settings/webkitsettings.cpp
settings/webkit_filter.cpp
ui/searchbar.cpp
ui/passwordbar.cpp
)
########################### kwebkitpart #############################
kde4_add_plugin(kwebkitpart ${kwebkit_LIB_SRCS})
target_link_libraries(kwebkitpart
${KDE4_KPARTS_LIBS}
${KDE4_KDEWEBKIT_LIBS}
${QT_QTWEBKIT_LIBRARY}
${QT_QTUITOOLS_LIBRARY}
)
########################### kwebkitpart #############################
install(TARGETS kwebkitpart DESTINATION ${PLUGIN_INSTALL_DIR})
install(
FILES
kwebkitpart.desktop
DESTINATION ${SERVICES_INSTALL_DIR}
)
install(
FILES
error.html
kwebkitpart.rc
DESTINATION ${DATA_INSTALL_DIR}/kwebkitpart
)

View file

@ -1,54 +0,0 @@
<html>
<head>
<title>TITLE</title>
<style>
body {
padding: 3em 0em;
background: #eeeeee;
color: black;
}
img {
float: left;
}
#box {
background: white;
border: 1px solid lightgray;
max-width: 600px;
min-width: 300px;
padding: 60px;
margin: auto;
}
h1 {
font-size: 130%;
font-weight: bold;
border-bottom: 1px solid lightgray;
margin-left: 96px;
}
h2 {
font-size: 100%;
font-weight: normal;
border-bottom: 1px solid lightgray;
margin-left: 96px;
margin-bottom: 15px;
}
h3 {
font-size: 90%;
font-weight: bold;
}
ul {
font-size: 80%;
padding-left: 48px;
margin: 0;
}
p {
font-size: 80%;
}
</style>
</head>
<body dir="DIRECTION">
<div id="box">
<img alt="warning icon" src="ICON_PATH"/>
TEXT
</div>
</body>
</html>

View file

@ -1,947 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 - 2010 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "kwebkitpart.h"
#include "kwebkitpart_ext.h"
#include "sslinfodialog_p.h"
#include "webview.h"
#include "webpage.h"
#include "websslinfo.h"
#include "webhistoryinterface.h"
#include "ui/searchbar.h"
#include "ui/passwordbar.h"
#include "settings/webkitsettings.h"
#include <kdeversion.h>
#include <kcodecaction.h>
#include <kio/global.h>
#include <kactioncollection.h>
#include <kaboutdata.h>
#include <kcomponentdata.h>
#include <kdebug.h>
#include <kurllabel.h>
#include <kmessagebox.h>
#include <kstringhandler.h>
#include <kmenu.h>
#include <kwebwallet.h>
#include <ktoolinvocation.h>
#include <kacceleratormanager.h>
#include <kstatusbar.h>
#include <kfileitem.h>
#include <kmessagewidget.h>
#include <kprotocolinfo.h>
#include <kparts/statusbarextension.h>
#include <QTextCodec>
#include <QDBusInterface>
#include <QWebElement>
#include <QWebHistory>
K_GLOBAL_STATIC_WITH_ARGS(QUrl, globalBlankUrl, ("about:blank"))
static inline int convertStr2Int(const QString& value)
{
bool ok;
const int tempValue = value.toInt(&ok);
if (ok)
return tempValue;
return 0;
}
KWebKitPart::KWebKitPart(QWidget *parentWidget, QObject *parent,
const QByteArray& cachedHistory, const QStringList& /*args*/)
:KParts::ReadOnlyPart(parent),
m_emitOpenUrlNotify(true),
m_hasCachedFormData(false),
m_doLoadFinishedActions(false),
m_statusBarWalletLabel(0),
m_searchBar(0),
m_passwordBar(0)
{
KAboutData about = KAboutData("kwebkitpart", 0,
ki18nc("Program Name", "KWebKitPart"),
/*version*/ "1.3.0",
ki18nc("Short Description", "QtWebKit Browser Engine Component"),
KAboutData::License_LGPL,
ki18n("(C) 2009-2010 Dawit Alemayehu\n"
"(C) 2008-2010 Urs Wolfer\n"
"(C) 2007 Trolltech ASA"));
about.addAuthor(ki18n("Dawit Alemayehu"), ki18n("Maintainer, Developer"), "adawit@kde.org");
about.addAuthor(ki18n("Urs Wolfer"), ki18n("Maintainer, Developer"), "uwolfer@kde.org");
about.addAuthor(ki18n("Michael Howell"), ki18n("Developer"), "mhowell123@gmail.com");
about.addAuthor(ki18n("Laurent Montel"), ki18n("Developer"), "montel@kde.org");
about.addAuthor(ki18n("Dirk Mueller"), ki18n("Developer"), "mueller@kde.org");
KComponentData componentData(&about);
setComponentData(componentData, false /*don't load plugins yet*/);
// NOTE: If the application does not set its version number, we automatically
// set it to KDE's version number so that the default user-agent string contains
// proper application version number information. See QWebPage::userAgentForUrl...
if (QCoreApplication::applicationVersion().isEmpty())
QCoreApplication::setApplicationVersion(QString("%1.%2.%3")
.arg(KDE::versionMajor())
.arg(KDE::versionMinor())
.arg(KDE::versionRelease()));
setXMLFile(QLatin1String("kwebkitpart.rc"));
// Create this KPart's widget
QWidget *mainWidget = new QWidget (parentWidget);
mainWidget->setObjectName("kwebkitpart");
// Create the WebView...
m_webView = new WebView (this, parentWidget);
// Create the browser extension.
m_browserExtension = new WebKitBrowserExtension(this, cachedHistory);
// Add status bar extension...
m_statusBarExtension = new KParts::StatusBarExtension(this);
// Add a web history interface for storing visited links.
if (!QWebHistoryInterface::defaultInterface())
QWebHistoryInterface::setDefaultInterface(new WebHistoryInterface(this));
// Add text and html extensions...
new KWebKitTextExtension(this);
new KWebKitHtmlExtension(this);
new KWebKitScriptableExtension(this);
// Layout the GUI...
QVBoxLayout* l = new QVBoxLayout(mainWidget);
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addWidget(m_webView);
mainWidget->setLayout(l);
// Set the part's widget
setWidget(mainWidget);
// Set the web view as the the focus object
mainWidget->setFocusProxy(m_webView);
// Connect the signals from the webview
connect(m_webView, SIGNAL(titleChanged(QString)),
this, SIGNAL(setWindowCaption(QString)));
connect(m_webView, SIGNAL(urlChanged(QUrl)),
this, SLOT(slotUrlChanged(QUrl)));
connect(m_webView, SIGNAL(linkMiddleOrCtrlClicked(KUrl)),
this, SLOT(slotLinkMiddleOrCtrlClicked(KUrl)));
connect(m_webView, SIGNAL(selectionClipboardUrlPasted(KUrl,QString)),
this, SLOT(slotSelectionClipboardUrlPasted(KUrl,QString)));
connect(m_webView, SIGNAL(loadFinished(bool)),
this, SLOT(slotLoadFinished(bool)));
// Connect the signals from the page...
connectWebPageSignals(page());
// Init the QAction we are going to use...
initActions();
// Load plugins once we are fully ready
loadPlugins();
}
KWebKitPart::~KWebKitPart()
{
}
WebPage* KWebKitPart::page()
{
if (m_webView)
return qobject_cast<WebPage*>(m_webView->page());
return 0;
}
void KWebKitPart::initActions()
{
KAction *action = actionCollection()->addAction(KStandardAction::SaveAs, "saveDocument",
m_browserExtension, SLOT(slotSaveDocument()));
action = new KAction(i18n("Save &Frame As..."), this);
actionCollection()->addAction("saveFrame", action);
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(slotSaveFrame()));
action = new KAction(KIcon("document-print-preview"), i18n("Print Preview"), this);
actionCollection()->addAction("printPreview", action);
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(slotPrintPreview()));
action = new KAction(KIcon("zoom-in"), i18nc("zoom in action", "Zoom In"), this);
actionCollection()->addAction("zoomIn", action);
action->setShortcut(KShortcut("CTRL++; CTRL+="));
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(zoomIn()));
action = new KAction(KIcon("zoom-out"), i18nc("zoom out action", "Zoom Out"), this);
actionCollection()->addAction("zoomOut", action);
action->setShortcut(KShortcut("CTRL+-; CTRL+_"));
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(zoomOut()));
action = new KAction(KIcon("zoom-original"), i18nc("reset zoom action", "Actual Size"), this);
actionCollection()->addAction("zoomNormal", action);
action->setShortcut(KShortcut("CTRL+0"));
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(zoomNormal()));
action = new KAction(i18n("Zoom Text Only"), this);
action->setCheckable(true);
KConfigGroup cgHtml(KGlobal::config(), "HTML Settings");
bool zoomTextOnly = cgHtml.readEntry("ZoomTextOnly", false);
action->setChecked(zoomTextOnly);
actionCollection()->addAction("zoomTextOnly", action);
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(toogleZoomTextOnly()));
action = actionCollection()->addAction(KStandardAction::SelectAll, "selectAll",
m_browserExtension, SLOT(slotSelectAll()));
action->setShortcutContext(Qt::WidgetShortcut);
m_webView->addAction(action);
KCodecAction *codecAction = new KCodecAction( KIcon("character-set"), i18n( "Set &Encoding" ), this, true );
actionCollection()->addAction( "setEncoding", codecAction );
connect(codecAction, SIGNAL(triggered(QTextCodec*)), SLOT(slotSetTextEncoding(QTextCodec*)));
action = new KAction(i18n("View Do&cument Source"), this);
actionCollection()->addAction("viewDocumentSource", action);
action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
connect(action, SIGNAL(triggered(bool)), m_browserExtension, SLOT(slotViewDocumentSource()));
action = new KAction(i18nc("Secure Sockets Layer", "SSL"), this);
actionCollection()->addAction("security", action);
connect(action, SIGNAL(triggered(bool)), SLOT(slotShowSecurity()));
action = actionCollection()->addAction(KStandardAction::Find, "find", this, SLOT(slotShowSearchBar()));
action->setWhatsThis(i18nc("find action \"whats this\" text", "<h3>Find text</h3>"
"Shows a dialog that allows you to find text on the displayed page."));
}
void KWebKitPart::updateActions()
{
m_browserExtension->updateActions();
QAction* action = actionCollection()->action(QLatin1String("saveDocument"));
if (action) {
const QString protocol (url().protocol());
action->setEnabled(protocol != QLatin1String("about") && protocol != QLatin1String("error"));
}
action = actionCollection()->action(QLatin1String("printPreview"));
if (action) {
action->setEnabled(m_browserExtension->isActionEnabled("print"));
}
action = actionCollection()->action(QLatin1String("saveFrame"));
if (action) {
action->setEnabled((view()->page()->currentFrame() != view()->page()->mainFrame()));
}
}
void KWebKitPart::connectWebPageSignals(WebPage* page)
{
if (!page)
return;
connect(page, SIGNAL(loadStarted()),
this, SLOT(slotLoadStarted()));
connect(page, SIGNAL(loadAborted(KUrl)),
this, SLOT(slotLoadAborted(KUrl)));
connect(page, SIGNAL(linkHovered(QString,QString,QString)),
this, SLOT(slotLinkHovered(QString,QString,QString)));
connect(page, SIGNAL(saveFrameStateRequested(QWebFrame*,QWebHistoryItem*)),
this, SLOT(slotSaveFrameState(QWebFrame*,QWebHistoryItem*)));
connect(page, SIGNAL(restoreFrameStateRequested(QWebFrame*)),
this, SLOT(slotRestoreFrameState(QWebFrame*)));
connect(page, SIGNAL(statusBarMessage(QString)),
this, SLOT(slotSetStatusBarText(QString)));
connect(page, SIGNAL(windowCloseRequested()),
this, SLOT(slotWindowCloseRequested()));
connect(page, SIGNAL(printRequested(QWebFrame*)),
m_browserExtension, SLOT(slotPrintRequested(QWebFrame*)));
connect(page, SIGNAL(frameCreated(QWebFrame*)),
this, SLOT(slotFrameCreated(QWebFrame*)));
connect(m_webView, SIGNAL(linkShiftClicked(KUrl)),
page, SLOT(downloadUrl(KUrl)));
connect(page, SIGNAL(loadProgress(int)),
m_browserExtension, SIGNAL(loadingProgress(int)));
connect(page, SIGNAL(selectionChanged()),
m_browserExtension, SLOT(updateEditActions()));
connect(m_browserExtension, SIGNAL(saveUrl(KUrl)),
page, SLOT(downloadUrl(KUrl)));
connect(page->mainFrame(), SIGNAL(loadFinished(bool)),
this, SLOT(slotMainFrameLoadFinished(bool)));
KWebWallet *wallet = page->wallet();
if (wallet) {
connect(wallet, SIGNAL(saveFormDataRequested(QString,QUrl)),
this, SLOT(slotSaveFormDataRequested(QString,QUrl)));
connect(wallet, SIGNAL(fillFormRequestCompleted(bool)),
this, SLOT(slotFillFormRequestCompleted(bool)));
connect(wallet, SIGNAL(walletClosed()), this, SLOT(slotWalletClosed()));
}
}
bool KWebKitPart::openUrl(const KUrl &_u)
{
KUrl u (_u);
kDebug() << u;
// Ignore empty requests...
if (u.isEmpty())
return false;
// If the URL given is a supported local protocol, e.g. "bookmark" but lacks
// a path component, we set the path to "/" here so that the security context
// will properly allow access to local resources.
if (u.host().isEmpty() && u.path().isEmpty()
&& KProtocolInfo::protocolClass(u.protocol()) == QLatin1String(":local")) {
u.setPath(QLatin1String("/"));
}
// Do not emit update history when url is typed in since the embedding part
// should handle that automatically itself. At least Konqueror does that.
m_emitOpenUrlNotify = false;
// Pointer to the page object...
WebPage* p = page();
Q_ASSERT(p);
// Handle error conditions...
if (u.protocol().compare(QLatin1String("error"), Qt::CaseInsensitive) == 0 && u.hasSubUrl()) {
/**
* The format of the error url is that two variables are passed in the query:
* error = int kio error code, errText = QString error text from kio
* and the URL where the error happened is passed as a sub URL.
*/
KUrl::List urls = KUrl::split(u);
if ( urls.count() > 1 ) {
KUrl mainURL = urls.first();
int error = convertStr2Int(mainURL.queryItem("error"));
// error=0 isn't a valid error code, so 0 means it's missing from the URL
if ( error == 0 )
error = KIO::ERR_UNKNOWN;
const QString errorText = mainURL.queryItem( "errText" );
urls.pop_front();
KUrl reqUrl = KUrl::join( urls );
emit m_browserExtension->setLocationBarUrl(reqUrl.prettyUrl());
if (p) {
m_webView->setHtml(p->errorPage(error, errorText, reqUrl));
return true;
}
}
return false;
}
KParts::BrowserArguments bargs (m_browserExtension->browserArguments());
KParts::OpenUrlArguments args (arguments());
if (u != *globalBlankUrl) {
// Get the SSL information sent, if any...
if (args.metaData().contains(QLatin1String("ssl_in_use"))) {
WebSslInfo sslInfo;
sslInfo.restoreFrom(KIO::MetaData(args.metaData()).toVariant());
sslInfo.setUrl(u);
p->setSslInfo(sslInfo);
}
}
// Set URL in KParts before emitting started; konq plugins rely on that.
setUrl(u);
m_doLoadFinishedActions = true;
m_webView->loadUrl(u, args, bargs);
return true;
}
bool KWebKitPart::closeUrl()
{
m_webView->triggerPageAction(QWebPage::StopScheduledPageRefresh);
m_webView->stop();
return true;
}
QWebView* KWebKitPart::view()
{
return m_webView;
}
bool KWebKitPart::isModified() const
{
return m_webView->isModified();
}
void KWebKitPart::guiActivateEvent(KParts::GUIActivateEvent *event)
{
if (event && event->activated() && m_webView) {
emit setWindowCaption(m_webView->title());
}
}
bool KWebKitPart::openFile()
{
// never reached
return false;
}
/// slots...
void KWebKitPart::slotLoadStarted()
{
emit started(0);
updateActions();
}
void KWebKitPart::slotFrameLoadFinished(bool ok)
{
QWebFrame* frame = (sender() ? qobject_cast<QWebFrame*>(sender()) : page()->mainFrame());
if (ok) {
const QUrl currentUrl (frame->baseUrl().resolved(frame->url()));
// kDebug() << "mainframe:" << m_webView->page()->mainFrame() << "frame:" << sender();
// kDebug() << "url:" << frame->url() << "base url:" << frame->baseUrl() << "request url:" << frame->requestedUrl();
if (currentUrl != *globalBlankUrl) {
m_hasCachedFormData = false;
if (WebKitSettings::self()->isNonPasswordStorableSite(currentUrl.host())) {
addWalletStatusBarIcon();
} else {
// Attempt to fill the web form...
KWebWallet *webWallet = page() ? page()->wallet() : 0;
if (webWallet) {
webWallet->fillFormData(frame, false);
}
}
}
}
}
void KWebKitPart::slotMainFrameLoadFinished (bool ok)
{
if (!ok || !m_doLoadFinishedActions)
return;
m_doLoadFinishedActions = false;
if (!m_emitOpenUrlNotify) {
m_emitOpenUrlNotify = true; // Save history once page loading is done.
}
// If the document contains no <title> tag, then set it to the current url.
if (m_webView->title().trimmed().isEmpty()) {
// If the document title is empty, then set it to the current url
const QUrl url (m_webView->url());
const QString caption (url.toString((QUrl::RemoveQuery|QUrl::RemoveFragment)));
emit setWindowCaption(caption);
// The urlChanged signal is emitted if and only if the main frame
// receives the title of the page so we manually invoke the slot as a
// work around here for pages that do not contain it, such as text
// documents...
slotUrlChanged(url);
}
QWebFrame* frame = page()->mainFrame();
if (!frame || frame->url() == *globalBlankUrl)
return;
// Set the favicon specified through the <link> tag...
if (WebKitSettings::self()->favIconsEnabled()
&& !frame->page()->settings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
const QWebElement element = frame->findFirstElement(QLatin1String("head>link[rel=icon], "
"head>link[rel=\"shortcut icon\"]"));
KUrl shortcutIconUrl;
if (element.isNull()) {
shortcutIconUrl = frame->baseUrl();
QString urlPath = shortcutIconUrl.path();
const int index = urlPath.indexOf(QLatin1Char('/'));
if (index > -1)
urlPath.truncate(index);
urlPath += QLatin1String("/favicon.ico");
shortcutIconUrl.setPath(urlPath);
} else {
shortcutIconUrl = KUrl (frame->baseUrl(), element.attribute("href"));
}
//kDebug() << "setting favicon to" << shortcutIconUrl;
m_browserExtension->setIconUrl(shortcutIconUrl);
}
slotFrameLoadFinished(ok);
}
void KWebKitPart::slotLoadFinished(bool ok)
{
bool pending = false;
if (m_doLoadFinishedActions) {
updateActions();
QWebFrame* frame = (page() ? page()->currentFrame() : 0);
if (ok &&
frame == page()->mainFrame() &&
!frame->findFirstElement(QLatin1String("head>meta[http-equiv=refresh]")).isNull()) {
if (WebKitSettings::self()->autoPageRefresh()) {
pending = true;
} else {
frame->page()->triggerAction(QWebPage::StopScheduledPageRefresh);
}
}
}
emit completed ((ok && pending));
}
void KWebKitPart::slotLoadAborted(const KUrl & url)
{
closeUrl();
m_doLoadFinishedActions = false;
if (url.isValid())
emit m_browserExtension->openUrlRequest(url);
else
setUrl(m_webView->url());
}
void KWebKitPart::slotUrlChanged(const QUrl& url)
{
// Ignore if empty
if (url.isEmpty())
return;
// Ignore if error url
if (url.scheme().compare(QLatin1String("error"), Qt::CaseInsensitive) == 0)
return;
const KUrl u (url);
// Ignore if url has not changed!
if (this->url() == u)
return;
m_doLoadFinishedActions = true;
setUrl(u);
// Do not update the location bar with about:blank
if (url != *globalBlankUrl) {
//kDebug() << "Setting location bar to" << u.prettyUrl() << "current URL:" << this->url();
emit m_browserExtension->setLocationBarUrl(u.prettyUrl());
}
}
void KWebKitPart::slotShowSecurity()
{
if (!page())
return;
const WebSslInfo& sslInfo = page()->sslInfo();
if (!sslInfo.isValid()) {
KMessageBox::information(0, i18n("The SSL information for this site "
"appears to be corrupt."),
i18nc("Secure Sockets Layer", "SSL"));
return;
}
KSslInfoDialog *dlg = new KSslInfoDialog (widget());
dlg->setSslInfo(sslInfo.certificateChain(),
sslInfo.peerAddress().toString(),
url().host(),
sslInfo.protocol(),
sslInfo.ciphers(),
sslInfo.usedChiperBits(),
sslInfo.supportedChiperBits(),
KSslInfoDialog::errorsFromString(sslInfo.certificateErrors()));
dlg->open();
}
void KWebKitPart::slotSaveFrameState(QWebFrame *frame, QWebHistoryItem *item)
{
if (!frame || !item) {
return;
}
// Handle actions that apply only to the mainframe...
if (frame == view()->page()->mainFrame()) {
slotWalletClosed();
// If "NoEmitOpenUrlNotification" property is set to true, do not
// emit the open url notification. Property is set by this part's
// extension to prevent openUrl notification being sent when
// handling history navigation requests.
const bool doNotEmitOpenUrl = property("NoEmitOpenUrlNotification").toBool();
if (doNotEmitOpenUrl) {
setProperty("NoEmitOpenUrlNotification", QVariant());
}
// Only emit open url notify for the main frame. Do not
if (m_emitOpenUrlNotify && !doNotEmitOpenUrl) {
// kDebug() << "***** EMITTING openUrlNotify" << item->url();
emit m_browserExtension->openUrlNotify();
}
}
// For some reason, QtWebKit does not restore scroll position when
// QWebHistory is restored from persistent storage. Therefore, we
// preserve that information and restore it as needed. See
// slotRestoreFrameState.
const QPoint scrollPos (frame->scrollPosition());
if (!scrollPos.isNull()) {
// kDebug() << "Saving scroll position:" << scrollPos;
item->setUserData(scrollPos);
}
}
void KWebKitPart::slotRestoreFrameState(QWebFrame *frame)
{
if (!frame)
return;
QWebPage* page = (frame ? frame->page() : 0);
QWebHistory* history = (page ? page->history() : 0);
// No history item...
if (!history || history->count() < 1)
return;
QWebHistoryItem currentHistoryItem (history->currentItem());
// Update the scroll position if needed. See comment in slotSaveFrameState above.
if (frame->baseUrl().resolved(frame->url()) == currentHistoryItem.url()) {
const QPoint currentPos (frame->scrollPosition());
const QPoint desiredPos (currentHistoryItem.userData().toPoint());
if (currentPos.isNull() && !desiredPos.isNull()) {
frame->setScrollPosition(desiredPos);
}
}
}
void KWebKitPart::slotLinkHovered(const QString& _link, const QString& /*title*/, const QString& /*content*/)
{
QString message;
if (_link.isEmpty()) {
message = QLatin1String("");
emit m_browserExtension->mouseOverInfo(KFileItem());
} else {
QUrl linkUrl (_link);
const QString scheme = linkUrl.scheme();
// Protect the user against URL spoofing!
linkUrl.setUserName(QString());
const QString link (linkUrl.toString());
if (QString::compare(scheme, QLatin1String("mailto"), Qt::CaseInsensitive) == 0) {
message += i18nc("status bar text when hovering email links; looks like \"Email: xy@kde.org - CC: z@kde.org -BCC: x@kde.org - Subject: Hi translator\"", "Email: ");
// Workaround: for QUrl's parsing deficiencies of "mailto:foo@bar.com".
if (!linkUrl.hasQuery())
linkUrl = QUrl(scheme + '?' + linkUrl.path());
QMap<QString, QStringList> fields;
QList<QPair<QString, QString> > queryItems = linkUrl.queryItems();
const int count = queryItems.count();
for(int i = 0; i < count; ++i) {
const QPair<QString, QString> queryItem (queryItems.at(i));
//kDebug() << "query: " << queryItem.first << queryItem.second;
if (queryItem.first.contains(QLatin1Char('@')) && queryItem.second.isEmpty())
fields["to"] << queryItem.first;
if (QString::compare(queryItem.first, QLatin1String("to"), Qt::CaseInsensitive) == 0)
fields["to"] << queryItem.second;
if (QString::compare(queryItem.first, QLatin1String("cc"), Qt::CaseInsensitive) == 0)
fields["cc"] << queryItem.second;
if (QString::compare(queryItem.first, QLatin1String("bcc"), Qt::CaseInsensitive) == 0)
fields["bcc"] << queryItem.second;
if (QString::compare(queryItem.first, QLatin1String("subject"), Qt::CaseInsensitive) == 0)
fields["subject"] << queryItem.second;
}
if (fields.contains(QLatin1String("to")))
message += fields.value(QLatin1String("to")).join(QLatin1String(", "));
if (fields.contains(QLatin1String("cc")))
message += i18nc("status bar text when hovering email links; looks like \"Email: xy@kde.org - CC: z@kde.org -BCC: x@kde.org - Subject: Hi translator\"", " - CC: ") + fields.value(QLatin1String("cc")).join(QLatin1String(", "));
if (fields.contains(QLatin1String("bcc")))
message += i18nc("status bar text when hovering email links; looks like \"Email: xy@kde.org - CC: z@kde.org -BCC: x@kde.org - Subject: Hi translator\"", " - BCC: ") + fields.value(QLatin1String("bcc")).join(QLatin1String(", "));
if (fields.contains(QLatin1String("subject")))
message += i18nc("status bar text when hovering email links; looks like \"Email: xy@kde.org - CC: z@kde.org -BCC: x@kde.org - Subject: Hi translator\"", " - Subject: ") + fields.value(QLatin1String("subject")).join(QLatin1String(" "));
} else if (scheme == QLatin1String("javascript")) {
message = KStringHandler::rsqueeze(link, 150);
if (link.startsWith(QLatin1String("javascript:window.open")))
message += i18n(" (In new window)");
} else {
message = link;
QWebFrame* frame = page() ? page()->currentFrame() : 0;
if (frame) {
QWebHitTestResult result = frame->hitTestContent(page()->view()->mapFromGlobal(QCursor::pos()));
QWebFrame* target = result.linkTargetFrame();
if (frame->parentFrame() && target == frame->parentFrame()) {
message += i18n(" (In parent frame)");
} else if (!target || target != frame) {
message += i18n(" (In new window)");
}
}
KFileItem item (linkUrl, QString(), KFileItem::Unknown);
emit m_browserExtension->mouseOverInfo(item);
}
}
emit setStatusBarText(message);
}
void KWebKitPart::slotSearchForText(const QString &text, bool backward)
{
QWebPage::FindFlags flags = QWebPage::FindWrapsAroundDocument;
if (backward)
flags |= QWebPage::FindBackward;
if (m_searchBar->caseSensitive())
flags |= QWebPage::FindCaseSensitively;
if (m_searchBar->highlightMatches())
flags |= QWebPage::HighlightAllOccurrences;
//kDebug() << "search for text:" << text << ", backward ?" << backward;
m_searchBar->setFoundMatch(page()->findText(text, flags));
}
void KWebKitPart::slotShowSearchBar()
{
if (!m_searchBar) {
// Create the search bar...
m_searchBar = new SearchBar(widget());
connect(m_searchBar, SIGNAL(searchTextChanged(QString,bool)),
this, SLOT(slotSearchForText(QString,bool)));
actionCollection()->addAction(KStandardAction::FindNext, "findnext",
m_searchBar, SLOT(findNext()));
actionCollection()->addAction(KStandardAction::FindPrev, "findprev",
m_searchBar, SLOT(findPrevious()));
QBoxLayout* lay = qobject_cast<QBoxLayout*>(widget()->layout());
if (lay) {
lay->addWidget(m_searchBar);
}
}
const QString text = m_webView->selectedText();
m_searchBar->setSearchText(text.left(150));
}
void KWebKitPart::slotLinkMiddleOrCtrlClicked(const KUrl& linkUrl)
{
emit m_browserExtension->createNewWindow(linkUrl);
}
void KWebKitPart::slotSelectionClipboardUrlPasted(const KUrl& selectedUrl, const QString& searchText)
{
if (!WebKitSettings::self()->isOpenMiddleClickEnabled())
return;
if (!searchText.isEmpty() &&
KMessageBox::questionYesNo(m_webView,
i18n("<qt>Do you want to search for <b>%1</b>?</qt>", searchText),
i18n("Internet Search"), KGuiItem(i18n("&Search"), "edit-find"),
KStandardGuiItem::cancel(), "MiddleClickSearch") != KMessageBox::Yes)
return;
emit m_browserExtension->openUrlRequest(selectedUrl);
}
void KWebKitPart::slotWalletClosed()
{
if (!m_statusBarWalletLabel)
return;
m_statusBarExtension->removeStatusBarItem(m_statusBarWalletLabel);
delete m_statusBarWalletLabel;
m_statusBarWalletLabel = 0;
m_hasCachedFormData = false;
}
void KWebKitPart::slotShowWalletMenu()
{
KMenu *menu = new KMenu(0);
if (m_webView && WebKitSettings::self()->isNonPasswordStorableSite(m_webView->url().host()))
menu->addAction(i18n("&Allow password caching for this site"), this, SLOT(slotDeleteNonPasswordStorableSite()));
if (m_hasCachedFormData)
menu->addAction(i18n("Remove all cached passwords for this site"), this, SLOT(slotRemoveCachedPasswords()));
menu->addSeparator();
menu->addAction(i18n("&Close Wallet"), this, SLOT(slotWalletClosed()));
KAcceleratorManager::manage(menu);
menu->popup(QCursor::pos());
}
void KWebKitPart::slotLaunchWalletManager()
{
QDBusInterface r("org.kde.kwalletmanager", "/kwalletmanager/MainWindow_1");
if (r.isValid())
r.call(QDBus::NoBlock, "show");
else
KToolInvocation::startServiceByDesktopName("kwalletmanager_show");
}
void KWebKitPart::slotDeleteNonPasswordStorableSite()
{
if (m_webView)
WebKitSettings::self()->removeNonPasswordStorableSite(m_webView->url().host());
}
void KWebKitPart::slotRemoveCachedPasswords()
{
if (!page() || !page()->wallet())
return;
page()->wallet()->removeFormData(page()->mainFrame(), true);
m_hasCachedFormData = false;
}
void KWebKitPart::slotSetTextEncoding(QTextCodec * codec)
{
// FIXME: The code below that sets the text encoding has been reported not to work.
if (!page())
return;
QWebSettings *localSettings = page()->settings();
if (!localSettings)
return;
// kDebug() << codec->name();
localSettings->setDefaultTextEncoding(codec->name());
openUrl(url());
}
void KWebKitPart::slotSetStatusBarText(const QString& text)
{
const QString host (page() ? page()->currentFrame()->url().host() : QString());
if (WebKitSettings::self()->windowStatusPolicy(host) == KParts::HtmlSettingsInterface::JSWindowStatusAllow)
emit setStatusBarText(text);
}
void KWebKitPart::slotWindowCloseRequested()
{
emit m_browserExtension->requestFocus(this);
#if 0
if (KMessageBox::questionYesNo(m_webView,
i18n("Close window?"), i18n("Confirmation Required"),
KStandardGuiItem::close(), KStandardGuiItem::cancel())
!= KMessageBox::Yes)
return;
#endif
this->deleteLater();
}
void KWebKitPart::slotSaveFormDataRequested (const QString& key, const QUrl& url)
{
if (WebKitSettings::self()->isNonPasswordStorableSite(url.host()))
return;
if (!WebKitSettings::self()->askToSaveSitePassword())
return;
if (m_passwordBar && m_passwordBar->isVisible())
return;
if (!m_passwordBar) {
m_passwordBar = new PasswordBar(widget());
KWebWallet* wallet = page()->wallet();
if (!wallet) {
kWarning() << "No wallet instance found! This should never happen!";
return;
}
connect(m_passwordBar, SIGNAL(saveFormDataAccepted(QString)),
wallet, SLOT(acceptSaveFormDataRequest(QString)));
connect(m_passwordBar, SIGNAL(saveFormDataRejected(QString)),
wallet, SLOT(rejectSaveFormDataRequest(QString)));
connect(m_passwordBar, SIGNAL(done()),
this, SLOT(slotSaveFormDataDone()));
}
Q_ASSERT(m_passwordBar);
m_passwordBar->setUrl(url);
m_passwordBar->setRequestKey(key);
m_passwordBar->setText(i18n("<html>Do you want %1 to remember the login "
"information for <b>%2</b>?</html>",
QCoreApplication::applicationName(),
url.host()));
QBoxLayout* lay = qobject_cast<QBoxLayout*>(widget()->layout());
if (lay)
lay->insertWidget(0, m_passwordBar);
m_passwordBar->animatedShow();
}
void KWebKitPart::slotSaveFormDataDone()
{
if (!m_passwordBar)
return;
QBoxLayout* lay = qobject_cast<QBoxLayout*>(widget()->layout());
if (lay)
lay->removeWidget(m_passwordBar);
}
void KWebKitPart::addWalletStatusBarIcon ()
{
if (m_statusBarWalletLabel) {
m_statusBarExtension->removeStatusBarItem(m_statusBarWalletLabel);
} else {
m_statusBarWalletLabel = new KUrlLabel(m_statusBarExtension->statusBar());
m_statusBarWalletLabel->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum));
m_statusBarWalletLabel->setUseCursor(false);
m_statusBarWalletLabel->setPixmap(SmallIcon("wallet-open"));
connect(m_statusBarWalletLabel, SIGNAL(leftClickedUrl()), SLOT(slotLaunchWalletManager()));
connect(m_statusBarWalletLabel, SIGNAL(rightClickedUrl()), SLOT(slotShowWalletMenu()));
}
m_statusBarExtension->addStatusBarItem(m_statusBarWalletLabel, 0, false);
}
void KWebKitPart::slotFillFormRequestCompleted (bool ok)
{
if ((m_hasCachedFormData = ok))
addWalletStatusBarIcon();
}
void KWebKitPart::slotFrameCreated (QWebFrame* frame)
{
if (frame != page()->mainFrame()) {
connect(frame, SIGNAL(loadFinished(bool)), this, SLOT(slotFrameLoadFinished(bool)), Qt::UniqueConnection);
}
}

View file

@ -1,115 +0,0 @@
[Desktop Entry]
Type=Service
Comment=Embeddable HTML component
Comment[ar]=مكون HTML قابل للدمج
Comment[ast]=Componente HTML empotrable
Comment[bg]=Компонент HTML за вграждане
Comment[bs]=Ugradiva HTML komponenta
Comment[ca]=Component HTML incrustable
Comment[ca@valencia]=Component HTML encastable
Comment[cs]=Zapouzdřitelná HTML komponenta
Comment[da]=HTML-komponent som kan indlejres
Comment[de]=Einbettungsfähige HTML-Komponente
Comment[el]=Συστατικό HTML με δυνατότητα ενσωμάτωσης
Comment[en_GB]=Embeddable HTML component
Comment[es]=Componente HTML empotrable
Comment[et]=Põimitav HTML-komponent
Comment[eu]=HTML osagai txertagarria
Comment[fa]=مؤلفه نهفتنی HTML
Comment[fi]=Upotettava HTML-osa
Comment[fr]=Composant HTML intégrable
Comment[ga]=Comhpháirt Inleabaithe HTML
Comment[gl]=Compoñente HTML incrustábel
Comment[hu]=Beágyazható HTML-komponens
Comment[is]=Innfellanleg HTML eining
Comment[it]=Componente HTML integrabile
Comment[kk]=HTML ендірме компоненті
Comment[km]= HTML
Comment[ko]= HTML
Comment[lt]=Įdedamas HTML komponentas
Comment[mai]=
Comment[ml]=ി ി
Comment[mr]= HTML
Comment[ms]=Komponen HTML boleh lekap
Comment[nb]=Innebyggbar HTML-komponent
Comment[nds]=Inbettbor HTML-Komponent
Comment[nl]=Inbedbaar HTML-component
Comment[pa]= HTML
Comment[pl]=Komponent osadzany HTML
Comment[pt]=Componente de HTML incorporada
Comment[pt_BR]=Componente HTML que pode ser embutido
Comment[ro]=Componentă HTML încorporabilă
Comment[ru]=Встраиваемый компонент HTML
Comment[sk]=Vložiteľný HTML komponent
Comment[sl]=Vgradljiv sestavni del HTML
Comment[sr]=Угнездива ХТМЛ компонента
Comment[sr@ijekavian]=Угњездива ХТМЛ компонента
Comment[sr@ijekavianlatin]=Ugnjezdiva HTML komponenta
Comment[sr@latin]=Ugnezdiva HTML komponenta
Comment[sv]=Inbäddningsbar HTML-komponent
Comment[th]= HTML
Comment[tr]=Gömülebilir HTML bileşeni
Comment[ug]=سىڭدۈرۈشكە بولىدىغان HTML بۆلەك
Comment[uk]=Вмонтований HTML-компонент
Comment[x-test]=xxEmbeddable HTML componentxx
Comment[zh_CN]= HTML
Comment[zh_TW]= HTML
Icon=webkit
MimeType=text/html;application/xml;application/xhtml+xml;
Name=WebKit
Name[ar]=ويب كت
Name[ast]=WebKit
Name[bg]=WebKit
Name[bs]=Webkit
Name[ca]=WebKit
Name[ca@valencia]=WebKit
Name[cs]=WebKit
Name[da]=WebKit
Name[de]=WebKit
Name[el]=WebKit
Name[en_GB]=WebKit
Name[es]=WebKit
Name[et]=WebKit
Name[eu]=WebKit
Name[fa]=WebKit
Name[fi]=WebKit
Name[fr]=WebKit
Name[ga]=WebKit
Name[gl]=WebKit
Name[hu]=WebKit
Name[is]=WebKit
Name[it]=WebKit
Name[kk]=WebKit
Name[km]=WebKit
Name[ko]=WebKit
Name[lt]=WebKit
Name[ml]=ി
Name[mr]=ि
Name[ms]=WebKit
Name[nb]=WebKit
Name[nds]=Nettbuukasten
Name[nl]=WebKit
Name[pa]=ਿ
Name[pl]=WebKit
Name[pt]=WebKit
Name[pt_BR]=WebKit
Name[ro]=WebKit
Name[ru]=WebKit
Name[sk]=WebKit
Name[sl]=WebKit
Name[sr]=Вебкит
Name[sr@ijekavian]=Вебкит
Name[sr@ijekavianlatin]=WebKit
Name[sr@latin]=WebKit
Name[sv]=Webkit
Name[th]= WebKit
Name[tr]=WebKit
Name[ug]=WebKit
Name[uk]=WebKit
Name[x-test]=xxWebKitxx
Name[zh_CN]=WebKit
Name[zh_TW]=WebKit
X-KDE-Default-UserAgent=Mozilla/5.0 (%PLATFORM%; %SECURITY%; %OSNAME% %OSVERSION% %SYSTYPE%; %LANGUAGE%) AppleWebKit/534.34 (KHTML, like Gecko) %APPVERSION% Safari/534.34
X-KDE-ServiceTypes=KParts/ReadOnlyPart,Browser/View
X-KDE-Library=kwebkitpart
InitialPreference=11

View file

@ -1,158 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef KWEBKITPART_H
#define KWEBKITPART_H
#include <kparts/part.h>
namespace KParts {
class BrowserExtension;
class StatusBarExtension;
}
class QWebView;
class QWebFrame;
class QWebHistoryItem;
class WebView;
class WebPage;
class SearchBar;
class PasswordBar;
class KUrlLabel;
class WebKitBrowserExtension;
/**
* A KPart wrapper for the QtWebKit's browser rendering engine.
*
* This class attempts to provide the same type of integration into KPart
* plugin applications, such as Konqueror, in much the same way as KHTML.
*
* Unlink the KHTML part however, access into the internals of the rendering
* engine are provided through existing QtWebKit class ; @see QWebView.
*
*/
class KWebKitPart : public KParts::ReadOnlyPart
{
Q_OBJECT
Q_PROPERTY( bool modified READ isModified )
public:
explicit KWebKitPart(QWidget* parentWidget = 0, QObject* parent = 0,
const QByteArray& cachedHistory = QByteArray(),
const QStringList& = QStringList());
~KWebKitPart();
/**
* Re-implemented for internal reasons. API remains unaffected.
*
* @see KParts::ReadOnlyPart::openUrl
*/
virtual bool openUrl(const KUrl &);
/**
* Re-implemented for internal reasons. API remains unaffected.
*
* @see KParts::ReadOnlyPart::closeUrl
*/
virtual bool closeUrl();
/**
* Returns a pointer to the render widget used to display a web page.
*
* @see QWebView.
*/
virtual QWebView *view();
/**
* Checks whether the page contains unsubmitted form changes.
*
* @return @p true if form changes exist.
*/
bool isModified() const;
/**
* Connects the appropriate signals from the given page to the slots
* in this class.
*/
void connectWebPageSignals(WebPage* page);
protected:
/**
* Re-implemented for internal reasons. API remains unaffected.
*
* @see KParts::ReadOnlyPart::guiActivateEvent
*/
virtual void guiActivateEvent(KParts::GUIActivateEvent *);
/**
* Re-implemented for internal reasons. API remains unaffected.
*
* @see KParts::ReadOnlyPart::openFile
*/
virtual bool openFile();
private Q_SLOTS:
void slotShowSecurity();
void slotShowSearchBar();
void slotLoadStarted();
void slotLoadAborted(const KUrl &);
void slotLoadFinished(bool);
void slotFrameLoadFinished(bool);
void slotMainFrameLoadFinished(bool);
void slotSearchForText(const QString &text, bool backward);
void slotLinkHovered(const QString &, const QString&, const QString &);
void slotSaveFrameState(QWebFrame *frame, QWebHistoryItem *item);
void slotRestoreFrameState(QWebFrame *frame);
void slotLinkMiddleOrCtrlClicked(const KUrl&);
void slotSelectionClipboardUrlPasted(const KUrl&, const QString&);
void slotUrlChanged(const QUrl &);
void slotWalletClosed();
void slotShowWalletMenu();
void slotLaunchWalletManager();
void slotDeleteNonPasswordStorableSite();
void slotRemoveCachedPasswords();
void slotSetTextEncoding(QTextCodec*);
void slotSetStatusBarText(const QString& text);
void slotWindowCloseRequested();
void slotSaveFormDataRequested(const QString &, const QUrl &);
void slotSaveFormDataDone();
void slotFillFormRequestCompleted(bool);
void slotFrameCreated(QWebFrame*);
private:
WebPage* page();
void initActions();
void updateActions();
void addWalletStatusBarIcon();
bool m_emitOpenUrlNotify;
bool m_hasCachedFormData;
bool m_doLoadFinishedActions;
KUrlLabel* m_statusBarWalletLabel;
SearchBar* m_searchBar;
PasswordBar* m_passwordBar;
WebKitBrowserExtension* m_browserExtension;
KParts::StatusBarExtension* m_statusBarExtension;
WebView* m_webView;
};
#endif // WEBKITPART_H

View file

@ -1,31 +0,0 @@
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
<kpartgui name="kwebkitpart" version="7">
<MenuBar>
<Menu name="file">
<Action name="saveDocument" />
<Action name="saveFrame" />
<Separator />
<Action name="printPreview" group="print" />
</Menu>
<Menu name="edit">
<Action name="selectAll" />
<Separator />
<Action name="find" />
</Menu>
<Menu name="view">
<Action name="zoomIn" />
<Action name="zoomOut" />
<Action name="zoomNormal" />
<Action name="zoomTextOnly" />
<Separator />
<Action name="setEncoding" />
<Action name="viewDocumentSource" />
<ActionList name="debugScriptList" />
</Menu>
</MenuBar>
<ToolBar name="htmlToolBar" iconText="icononly" iconSize="22" hidden="true"><text>HTML Toolbar</text>
<Action name="zoomIn" />
<Action name="zoomOut" />
<Action name="zoomNormal" />
</ToolBar>
</kpartgui>

File diff suppressed because it is too large Load diff

View file

@ -1,200 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBKITPART_EXT_H
#define WEBKITPART_EXT_H
#include <kparts/browserextension.h>
#include <kparts/textextension.h>
#include <kparts/htmlextension.h>
#include <kparts/scriptableextension.h>
class KUrl;
class KWebKitPart;
class WebView;
class KSaveFile;
class QWebFrame;
class WebKitBrowserExtension : public KParts::BrowserExtension
{
Q_OBJECT
public:
WebKitBrowserExtension(KWebKitPart *parent, const QByteArray& cachedHistoryData);
~WebKitBrowserExtension();
virtual int xOffset();
virtual int yOffset();
virtual void saveState(QDataStream &);
virtual void restoreState(QDataStream &);
void saveHistory();
Q_SIGNALS:
void saveUrl(const KUrl &);
void saveHistory(QObject*, const QByteArray&);
public Q_SLOTS:
void cut();
void copy();
void paste();
void print();
void slotSaveDocument();
void slotSaveFrame();
void searchProvider();
void reparseConfiguration();
void disableScrolling();
void zoomIn();
void zoomOut();
void zoomNormal();
void toogleZoomTextOnly();
void slotSelectAll();
void slotFrameInWindow();
void slotFrameInTab();
void slotFrameInTop();
void slotReloadFrame();
void slotBlockIFrame();
void slotSaveImageAs();
void slotSendImage();
void slotCopyImageURL();
void slotCopyImage();
void slotViewImage();
void slotBlockImage();
void slotBlockHost();
void slotCopyLinkURL();
void slotCopyLinkText();
void slotSaveLinkAs();
void slotCopyEmailAddress();
void slotViewDocumentSource();
void slotViewFrameSource();
void updateEditActions();
void updateActions();
void slotPlayMedia();
void slotMuteMedia();
void slotLoopMedia();
void slotShowMediaControls();
void slotSaveMedia();
void slotCopyMedia();
void slotTextDirectionChanged();
void slotCheckSpelling();
void slotSpellCheckSelection();
void slotSpellCheckDone(const QString&);
void spellCheckerCorrected(const QString&, int, const QString&);
void spellCheckerMisspelling(const QString&, int);
void slotPrintRequested(QWebFrame*);
void slotPrintPreview();
void slotOpenSelection();
void slotLinkInTop();
private:
WebView* view();
QPointer<KWebKitPart> m_part;
QPointer<WebView> m_view;
quint32 m_spellTextSelectionStart;
quint32 m_spellTextSelectionEnd;
QByteArray m_historyData;
};
/**
* @internal
* Implements the TextExtension interface
*/
class KWebKitTextExtension : public KParts::TextExtension
{
Q_OBJECT
public:
KWebKitTextExtension(KWebKitPart* part);
virtual bool hasSelection() const;
virtual QString selectedText(Format format) const;
virtual QString completeText(Format format) const;
private:
KWebKitPart* part() const;
};
/**
* @internal
* Implements the HtmlExtension interface
*/
class KWebKitHtmlExtension : public KParts::HtmlExtension,
public KParts::SelectorInterface,
public KParts::HtmlSettingsInterface
{
Q_OBJECT
Q_INTERFACES(KParts::SelectorInterface)
Q_INTERFACES(KParts::HtmlSettingsInterface)
public:
KWebKitHtmlExtension(KWebKitPart* part);
// HtmlExtension
virtual KUrl baseUrl() const;
virtual bool hasSelection() const;
// SelectorInterface
virtual QueryMethods supportedQueryMethods() const;
virtual Element querySelector(const QString& query, KParts::SelectorInterface::QueryMethod method) const;
virtual QList<Element> querySelectorAll(const QString& query, KParts::SelectorInterface::QueryMethod method) const;
// HtmlSettingsInterface
virtual QVariant htmlSettingsProperty(HtmlSettingsType type) const;
virtual bool setHtmlSettingsProperty(HtmlSettingsType type, const QVariant& value);
private:
KWebKitPart* part() const;
};
class KWebKitScriptableExtension : public KParts::ScriptableExtension
{
Q_OBJECT
public:
KWebKitScriptableExtension(KWebKitPart* part);
virtual QVariant rootObject();
virtual QVariant get(ScriptableExtension* callerPrincipal, quint64 objId, const QString& propName);
virtual bool put(ScriptableExtension* callerPrincipal, quint64 objId, const QString& propName, const QVariant& value);
virtual bool setException(ScriptableExtension* callerPrincipal, const QString& message);
virtual QVariant evaluateScript(ScriptableExtension* callerPrincipal,
quint64 contextObjectId,
const QString& code,
ScriptLanguage language = ECMAScript);
virtual bool isScriptLanguageSupported(ScriptLanguage lang) const;
private:
virtual QVariant encloserForKid(KParts::ScriptableExtension* kid);
KWebKitPart* part();
};
#endif // WEBKITPART_EXT_H

View file

@ -1,70 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "kwebkitpartfactory.h"
#include "kwebkitpart_ext.h"
#include "kwebkitpart.h"
#include <kdebug.h>
#include <QWidget>
KWebKitFactory::~KWebKitFactory()
{
// kDebug() << this;
}
QObject *KWebKitFactory::create(const char* iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString& keyword)
{
Q_UNUSED(iface);
Q_UNUSED(keyword);
Q_UNUSED(args);
kDebug() << parentWidget << parent;
connect(parentWidget, SIGNAL(destroyed(QObject*)), this, SLOT(slotDestroyed(QObject*)));
// NOTE: The code below is what makes it possible to properly integrate QtWebKit's
// history management with any KParts based application.
QByteArray histData (m_historyBufContainer.value(parentWidget));
if (!histData.isEmpty()) histData = qUncompress(histData);
KWebKitPart* part = new KWebKitPart(parentWidget, parent, histData);
WebKitBrowserExtension* ext = qobject_cast<WebKitBrowserExtension*>(part->browserExtension());
if (ext) {
connect(ext, SIGNAL(saveHistory(QObject*,QByteArray)), this, SLOT(slotSaveHistory(QObject*,QByteArray)));
}
return part;
}
void KWebKitFactory::slotSaveHistory(QObject* widget, const QByteArray& buffer)
{
// kDebug() << "Caching history data from" << widget;
m_historyBufContainer.insert(widget, buffer);
}
void KWebKitFactory::slotDestroyed(QObject* object)
{
// kDebug() << "Removing cached history data of" << object;
m_historyBufContainer.remove(object);
}
K_EXPORT_PLUGIN(KWebKitFactory)
#include "moc_kwebkitpartfactory.cpp"

View file

@ -1,43 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBKITPARTFACTORY
#define WEBKITPARTFACTORY
#include <kpluginfactory.h>
#include <QWidget>
class KWebKitFactory : public KPluginFactory
{
Q_OBJECT
public:
virtual ~KWebKitFactory();
virtual QObject *create(const char* iface, QWidget *parentWidget, QObject *parent, const QVariantList& args, const QString &keyword);
private Q_SLOTS:
void slotDestroyed(QObject* object);
void slotSaveHistory(QObject* widget, const QByteArray&);
private:
QHash<QObject*, QByteArray> m_historyBufContainer;
};
#endif // WEBKITPARTFACTORY

View file

@ -1,147 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "networkaccessmanager.h"
#include "settings/webkitsettings.h"
#include <kdebug.h>
#include <klocalizedstring.h>
#include <kprotocolinfo.h>
#include <krun.h>
#include <QWidget>
#include <QNetworkReply>
#include <QWebFrame>
#include <QWebElement>
#define HIDABLE_ELEMENTS QLatin1String("audio,img,embed,object,iframe,frame,video")
/* Null network reply */
class NullNetworkReply : public QNetworkReply
{
public:
NullNetworkReply(const QNetworkRequest &req, QObject* parent = 0)
:QNetworkReply(parent)
{
setRequest(req);
setUrl(req.url());
setHeader(QNetworkRequest::ContentLengthHeader, 0);
setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
setError(QNetworkReply::ContentAccessDenied, i18n("Blocked by ad filter"));
setAttribute(QNetworkRequest::User, QNetworkReply::ContentAccessDenied);
QTimer::singleShot(0, this, SIGNAL(finished()));
}
virtual void abort() {}
virtual qint64 bytesAvailable() const { return 0; }
protected:
virtual qint64 readData(char*, qint64) {return -1;}
};
namespace KDEPrivate {
MyNetworkAccessManager::MyNetworkAccessManager(QObject *parent)
: KIO::AccessManager(parent)
{
}
static bool blockRequest(QNetworkAccessManager::Operation op, const QUrl& requestUrl)
{
if (op != QNetworkAccessManager::GetOperation)
return false;
if (!WebKitSettings::self()->isAdFilterEnabled())
return false;
if (!WebKitSettings::self()->isAdFiltered(requestUrl.toString()))
return false;
kDebug() << "*** REQUEST BLOCKED: URL" << requestUrl << "RULE" << WebKitSettings::self()->adFilteredBy(requestUrl.toString());
return true;
}
QNetworkReply *MyNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
if (!blockRequest(op, req.url())) {
if (KProtocolInfo::isHelperProtocol(req.url())) {
(void) new KRun(req.url(), qobject_cast<QWidget*>(req.originatingObject()));
return new NullNetworkReply(req, this);
}
return KIO::AccessManager::createRequest(op, req, outgoingData);
}
QWebFrame* frame = qobject_cast<QWebFrame*>(req.originatingObject());
if (frame) {
if (!m_blockedRequests.contains(frame))
connect(frame, SIGNAL(loadFinished(bool)), this, SLOT(slotFinished(bool)));
m_blockedRequests.insert(frame, req.url());
}
return new NullNetworkReply(req, this);
}
static void hideBlockedElements(const QUrl& url, QWebElementCollection& collection)
{
for (QWebElementCollection::iterator it = collection.begin(); it != collection.end(); ++it) {
const QUrl baseUrl ((*it).webFrame()->baseUrl());
QString src = (*it).attribute(QLatin1String("src"));
if (src.isEmpty())
src = (*it).evaluateJavaScript(QLatin1String("this.src")).toString();
if (src.isEmpty())
continue;
const QUrl resolvedUrl (baseUrl.resolved(src));
if (url == resolvedUrl) {
//kDebug() << "*** HIDING ELEMENT: " << (*it).tagName() << resolvedUrl;
(*it).removeFromDocument();
}
}
}
void MyNetworkAccessManager::slotFinished(bool ok)
{
if (!ok)
return;
if(!WebKitSettings::self()->isAdFilterEnabled())
return;
if(!WebKitSettings::self()->isHideAdsEnabled())
return;
QWebFrame* frame = qobject_cast<QWebFrame*>(sender());
if (!frame)
return;
QList<QUrl> urls = m_blockedRequests.values(frame);
if (urls.isEmpty())
return;
QWebElementCollection collection = frame->findAllElements(HIDABLE_ELEMENTS);
if (frame->parentFrame())
collection += frame->parentFrame()->findAllElements(HIDABLE_ELEMENTS);
Q_FOREACH(const QUrl& url, urls)
hideBlockedElements(url, collection);
}
}
#include "moc_networkaccessmanager.cpp"

View file

@ -1,53 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef NETWORKACCESSMANAGER_H
#define NETWORKACCESSMANAGER_H
#include <kio/accessmanager.h>
#include <QMultiHash>
class QWebFrame;
namespace KDEPrivate {
/**
* Re-implemented for internal reasons. API remains unaffected.
*/
class MyNetworkAccessManager : public KIO::AccessManager
{
Q_OBJECT
public:
MyNetworkAccessManager(QObject *parent = 0);
protected:
virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData = 0);
private Q_SLOTS:
void slotFinished(bool);
private:
QMultiHash<QWebFrame*, QUrl> m_blockedRequests;
};
}
#endif // NETWORKACCESSMANAGER_P_H

View file

@ -1,345 +0,0 @@
/* This file is part of the KDE project
Copyright (C) 2005 Ivor Hewitt <ivor@kde.org>
Copyright (C) 2008 Maksim Orlovich <maksim@kde.org>
Copyright (C) 2008 Vyacheslav Tokarev <tsjoker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "webkit_filter.h"
#include <kdebug.h>
#include <QHash>
#include <QBitArray>
// rolling hash parameters
#define HASH_P (1997)
#define HASH_Q (17509)
// HASH_MOD = (HASH_P^7) % HASH_Q
#define HASH_MOD (523)
using namespace KDEPrivate;
// Updateable Multi-String Matcher based on Rabin-Karp's algorithm
class StringsMatcher {
public:
// add filter to matching set
void addString(const QString& pattern)
{
if (pattern.length() < 8) {
// handle short string differently
shortStringFilters.append(pattern);
} else {
// use modified Rabin-Karp's algorithm with 8-length string hash
// i.e. store hash of first 8 chars in the HashMap for fast look-up
stringFilters.append(pattern);
int ind = stringFilters.size() - 1;
int current = 0;
// compute hash using rolling hash
// hash for string: x0,x1,x2...xn-1 will be:
// (p^(n-1)*x0 + p^(n-2)*x1 + ... + p * xn-2 + xn-1) % q
// where p and q some wisely-chosen integers
/*for (int k = 0; k < 8; ++k)*/
int len = pattern.length();
for (int k = len - 8; k < len; ++k)
current = (current * HASH_P + pattern[k].unicode()) % HASH_Q;
// insert computed hash value into HashMap
QHash<int, QVector<int> >::iterator it = stringFiltersHash.find(current + 1);
if (it == stringFiltersHash.end()) {
QVector<int> list;
list.append(ind);
stringFiltersHash.insert(current + 1, list);
fastLookUp.setBit(current);
} else {
it->append(ind);
}
}
}
// check if string match at least one string from matching set
bool isMatched(const QString& str, QString *by = 0) const
{
// check short strings first
for (int i = 0; i < shortStringFilters.size(); ++i) {
if (str.contains(shortStringFilters[i]))
{
if (by != 0) *by = shortStringFilters[i];
return true;
}
}
int len = str.length();
int k;
int current = 0;
int next = 0;
// compute hash for first 8 characters
for (k = 0; k < 8 && k < len; ++k)
current = (current * HASH_P + str[k].unicode()) % HASH_Q;
QHash<int, QVector<int> >::const_iterator hashEnd = stringFiltersHash.end();
// main Rabin-Karp's algorithm loop
for (k = 7; k < len; ++k, current = next) {
// roll the hash if not at the end
// (calculate hash for the next iteration)
if (k + 1 < len)
next = (HASH_P * ((current + HASH_Q - ((HASH_MOD * str[k - 7].unicode()) % HASH_Q)) % HASH_Q) + str[k + 1].unicode()) % HASH_Q;
if (!fastLookUp.testBit(current))
continue;
// look-up the hash in the HashMap and check all strings
QHash<int, QVector<int> >::const_iterator it = stringFiltersHash.find(current + 1);
// check possible strings
if (it != hashEnd) {
for (int j = 0; j < it->size(); ++j) {
int index = it->value(j);
// check if we got simple string or REs prefix
if (index >= 0) {
int flen = stringFilters[index].length();
if (k - flen + 1 >= 0 && stringFilters[index] == str.midRef(k - flen + 1 , flen))
{
if (by != 0) *by = stringFilters[index];
return true;
}
} else {
index = -index - 1;
int flen = rePrefixes[index].length();
if (k - 8 + flen < len && rePrefixes[index] == str.midRef(k - 7, flen))
{
int remStart = k - 7 + flen;
QString remainder = QString::fromRawData(str.unicode() + remStart,
str.length() - remStart);
if (reFilters[index].exactMatch(remainder)) {
if (by != 0) *by = rePrefixes[index]+reFilters[index].pattern();
return true;
}
}
}
}
}
}
return false;
}
// add filter to matching set with wildcards (*,?) in it
void addWildedString(const QString& prefix, const QRegExp& rx)
{
rePrefixes.append(prefix);
reFilters.append(rx);
int index = -rePrefixes.size();
int current = 0;
for (int k = 0; k < 8; ++k)
current = (current * HASH_P + prefix[k].unicode()) % HASH_Q;
// insert computed hash value into HashMap
QHash<int, QVector<int> >::iterator it = stringFiltersHash.find(current + 1);
if (it == stringFiltersHash.end()) {
QVector<int> list;
list.append(index);
stringFiltersHash.insert(current + 1, list);
fastLookUp.setBit(current);
} else {
it->append(index);
}
}
void clear()
{
stringFilters.clear();
shortStringFilters.clear();
reFilters.clear();
rePrefixes.clear();
stringFiltersHash.clear();
fastLookUp.resize(HASH_Q);
fastLookUp.fill(0, 0, HASH_Q);
}
private:
QVector<QString> stringFilters;
QVector<QString> shortStringFilters;
QVector<QRegExp> reFilters;
QVector<QString> rePrefixes;
QBitArray fastLookUp;
QHash<int, QVector<int> > stringFiltersHash;
};
// We only want a subset of features of wildcards -- just the
// star, so we escape the rest before passing to QRegExp.
// The \ is escaped due to a QRegExp bug.
// ### we really should rather parse it ourselves, in order to
// handle adblock-special things like | and ^ properly.
static QRegExp fromAdBlockWildcard(const QString& wcStr) {
QRegExp rx;
rx.setPatternSyntax(QRegExp::Wildcard);
QString out;
for (int p = 0; p < wcStr.length(); ++p) {
QChar c = wcStr[p];
if (c == QLatin1Char('?'))
out += QLatin1String("[?]");
else if (c == QLatin1Char('['))
out += QLatin1String("[[]");
else if (c == QLatin1Char('\\'))
out += QLatin1String("[\\]");
else
out += c;
}
rx.setPattern(out);
return rx;
}
FilterSet::FilterSet()
:stringFiltersMatcher(new StringsMatcher)
{
}
FilterSet::~FilterSet()
{
delete stringFiltersMatcher;
}
void FilterSet::addFilter(const QString& filterStr)
{
QString filter = filterStr;
/** ignore special lines starting with "[", "!", "&", or "#" or contain "#" (comments or features are not supported by KHTML's AdBlock */
QChar firstChar = filter.at(0);
if (firstChar == QLatin1Char('[') || firstChar == QLatin1Char('!') || firstChar == QLatin1Char('&') || firstChar == QLatin1Char('#') || filter.contains(QLatin1Char('#')))
return;
// Strip leading @@
int first = 0;
int last = filter.length() - 1;
if (filter.startsWith(QLatin1String("@@")))
first = 2;
// Strip options, we ignore them for now.
// TODO: Add support for filters with options. See #310230.
int dollar = filter.lastIndexOf(QLatin1Char('$'));
if (dollar != -1) {
return;
}
// Perhaps nothing left?
if (first > last)
return;
filter = filter.mid(first, last - first + 1);
// Is it a regexp filter?
if (filter.length()>2 && filter.startsWith(QLatin1Char('/')) && filter.endsWith(QLatin1Char('/')))
{
QString inside = filter.mid(1, filter.length()-2);
QRegExp rx(inside);
reFilters.append(rx);
// qDebug() << "R:" << inside;
}
else
{
// Nope, a wildcard one.
// Note: For these, we also need to handle |.
// Strip wildcards at the ends
first = 0;
last = filter.length() - 1;
while (first < filter.length() && filter[first] == QLatin1Char('*'))
++first;
while (last >= 0 && filter[last] == QLatin1Char('*'))
--last;
if (first > last)
filter = QLatin1String("*"); // erm... Well, they asked for it.
else
filter = filter.mid(first, last - first + 1);
// Now, do we still have any wildcard stuff left?
if (filter.contains("*"))
{
// check if we can use RK first (and then check full RE for the rest) for better performance
int aPos = filter.indexOf('*');
if (aPos < 0)
aPos = filter.length();
if (aPos > 7) {
QRegExp rx = fromAdBlockWildcard(filter.mid(aPos) + QLatin1Char('*'));
// We pad the final r.e. with * so we can check for an exact match
stringFiltersMatcher->addWildedString(filter.mid(0, aPos), rx);
} else {
QRegExp rx = fromAdBlockWildcard(filter);
reFilters.append(rx);
}
}
else
{
// Fast path
stringFiltersMatcher->addString(filter);
}
}
}
bool FilterSet::isUrlMatched(const QString& url)
{
if (stringFiltersMatcher->isMatched(url))
return true;
for (int c = 0; c < reFilters.size(); ++c)
{
if (url.contains(reFilters[c]))
return true;
}
return false;
}
QString FilterSet::urlMatchedBy(const QString& url)
{
QString by;
if (stringFiltersMatcher->isMatched(url, &by))
return by;
for (int c = 0; c < reFilters.size(); ++c)
{
if (url.contains(reFilters[c]))
{
by = reFilters[c].pattern();
break;
}
}
return by;
}
void FilterSet::clear()
{
reFilters.clear();
stringFiltersMatcher->clear();
}
// kate: indent-width 4; replace-tabs on; tab-width 4; space-indent on;

View file

@ -1,59 +0,0 @@
/* This file is part of the KDE project
Copyright (C) 2005 Ivor Hewitt <ivor@kde.org>
Copyright (C) 2008 Maksim Orlovich <maksim@kde.org>
Copyright (C) 2008 Vyacheslav Tokarev <tsjoker@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef WEBKIT_FILTER_P_H
#define WEBKIT_FILTER_P_H
#include <QRegExp>
#include <QVector>
#include <kwebkitpart.h>
class StringsMatcher;
namespace KDEPrivate
{
// This represents a set of filters that may match URLs.
// Currently it supports a subset of AddBlock Plus functionality.
class FilterSet {
public:
FilterSet();
~FilterSet();
// Parses and registers a filter. This will also strip @@ for exclusion rules, skip comments, etc.
// The user does have to split black and white lists into separate sets, however
void addFilter(const QString& filter);
bool isUrlMatched(const QString& url);
QString urlMatchedBy(const QString& url);
void clear();
private:
QVector<QRegExp> reFilters;
StringsMatcher* stringFiltersMatcher;
};
}
#endif // WEBKIT_FILTER_P_H
// kate: indent-width 4; replace-tabs on; tab-width 4; space-indent on;

File diff suppressed because it is too large Load diff

View file

@ -1,205 +0,0 @@
/* This file is part of the KDE project
Copyright (C) 1999 David Faure <faure@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef WEBKITSETTINGS_H
#define WEBKITSETTINGS_H
class KConfig;
class KConfigGroup;
#include <QColor>
#include <QPair>
#include <kparts/htmlextension.h>
struct KPerDomainSettings;
class WebKitSettingsPrivate;
/**
* Settings for the HTML view.
*/
class WebKitSettings
{
public:
enum KAnimationAdvice {
KAnimationDisabled=0,
KAnimationLoopOnce,
KAnimationEnabled
};
enum KSmoothScrollingMode {
KSmoothScrollingDisabled=0,
KSmoothScrollingWhenEfficient,
KSmoothScrollingEnabled
};
/**
* Called by constructor and reparseConfiguration
*/
void init();
/**
* Destructor. Don't delete any instance by yourself.
*/
virtual ~WebKitSettings();
void computeFontSizes(int logicalDpi);
// Automatic page reload/refresh...
bool autoPageRefresh() const;
bool isOpenMiddleClickEnabled();
// Java and JavaScript
bool isJavaEnabled( const QString& hostname = QString() ) const;
bool isJavaScriptEnabled( const QString& hostname = QString() ) const;
bool isJavaScriptDebugEnabled( const QString& hostname = QString() ) const;
bool isJavaScriptErrorReportingEnabled( const QString& hostname = QString() ) const;
bool isPluginsEnabled( const QString& hostname = QString() ) const;
bool isLoadPluginsOnDemandEnabled() const;
bool isInternalPluginHandlingDisabled() const;
// AdBlocK Filtering
bool isAdFiltered( const QString &url ) const;
bool isAdFilterEnabled() const;
bool isHideAdsEnabled() const;
void addAdFilter( const QString &url );
QString adFilteredBy( const QString &url, bool *isWhiteListed = 0 ) const;
// Access Keys
bool accessKeysEnabled() const;
// Favicons
bool favIconsEnabled() const;
KParts::HtmlSettingsInterface::JSWindowOpenPolicy windowOpenPolicy( const QString& hostname = QString() ) const;
KParts::HtmlSettingsInterface::JSWindowMovePolicy windowMovePolicy( const QString& hostname = QString() ) const;
KParts::HtmlSettingsInterface::JSWindowResizePolicy windowResizePolicy( const QString& hostname = QString() ) const;
KParts::HtmlSettingsInterface::JSWindowStatusPolicy windowStatusPolicy( const QString& hostname = QString() ) const;
KParts::HtmlSettingsInterface::JSWindowFocusPolicy windowFocusPolicy( const QString& hostname = QString() ) const;
QString settingsToCSS() const;
QString userStyleSheet() const;
// Form completion
bool isFormCompletionEnabled() const;
int maxFormCompletionItems() const;
// Meta refresh/redirect (http-equiv)
bool isAutoDelayedActionsEnabled () const;
// CookieJar...
bool isCookieJarEnabled() const;
// Password storage...
bool isNonPasswordStorableSite(const QString &host) const;
void addNonPasswordStorableSite(const QString &host);
void removeNonPasswordStorableSite(const QString &host);
bool askToSaveSitePassword() const;
// Global config object stuff.
static WebKitSettings* self();
private:
/**
* Read settings from @p config.
* @param config is a pointer to KConfig object.
* @param reset if true, settings are always set; if false,
* settings are only set if the config file has a corresponding key.
*/
void init( KConfig * config, bool reset = true );
// Behavior settings
bool changeCursor() const;
bool underlineLink() const;
bool hoverLink() const;
bool allowTabulation() const;
bool autoSpellCheck() const;
KAnimationAdvice showAnimations() const;
KSmoothScrollingMode smoothScrolling() const;
bool zoomTextOnly() const;
// Font settings
QString stdFontName() const;
QString fixedFontName() const;
QString serifFontName() const;
QString sansSerifFontName() const;
QString cursiveFontName() const;
QString fantasyFontName() const;
// these two can be set. Mainly for historical reasons (the method in KHTMLPart exists...)
void setStdFontName(const QString &n);
void setFixedFontName(const QString &n);
int minFontSize() const;
int mediumFontSize() const;
bool jsErrorsEnabled() const;
void setJSErrorsEnabled(bool enabled);
const QString &encoding() const;
bool followSystemColors() const;
// Color settings
const QColor& textColor() const;
const QColor& baseColor() const;
const QColor& linkColor() const;
const QColor& vLinkColor() const;
// Autoload images
bool autoLoadImages() const;
bool unfinishedImageFrame() const;
/**
* reads from @p config's current group, forcing initialization
* if @p reset is true.
* @param config is a pointer to KConfig object.
* @param reset true if initialization is to be forced.
* @param global true if the global domain is to be read.
* @param pd_settings will be initialised with the computed (inherited)
* settings.
*/
void readDomainSettings(const KConfigGroup &config, bool reset,
bool global, KPerDomainSettings &pd_settings);
QList< QPair< QString, QChar > > fallbackAccessKeysAssignments() const;
// Whether to show passive popup when windows are blocked
void setJSPopupBlockerPassivePopup(bool enabled);
bool jsPopupBlockerPassivePopup() const;
QString lookupFont(int i) const;
void initWebKitSettings();
void initCookieJarSettings();
void initNSPluginSettings();
/**
* @internal Constructor
*/
WebKitSettings();
WebKitSettingsPrivate* const d;
};
#endif

View file

@ -1,101 +0,0 @@
/* This file is part of the KDE project
*
* Copyright (C) 2000-2003 George Staikos <staikos@kde.org>
* Copyright (C) 2000 Malte Starostik <malte@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef SSLINFODIALOG_P_H
#define SSLINFODIALOG_P_H
#include <kdialog.h>
#include <ktcpsocket.h>
// NOTE: We need a copy of this header file here because it is never
// installed by default!
/**
* KDE SSL Information Dialog
*
* This class creates a dialog that can be used to display information about
* an SSL session.
*
* There are NO GUARANTEES that KSslInfoDialog will remain binary compatible/
* Contact staikos@kde.org for details if needed.
*
* @author George Staikos <staikos@kde.org>
* @see KSSL
* @short KDE SSL Information Dialog
*/
class KSslInfoDialog : public KDialog {
Q_OBJECT
public:
/**
* Construct a KSSL Information Dialog
*
* @param parent the parent widget
*/
explicit KSslInfoDialog(QWidget *parent = 0);
/**
* Destroy this dialog
*/
virtual ~KSslInfoDialog();
/**
* Tell the dialog if the connection has portions that may not be
* secure (ie. a mixture of secure and insecure frames)
*
* @param isIt true if security is in question
*/
void setSecurityInQuestion(bool isIt);
/**
* Set information to display about the SSL connection.
*
* @param certificateChain the certificate chain leading from the certificate
* authority to the peer.
* @param ip the ip of the remote host
* @param host the remote hostname
* @param sslProtocol the version of SSL in use (SSLv2, SSLv3, TLSv1)
* @param cipher the cipher in use
* @param usedBits the used bits of the key
* @param bits the key size of the cipher in use
* @param validationErrors errors validating the certificates, if any
*/
void setSslInfo(const QList<QSslCertificate> &certificateChain,
const QString &ip, const QString &host,
const QString &sslProtocol, const QString &cipher,
int usedBits, int bits,
const QList<QList<QSslError::SslError> > &validationErrors);
void setMainPartEncrypted(bool);
void setAuxiliaryPartsEncrypted(bool);
static QList<QList<QSslError::SslError> > errorsFromString(const QString &s);
private Q_SLOTS:
void launchConfig();
void displayFromChain(int);
private:
void updateWhichPartsEncrypted();
class KSslInfoDialogPrivate;
KSslInfoDialogPrivate* const d;
};
#endif // SSLINFODIALOG_P_H

View file

@ -1,107 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "passwordbar.h"
#include "settings/webkitsettings.h"
#include <kicon.h>
#include <kdebug.h>
#include <kcolorscheme.h>
#include <klocalizedstring.h>
#include <QCoreApplication>
#include <QAction>
#include <QPalette>
PasswordBar::PasswordBar(QWidget *parent)
:KMessageWidget(parent)
{
setCloseButtonVisible(false);
setMessageType(KMessageWidget::Information);
QAction* action = new QAction(i18nc("@action:remember password", "&Remember"), this);
connect(action, SIGNAL(triggered()), this, SLOT(onRememberButtonClicked()));
addAction(action);
action = new QAction(i18nc("@action:never for this site", "Ne&ver for this site"), this);
connect(action, SIGNAL(triggered()), this, SLOT(onNeverButtonClicked()));
addAction(action);
action = new QAction(i18nc("@action:not now", "N&ot now"), this);
connect(action, SIGNAL(triggered()), this, SLOT(onNotNowButtonClicked()));
addAction(action);
}
PasswordBar::~PasswordBar()
{
}
QUrl PasswordBar::url() const
{
return m_url;
}
QString PasswordBar::requestKey() const
{
return m_requestKey;
}
void PasswordBar::setUrl (const QUrl& url)
{
m_url = url;
}
void PasswordBar::setRequestKey (const QString& key)
{
m_requestKey = key;
}
void PasswordBar::onNotNowButtonClicked()
{
animatedHide();
emit saveFormDataRejected (m_requestKey);
emit done();
clear();
}
void PasswordBar::onNeverButtonClicked()
{
WebKitSettings::self()->addNonPasswordStorableSite(m_url.host());
onNotNowButtonClicked();
}
void PasswordBar::onRememberButtonClicked()
{
animatedHide();
emit saveFormDataAccepted(m_requestKey);
emit done();
clear();
}
void PasswordBar::clear()
{
m_requestKey.clear();
m_url.clear();
}
#include "moc_passwordbar.cpp"

View file

@ -1,60 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef PASSWORDBAR_H
#define PASSWORDBAR_H
#include <kmessagewidget.h>
#include <QUrl>
class PasswordBar : public KMessageWidget
{
Q_OBJECT
public:
explicit PasswordBar(QWidget *parent = 0);
~PasswordBar();
QUrl url() const;
QString requestKey() const;
void setUrl(const QUrl&);
void setRequestKey(const QString&);
Q_SIGNALS:
void saveFormDataRejected(const QString &key);
void saveFormDataAccepted(const QString &key);
void done();
private Q_SLOTS:
void onNotNowButtonClicked();
void onNeverButtonClicked();
void onRememberButtonClicked();
private:
void clear();
QUrl m_url;
QString m_requestKey;
};
#endif // PASSWORDBAR_H

View file

@ -1,194 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Benjamin C. Meyer <ben@meyerhome.net>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "searchbar.h"
#include <klineedit.h>
#include <kcolorscheme.h>
#include <kicon.h>
#include <klocalizedstring.h>
#include <QtGui/qevent.h>
SearchBar::SearchBar(QWidget *parent)
:QWidget(parent)
{
// Get the widget that currently has the focus so we can properly
// restore it when the filter bar is closed.
QWidget* widgetWindow = (parent ? parent->window() : 0);
m_focusWidget = (widgetWindow ? widgetWindow->focusWidget() : 0);
// Initialize the user interface...
m_ui.setupUi(this);
m_ui.optionsButton->addAction(m_ui.actionMatchCase);
m_ui.optionsButton->addAction(m_ui.actionHighlightMatch);
m_ui.optionsButton->addAction(m_ui.actionSearchAutomatically);
m_ui.closeButton->setIcon(KIcon("dialog-close"));
m_ui.previousButton->setIcon(KIcon("go-up-search"));
m_ui.nextButton->setIcon(KIcon("go-down-search"));
m_ui.previousButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
m_ui.nextButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
m_ui.searchInfo->setText(i18nc("label for input line to find text", "&Find:"));
setFocusProxy(m_ui.searchComboBox);
connect(m_ui.nextButton, SIGNAL(clicked()),
this, SLOT(findNext()));
connect(m_ui.previousButton, SIGNAL(clicked()),
this, SLOT(findPrevious()));
connect(m_ui.searchComboBox, SIGNAL(returnPressed()),
this, SLOT(findNext()));
connect(m_ui.searchComboBox, SIGNAL(editTextChanged(QString)),
this, SLOT(textChanged(QString)));
// Start off hidden by default...
setVisible(false);
}
SearchBar::~SearchBar()
{
// NOTE: For some reason, if we do not clear the focus from the line edit
// widget before we delete this object, it seems to cause a crash!!
m_ui.searchComboBox->clearFocus();
}
void SearchBar::clear()
{
m_ui.searchComboBox->clear();
}
void SearchBar::setVisible (bool visible)
{
if (visible) {
m_ui.searchComboBox->setFocus(Qt::ActiveWindowFocusReason);
m_ui.searchComboBox->lineEdit()->selectAll();
} else {
m_ui.searchComboBox->setPalette(QPalette());
emit searchTextChanged(QString());
}
QWidget::setVisible(visible);
}
QString SearchBar::searchText() const
{
return m_ui.searchComboBox->currentText();
}
bool SearchBar::caseSensitive() const
{
return m_ui.actionMatchCase->isChecked();
}
bool SearchBar::highlightMatches() const
{
return m_ui.actionHighlightMatch->isChecked();
}
void SearchBar::setSearchText(const QString& text)
{
show();
m_ui.searchComboBox->setEditText(text);
}
void SearchBar::setFoundMatch(bool match)
{
//kDebug() << match;
if (m_ui.searchComboBox->currentText().isEmpty()) {
m_ui.searchComboBox->setPalette(QPalette());
return;
}
KColorScheme::BackgroundRole role = (match ? KColorScheme::PositiveBackground : KColorScheme::NegativeBackground);
QPalette newPal(m_ui.searchComboBox->palette());
KColorScheme::adjustBackground(newPal, role);
m_ui.searchComboBox->setPalette(newPal);
}
void SearchBar::findNext()
{
if (!isVisible())
return;
const QString text (m_ui.searchComboBox->currentText());
if (m_ui.searchComboBox->findText(text) == -1) {
m_ui.searchComboBox->addItem(text);
}
emit searchTextChanged(text);
}
void SearchBar::findPrevious()
{
if (!isVisible())
return;
const QString text (m_ui.searchComboBox->currentText());
if (m_ui.searchComboBox->findText(text) == -1) {
m_ui.searchComboBox->addItem(text);
}
emit searchTextChanged(m_ui.searchComboBox->currentText(), true);
}
void SearchBar::textChanged(const QString &text)
{
if (text.isEmpty()) {
m_ui.searchComboBox->setPalette(QPalette());
m_ui.nextButton->setEnabled(false);
m_ui.previousButton->setEnabled(false);
} else {
m_ui.nextButton->setEnabled(true);
m_ui.previousButton->setEnabled(true);
}
if (m_ui.actionSearchAutomatically->isChecked()) {
emit searchTextChanged(m_ui.searchComboBox->currentText());
}
}
bool SearchBar::event(QEvent* e)
{
// Close the bar when Escape is pressed. Note we cannot
// assign Escape as a shortcut key because it would cause
// a conflict with the Stop button.
if (e->type() == QEvent::ShortcutOverride) {
QKeyEvent* kev = static_cast<QKeyEvent*>(e);
if (kev->key() == Qt::Key_Escape) {
e->accept();
close();
if (m_focusWidget) {
m_focusWidget->setFocus();
m_focusWidget = 0;
}
return true;
}
}
return QWidget::event(e);
}
#include "moc_searchbar.cpp"

View file

@ -1,68 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright 2008 Benjamin C. Meyer <ben@meyerhome.net>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SEARCHBAR_P_H
#define SEARCHBAR_P_H
#include <QWidget>
#include "ui_searchbar.h"
#include <QEvent>
/**
* This is the widget that shows up when the search is initiated.
*/
class SearchBar : public QWidget
{
Q_OBJECT
public:
SearchBar(QWidget *parent = 0);
~SearchBar();
QString searchText() const;
bool caseSensitive() const;
bool highlightMatches() const;
void setFoundMatch(bool match);
void setSearchText(const QString&);
virtual bool event(QEvent* e);
public Q_SLOTS:
virtual void setVisible(bool visible);
void clear();
void findNext();
void findPrevious();
void textChanged(const QString&);
Q_SIGNALS:
void searchTextChanged(const QString& text, bool backward = false);
private:
Ui::SearchBar m_ui;
QPointer<QWidget> m_focusWidget;
};
#endif // SEARCHBAR_P_H

View file

@ -1,168 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SearchBar</class>
<widget class="QWidget" name="SearchBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>564</width>
<height>34</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QToolButton" name="closeButton">
<property name="toolTip">
<string>Close the search bar</string>
</property>
<property name="autoRaise">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="searchInfo">
<property name="text">
<string>&amp;Find:</string>
</property>
<property name="buddy">
<cstring>searchComboBox</cstring>
</property>
</widget>
</item>
<item>
<widget class="KHistoryComboBox" name="searchComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="nextButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Find the next match for the current search phrase</string>
</property>
<property name="text">
<string>&amp;Next</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="previousButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Find the previous match for the current search phrase</string>
</property>
<property name="text">
<string>&amp;Previous</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="optionsButton">
<property name="toolTip">
<string>Find the previous match for the current search phrase</string>
</property>
<property name="text">
<string>&amp;Options</string>
</property>
<property name="popupMode">
<enum>QToolButton::InstantPopup</enum>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::MinimumExpanding</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
<action name="actionMatchCase">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>&amp;Match Case</string>
</property>
</action>
<action name="actionSearchAutomatically">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>&amp;Search As You Type</string>
</property>
</action>
<action name="actionHighlightMatch">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>&amp;Highlight All Matches</string>
</property>
<property name="toolTip">
<string>Highlight Matches</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>KComboBox</class>
<extends>QComboBox</extends>
<header>kcombobox.h</header>
</customwidget>
<customwidget>
<class>KHistoryComboBox</class>
<extends>KComboBox</extends>
<header>khistorycombobox.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>closeButton</sender>
<signal>clicked()</signal>
<receiver>SearchBar</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>16</x>
<y>16</y>
</hint>
<hint type="destinationlabel">
<x>290</x>
<y>16</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View file

@ -1,39 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2011 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "webhistoryinterface.h"
#include <kparts/historyprovider.h>
WebHistoryInterface::WebHistoryInterface(QObject* parent)
:QWebHistoryInterface(parent)
{
}
void WebHistoryInterface::addHistoryEntry(const QString& url)
{
KParts::HistoryProvider::self()->insert(url);
}
bool WebHistoryInterface::historyContains(const QString& url) const
{
return KParts::HistoryProvider::self()->contains(url);
}

View file

@ -1,33 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2011 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBHISTORYINTERFACE_H
#define WEBHISTORYINTERFACE_H
#include <QWebHistoryInterface>
class WebHistoryInterface : public QWebHistoryInterface
{
public:
WebHistoryInterface(QObject* parent = 0);
void addHistoryEntry (const QString & url);
bool historyContains (const QString & url) const;
};
#endif //WEBHISTORYINTERFACE_H

View file

@ -1,998 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2008 - 2010 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "webpage.h"
#include "kwebkitpart.h"
#include "websslinfo.h"
#include "webview.h"
#include "sslinfodialog_p.h"
#include "networkaccessmanager.h"
#include "settings/webkitsettings.h"
#include "webpluginfactory.h"
#include <kdeversion.h>
#include <kmessagebox.h>
#include <kglobalsettings.h>
#include <kglobal.h>
#include <klocale.h>
#include <krun.h>
#include <kshell.h>
#include <kstandarddirs.h>
#include <kauthorized.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <kprotocolinfo.h>
#include <kstringhandler.h>
#include <kio/job.h>
#include <kio/accessmanager.h>
#include <kio/scheduler.h>
#include <kparts/htmlextension.h>
#include <QApplication>
#include <QTextDocument> // Qt::escape
#include <QNetworkReply>
#include <QWebFrame>
#include <QWebElement>
#include <QWebHistory>
#include <QWebSecurityOrigin>
static bool isBlankUrl(const KUrl& url)
{
return (url.isEmpty() || url.url() == QLatin1String("about:blank"));
}
WebPage::WebPage(KWebKitPart *part, QWidget *parent)
:KWebPage(parent, (KWebPage::KPartsIntegration|KWebPage::KWalletIntegration)),
m_kioErrorCode(0),
m_ignoreError(false),
m_noJSOpenWindowCheck(false),
m_part(part)
{
// FIXME: Need a better way to handle request filtering than to inherit
// KIO::Integration::AccessManager...
KDEPrivate::MyNetworkAccessManager *manager = new KDEPrivate::MyNetworkAccessManager(this);
manager->setEmitReadyReadOnMetaDataChange(true);
manager->setCache(0);
QWidget* window = parent ? parent->window() : 0;
if (window) {
manager->setWindow(window);
}
setNetworkAccessManager(manager);
setPluginFactory(new WebPluginFactory(part, this));
setSessionMetaData(QLatin1String("ssl_activate_warnings"), QLatin1String("TRUE"));
// Set font sizes accordingly...
if (view())
WebKitSettings::self()->computeFontSizes(view()->logicalDpiY());
setForwardUnsupportedContent(true);
// Add all KDE's local protocols to QWebSecurityOrigin
Q_FOREACH (const QString& protocol, KProtocolInfo::protocols()) {
// file is already a known local scheme and about must not be added
// to this list since there is about:blank.
if (protocol == QLatin1String("about") || protocol == QLatin1String("file"))
continue;
if (KProtocolInfo::protocolClass(protocol) != QLatin1String(":local"))
continue;
QWebSecurityOrigin::addLocalScheme(protocol);
}
connect(this, SIGNAL(geometryChangeRequested(QRect)),
this, SLOT(slotGeometryChangeRequested(QRect)));
connect(this, SIGNAL(downloadRequested(QNetworkRequest)),
this, SLOT(downloadRequest(QNetworkRequest)));
connect(this, SIGNAL(unsupportedContent(QNetworkReply*)),
this, SLOT(slotUnsupportedContent(QNetworkReply*)));
connect(networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
this, SLOT(slotRequestFinished(QNetworkReply*)));
}
WebPage::~WebPage()
{
//kDebug() << this;
}
const WebSslInfo& WebPage::sslInfo() const
{
return m_sslInfo;
}
void WebPage::setSslInfo (const WebSslInfo& info)
{
m_sslInfo = info;
}
static void checkForDownloadManager(QWidget* widget, QString& cmd)
{
cmd.clear();
KGlobal::locale();
KConfigGroup cfg (KSharedConfig::openConfig("konquerorrc", KConfig::NoGlobals), "HTML Settings");
const QString fileName (cfg.readPathEntry("DownloadManager", QString()));
if (fileName.isEmpty())
return;
const QString exeName = KStandardDirs::findExe(fileName);
if (exeName.isEmpty()) {
KMessageBox::detailedSorry(widget,
i18n("The download manager (%1) could not be found in your installation.", fileName),
i18n("Try to reinstall it and make sure that it is available in $PATH. \n\nThe integration will be disabled."));
cfg.writePathEntry("DownloadManager", QString());
cfg.sync();
return;
}
cmd = exeName;
}
void WebPage::downloadRequest(const QNetworkRequest &request)
{
const KUrl url(request.url());
// Integration with a download manager...
if (!url.isLocalFile()) {
QString managerExe;
checkForDownloadManager(view(), managerExe);
if (!managerExe.isEmpty()) {
//kDebug() << "Calling command" << cmd;
KRun::runCommand((managerExe + QLatin1Char(' ') + KShell::quoteArg(url.url())), view());
return;
}
}
KWebPage::downloadRequest(request);
}
static QString warningIconData()
{
QString data;
QFile f (KIconLoader::global()->iconPath("dialog-warning", -KIconLoader::SizeHuge));
if (f.open(QIODevice::ReadOnly)) {
KMimeType::Ptr mime = KMimeType::mimeType(f.fileName(), KMimeType::ResolveAliases);
data += QLatin1String("data:");
data += mime ? mime->name() : KMimeType::defaultMimeType();
data += QLatin1String(";base64,");
data += f.readAll().toBase64();
f.close();
}
return data;
}
QString WebPage::errorPage(int code, const QString& text, const KUrl& reqUrl) const
{
QString errorName, techName, description;
QStringList causes, solutions;
QByteArray raw = KIO::rawErrorDetail( code, text, &reqUrl );
QDataStream stream(raw);
stream >> errorName >> techName >> description >> causes >> solutions;
QFile file (KStandardDirs::locate ("data", QLatin1String("kwebkitpart/error.html")));
if ( !file.open( QIODevice::ReadOnly ) )
return i18n("<html><body><h3>Unable to display error message</h3>"
"<p>The error template file <em>error.html</em> could not be "
"found.</p></body></html>");
QString html( QLatin1String(file.readAll()) );
html.replace( QLatin1String( "TITLE" ), i18n( "Error: %1", errorName ) );
html.replace( QLatin1String( "DIRECTION" ), QApplication::isRightToLeft() ? "rtl" : "ltr" );
html.replace( QLatin1String( "ICON_PATH" ), warningIconData());
QString doc (QLatin1String( "<h1>" ));
doc += i18n( "The requested operation could not be completed" );
doc += QLatin1String( "</h1><h2>" );
doc += errorName;
doc += QLatin1String( "</h2>" );
if ( !techName.isNull() ) {
doc += QLatin1String( "<h2>" );
doc += i18n( "Technical Reason: %1", techName );
doc += QLatin1String( "</h2>" );
}
doc += QLatin1String( "<h3>" );
doc += i18n( "Details of the Request:" );
doc += QLatin1String( "</h3><ul><li>" );
// escape URL twice: once for i18n, and once for HTML.
doc += i18n( "URL: %1", Qt::escape( Qt::escape( reqUrl.prettyUrl() ) ) );
doc += QLatin1String( "</li><li>" );
const QString protocol (reqUrl.protocol());
if ( !protocol.isNull() ) {
// escape protocol twice: once for i18n, and once for HTML.
doc += i18n( "Protocol: %1", Qt::escape( Qt::escape( protocol ) ) );
doc += QLatin1String( "</li><li>" );
}
doc += i18n( "Date and Time: %1",
KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate) );
doc += QLatin1String( "</li><li>" );
// escape text twice: once for i18n, and once for HTML.
doc += i18n( "Additional Information: %1", Qt::escape( Qt::escape( text ) ) );
doc += QLatin1String( "</li></ul><h3>" );
doc += i18n( "Description:" );
doc += QLatin1String( "</h3><p>" );
doc += Qt::escape( description );
doc += QLatin1String( "</p>" );
if ( causes.count() ) {
doc += QLatin1String( "<h3>" );
doc += i18n( "Possible Causes:" );
doc += QLatin1String( "</h3><ul><li>" );
doc += causes.join( "</li><li>" );
doc += QLatin1String( "</li></ul>" );
}
if ( solutions.count() ) {
doc += QLatin1String( "<h3>" );
doc += i18n( "Possible Solutions:" );
doc += QLatin1String( "</h3><ul><li>" );
doc += solutions.join( "</li><li>" );
doc += QLatin1String( "</li></ul>" );
}
html.replace( QLatin1String("TEXT"), doc );
return html;
}
bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output)
{
switch (extension) {
case QWebPage::ErrorPageExtension: {
if (!m_ignoreError) {
const QWebPage::ErrorPageExtensionOption *extOption = static_cast<const QWebPage::ErrorPageExtensionOption*>(option);
QWebPage::ErrorPageExtensionReturn *extOutput = static_cast<QWebPage::ErrorPageExtensionReturn*>(output);
if (extOutput && extOption && extOption->domain != QWebPage::WebKit) {
extOutput->content = errorPage(m_kioErrorCode, extOption->errorString, extOption->url).toUtf8();
extOutput->baseUrl = extOption->url;
return true;
}
}
break;
}
case QWebPage::ChooseMultipleFilesExtension: {
const QWebPage::ChooseMultipleFilesExtensionOption* extOption = static_cast<const QWebPage::ChooseMultipleFilesExtensionOption*> (option);
QWebPage::ChooseMultipleFilesExtensionReturn *extOutput = static_cast<QWebPage::ChooseMultipleFilesExtensionReturn*>(output);
if (extOutput && extOption && currentFrame() == extOption->parentFrame) {
if (extOption->suggestedFileNames.isEmpty())
extOutput->fileNames = KFileDialog::getOpenFileNames(KUrl(), QString(), view(),
i18n("Choose files to upload"));
else
extOutput->fileNames = KFileDialog::getOpenFileNames(KUrl(extOption->suggestedFileNames.first()),
QString(), view(), i18n("Choose files to upload"));
return true;
}
break;
}
default:
break;
}
return KWebPage::extension(extension, option, output);
}
bool WebPage::supportsExtension(Extension extension) const
{
//kDebug() << extension << m_ignoreError;
switch (extension) {
case QWebPage::ErrorPageExtension:
return (!m_ignoreError);
case QWebPage::ChooseMultipleFilesExtension:
return true;
default:
break;
}
return KWebPage::supportsExtension(extension);
}
QWebPage *WebPage::createWindow(WebWindowType type)
{
// kDebug() << "window type:" << type;
// Crete an instance of NewWindowPage class to capture all the
// information we need to create a new window. See documentation of
// the class for more information...
NewWindowPage* page = new NewWindowPage(type, part(), m_noJSOpenWindowCheck);
m_noJSOpenWindowCheck = false;
return page;
}
// Returns true if the scheme and domain of the two urls match...
static bool domainSchemeMatch(const QUrl& u1, const QUrl& u2)
{
if (u1.scheme() != u2.scheme())
return false;
QStringList u1List = u1.host().split(QLatin1Char('.'), QString::SkipEmptyParts);
QStringList u2List = u2.host().split(QLatin1Char('.'), QString::SkipEmptyParts);
if (qMin(u1List.count(), u2List.count()) < 2)
return false; // better safe than sorry...
while (u1List.count() > 2)
u1List.removeFirst();
while (u2List.count() > 2)
u2List.removeFirst();
return (u1List == u2List);
}
static void resetPluginsLoadedOnDemandFor(QWebPluginFactory* _factory)
{
WebPluginFactory* factory = qobject_cast<WebPluginFactory*>(_factory);
if (factory) {
factory->resetPluginOnDemandList();
}
}
bool WebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type)
{
QUrl reqUrl (request.url());
// Handle "mailto:" url here...
if (handleMailToUrl(reqUrl, type))
return false;
const bool isMainFrameRequest = (frame == mainFrame());
const bool isTypedUrl = property("NavigationTypeUrlEntered").toBool();
/*
NOTE: We use a dynamic QObject property called "NavigationTypeUrlEntered"
to distinguish between requests generated by user entering a url vs those
that were generated programatically through javascript (AJAX requests).
*/
if (isMainFrameRequest && isTypedUrl)
setProperty("NavigationTypeUrlEntered", QVariant());
if (frame) {
// inPage requests are those generarted within the current page through
// link clicks, javascript queries, and button clicks (form submission).
bool inPageRequest = true;
switch (type) {
case QWebPage::NavigationTypeFormSubmitted:
if (!checkFormData(request))
return false;
break;
case QWebPage::NavigationTypeFormResubmitted:
if (!checkFormData(request))
return false;
if (KMessageBox::warningContinueCancel(view(),
i18n("<qt><p>To display the requested web page again, "
"the browser needs to resend information you have "
"previously submitted.</p>"
"<p>If you were shopping online and made a purchase, "
"click the Cancel button to prevent a duplicate purchase."
"Otherwise, click the Continue button to display the web"
"page again.</p>"),
i18n("Resubmit Information")) == KMessageBox::Cancel) {
return false;
}
break;
case QWebPage::NavigationTypeBackOrForward:
// If history navigation is locked, ignore all such requests...
if (property("HistoryNavigationLocked").toBool()) {
setProperty("HistoryNavigationLocked", QVariant());
kDebug() << "Rejected history navigation because 'HistoryNavigationLocked' property is set!";
return false;
}
//kDebug() << "Navigating to item (" << history()->currentItemIndex()
// << "of" << history()->count() << "):" << history()->currentItem().url();
inPageRequest = false;
if (!isBlankUrl(reqUrl)) {
resetPluginsLoadedOnDemandFor(pluginFactory());
}
break;
case QWebPage::NavigationTypeReload:
setRequestMetaData(QLatin1String("cache"), QLatin1String("reload"));
inPageRequest = false;
if (!isBlankUrl(reqUrl)) {
resetPluginsLoadedOnDemandFor(pluginFactory());
}
break;
case QWebPage::NavigationTypeOther:
inPageRequest = !isTypedUrl;
if (isTypedUrl && !isBlankUrl(reqUrl)) {
resetPluginsLoadedOnDemandFor(pluginFactory());
}
break;
default:
break;
}
if (inPageRequest) {
if (!checkLinkSecurity(request, type))
return false;
if (m_sslInfo.isValid())
setRequestMetaData(QLatin1String("ssl_was_in_use"), QLatin1String("TRUE"));
}
// Set the "main_frame_request" meta-data to aid SSL verification in KIO.
setRequestMetaData(QLatin1String("main_frame_request"), (isMainFrameRequest ? QLatin1String("TRUE") : QLatin1String("FALSE")));
// Insert the request into the queue...
reqUrl.setUserInfo(QString());
m_requestQueue << reqUrl;
} else {
// If request came from javascript, set m_noJSOpenWindowCheck to true.
m_noJSOpenWindowCheck = (!isTypedUrl && type != QWebPage::NavigationTypeOther);
}
// Honor the enabling/disabling of plugins per host.
settings()->setAttribute(QWebSettings::PluginsEnabled, WebKitSettings::self()->isPluginsEnabled(reqUrl.host()));
return KWebPage::acceptNavigationRequest(frame, request, type);
}
QString WebPage::userAgentForUrl(const QUrl& url) const
{
QString userAgent = KWebPage::userAgentForUrl(url);
// Remove the useless "U" if it is present.
const int index = userAgent.indexOf(QLatin1String(" U;"), -1, Qt::CaseInsensitive);
if (index > -1)
userAgent.remove(index, 3);
return userAgent.trimmed();
}
static int errorCodeFromReply(QNetworkReply* reply)
{
// First check if there is a KIO error code sent back and use that,
// if not attempt to convert QNetworkReply's NetworkError to KIO::Error.
QVariant attr = reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::KioError));
if (attr.isValid() && attr.type() == QVariant::Int)
return attr.toInt();
switch (reply->error()) {
case QNetworkReply::ConnectionRefusedError:
return KIO::ERR_COULD_NOT_CONNECT;
case QNetworkReply::HostNotFoundError:
return KIO::ERR_UNKNOWN_HOST;
case QNetworkReply::TimeoutError:
return KIO::ERR_SERVER_TIMEOUT;
case QNetworkReply::OperationCanceledError:
return KIO::ERR_USER_CANCELED;
case QNetworkReply::ProxyNotFoundError:
return KIO::ERR_UNKNOWN_PROXY_HOST;
case QNetworkReply::ContentAccessDenied:
return KIO::ERR_ACCESS_DENIED;
case QNetworkReply::ContentOperationNotPermittedError:
return KIO::ERR_WRITE_ACCESS_DENIED;
case QNetworkReply::ContentNotFoundError:
return KIO::ERR_NO_CONTENT;
case QNetworkReply::AuthenticationRequiredError:
return KIO::ERR_COULD_NOT_AUTHENTICATE;
case QNetworkReply::ProtocolUnknownError:
return KIO::ERR_UNSUPPORTED_PROTOCOL;
case QNetworkReply::ProtocolInvalidOperationError:
return KIO::ERR_UNSUPPORTED_ACTION;
case QNetworkReply::UnknownNetworkError:
return KIO::ERR_UNKNOWN;
case QNetworkReply::NoError:
default:
break;
}
return 0;
}
KWebKitPart* WebPage::part() const
{
return m_part.data();
}
void WebPage::setPart(KWebKitPart* part)
{
m_part = part;
}
void WebPage::slotRequestFinished(QNetworkReply *reply)
{
Q_ASSERT(reply);
QUrl requestUrl (reply->request().url());
requestUrl.setUserInfo(QString());
// Disregards requests that are not in the request queue...
if (!m_requestQueue.removeOne(requestUrl))
return;
QWebFrame* frame = qobject_cast<QWebFrame *>(reply->request().originatingObject());
if (!frame)
return;
const bool shouldResetSslInfo = (m_sslInfo.isValid() && !domainSchemeMatch(requestUrl, m_sslInfo.url()));
// Only deal with non-redirect responses...
const QVariant redirectVar = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
const bool isMainFrameRequest = (frame == mainFrame());
if (isMainFrameRequest && redirectVar.isValid()) {
m_sslInfo.restoreFrom(reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)),
reply->url(), shouldResetSslInfo);
return;
}
const int errCode = errorCodeFromReply(reply);
kDebug() << frame << "is main frame request?" << isMainFrameRequest << requestUrl;
// Handle any error...
switch (errCode) {
case 0:
case KIO::ERR_NO_CONTENT:
if (isMainFrameRequest) {
m_sslInfo.restoreFrom(reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)),
reply->url(), shouldResetSslInfo);
setPageJScriptPolicy(reply->url());
}
break;
case KIO::ERR_ABORTED:
case KIO::ERR_USER_CANCELED: // Do nothing if request is cancelled/aborted
//kDebug() << "User aborted request!";
m_ignoreError = true;
emit loadAborted(QUrl());
return;
// Handle the user clicking on a link that refers to a directory
// Since KIO cannot automatically convert a GET request to a LISTDIR one.
case KIO::ERR_IS_DIRECTORY:
m_ignoreError = true;
emit loadAborted(reply->url());
return;
default:
// Make sure the saveFrameStateRequested signal is emitted so
// the page can restored properly.
if (isMainFrameRequest)
emit saveFrameStateRequested(frame, 0);
m_ignoreError = (reply->attribute(QNetworkRequest::User).toInt() == QNetworkReply::ContentAccessDenied);
m_kioErrorCode = errCode;
break;
}
if (isMainFrameRequest) {
const WebPageSecurity security = (m_sslInfo.isValid() ? PageEncrypted : PageUnencrypted);
emit m_part->browserExtension()->setPageSecurity(security);
}
}
void WebPage::slotUnsupportedContent(QNetworkReply* reply)
{
//kDebug() << reply->url();
QString mimeType;
KIO::MetaData metaData;
KIO::AccessManager::putReplyOnHold(reply);
QString downloadCmd;
checkForDownloadManager(view(), downloadCmd);
if (!downloadCmd.isEmpty()) {
reply->setProperty("DownloadManagerExe", downloadCmd);
}
if (KWebPage::handleReply(reply, &mimeType, &metaData)) {
reply->deleteLater();
if (qobject_cast<NewWindowPage*>(this) && isBlankUrl(m_part->url())) {
m_part->closeUrl();
if (m_part->arguments().metaData().contains(QLatin1String("new-window"))) {
m_part->widget()->topLevelWidget()->close();
} else {
delete m_part;
}
}
return;
}
//kDebug() << "mimetype=" << mimeType << "metadata:" << metaData;
if (reply->request().originatingObject() == this->mainFrame()) {
KParts::OpenUrlArguments args;
args.setMimeType(mimeType);
args.metaData() = metaData;
emit m_part->browserExtension()->openUrlRequest(reply->url(), args, KParts::BrowserArguments());
return;
}
reply->deleteLater();
}
void WebPage::slotGeometryChangeRequested(const QRect & rect)
{
const QString host = mainFrame()->url().host();
// NOTE: If a new window was created from another window which is in
// maximized mode and its width and/or height were not specified at the
// time of its creation, which is always the case in QWebPage::createWindow,
// then any move operation will seem not to work. That is because the new
// window will be in maximized mode where moving it will not be possible...
if (WebKitSettings::self()->windowMovePolicy(host) == KParts::HtmlSettingsInterface::JSWindowMoveAllow &&
(view()->x() != rect.x() || view()->y() != rect.y()))
emit m_part->browserExtension()->moveTopLevelWidget(rect.x(), rect.y());
const int height = rect.height();
const int width = rect.width();
// parts of following code are based on kjs_window.cpp
// Security check: within desktop limits and bigger than 100x100 (per spec)
if (width < 100 || height < 100) {
kWarning() << "Window resize refused, window would be too small (" << width << "," << height << ")";
return;
}
QRect sg = KGlobalSettings::desktopGeometry(view());
if (width > sg.width() || height > sg.height()) {
kWarning() << "Window resize refused, window would be too big (" << width << "," << height << ")";
return;
}
if (WebKitSettings::self()->windowResizePolicy(host) == KParts::HtmlSettingsInterface::JSWindowResizeAllow) {
//kDebug() << "resizing to " << width << "x" << height;
emit m_part->browserExtension()->resizeTopLevelWidget(width, height);
}
// If the window is out of the desktop, move it up/left
// (maybe we should use workarea instead of sg, otherwise the window ends up below kicker)
const int right = view()->x() + view()->frameGeometry().width();
const int bottom = view()->y() + view()->frameGeometry().height();
int moveByX = 0, moveByY = 0;
if (right > sg.right())
moveByX = - right + sg.right(); // always <0
if (bottom > sg.bottom())
moveByY = - bottom + sg.bottom(); // always <0
if ((moveByX || moveByY) && WebKitSettings::self()->windowMovePolicy(host) == KParts::HtmlSettingsInterface::JSWindowMoveAllow)
emit m_part->browserExtension()->moveTopLevelWidget(view()->x() + moveByX, view()->y() + moveByY);
}
bool WebPage::checkLinkSecurity(const QNetworkRequest &req, NavigationType type) const
{
return true;
}
bool WebPage::checkFormData(const QNetworkRequest &req) const
{
const QString scheme (req.url().scheme());
if (m_sslInfo.isValid() &&
!scheme.compare(QLatin1String("https")) && !scheme.compare(QLatin1String("mailto")) &&
(KMessageBox::warningContinueCancel(0,
i18n("Warning: This is a secure form "
"but it is attempting to send "
"your data back unencrypted.\n"
"A third party may be able to "
"intercept and view this "
"information.\nAre you sure you "
"want to send the data unencrypted?"),
i18n("Network Transmission"),
KGuiItem(i18n("&Send Unencrypted"))) == KMessageBox::Cancel)) {
return false;
}
if (scheme.compare(QLatin1String("mailto")) == 0 &&
(KMessageBox::warningContinueCancel(0, i18n("This site is attempting to "
"submit form data via email.\n"
"Do you want to continue?"),
i18n("Network Transmission"),
KGuiItem(i18n("&Send Email")),
KStandardGuiItem::cancel(),
"WarnTriedEmailSubmit") == KMessageBox::Cancel)) {
return false;
}
return true;
}
// Sanitizes the "mailto:" url, e.g. strips out any "attach" parameters.
static QUrl sanitizeMailToUrl(const QUrl &url, QStringList& files) {
QUrl sanitizedUrl;
// NOTE: This is necessary to ensure we can properly use QUrl's query
// related APIs to process 'mailto:' urls of form 'mailto:foo@bar.com'.
if (url.hasQuery())
sanitizedUrl = url;
else
sanitizedUrl = QUrl(url.scheme() + QLatin1String(":?") + url.path());
QListIterator<QPair<QString, QString> > it (sanitizedUrl.queryItems());
sanitizedUrl.setEncodedQuery(QByteArray()); // clear out the query componenet
while (it.hasNext()) {
QPair<QString, QString> queryItem = it.next();
if (queryItem.first.contains(QLatin1Char('@')) && queryItem.second.isEmpty()) {
// ### DF: this hack breaks mailto:faure@kde.org, kmail doesn't expect mailto:?to=faure@kde.org
queryItem.second = queryItem.first;
queryItem.first = "to";
} else if (QString::compare(queryItem.first, QLatin1String("attach"), Qt::CaseInsensitive) == 0) {
files << queryItem.second;
continue;
}
sanitizedUrl.addQueryItem(queryItem.first, queryItem.second);
}
return sanitizedUrl;
}
bool WebPage::handleMailToUrl (const QUrl &url, NavigationType type) const
{
if (QString::compare(url.scheme(), QLatin1String("mailto"), Qt::CaseInsensitive) == 0) {
QStringList files;
QUrl mailtoUrl (sanitizeMailToUrl(url, files));
switch (type) {
case QWebPage::NavigationTypeLinkClicked:
if (!files.isEmpty() && KMessageBox::warningContinueCancelList(0,
i18n("<qt>Do you want to allow this site to attach "
"the following files to the email message?</qt>"),
files, i18n("Email Attachment Confirmation"),
KGuiItem(i18n("&Allow attachments")),
KGuiItem(i18n("&Ignore attachments")), QLatin1String("WarnEmailAttachment")) == KMessageBox::Continue) {
// Re-add the attachments...
QStringListIterator filesIt (files);
while (filesIt.hasNext()) {
mailtoUrl.addQueryItem(QLatin1String("attach"), filesIt.next());
}
}
break;
case QWebPage::NavigationTypeFormSubmitted:
case QWebPage::NavigationTypeFormResubmitted:
if (!files.isEmpty()) {
KMessageBox::information(0, i18n("This site attempted to attach a file from your "
"computer in the form submission. The attachment "
"was removed for your protection."),
i18n("Attachment Removed"), "InfoTriedAttach");
}
break;
default:
break;
}
//kDebug() << "Emitting openUrlRequest with " << mailtoUrl;
emit m_part->browserExtension()->openUrlRequest(mailtoUrl);
return true;
}
return false;
}
void WebPage::setPageJScriptPolicy(const QUrl &url)
{
const QString hostname (url.host());
settings()->setAttribute(QWebSettings::JavascriptEnabled,
WebKitSettings::self()->isJavaScriptEnabled(hostname));
const KParts::HtmlSettingsInterface::JSWindowOpenPolicy policy = WebKitSettings::self()->windowOpenPolicy(hostname);
settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,
(policy != KParts::HtmlSettingsInterface::JSWindowOpenDeny &&
policy != KParts::HtmlSettingsInterface::JSWindowOpenSmart));
}
/************************************* Begin NewWindowPage ******************************************/
NewWindowPage::NewWindowPage(WebWindowType type, KWebKitPart* part, bool disableJSOpenwindowCheck, QWidget* parent)
:WebPage(part, parent) , m_type(type) , m_createNewWindow(true)
, m_disableJSOpenwindowCheck(disableJSOpenwindowCheck)
{
Q_ASSERT_X (part, "NewWindowPage", "Must specify a valid KPart");
connect(this, SIGNAL(menuBarVisibilityChangeRequested(bool)),
this, SLOT(slotMenuBarVisibilityChangeRequested(bool)));
connect(this, SIGNAL(toolBarVisibilityChangeRequested(bool)),
this, SLOT(slotToolBarVisibilityChangeRequested(bool)));
connect(this, SIGNAL(statusBarVisibilityChangeRequested(bool)),
this, SLOT(slotStatusBarVisibilityChangeRequested(bool)));
connect(mainFrame(), SIGNAL(loadFinished(bool)), this, SLOT(slotLoadFinished(bool)));
}
NewWindowPage::~NewWindowPage()
{
//kDebug() << this;
}
bool NewWindowPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type)
{
// kDebug() << "url:" << request.url() << ",type:" << type << ",frame:" << frame;
if (m_createNewWindow) {
const KUrl reqUrl (request.url());
if (!m_disableJSOpenwindowCheck) {
const KParts::HtmlSettingsInterface::JSWindowOpenPolicy policy = WebKitSettings::self()->windowOpenPolicy(reqUrl.host());
switch (policy) {
case KParts::HtmlSettingsInterface::JSWindowOpenDeny:
// TODO: Implement support for dealing with blocked pop up windows.
this->deleteLater();
return false;
case KParts::HtmlSettingsInterface::JSWindowOpenAsk: {
const QString message = (reqUrl.isEmpty() ?
i18n("This site is requesting to open a new popup window.\n"
"Do you want to allow this?") :
i18n("<qt>This site is requesting to open a popup window to"
"<p>%1</p><br/>Do you want to allow this?</qt>",
KStringHandler::rsqueeze(Qt::escape(reqUrl.prettyUrl()), 100)));
if (KMessageBox::questionYesNo(view(), message,
i18n("Javascript Popup Confirmation"),
KGuiItem(i18n("Allow")),
KGuiItem(i18n("Do Not Allow"))) == KMessageBox::No) {
// TODO: Implement support for dealing with blocked pop up windows.
this->deleteLater();
return false;
}
break;
}
default:
break;
}
}
if (!part() && frame != mainFrame() && type != QWebPage::NavigationTypeOther)
return false;
// Browser args...
KParts::BrowserArguments bargs;
bargs.frameName = mainFrame()->frameName();
if (m_type == WebModalDialog)
bargs.setForcesNewWindow(true);
// OpenUrl args...
KParts::OpenUrlArguments uargs;
uargs.setMimeType(QLatin1String("text/html"));
uargs.setActionRequestedByUser(false);
// Window args...
KParts::WindowArgs wargs (m_windowArgs);
KParts::ReadOnlyPart* newWindowPart =0;
part()->browserExtension()->createNewWindow(KUrl(), uargs, bargs, wargs, &newWindowPart);
kDebug() << "Created new window" << newWindowPart;
if (!newWindowPart) {
return false;
} else if (newWindowPart->widget()->topLevelWidget() != part()->widget()->topLevelWidget()) {
KParts::OpenUrlArguments args;
args.metaData().insert(QLatin1String("new-window"), QLatin1String("true"));
newWindowPart->setArguments(args);
}
// Get the webview...
KWebKitPart* webkitPart = qobject_cast<KWebKitPart*>(newWindowPart);
WebView* webView = webkitPart ? qobject_cast<WebView*>(webkitPart->view()) : 0;
// If the newly created window is NOT a webkitpart...
if (!webView) {
newWindowPart->openUrl(reqUrl);
this->deleteLater();
return false;
}
// Reparent this page to the new webview to prevent memory leaks.
setParent(webView);
// Replace the webpage of the new webview with this one. Nice trick...
webView->setPage(this);
// Set the new part as the one this page will use going forward.
setPart(webkitPart);
// Connect all the signals from this page to the slots in the new part.
webkitPart->connectWebPageSignals(this);
//Set the create new window flag to false...
m_createNewWindow = false;
}
return WebPage::acceptNavigationRequest(frame, request, type);
}
void NewWindowPage::slotGeometryChangeRequested(const QRect & rect)
{
if (!rect.isValid())
return;
if (!m_createNewWindow) {
WebPage::slotGeometryChangeRequested(rect);
return;
}
m_windowArgs.setX(rect.x());
m_windowArgs.setY(rect.y());
m_windowArgs.setWidth(qMax(rect.width(), 100));
m_windowArgs.setHeight(qMax(rect.height(), 100));
}
void NewWindowPage::slotMenuBarVisibilityChangeRequested(bool visible)
{
//kDebug() << visible;
m_windowArgs.setMenuBarVisible(visible);
}
void NewWindowPage::slotStatusBarVisibilityChangeRequested(bool visible)
{
//kDebug() << visible;
m_windowArgs.setStatusBarVisible(visible);
}
void NewWindowPage::slotToolBarVisibilityChangeRequested(bool visible)
{
//kDebug() << visible;
m_windowArgs.setToolBarsVisible(visible);
}
void NewWindowPage::slotLoadFinished(bool ok)
{
Q_UNUSED(ok)
//kDebug() << ok;
if (!m_createNewWindow)
return;
// Browser args...
KParts::BrowserArguments bargs;
bargs.frameName = mainFrame()->frameName();
if (m_type == WebModalDialog)
bargs.setForcesNewWindow(true);
// OpenUrl args...
KParts::OpenUrlArguments uargs;
uargs.setMimeType(QLatin1String("text/html"));
uargs.setActionRequestedByUser(false);
// Window args...
KParts::WindowArgs wargs (m_windowArgs);
KParts::ReadOnlyPart* newWindowPart =0;
part()->browserExtension()->createNewWindow(KUrl(), uargs, bargs, wargs, &newWindowPart);
kDebug() << "Created new window" << newWindowPart;
// Get the webview...
KWebKitPart* webkitPart = newWindowPart ? qobject_cast<KWebKitPart*>(newWindowPart) : 0;
WebView* webView = webkitPart ? qobject_cast<WebView*>(webkitPart->view()) : 0;
if (webView) {
// if a new window is created, set a new window meta-data flag.
if (newWindowPart->widget()->topLevelWidget() != part()->widget()->topLevelWidget()) {
KParts::OpenUrlArguments args;
args.metaData().insert(QLatin1String("new-window"), QLatin1String("true"));
newWindowPart->setArguments(args);
}
// Reparent this page to the new webview to prevent memory leaks.
setParent(webView);
// Replace the webpage of the new webview with this one. Nice trick...
webView->setPage(this);
// Set the new part as the one this page will use going forward.
setPart(webkitPart);
// Connect all the signals from this page to the slots in the new part.
webkitPart->connectWebPageSignals(this);
}
//Set the create new window flag to false...
m_createNewWindow = false;
}
/****************************** End NewWindowPage *************************************************/

View file

@ -1,191 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBPAGE_H
#define WEBPAGE_H
#include "websslinfo.h"
#include <kwebpage.h>
#include <kparts/browserextension.h>
#include <QMultiHash>
class KUrl;
class WebSslInfo;
class KWebKitPart;
class QWebFrame;
class WebPage : public KWebPage
{
Q_OBJECT
public:
explicit WebPage(KWebKitPart *wpart, QWidget *parent = 0);
~WebPage();
/**
* Returns the SSL information for the current page.
*
* @see WebSslInfo.
*/
const WebSslInfo& sslInfo() const;
/**
* Sets the page's SSL information to @p other.
*
* @see WebSslInfo
*/
void setSslInfo (const WebSslInfo &other);
/**
* Reimplemented for internal reasons. The API is not affected.
*
* @internal
* @see KWebPage::downloadRequest.
*/
void downloadRequest(const QNetworkRequest &request);
/**
* Returns the error page associated with the KIO error @p code.
*
* @param text the error message.
* @param url the url where the error was encountered.
*
* @return html error page.
*/
QString errorPage(int code, const QString& text, const KUrl& url) const;
/**
* Re-implemented to handle ErrorPageExtension.
*
* @see QWebPage::extension()
*/
bool extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output);
/**
* Re-implemented to handle ErrorPageExtension.
*
* @see QWebPage::supportsExtension()
*/
bool supportsExtension(Extension extension) const;
Q_SIGNALS:
/**
* This signal is emitted whenever a user cancels/aborts a load resource
* request.
*/
void loadAborted(const KUrl &url);
protected:
/**
* Returns the webkit part in use by this object.
* @internal
*/
KWebKitPart* part() const;
/**
* Sets the webkit part to be used by this object.
* @internal
*/
void setPart(KWebKitPart*);
/**
* Reimplemented for internal reasons, the API is not affected.
* @internal
*/
virtual QWebPage* createWindow(WebWindowType type);
/**
* Reimplemented for internal reasons, the API is not affected.
* @internal
*/
virtual bool acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest& request, NavigationType type);
/**
* Reimplemented for internal reasons, the API is not affected.
* @internal
*/
virtual QString userAgentForUrl(const QUrl& url) const;
protected Q_SLOTS:
void slotRequestFinished(QNetworkReply* reply);
void slotUnsupportedContent(QNetworkReply* reply);
virtual void slotGeometryChangeRequested(const QRect& rect);
private:
bool checkLinkSecurity(const QNetworkRequest& req, NavigationType type) const;
bool checkFormData(const QNetworkRequest& req) const;
bool handleMailToUrl (const QUrl& , NavigationType type) const;
void setPageJScriptPolicy(const QUrl& url);
private:
enum WebPageSecurity { PageUnencrypted, PageEncrypted, PageMixed };
int m_kioErrorCode;
bool m_ignoreError;
bool m_noJSOpenWindowCheck;
WebSslInfo m_sslInfo;
QList<QUrl> m_requestQueue;
QPointer<KWebKitPart> m_part;
};
/**
* This is a fake implementation of WebPage to workaround the ugly API used
* to request for the creation of a new window from javascript in QtWebKit.
*
* The KPart API for creating new windows requires all the information about the
* new window up front. Unfortunately QWebPage::createWindow function does not
* provide any of these necessary information except for the window type. All
* the other necessary information is emitted as signals instead! Hence, the
* need for this class to collect all of the necessary information, such as
* window name, size and position, before calling KPart's createNewWindow
* function.
*/
class NewWindowPage : public WebPage
{
Q_OBJECT
public:
NewWindowPage(WebWindowType windowType, KWebKitPart* part,
bool disableJSWindowOpenCheck= false, QWidget* parent = 0);
virtual ~NewWindowPage();
protected:
virtual bool acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest& request, NavigationType type);
private Q_SLOTS:
void slotGeometryChangeRequested(const QRect& rect);
void slotMenuBarVisibilityChangeRequested(bool visible);
void slotStatusBarVisibilityChangeRequested(bool visible);
void slotToolBarVisibilityChangeRequested(bool visible);
void slotLoadFinished(bool);
private:
KParts::WindowArgs m_windowArgs;
WebWindowType m_type;
bool m_createNewWindow;
bool m_disableJSOpenwindowCheck;
};
#endif // WEBPAGE_H

View file

@ -1,274 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2012 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "webpluginfactory.h"
#include "webpage.h"
#include "kwebkitpart.h"
#include "settings/webkitsettings.h"
#include <kdebug.h>
#include <kconfiggroup.h>
#include <ksharedconfig.h>
#include <klocalizedstring.h>
#include <kparts/part.h>
#include <kparts/browserextension.h>
#include <kparts/scriptableextension.h>
#include <QHBoxLayout>
#include <QSpacerItem>
#include <QPushButton>
#include <QWebFrame>
#include <QWebView>
#include <QWebElement>
static QWebView* webViewFrom(QWidget* widget)
{
QWidget* parent = widget;
QWebView *view = 0;
while (parent) {
if (QWebView *aView = qobject_cast<QWebView*>(parent)) {
view = aView;
break;
}
parent = parent->parentWidget();
}
return view;
}
FakePluginWidget::FakePluginWidget (uint id, const QUrl& url, const QString& mimeType, QWidget* parent)
:QWidget(parent)
,m_swapping(false)
,m_updateScrollPosition(false)
,m_mimeType(mimeType)
,m_id(id)
{
QHBoxLayout* horizontalLayout = new QHBoxLayout;
setLayout(horizontalLayout);
QSpacerItem* horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
horizontalLayout->addSpacerItem(horizontalSpacer);
QPushButton* startPluginButton = new QPushButton(this);
startPluginButton->setText(i18n("Start Plugin"));
horizontalLayout->addWidget(startPluginButton);
horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
horizontalLayout->addSpacerItem(horizontalSpacer);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint)));
connect(startPluginButton, SIGNAL(clicked()), this, SLOT(load()));
setToolTip(url.toString());
}
void FakePluginWidget::loadAll()
{
load (true);
}
void FakePluginWidget::load (bool loadAll)
{
QWebView *view = webViewFrom(parentWidget());
if (!view)
return;
// WORKAROUND: For some reason, when we load on demand plugins the scroll
// position gets utterly screwed up and reset to the beginning of the
// document. This is an effort to workaround that issue.
connect(view->page(), SIGNAL(scrollRequested(int,int,QRect)),
this, SLOT(updateScrollPoisition(int,int,QRect)), Qt::QueuedConnection);
hide();
m_swapping = true;
QList<QWebFrame*> frames;
frames.append(view->page()->mainFrame());
QString selector (QLatin1String("applet:not([type]),embed:not([type]),object:not([type]),applet[type=\""));
selector += m_mimeType;
selector += QLatin1String("\"],embed[type=\"");
selector += m_mimeType;
selector += QLatin1String("\"],object[type=\"");
selector += m_mimeType;
selector += QLatin1String("\"]");
while (!frames.isEmpty()) {
bool loaded = false;
QWebFrame *frame = frames.takeFirst();
QWebElement docElement = frame->documentElement();
QWebElementCollection elements = docElement.findAll(selector);
Q_FOREACH (QWebElement element, elements) {
if (loadAll || element.evaluateJavaScript(QLatin1String("this.swapping")).toBool()) {
QWebElement substitute = element.clone();
emit pluginLoaded(m_id);
m_updateScrollPosition = true;
element.replace(substitute);
deleteLater();
if (!loadAll) {
loaded = true;
break; // Found the one plugin we wanted to start so exit loop.
}
}
}
if (loaded && !loadAll) {
break; // Loading only one item, exit the outer loop as well...
}
frames += frame->childFrames();
}
m_swapping = false;
}
void FakePluginWidget::showContextMenu(const QPoint&)
{
// TODO: Implement context menu, e.g. load all and configure plugins.
}
void FakePluginWidget::updateScrollPoisition (int dx, int dy, const QRect& rect)
{
if (m_updateScrollPosition) {
QWebView* view = webViewFrom(parentWidget());
if (view)
view->page()->mainFrame()->setScrollPosition(QPoint(dx, dy));
}
Q_UNUSED(rect);
}
WebPluginFactory::WebPluginFactory (KWebKitPart* part, QObject* parent)
: KWebPluginFactory (parent)
, mPart (part)
{
}
static uint pluginId(const QUrl& url, const QStringList& argumentNames, const QStringList& argumentValues)
{
static const char* properties[] = {"src","data","width","height","type","id","name",0};
QString signature = url.toString();
for (int i = 0; properties[i]; ++i) {
const int index = argumentNames.indexOf(properties[i]);
if (index > -1) {
signature += argumentNames.at(index);
signature += QLatin1Char('=');
signature += argumentValues.at(index);
}
}
return qHash(signature);
}
QObject* WebPluginFactory::create (const QString& _mimeType, const QUrl& url, const QStringList& argumentNames, const QStringList& argumentValues) const
{
//kDebug() << _mimeType << url << argumentNames;
QString mimeType (_mimeType.trimmed());
if (mimeType.isEmpty()) {
extractGuessedMimeType (url, &mimeType);
}
const bool noPluginHandling = WebKitSettings::self()->isInternalPluginHandlingDisabled();
if (!noPluginHandling && WebKitSettings::self()->isLoadPluginsOnDemandEnabled()) {
const uint id = pluginId(url, argumentNames, argumentValues);
if (!mPluginsLoadedOnDemand.contains(id)) {
FakePluginWidget* widget = new FakePluginWidget(id, url, mimeType);
connect(widget, SIGNAL(pluginLoaded(uint)), this, SLOT(loadedPlugin(uint)));
return widget;
}
}
Q_ASSERT(mPart); // should never happen!!
KParts::ReadOnlyPart* part = 0;
QWebView* view = (mPart ? mPart->view() : 0);
if (noPluginHandling || !excludedMimeType(mimeType)) {
QWebFrame* frame = (view ? view->page()->currentFrame() : 0);
if (frame) {
part = createPartInstanceFrom(mimeType, argumentNames, argumentValues, view, frame);
}
}
kDebug() << "Asked for" << mimeType << "plugin, got" << part;
if (part) {
connect (part->browserExtension(), SIGNAL (openUrlNotify()),
mPart->browserExtension(), SIGNAL (openUrlNotify()));
connect (part->browserExtension(), SIGNAL (openUrlRequest (KUrl, KParts::OpenUrlArguments, KParts::BrowserArguments)),
mPart->browserExtension(), SIGNAL (openUrlRequest (KUrl, KParts::OpenUrlArguments, KParts::BrowserArguments)));
// Check if this part is scriptable
KParts::ScriptableExtension* scriptExt = KParts::ScriptableExtension::childObject(part);
if (!scriptExt) {
// Try to fall back to LiveConnectExtension compat
KParts::LiveConnectExtension* lc = KParts::LiveConnectExtension::childObject(part);
if (lc) {
scriptExt = KParts::ScriptableExtension::adapterFromLiveConnect(part, lc);
}
}
if (scriptExt) {
scriptExt->setHost(KParts::ScriptableExtension::childObject(mPart));
}
QMap<QString, QString> metaData = part->arguments().metaData();
QString urlStr = url.toString (QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment);
metaData.insert ("PropagateHttpHeader", "true");
metaData.insert ("referrer", urlStr);
metaData.insert ("cross-domain", urlStr);
metaData.insert ("main_frame_request", "TRUE");
metaData.insert ("ssl_activate_warnings", "TRUE");
KWebPage *page = (view ? qobject_cast<KWebPage*>(view->page()) : 0);
if (page) {
const QString scheme = page->currentFrame()->url().scheme();
if (page && (QString::compare (scheme, QLatin1String ("https"), Qt::CaseInsensitive) == 0 ||
QString::compare (scheme, QLatin1String ("webdavs"), Qt::CaseInsensitive) == 0))
metaData.insert ("ssl_was_in_use", "TRUE");
else
metaData.insert ("ssl_was_in_use", "FALSE");
}
KParts::OpenUrlArguments openUrlArgs = part->arguments();
openUrlArgs.metaData() = metaData;
openUrlArgs.setMimeType(mimeType);
part->setArguments(openUrlArgs);
QMetaObject::invokeMethod(part, "openUrl", Qt::QueuedConnection, Q_ARG(KUrl, KUrl(url)));
return part->widget();
}
return 0;
}
void WebPluginFactory::loadedPlugin (uint id)
{
mPluginsLoadedOnDemand << id;
}
void WebPluginFactory::resetPluginOnDemandList()
{
mPluginsLoadedOnDemand.clear();
}

View file

@ -1,73 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2012 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBPLUGINFACTORY_H
#define WEBPLUGINFACTORY_H
#include <kwebpluginfactory.h>
#include <QWidget>
#include <QPointer>
class KWebKitPart;
#include <QPoint>
class FakePluginWidget : public QWidget
{
Q_OBJECT
Q_PROPERTY(bool swapping READ swapping)
public:
FakePluginWidget(uint id, const QUrl& url, const QString& mimeType, QWidget* parent = 0);
bool swapping() const { return m_swapping; }
Q_SIGNALS:
void pluginLoaded(uint);
private Q_SLOTS:
void loadAll();
void load(bool loadAll = false);
void showContextMenu(const QPoint&);
void updateScrollPoisition(int, int, const QRect&);
private:
bool m_swapping;
bool m_updateScrollPosition;
QString m_mimeType;
uint m_id;
};
class WebPluginFactory : public KWebPluginFactory
{
Q_OBJECT
public:
WebPluginFactory (KWebKitPart* part, QObject* parent = 0);
virtual QObject* create (const QString&, const QUrl&, const QStringList&, const QStringList&) const;
void resetPluginOnDemandList();
private Q_SLOTS:
void loadedPlugin(uint);
private:
QPointer<KWebKitPart> mPart;
mutable QList<uint> mPluginsLoadedOnDemand;
};
#endif

View file

@ -1,224 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "websslinfo.h"
#include <QVariant>
class WebSslInfo::WebSslInfoPrivate
{
public:
WebSslInfoPrivate()
: usedCipherBits(0), supportedCipherBits(0) {}
QUrl url;
QString ciphers;
QString protocol;
QString certErrors;
QHostAddress peerAddress;
QHostAddress parentAddress;
QList<QSslCertificate> certificateChain;
int usedCipherBits;
int supportedCipherBits;
};
WebSslInfo::WebSslInfo()
:d(new WebSslInfo::WebSslInfoPrivate)
{
}
WebSslInfo::WebSslInfo(const WebSslInfo& other)
:d(new WebSslInfo::WebSslInfoPrivate)
{
*this = other;
}
WebSslInfo::~WebSslInfo()
{
delete d;
d = 0;
}
bool WebSslInfo::isValid() const
{
return (d ? !d->peerAddress.isNull() : false);
}
QUrl WebSslInfo::url() const
{
return (d ? d->url : QUrl());
}
QHostAddress WebSslInfo::parentAddress() const
{
return (d ? d->parentAddress : QHostAddress());
}
QHostAddress WebSslInfo::peerAddress() const
{
return (d ? d->peerAddress : QHostAddress());
}
QString WebSslInfo::protocol() const
{
return (d ? d->protocol : QString());
}
QString WebSslInfo::ciphers() const
{
return (d ? d->ciphers : QString());
}
QString WebSslInfo::certificateErrors() const
{
return (d ? d->certErrors : QString());
}
int WebSslInfo::supportedChiperBits () const
{
return (d ? d->supportedCipherBits : 0);
}
int WebSslInfo::usedChiperBits () const
{
return (d ? d->usedCipherBits : 0);
}
QList<QSslCertificate> WebSslInfo::certificateChain() const
{
return (d ? d->certificateChain : QList<QSslCertificate>());
}
WebSslInfo& WebSslInfo::operator=(const WebSslInfo& other)
{
if (d) {
d->ciphers = other.d->ciphers;
d->protocol = other.d->protocol;
d->certErrors = other.d->certErrors;
d->peerAddress = other.d->peerAddress;
d->parentAddress = other.d->parentAddress;
d->certificateChain = other.d->certificateChain;
d->usedCipherBits = other.d->usedCipherBits;
d->supportedCipherBits = other.d->supportedCipherBits;
d->url = other.d->url;
}
return *this;
}
bool WebSslInfo::saveTo(QMap<QString, QVariant>& data) const
{
const bool ok = isValid();
if (ok) {
data.insert("ssl_in_use", true);
data.insert("ssl_peer_ip", d->peerAddress.toString());
data.insert("ssl_parent_ip", d->parentAddress.toString());
data.insert("ssl_protocol_version", d->protocol);
data.insert("ssl_cipher", d->ciphers);
data.insert("ssl_cert_errors", d->certErrors);
data.insert("ssl_cipher_used_bits", d->usedCipherBits);
data.insert("ssl_cipher_bits", d->supportedCipherBits);
QByteArray certChain;
Q_FOREACH(const QSslCertificate& cert, d->certificateChain)
certChain += cert.toPem();
data.insert("ssl_peer_chain", certChain);
}
return ok;
}
void WebSslInfo::restoreFrom(const QVariant& value, const QUrl& url, bool reset)
{
if (reset) {
*this = WebSslInfo();
}
if (value.isValid() && value.type() == QVariant::Map) {
QMap<QString,QVariant> metaData = value.toMap();
if (metaData.value("ssl_in_use", false).toBool()) {
setCertificateChain(metaData.value("ssl_peer_chain").toByteArray());
setPeerAddress(metaData.value("ssl_peer_ip").toString());
setParentAddress(metaData.value("ssl_parent_ip").toString());
setProtocol(metaData.value("ssl_protocol_version").toString());
setCiphers(metaData.value("ssl_cipher").toString());
setCertificateErrors(metaData.value("ssl_cert_errors").toString());
setUsedCipherBits(metaData.value("ssl_cipher_used_bits").toString());
setSupportedCipherBits(metaData.value("ssl_cipher_bits").toString());
setUrl(url);
}
}
}
void WebSslInfo::setUrl (const QUrl &url)
{
if (d)
d->url = url;
}
void WebSslInfo::setPeerAddress(const QString& address)
{
if (d)
d->peerAddress = address;
}
void WebSslInfo::setParentAddress(const QString& address)
{
if (d)
d->parentAddress = address;
}
void WebSslInfo::setProtocol(const QString& protocol)
{
if (d)
d->protocol = protocol;
}
void WebSslInfo::setCertificateChain(const QByteArray& chain)
{
if (d)
d->certificateChain = QSslCertificate::fromData(chain);
}
void WebSslInfo::setCiphers(const QString& ciphers)
{
if (d)
d->ciphers = ciphers;
}
void WebSslInfo::setUsedCipherBits(const QString& bits)
{
if (d)
d->usedCipherBits = bits.toInt();
}
void WebSslInfo::setSupportedCipherBits(const QString& bits)
{
if (d)
d->supportedCipherBits = bits.toInt();
}
void WebSslInfo::setCertificateErrors(const QString& certErrors)
{
if (d)
d->certErrors = certErrors;
}

View file

@ -1,66 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBSSLINFO_H
#define WEBSSLINFO_H
#include <QUrl>
#include <QHostAddress>
#include <QSslCertificate>
class WebSslInfo
{
public:
WebSslInfo();
WebSslInfo(const WebSslInfo&);
virtual ~WebSslInfo();
bool isValid() const;
QUrl url() const;
QHostAddress peerAddress() const;
QHostAddress parentAddress() const;
QString ciphers() const;
QString protocol() const;
QString certificateErrors() const;
int supportedChiperBits () const;
int usedChiperBits () const;
QList<QSslCertificate> certificateChain() const;
bool saveTo(QMap<QString, QVariant>&) const;
void restoreFrom(const QVariant &, const QUrl& = QUrl(), bool reset = false);
void setUrl (const QUrl &url);
WebSslInfo& operator = (const WebSslInfo&);
protected:
void setCiphers(const QString& ciphers);
void setProtocol(const QString& protocol);
void setPeerAddress(const QString& address);
void setParentAddress(const QString& address);
void setCertificateChain(const QByteArray& chain);
void setCertificateErrors(const QString& certErrors);
void setUsedCipherBits(const QString& bits);
void setSupportedCipherBits(const QString& bits);
private:
class WebSslInfoPrivate;
WebSslInfoPrivate* d;
};
#endif // WEBSSLINFO_H

File diff suppressed because it is too large Load diff

View file

@ -1,150 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WEBVIEW_H
#define WEBVIEW_H
#include <kparts/browserextension.h>
#include <kwebview.h>
#include <QWebFrame>
class KUrl;
class KWebKitPart;
class QWebHitTestResult;
class QWebInspector;
#include <QLabel>
class WebView : public KWebView
{
Q_OBJECT
public:
WebView(KWebKitPart* part, QWidget* parent);
~WebView();
/**
* Same as QWebPage::load, but with KParts style arguments instead.
*
* @see KParts::OpenUrlArguments, KParts::BrowserArguments.
*
* @param url the url to load.
* @param args reference to a OpenUrlArguments object.
* @param bargs reference to a BrowserArguments object.
*/
void loadUrl(const KUrl& url, const KParts::OpenUrlArguments& args, const KParts::BrowserArguments& bargs);
QWebHitTestResult contextMenuResult() const;
protected:
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWebView::dropEvent
* @internal
*/
virtual void dropEvent(QDropEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::contextMenuEvent
* @internal
*/
virtual void contextMenuEvent(QContextMenuEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::keyPressEvent
* @internal
*/
virtual void keyPressEvent(QKeyEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::keyReleaseEvent
* @internal
*/
virtual void keyReleaseEvent(QKeyEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::mouseReleaseEvent
* @internal
*/
virtual void mouseReleaseEvent(QMouseEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QObject::timerEvent
* @internal
*/
virtual void timerEvent(QTimerEvent*);
/**
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::wheelEvent
* @internal
*/
virtual void wheelEvent(QWheelEvent*);
private Q_SLOTS:
void slotStopAutoScroll();
void hideAccessKeys();
private:
void editableContentActionPopupMenu(KParts::BrowserExtension::ActionGroupMap&);
void selectActionPopupMenu(KParts::BrowserExtension::ActionGroupMap&);
void linkActionPopupMenu(KParts::BrowserExtension::ActionGroupMap&);
void partActionPopupMenu(KParts::BrowserExtension::ActionGroupMap &);
void multimediaActionPopupMenu(KParts::BrowserExtension::ActionGroupMap&);
void addSearchActions(QList<QAction*>& selectActions, QWebView*);
void showAccessKeys();
bool checkForAccessKey(QKeyEvent *event);
void makeAccessKeyLabel(const QChar &accessKey, const QWebElement &element);
KActionCollection* m_actionCollection;
QWebHitTestResult m_result;
QPointer<KWebKitPart> m_part;
QWebInspector* m_webInspector;
qint32 m_autoScrollTimerId;
qint32 m_verticalAutoScrollSpeed;
qint32 m_horizontalAutoScrollSpeed;
enum AccessKeyState {
NotActivated,
PreActivated,
Activated
};
AccessKeyState m_accessKeyActivated;
QList<QLabel*> m_accessKeyLabels;
QHash<QChar, QWebElement> m_accessKeyNodes;
QHash<QString, QChar> m_duplicateLinkElements;
};
#endif // WEBVIEW_H

View file

@ -1,606 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009,2010 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
// Own
#include "kwebpage.h"
#include "kwebwallet.h"
// Local
#include "kwebpluginfactory.h"
// KDE
#include <kaction.h>
#include <kfiledialog.h>
#include <kprotocolmanager.h>
#include <kjobuidelegate.h>
#include <krun.h>
#include <kstandarddirs.h>
#include <kstandardshortcut.h>
#include <kurl.h>
#include <kdebug.h>
#include <kshell.h>
#include <kmimetypetrader.h>
#include <klocalizedstring.h>
#include <ktemporaryfile.h>
#include <kio/accessmanager.h>
#include <kio/job.h>
#include <kio/copyjob.h>
#include <kio/jobuidelegate.h>
#include <kio/renamedialog.h>
#include <kio/scheduler.h>
#include <kparts/browseropenorsavequestion.h>
// Qt
#include <QtCore/QPointer>
#include <QtCore/QFileInfo>
#include <QtCore/QCoreApplication>
#include <QtWebKit/QWebFrame>
#include <QtNetwork/QNetworkReply>
#define QL1S(x) QLatin1String(x)
#define QL1C(x) QLatin1Char(x)
static void reloadRequestWithoutDisposition (QNetworkReply* reply)
{
QNetworkRequest req (reply->request());
req.setRawHeader("x-kdewebkit-ignore-disposition", "true");
QWebFrame* frame = qobject_cast<QWebFrame*> (req.originatingObject());
if (!frame)
return;
frame->load(req);
}
static bool isMimeTypeAssociatedWithSelf(const KService::Ptr &offer)
{
if (!offer)
return false;
kDebug(800) << offer->desktopEntryName();
const QString& appName = QCoreApplication::applicationName();
if (appName == offer->desktopEntryName() || offer->exec().trimmed().startsWith(appName))
return true;
// konqueror exception since it uses kfmclient to open html content...
if (appName == QL1S("konqueror") && offer->exec().trimmed().startsWith(QL1S("kfmclient")))
return true;
return false;
}
static void extractMimeType(const QNetworkReply* reply, QString& mimeType)
{
mimeType.clear();
const KIO::MetaData& metaData = reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap();
if (metaData.contains(QL1S("content-type")))
mimeType = metaData.value(QL1S("content-type"));
if (!mimeType.isEmpty())
return;
if (!reply->hasRawHeader("Content-Type"))
return;
const QString value (QL1S(reply->rawHeader("Content-Type").simplified().constData()));
const int index = value.indexOf(QL1C(';'));
mimeType = ((index == -1) ? value : value.left(index));
}
static bool downloadResource (const KUrl& srcUrl, const QString& suggestedName = QString(),
QWidget* parent = 0, const KIO::MetaData& metaData = KIO::MetaData())
{
const QString fileName = suggestedName.isEmpty() ? srcUrl.fileName() : suggestedName;
// convert filename to URL using fromPath to avoid trouble with ':' in filenames (#184202)
KUrl destUrl = KFileDialog::getSaveFileName(KUrl::fromPath(fileName), QString(), parent);
if (!destUrl.isValid())
return false;
// Using KIO::copy rather than file_copy, to benefit from "dest already exists" dialogs.
KIO::Job *job = KIO::copy(srcUrl, destUrl);
if (!metaData.isEmpty())
job->setMetaData(metaData);
job->addMetaData(QL1S("MaxCacheSize"), QL1S("0")); // Don't store in http cache.
job->addMetaData(QL1S("cache"), QL1S("cache")); // Use entry from cache if available.
job->ui()->setWindow((parent ? parent->window() : 0));
job->ui()->setAutoErrorHandlingEnabled(true);
return true;
}
static bool isReplyStatusOk(const QNetworkReply* reply)
{
if (!reply || reply->error() != QNetworkReply::NoError)
return false;
// Check HTTP status code only for http and webdav protocols...
const QString scheme = reply->url().scheme();
if (scheme.startsWith(QLatin1String("http"), Qt::CaseInsensitive) ||
scheme.startsWith(QLatin1String("webdav"), Qt::CaseInsensitive)) {
bool ok = false;
const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(&ok);
if (!ok || statusCode < 200 || statusCode > 299)
return false;
}
return true;
}
class KWebPage::KWebPagePrivate
{
public:
KWebPagePrivate(KWebPage* page)
: q(page)
, inPrivateBrowsingMode(false)
{
}
QWidget* windowWidget()
{
return (window ? window.data() : q->view());
}
void _k_copyResultToTempFile(KJob* job)
{
KIO::FileCopyJob* cJob = qobject_cast<KIO::FileCopyJob *>(job);
if (cJob && !cJob->error() ) {
// Same as KRun::foundMimeType but with a different URL
(void)KRun::runUrl(cJob->destUrl(), mimeType, window);
}
}
void _k_receivedContentType(KIO::Job* job, const QString& mimetype)
{
KIO::TransferJob* tJob = qobject_cast<KIO::TransferJob*>(job);
if (tJob && !tJob->error()) {
tJob->putOnHold();
KIO::Scheduler::publishSlaveOnHold();
// Get suggested file name...
mimeType = mimetype;
const QString suggestedFileName (tJob->queryMetaData(QL1S("content-disposition-filename")));
// kDebug(800) << "suggested filename:" << suggestedFileName << ", mimetype:" << mimetype;
(void) downloadResource(tJob->url(), suggestedFileName, window, tJob->metaData());
}
}
void _k_contentTypeCheckFailed(KJob* job)
{
KIO::TransferJob* tJob = qobject_cast<KIO::TransferJob*>(job);
// On error simply call downloadResource which will probably fail as well.
if (tJob && tJob->error()) {
(void)downloadResource(tJob->url(), QString(), window, tJob->metaData());
}
}
KWebPage* q;
QPointer<QWidget> window;
QString mimeType;
QPointer<KWebWallet> wallet;
bool inPrivateBrowsingMode;
};
static void setActionIcon(QAction* action, const QIcon& icon)
{
if (action) {
action->setIcon(icon);
}
}
static void setActionShortcut(QAction* action, const KShortcut& shortcut)
{
if (action) {
action->setShortcuts(shortcut.toList());
}
}
KWebPage::KWebPage(QObject *parent, Integration flags)
:QWebPage(parent), d(new KWebPagePrivate(this))
{
// KDE KParts integration for <embed> tag...
if (!flags || (flags & KPartsIntegration))
setPluginFactory(new KWebPluginFactory(this));
QWidget *parentWidget = qobject_cast<QWidget*>(parent);
d->window = (parentWidget ? parentWidget->window() : 0);
// KDE IO (KIO) integration...
if (!flags || (flags & KIOIntegration)) {
KIO::Integration::AccessManager *manager = new KIO::Integration::AccessManager(this);
// Disable QtWebKit's internal cache to avoid duplication with the one in KIO...
manager->setCache(0);
manager->setWindow(d->window);
manager->setEmitReadyReadOnMetaDataChange(true);
setNetworkAccessManager(manager);
}
// KWallet integration...
if (!flags || (flags & KWalletIntegration)) {
setWallet(new KWebWallet(0, (d->window ? d->window->winId() : 0) ));
}
setActionIcon(action(Back), KIcon("go-previous"));
setActionIcon(action(Forward), KIcon("go-next"));
setActionIcon(action(Reload), KIcon("view-refresh"));
setActionIcon(action(Stop), KIcon("process-stop"));
setActionIcon(action(Cut), KIcon("edit-cut"));
setActionIcon(action(Copy), KIcon("edit-copy"));
setActionIcon(action(Paste), KIcon("edit-paste"));
setActionIcon(action(Undo), KIcon("edit-undo"));
setActionIcon(action(Redo), KIcon("edit-redo"));
setActionIcon(action(SelectAll), KIcon("edit-select-all"));
setActionIcon(action(InspectElement), KIcon("view-process-all"));
setActionIcon(action(OpenLinkInNewWindow), KIcon("window-new"));
setActionIcon(action(OpenFrameInNewWindow), KIcon("window-new"));
setActionIcon(action(OpenImageInNewWindow), KIcon("window-new"));
setActionIcon(action(CopyLinkToClipboard), KIcon("edit-copy"));
setActionIcon(action(CopyImageToClipboard), KIcon("edit-copy"));
setActionIcon(action(ToggleBold), KIcon("format-text-bold"));
setActionIcon(action(ToggleItalic), KIcon("format-text-italic"));
setActionIcon(action(ToggleUnderline), KIcon("format-text-underline"));
setActionIcon(action(DownloadLinkToDisk), KIcon("document-save"));
setActionIcon(action(DownloadImageToDisk), KIcon("document-save"));
settings()->setWebGraphic(QWebSettings::MissingPluginGraphic, KIcon("preferences-plugin").pixmap(32, 32));
settings()->setWebGraphic(QWebSettings::MissingImageGraphic, KIcon("image-missing").pixmap(32, 32));
settings()->setWebGraphic(QWebSettings::DefaultFrameIconGraphic, KIcon("applications-internet").pixmap(32, 32));
setActionShortcut(action(Back), KStandardShortcut::back());
setActionShortcut(action(Forward), KStandardShortcut::forward());
setActionShortcut(action(Reload), KStandardShortcut::reload());
setActionShortcut(action(Stop), KShortcut(QKeySequence(Qt::Key_Escape)));
setActionShortcut(action(Cut), KStandardShortcut::cut());
setActionShortcut(action(Copy), KStandardShortcut::copy());
setActionShortcut(action(Paste), KStandardShortcut::paste());
setActionShortcut(action(Undo), KStandardShortcut::undo());
setActionShortcut(action(Redo), KStandardShortcut::redo());
setActionShortcut(action(SelectAll), KStandardShortcut::selectAll());
}
KWebPage::~KWebPage()
{
delete d;
}
bool KWebPage::isExternalContentAllowed() const
{
KIO::AccessManager *manager = qobject_cast<KIO::AccessManager*>(networkAccessManager());
if (manager)
return manager->isExternalContentAllowed();
return true;
}
KWebWallet *KWebPage::wallet() const
{
return d->wallet;
}
void KWebPage::setAllowExternalContent(bool allow)
{
KIO::AccessManager *manager = qobject_cast<KIO::AccessManager*>(networkAccessManager());
if (manager)
manager->setExternalContentAllowed(allow);
}
void KWebPage::setWallet(KWebWallet* wallet)
{
// Delete the current wallet if this object is its parent...
if (d->wallet && this == d->wallet->parent())
delete d->wallet;
d->wallet = wallet;
if (d->wallet)
d->wallet->setParent(this);
}
void KWebPage::downloadRequest(const QNetworkRequest& request)
{
KIO::TransferJob* job = KIO::get(request.url());
connect(job, SIGNAL(mimetype(KIO::Job*,QString)),
this, SLOT(_k_receivedContentType(KIO::Job*,QString)));
job->setMetaData(request.attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap());
job->addMetaData(QL1S("MaxCacheSize"), QL1S("0")); // Don't store in http cache.
job->addMetaData(QL1S("cache"), QL1S("cache")); // Use entry from cache if available.
job->ui()->setWindow(d->windowWidget());
}
void KWebPage::downloadUrl(const KUrl &url)
{
downloadRequest(QNetworkRequest(url));
}
void KWebPage::downloadResponse(QNetworkReply *reply)
{
Q_ASSERT(reply);
if (!reply)
return;
// Put the job on hold only for the protocols we know about (read: http).
KIO::Integration::AccessManager::putReplyOnHold(reply);
QString mimeType;
KIO::MetaData metaData;
if (handleReply(reply, &mimeType, &metaData)) {
return;
}
const KUrl replyUrl (reply->url());
// Ask KRun to handle the response when mimetype is unknown
if (mimeType.isEmpty()) {
(void)new KRun(replyUrl, d->windowWidget(), 0 , replyUrl.isLocalFile());
return;
}
// Ask KRun::runUrl to handle the response when mimetype is inode/*
if (mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive) &&
KRun::runUrl(replyUrl, mimeType, d->windowWidget(), false, false,
metaData.value(QL1S("content-disposition-filename")))) {
return;
}
}
QString KWebPage::sessionMetaData(const QString &key) const
{
QString value;
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
value = manager->sessionMetaData().value(key);
return value;
}
QString KWebPage::requestMetaData(const QString &key) const
{
QString value;
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
value = manager->requestMetaData().value(key);
return value;
}
void KWebPage::setSessionMetaData(const QString &key, const QString &value)
{
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
manager->sessionMetaData()[key] = value;
}
void KWebPage::setRequestMetaData(const QString &key, const QString &value)
{
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
manager->requestMetaData()[key] = value;
}
void KWebPage::removeSessionMetaData(const QString &key)
{
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
manager->sessionMetaData().remove(key);
}
void KWebPage::removeRequestMetaData(const QString &key)
{
KIO::Integration::AccessManager *manager = qobject_cast<KIO::Integration::AccessManager *>(networkAccessManager());
if (manager)
manager->requestMetaData().remove(key);
}
QString KWebPage::userAgentForUrl(const QUrl& _url) const
{
const KUrl url(_url);
const QString userAgent = KProtocolManager::userAgentForHost((url.isLocalFile() ? QL1S("localhost") : url.host()));
if (userAgent == KProtocolManager::defaultUserAgent())
return QWebPage::userAgentForUrl(_url);
return userAgent;
}
static void setDisableCookieJarStorage(QNetworkAccessManager* manager, bool status)
{
if (manager) {
KIO::Integration::CookieJar *cookieJar = manager ? qobject_cast<KIO::Integration::CookieJar*>(manager->cookieJar()) : 0;
if (cookieJar) {
//kDebug(800) << "Store cookies ?" << !status;
cookieJar->setDisableCookieStorage(status);
}
}
}
bool KWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type)
{
kDebug(800) << "url:" << request.url() << ", type:" << type << ", frame:" << frame;
if (frame && d->wallet && type == QWebPage::NavigationTypeFormSubmitted)
d->wallet->saveFormData(frame);
// Make sure nothing is cached when private browsing mode is enabled...
if (settings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
if (!d->inPrivateBrowsingMode) {
setDisableCookieJarStorage(networkAccessManager(), true);
setSessionMetaData(QL1S("no-cache"), QL1S("true"));
d->inPrivateBrowsingMode = true;
}
} else {
if (d->inPrivateBrowsingMode) {
setDisableCookieJarStorage(networkAccessManager(), false);
removeSessionMetaData(QL1S("no-cache"));
d->inPrivateBrowsingMode = false;
}
}
/*
If the navigation request is from the main frame, set the cross-domain
meta-data value to the current url for proper integration with KCookieJar...
*/
if (frame == mainFrame() && type != QWebPage::NavigationTypeReload)
setSessionMetaData(QL1S("cross-domain"), request.url().toString());
return QWebPage::acceptNavigationRequest(frame, request, type);
}
bool KWebPage::handleReply(QNetworkReply* reply, QString* contentType, KIO::MetaData* metaData)
{
// Reply url...
const KUrl replyUrl (reply->url());
// Get suggested file name...
const KIO::MetaData& data = reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap();
const QString suggestedFileName = data.value(QL1S("content-disposition-filename"));
if (metaData) {
*metaData = data;
}
// Get the mime-type...
QString mimeType;
extractMimeType(reply, mimeType);
if (contentType) {
*contentType = mimeType;
}
// Let the calling function deal with handling empty or inode/* mimetypes...
if (mimeType.isEmpty() || mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive)) {
return false;
}
// Convert executable text files to plain text...
if (KParts::BrowserRun::isTextExecutable(mimeType))
mimeType = QL1S("text/plain");
//kDebug(800) << "Content-disposition:" << suggestedFileName;
//kDebug(800) << "Got unsupported content of type:" << mimeType << "URL:" << replyUrl;
//kDebug(800) << "Error code:" << reply->error() << reply->errorString();
if (isReplyStatusOk(reply)) {
while (true) {
KParts::BrowserOpenOrSaveQuestion::Result result;
KParts::BrowserOpenOrSaveQuestion dlg(d->windowWidget(), replyUrl, mimeType);
dlg.setSuggestedFileName(suggestedFileName);
dlg.setFeatures(KParts::BrowserOpenOrSaveQuestion::ServiceSelection);
result = dlg.askOpenOrSave();
switch (result) {
case KParts::BrowserOpenOrSaveQuestion::Open:
// Handle Post operations that return content...
if (reply->operation() == QNetworkAccessManager::PostOperation) {
d->mimeType = mimeType;
QFileInfo finfo (suggestedFileName.isEmpty() ? replyUrl.fileName() : suggestedFileName);
KTemporaryFile tempFile;
tempFile.setSuffix(QL1C('.') + finfo.suffix());
tempFile.setAutoRemove(false);
tempFile.open();
KUrl destUrl;
destUrl.setPath(tempFile.fileName());
KIO::Job *job = KIO::file_copy(replyUrl, destUrl, 0600, KIO::Overwrite);
job->ui()->setWindow(d->windowWidget());
job->ui()->setAutoErrorHandlingEnabled(true);
connect(job, SIGNAL(result(KJob*)),
this, SLOT(_k_copyResultToTempFile(KJob*)));
return true;
}
// Ask before running any executables...
if (KParts::BrowserRun::allowExecution(mimeType, replyUrl)) {
KService::Ptr offer = dlg.selectedService();
// HACK: The check below is necessary to break an infinite
// recursion that occurs whenever this function is called as a result
// of receiving content that can be rendered by the app using this engine.
// For example a text/html header that containing a content-disposition
// header is received by the app using this class.
if (isMimeTypeAssociatedWithSelf(offer)) {
reloadRequestWithoutDisposition(reply);
} else {
KUrl::List list;
list.append(replyUrl);
bool success = false;
// kDebug(800) << "Suggested file name:" << suggestedFileName;
if (offer) {
success = KRun::run(*offer, list, d->windowWidget() , false, suggestedFileName);
} else {
success = KRun::displayOpenWithDialog(list, d->windowWidget(), false, suggestedFileName);
if (!success)
break;
}
// For non KIO apps and cancelled Open With dialog, remove slave on hold.
if (!success || (offer && !offer->categories().contains(QL1S("KDE")))) {
KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold...
}
}
return true;
}
// TODO: Instead of silently failing when allowExecution fails, notify
// the user why the requested action cannot be fulfilled...
return false;
case KParts::BrowserOpenOrSaveQuestion::Save:
// Do not download local files...
if (!replyUrl.isLocalFile()) {
QString downloadCmd (reply->property("DownloadManagerExe").toString());
if (!downloadCmd.isEmpty()) {
downloadCmd += QLatin1Char(' ');
downloadCmd += KShell::quoteArg(replyUrl.url());
if (!suggestedFileName.isEmpty()) {
downloadCmd += QLatin1Char(' ');
downloadCmd += KShell::quoteArg(suggestedFileName);
}
// kDebug(800) << "download command:" << downloadCmd;
if (KRun::runCommand(downloadCmd, view()))
return true;
}
if (!downloadResource(replyUrl, suggestedFileName, d->windowWidget()))
return true; // file dialog was cancelled, stop here
}
return true;
case KParts::BrowserOpenOrSaveQuestion::Cancel:
default:
KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold...
return true;
}
}
} else {
KService::Ptr offer = KMimeTypeTrader::self()->preferredService(mimeType);
if (isMimeTypeAssociatedWithSelf(offer)) {
reloadRequestWithoutDisposition(reply);
return true;
}
}
return false;
}
#include "moc_kwebpage.cpp"

View file

@ -1,368 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Dirk Mueller <mueller@kde.org>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009,2010 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KWEBPAGE_H
#define KWEBPAGE_H
#include <kdewebkit_export.h>
#include <QtWebKit/QWebPage>
class KWebWallet;
class KUrl;
class KJob;
namespace KIO {
class MetaData;
class Job;
}
/**
* @short An enhanced QWebPage that provides integration into the KDE environment.
*
* This is a convenience class that provides full integration with KDE
* technologies such as KIO for network request handling, KCookiejar for cookie
* handling, KParts for embedding non-html content and KWallet for storing
* form data. It also sets standard icons for many of the actions provided by
* QWebPage.
*
* Most of this integration happens behind the scenes. If you want KWallet
* integration, however, you will have to provide a mechanism for deciding
* whether to allow form data to be stored. To do this, you will need to
* connect to the KWebWallet::saveFormDataRequested signal and call either
* KWebWallet::acceptSaveFormDataRequest or
* KWebWallet::rejectSaveFormDataRequest, typically after asking the user
* whether they want to save the form data. If you do not do this, no form
* data will be saved.
*
* KWebPage will also not automatically load form data for you. You should
* connect to QWebPage::loadFinished and, if the page was loaded successfully,
* call
* @code
* page->wallet()->fillFormData(page->mainFrame());
* @endcode
*
* @see KIO::Integration
* @see KWebWallet
*
* @author Urs Wolfer <uwolfer @ kde.org>
* @author Dawit Alemayehu <adawit @ kde.org>
*
* @since 4.4
*/
class KDEWEBKIT_EXPORT KWebPage : public QWebPage
{
Q_OBJECT
Q_FLAGS (Integration)
public:
/**
* Flags for setting the desired level of integration.
*/
enum IntegrationFlags
{
/**
* Provide only very basic integration such as using KDE icons for the
* actions provided by QWebPage.
*/
NoIntegration = 0x01,
/**
* Use KIO to handle network requests.
*
* @see KIO::Integration::AccessManager
*/
KIOIntegration = 0x02,
/**
* Use KPart componenets, if available, to display content in
* &lt;embed&gt; and &lt;object&gt; tags.
*/
KPartsIntegration = 0x04,
/**
* Use KWallet to store login credentials and other form data from web
* sites.
*
* @see wallet() and setWallet()
*/
KWalletIntegration = 0x08
};
Q_DECLARE_FLAGS(Integration, IntegrationFlags)
/**
* Constructs a KWebPage with parent @p parent.
*
* Note that if no integration flags are set (the default), all integration
* options are activated. If you inherit from this class you can use the
* flags in @ref IntegrationFlags to control how much integration should
* be used.
*
* @see KIO::Integration::CookieJar
* @see KIO::Integration::AccessManager
* @see wallet() and setWallet()
*/
explicit KWebPage(QObject *parent = 0, Integration flags = Integration());
/**
* Destroys the KWebPage.
*/
~KWebPage();
/**
* Whether access to remote content is permitted.
*
* If this is @c false, only resources on the local system can be accessed
* through this web page. By default access to remote content is allowed.
*
* If KIO integration is disabled, this will always return @c true.
*
* @see setAllowExternalContent()
* @see KIO::Integration::AccessManager::isExternalContentAllowed()
*
* @return @c true if access to remote content is permitted, @c false otherwise
*/
bool isExternalContentAllowed() const;
/**
* The wallet integration manager.
*
* If you wish to use KDE wallet integration, you will have to connect to
* signals emitted by this object and react accordingly. See KWebWallet
* for more information.
*
* @return the wallet integration manager, or 0 if KDE wallet integration
* is disabled
*/
KWebWallet *wallet() const;
/**
* Set whether to allow remote content.
*
* If KIO integration is not enabled, this method will have no effect.
*
* @see isExternalContentAllowed()
* @see KIO::Integration::AccessManager::setAllowExternalContent(bool)
*
* @param allow @c true if access to remote content should be allowed,
* @c false if only local content should be accessible
*/
void setAllowExternalContent(bool allow);
/**
* Set the @ref KWebWallet that is used to store form data.
*
* This KWebPage will take ownership of @p wallet, so that the wallet
* is deleted when the KWebPage is deleted. If you do not want that
* to happen, you should call setParent() on @p wallet after calling
* this function.
*
* @see KWebWallet
*
* @param wallet the KWebWallet to be used for storing form data, or
* 0 to disable KWallet integration
*/
void setWallet(KWebWallet* wallet);
public Q_SLOTS:
/**
* Download @p request using KIO.
*
* This slot first prompts the user where to save the requested
* resource and then downloads it using KIO.
*/
virtual void downloadRequest(const QNetworkRequest &request);
/**
* Download @p url using KIO.
*
* This slot first prompts the user where to save the requested
* resource and then downloads it using KIO.
*/
virtual void downloadUrl(const KUrl &url);
/**
* Download the resource specified by @p reply using KIO.
*
* This slot first prompts the user where to save the requested resource
* and then downloads it using KIO.
*
* In KDE 4.8 and higher, if @p reply contains a QObject property called
* "DownloadManagerExe", then an attempt will be made to the command
* specified by that property to download the specified resource.
*
* If the "DownloadManagerExe" property is not defined or the command
* specified by it could not be successfully executed, then the user will
* be prompted for the action to take.
*
* @since 4.5
* @see handleReply
*/
void downloadResponse(QNetworkReply *reply);
protected:
/**
* Get an item of session metadata.
*
* Retrieves the value of the permanent (per-session) metadata for @p key.
*
* If KIO integration is disabled, this will always return an empty string.
*
* @see KIO::Integration::AccessManager::sessionMetaData
* @see setSessionMetaData
*
* @param key the key of the metadata to retrieve
* @return the value of the metadata associated with @p key, or an
* empty string if there is no such metadata
*/
QString sessionMetaData(const QString &key) const;
/**
* Get an item of request metadata.
*
* Retrieves the value of the temporary (per-request) metadata for @p key.
*
* If KIO integration is disabled, this will always return an empty string.
*
* @see KIO::Integration::AccessManager::requestMetaData
* @see setRequestMetaData
*
* @param key the key of the metadata to retrieve
* @return the value of the metadata associated with @p key, or an
* empty string if there is no such metadata
*/
QString requestMetaData(const QString &key) const;
/**
* Set an item of metadata to be sent to the KIO slave with every request.
*
* If KIO integration is disabled, this method will have no effect.
*
* Metadata set using this method will be sent with every request.
*
* @see KIO::Integration::AccessManager::sessionMetaData
*
* @param key the key for the metadata; any existing metadata associated
* with this key will be overwritten
* @param value the value to associate with @p key
*/
void setSessionMetaData(const QString &key, const QString &value);
/**
* Set an item of metadata to be sent to the KIO slave with the next request.
*
* If KIO integration is disabled, this method will have no effect.
*
* Metadata set using this method will be deleted after it has been sent
* once.
*
* @see KIO::Integration::AccessManager::requestMetaData
*
* @param key the key for the metadata; any existing metadata associated
* with this key will be overwritten
* @param value the value to associate with @p key
*/
void setRequestMetaData(const QString &key, const QString &value);
/**
* Remove an item of session metadata.
*
* Removes the permanent (per-session) metadata associated with @p key.
*
* @see KIO::Integration::AccessManager::sessionMetaData
* @see setSessionMetaData
*
* @param key the key for the metadata to remove
*/
void removeSessionMetaData(const QString &key);
/**
* Remove an item of request metadata.
*
* Removes the temporary (per-request) metadata associated with @p key.
*
* @see KIO::Integration::AccessManager::requestMetaData
* @see setRequestMetaData
*
* @param key the key for the metadata to remove
*/
void removeRequestMetaData(const QString &key);
/**
* @reimp
*
* This function is re-implemented to provide KDE user-agent management
* integration through KProtocolManager.
*
* If a special user-agent has been configured for the host indicated by
* @p url, that user-agent will be returned. Otherwise, QWebPage's
* default user agent is returned.
*
* @see KProtocolManager::userAgentForHost.
* @see QWebPage::userAgentForUrl.
*/
virtual QString userAgentForUrl(const QUrl& url) const;
/**
* @reimp
*
* This performs various integration-related actions when navigation is
* requested. If you override this method, make sure you call the parent's
* implementation unless you want to block the request outright.
*
* If you do override acceptNavigationRequest and call this method,
* however, be aware of the effect of the page's linkDelegationPolicy on
* how * QWebPage::acceptNavigationRequest behaves.
*
* @see QWebPage::acceptNavigationRequest
*/
virtual bool acceptNavigationRequest(QWebFrame * frame, const QNetworkRequest & request, NavigationType type);
/**
* Attempts to handle @p reply and returns true on success, false otherwise.
*
* In KDE 4.8 and higher, if @p reply contains a QObject property called
* "DownloadManagerExe", then an attempt will be made to let the command
* specified by that property to download the requested resource.
*
* If the "DownloadManagerExe" property is not defined or the command
* specified by it could not be successfully executed, then the user will
* be prompted for the action to take.
*
* @param reply the QNetworkReply object to be handled.
* @param contentType if not null, it will be set to the content-type specified in @p reply, if any.
* @param metaData if not null, it will be set to the KIO meta-data specified in @p reply, if any.
* @since 4.6.3
*/
bool handleReply (QNetworkReply* reply, QString* contentType = 0, KIO::MetaData* metaData = 0);
private:
class KWebPagePrivate;
KWebPagePrivate* const d;
Q_PRIVATE_SLOT(d, void _k_copyResultToTempFile(KJob*))
Q_PRIVATE_SLOT(d, void _k_receivedContentType(KIO::Job*, const QString&))
Q_PRIVATE_SLOT(d, void _k_contentTypeCheckFailed(KJob*))
};
Q_DECLARE_OPERATORS_FOR_FLAGS(KWebPage::Integration)
#endif // KWEBPAGE_H

View file

@ -1,167 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "kwebpluginfactory.h"
#include "kwebpage.h"
#include "kwebview.h"
#include <kmimetypetrader.h>
#include <kservicetypetrader.h>
#include <kmimetype.h>
#include <kdebug.h>
#include <kio/job.h>
#include <kparts/part.h>
#include <QtCore/qlist.h>
#include <QtCore/QStringList>
#include <QtCore/QList>
#include <QtWebKit/QWebPluginFactory>
#include <QtWebKit/QWebFrame>
#include <QtWebKit/QWebView>
#define QL1S(x) QLatin1String(x)
#define QL1C(x) QLatin1Char(x)
KWebPluginFactory::KWebPluginFactory(QObject *parent)
:QWebPluginFactory(parent),d(0)
{
}
KWebPluginFactory::~KWebPluginFactory()
{
}
QObject* KWebPluginFactory::create(const QString& _mimeType, const QUrl& url, const QStringList& argumentNames, const QStringList& argumentValues) const
{
QString mimeType (_mimeType.trimmed());
// If no mimetype is provided, we do our best to correctly determine it here...
if (mimeType.isEmpty()) {
kDebug(800) << "Looking up missing mimetype for plugin resource:" << url;
extractGuessedMimeType(url, &mimeType);
kDebug(800) << "Updated mimetype to" << mimeType;
}
// Defer handling of flash content to QtWebKit's builtin viewer.
// If you want to use/test KDE's nspluginviewer, comment out the
// if statement below.
KParts::ReadOnlyPart* part = (excludedMimeType(mimeType) ? 0 : createPartInstanceFrom(mimeType, argumentNames, argumentValues, 0, parent()));
kDebug(800) << "Asked for" << mimeType << "plugin, got" << part;
if (part) {
QMap<QString, QString> metaData = part->arguments().metaData();
QString urlStr = url.toString(QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment);
metaData.insert("PropagateHttpHeader", "true");
metaData.insert("referrer", urlStr);
metaData.insert("cross-domain", urlStr);
metaData.insert("main_frame_request", "TRUE");
metaData.insert("ssl_activate_warnings", "TRUE");
KWebPage *page = qobject_cast<KWebPage *>(parent());
if (page) {
const QString scheme = page->currentFrame()->url().scheme();
if (page && (QString::compare(scheme, QL1S("https"), Qt::CaseInsensitive) == 0 ||
QString::compare(scheme, QL1S("webdavs"), Qt::CaseInsensitive) == 0))
metaData.insert("ssl_was_in_use", "TRUE");
else
metaData.insert("ssl_was_in_use", "FALSE");
}
KParts::OpenUrlArguments openUrlArgs = part->arguments();
openUrlArgs.metaData() = metaData;
openUrlArgs.setMimeType(mimeType);
part->setArguments(openUrlArgs);
part->openUrl(url);
return part->widget();
}
return 0;
}
QList<KWebPluginFactory::Plugin> KWebPluginFactory::plugins() const
{
QList<Plugin> plugins;
return plugins;
}
static bool isHttpProtocol(const QUrl& url)
{
const QString scheme (url.scheme());
return (scheme.startsWith(QL1S("http"), Qt::CaseInsensitive)
|| scheme.startsWith(QL1S("webdav"), Qt::CaseInsensitive));
}
void KWebPluginFactory::extractGuessedMimeType (const QUrl& url, QString* mimeType) const
{
if (mimeType) {
const KUrl reqUrl ((isHttpProtocol(url) ? url.path() : url));
KMimeType::Ptr ptr = KMimeType::findByUrl(reqUrl, 0, reqUrl.isLocalFile(), true);
if (!ptr->isDefault() && !ptr->name().startsWith(QL1S("inode/"), Qt::CaseInsensitive)) {
*mimeType = ptr->name();
}
}
}
KParts::ReadOnlyPart* KWebPluginFactory::createPartInstanceFrom(const QString& mimeType,
const QStringList& argumentNames,
const QStringList& argumentValues,
QWidget* parentWidget,
QObject* parentObj) const
{
KParts::ReadOnlyPart* part = 0;
if (!mimeType.isEmpty()) {
// Only attempt to find a KPart for the supported mime types...
QVariantList arguments;
const int count = argumentNames.count();
for (int i = 0; i < count; ++i) {
arguments << QString(argumentNames.at(i) + QL1S("=\"") + argumentValues.at(i) + QL1C('\"'));
}
part = KMimeTypeTrader::createPartInstanceFromQuery<KParts::ReadOnlyPart>(mimeType, parentWidget, parentObj, QString(), arguments);
}
return part;
}
bool KWebPluginFactory::excludedMimeType (const QString& mimeType) const
{
if (mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive))
return true;
if (mimeType.startsWith(QL1S("application/x-java"), Qt::CaseInsensitive))
return true;
if (mimeType == QL1S("application/x-shockwave-flash") ||
mimeType == QL1S("application/futuresplash"))
return true;
return false;
}
#include "moc_kwebpluginfactory.cpp"

View file

@ -1,138 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KWEBPLUGINFACTORY_H
#define KWEBPLUGINFACTORY_H
#include <kdewebkit_export.h>
#include <QtWebKit/QWebPluginFactory>
namespace KParts {
class ReadOnlyPart;
}
/**
* @short A QWebPluginFactory with integration into the KDE environment.
*
* This class will attempt to find a KPart to satisfy a plugin request.
*
* @author Michael Howell <mhowell123@gmail.com>
* @author Dawit Alemayehu <adawit@kde.org>
*
* @see QWebPluginFactory
* @since 4.4
*/
class KDEWEBKIT_EXPORT KWebPluginFactory : public QWebPluginFactory
{
Q_OBJECT
public:
/**
* Constructs a KWebPluginFactory with parent @p parent.
*/
KWebPluginFactory(QObject *parent);
/**
* Destroys the KWebPage.
*/
~KWebPluginFactory();
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWebPluginFactory::create
* @internal
*/
virtual QObject *create(const QString &mimeType,
const QUrl &url,
const QStringList &argumentNames,
const QStringList &argumentValues) const;
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWebPluginFactory::plugins
* @internal
*/
virtual QList<Plugin> plugins() const;
protected:
/**
* Sets @p mimeType to the content type guessed from @p url.
*
* Note that attempting to guess mime-type will not always produce the
* correct content-type. This is especially true for the HTTP protocol
* since the URL present might be for a cgi script URL instead of a static
* URL that directly points to the content.
*
* If @p mimeType is not NULL, this function will set it to the content
* type determined from @p url.
*
* @since 4.8.3
*/
void extractGuessedMimeType(const QUrl& url, QString* mimeType) const;
/**
* Returns true if the given mime-type is excluded from being used to create
* a web plugin using KDE's trader.
*
* Currently this function only returns true for mimetypes 'x-java',
* 'x-shockwave-flash', and 'futuresplash' in the 'application' category
* and everything under the 'inode' category.
*
* @since 4.8.3
*/
bool excludedMimeType(const QString& mimeType) const;
/**
* Returns an instance of the service associated with @p mimeType.
*
* This function uses KDE's trader to create an instance of the service
* associated with the given parameters. The parameters are the <param>
* tags of the HTML object. The name and the value attributes of these
* tags are specified by the @p argumentNames and @p argumentValues
* respectively.
*
* The @p parentWidget and @p parent parameters specify the widget to use
* as the parent of the newly created part and the parent for the part
* itself respectively.
*
* The parameters for this function mirror that of @ref QWebPluginFactory::create.
*
* @see QWebPluginFactory::create
* @since 4.8.3
*/
KParts::ReadOnlyPart* createPartInstanceFrom(const QString& mimeType,
const QStringList &argumentNames,
const QStringList &argumentValues,
QWidget* parentWidget = 0,
QObject* parent = 0) const;
private:
class KWebPluginFactoryPrivate;
KWebPluginFactoryPrivate* const d;
};
#endif // KWEBPLUGINFACTORY_H

View file

@ -1,83 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "kwebview.h"
#include "kwebview_p.h"
#include "kwebpage.h"
#include <QtGui/qevent.h>
KWebView::KWebView(QWidget *parent, bool createCustomPage)
:QWebView(parent), d(new KWebViewPrivate<KWebView>(this))
{
if (createCustomPage)
setPage(new KWebPage(this));
}
KWebView::~KWebView()
{
delete d;
}
bool KWebView::isExternalContentAllowed() const
{
return d->isExternalContentAllowed();
}
void KWebView::setAllowExternalContent(bool allow)
{
d->setAllowExternalContent(allow);
}
void KWebView::wheelEvent(QWheelEvent *event)
{
if (d->wheelEvent(event->delta())) {
event->accept();
} else {
QWebView::wheelEvent(event);
}
}
void KWebView::mousePressEvent(QMouseEvent *event)
{
d->pressedButtons = event->buttons();
d->keyboardModifiers = event->modifiers();
QWebView::mousePressEvent(event);
}
void KWebView::mouseReleaseEvent(QMouseEvent *event)
{
if (d->mouseReleased(event->pos()) || d->handleUrlPasteFromClipboard(event)) {
event->accept();
return;
}
QWebView::mouseReleaseEvent(event);
}
#include "moc_kwebview.cpp"

View file

@ -1,185 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KWEBVIEW_H
#define KWEBVIEW_H
#include <kdewebkit_export.h>
#include <QtWebKit/QWebView>
class KUrl;
template<class T> class KWebViewPrivate;
/**
* @short A re-implementation of QWebView that provides KDE integration.
*
* This is a drop-in replacement for QWebView that provides full KDE
* integration through @ref KWebPage as well as additional signals that
* capture middle, shift and ctrl mouse clicks on links and URL pasting
* from the selection clipboard.
*
* The specific functionality provided by this class (over and above what
* would be acheived by using KWebPage with a QWebView) is that scrolling
* with the mouse wheel while holding down CTRL zooms the page (see
* QWebView::setZoomFactor) and several useful signals are emitted when
* the user performs certain actions.
*
* See the signal documentation for more details.
*
* @author Urs Wolfer <uwolfer @ kde.org>
* @author Dawit Alemayehu <adawit @ kde.org>
* @since 4.4
*/
class KDEWEBKIT_EXPORT KWebView : public QWebView
{
Q_OBJECT
Q_PROPERTY(bool externalContentAllowed READ isExternalContentAllowed WRITE setAllowExternalContent)
public:
/**
* Constructs a KWebView object with parent @p parent.
*
* Set @p createCustomPage to false to prevent the creation of a
* @ref KWebPage object for KDE integration. Doing so allows you to
* avoid unnecessary object creation and deletion if you are going to
* use a subclass of KWebPage.
*
* @param parent the parent object
* @param createCustomPage if @c true, the view's page is set to an
* instance of KWebPage
*/
explicit KWebView(QWidget *parent = 0, bool createCustomPage = true);
/**
* Destroys the KWebView.
*/
~KWebView();
/**
* Returns true if access to remote content is allowed.
*
* By default access to remote content is allowed.
*
* @see setAllowExternalContent()
* @see KWebPage::isExternalContentAllowed()
*/
bool isExternalContentAllowed() const;
/**
* Set @p allow to false if you want to prevent access to remote content.
*
* If this function is set to false only resources on the local system
* can be accessed through this class. By default fetching external content
* is allowed.
*
* @see isExternalContentAllowed()
* @see KWebPage::setAllowExternalContent(bool)
*/
void setAllowExternalContent(bool allow);
Q_SIGNALS:
/**
* Emitted when a URL from the selection clipboard is pasted on this view.
*
* This is triggered when the user clicks on the page with the middle
* mouse button when there is something in the global mouse selection
* clipboard. This is typically only possible on X11.
*
* Uri filters are applied to the selection clipboard to generate @p url.
*
* If the content in the selection clipboard is not a valid URL and a
* default search engine is configured, @p searchText will be set to the
* content of the clipboard (250 characters maximum) and @p url will be
* set to a query to the default search engine.
*
* @param url the URL generated from the selection clipboard content
* @param searchText content of the selection clipboard if it is not a
* valid URL
*
* @see KUriFilter
* @see QClipboard
* @since 4.6
*/
void selectionClipboardUrlPasted(const KUrl &url, const QString& searchText);
/**
* Emitted when a link is clicked with the left mouse button while SHIFT is
* held down.
*
* A KDE user would typically expect this to result in the triggering of a
* "save link as" action.
*
* @param url the URL of the clicked link
*/
void linkShiftClicked(const KUrl &url);
/**
* Emitted when a link is clicked with the middle mouse button or clicked
* with the left mouse button while CTRL is held down.
*
* Typically, the user would expect this to result in the URL being opened
* in a new tab or window.
*
* @param url the URL of the clicked link
*/
void linkMiddleOrCtrlClicked(const KUrl &url);
protected:
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::wheelEvent
* @internal
*/
void wheelEvent(QWheelEvent *event);
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::mousePressEvent
* @internal
*/
virtual void mousePressEvent(QMouseEvent *event);
/**
* @reimp
*
* Reimplemented for internal reasons, the API is not affected.
*
* @see QWidget::mouseReleaseEvent
* @internal
*/
virtual void mouseReleaseEvent(QMouseEvent *event);
private:
friend class KWebViewPrivate<KWebView>;
KWebViewPrivate<KWebView> * const d;
};
#endif // KWEBVIEW_H

View file

@ -1,148 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2007 Trolltech ASA
* Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>
* Copyright (C) 2008 Laurent Montel <montel@kde.org>
* Copyright (C) 2008 Michael Howell <mhowell123@gmail.com>
* Copyright (C) 2009 Dawit Alemayehu <adawit @ kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KWEBVIEW_P_H
#define KWEBVIEW_P_H
#include <QtCore/QEvent>
#include <QtGui/QClipboard>
#include <QtGui/QApplication>
#include <QtWebKit/QWebFrame>
#include <QtWebKit/QWebElement>
#include <kurl.h>
#include <kurifilter.h>
#include "kwebpage.h"
template <class T>
class KWebViewPrivate
{
public:
KWebViewPrivate(T *parent)
: q(parent),
keyboardModifiers(Qt::NoModifier) ,
pressedButtons(Qt::NoButton)
{
}
bool isExternalContentAllowed()
{
KWebPage *webPage = qobject_cast<KWebPage*>(q->page());
if (webPage) {
return webPage->isExternalContentAllowed();
}
return false;
}
void setAllowExternalContent(bool allow)
{
KWebPage *webPage = qobject_cast<KWebPage*>(q->page());
if (webPage) {
webPage->setAllowExternalContent(allow);
}
}
bool wheelEvent(int delta)
{
if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
const int numDegrees = delta / 8;
const int numSteps = numDegrees / 15;
q->setZoomFactor(q->zoomFactor() + numSteps * 0.1);
return true;
}
return false;
}
bool mouseReleased(const QPoint &pos)
{
hitTest = q->page()->mainFrame()->hitTestContent(pos);
const QUrl url = hitTest.linkUrl();
if (!url.isEmpty()) {
if ((pressedButtons & Qt::MiddleButton) ||
((pressedButtons & Qt::LeftButton) && (keyboardModifiers & Qt::ControlModifier))) {
emit q->linkMiddleOrCtrlClicked(url);
return true;
}
if ((pressedButtons & Qt::LeftButton) && (keyboardModifiers & Qt::ShiftModifier)) {
emit q->linkShiftClicked(url);
return true;
}
}
return false;
}
bool handleUrlPasteFromClipboard(QEvent* event)
{
QWebPage *page = q->page();
if ((pressedButtons & Qt::MiddleButton) && page) {
// WORKAROUND: Let the page handle the event first so that middle clicking
// on scroll bars does not cause navigation to a url that might have been
// copied into the selection clipboard.
page->event(event);
if (event->isAccepted())
return true;
if (!hitTest.linkUrl().isValid() && !hitTest.isContentEditable() && !page->isModified()) {
QString subType (QLatin1String("plain"));
const QString clipboardText = QApplication::clipboard()->text(subType, QClipboard::Selection);
if (!clipboardText.isEmpty()) {
KUriFilterData data (clipboardText.left(250).trimmed());
data.setCheckForExecutables(false); // don't allow executables...
if (KUriFilter::self()->filterUri(data, QStringList(QLatin1String("kshorturifilter")))) {
switch (data.uriType()) {
case KUriFilterData::LocalFile:
case KUriFilterData::LocalDir:
case KUriFilterData::NetProtocol:
emit q->selectionClipboardUrlPasted(data.uri(), QString());
return true;
default:
break;
}
} else if (KUriFilter::self()->filterSearchUri(data, KUriFilter::NormalTextFilter)) {
emit q->selectionClipboardUrlPasted(data.uri(), clipboardText);
return true;
}
}
}
}
return false;
}
T *q;
Qt::KeyboardModifiers keyboardModifiers;
Qt::MouseButtons pressedButtons;
QWebHitTestResult hitTest;
};
#endif // KWEBVIEW_P_H

View file

@ -1,617 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "kwebwallet.h"
#include <kwallet.h>
#include <kdebug.h>
#include <QtCore/QSet>
#include <QtCore/QHash>
#include <QtCore/QFile>
#include <QtCore/qsharedpointer.h>
#include <QtCore/QScopedPointer>
#include <QtWebKit/QWebPage>
#include <QtWebKit/QWebFrame>
#include <QtWebKit/QWebElement>
#include <qwindowdefs.h>
#define QL1S(x) QLatin1String(x)
#define QL1C(x) QLatin1Char(x)
// Javascript used to extract/set data from <form> elements.
#define FILLABLE_FORM_ELEMENT_EXTRACTOR_JS "(function (){ \
var forms; \
var formList = document.forms; \
if (formList.length > 0) { \
forms = new Array; \
for (var i = 0; i < formList.length; ++i) { \
var inputList = formList[i].elements; \
if (inputList.length < 1) { \
continue; \
} \
var formObject = new Object; \
formObject.name = formList[i].name; \
if (typeof(formObject.name) != 'string') { \
formObject.name = String(formList[i].id); \
} \
formObject.index = i; \
formObject.elements = new Array; \
for (var j = 0; j < inputList.length; ++j) { \
if (inputList[j].type != 'text' && inputList[j].type != 'email' && inputList[j].type != 'password') { \
continue; \
} \
if (inputList[j].disabled || inputList[j].autocomplete == 'off') { \
continue; \
} \
var element = new Object; \
element.name = inputList[j].name; \
if (typeof(element.name) != 'string' ) { \
element.name = String(inputList[j].id); \
} \
element.value = String(inputList[j].value); \
element.type = String(inputList[j].type); \
element.readonly = Boolean(inputList[j].readOnly); \
formObject.elements.push(element); \
} \
if (formObject.elements.length > 0) { \
forms.push(formObject); \
} \
} \
} \
return forms; \
}())"
/**
* Creates key used to store and retrieve form data.
*
*/
static QString walletKey(KWebWallet::WebForm form)
{
QString key = form.url.toString(QUrl::RemoveQuery|QUrl::RemoveFragment);
key += QL1C('#');
key += form.name;
return key;
}
static void collectAllChildFrames(QWebFrame* frame, QList<QWebFrame*>& list)
{
list << frame->childFrames();
QListIterator<QWebFrame*> it(frame->childFrames());
while (it.hasNext()) {
collectAllChildFrames(it.next(), list);
}
}
static QUrl urlForFrame(QWebFrame* frame)
{
return (frame->url().isEmpty() ? frame->baseUrl().resolved(frame->url()) : frame->url());
}
/*
Returns the top most window associated with widget.
Unlike QWidget::window(), this function does its best to find and return the
main application window associated with a given widget. It will not stop when
it encounters a dialog which likely "has (or could have) a window-system frame".
*/
static QWidget* topLevelWindow(QObject* obj)
{
QWebPage *page = qobject_cast<QWebPage*>(obj);
QWidget* widget = (page ? page->view() : qobject_cast<QWidget*>(page));
while (widget && widget->parentWidget()) {
widget = widget->parentWidget();
}
return (widget ? widget->window() : 0);
}
class KWebWallet::KWebWalletPrivate
{
public:
struct FormsData
{
QWeakPointer<QWebFrame> frame;
KWebWallet::WebFormList forms;
};
KWebWalletPrivate(KWebWallet* parent);
KWebWallet::WebFormList parseFormData(QWebFrame* frame, bool fillform = true, bool ignorepasswd = false);
void fillDataFromCache(KWebWallet::WebFormList &formList);
void saveDataToCache(const QString &key);
void removeDataFromCache(const WebFormList &formList);
void openWallet();
// Private slots...
void _k_openWalletDone(bool);
void _k_walletClosed();
WId wid;
KWebWallet *q;
QScopedPointer<KWallet::Wallet> wallet;
KWebWallet::WebFormList pendingRemoveRequests;
QHash<KUrl, FormsData> pendingFillRequests;
QHash<QString, KWebWallet::WebFormList> pendingSaveRequests;
QSet<KUrl> confirmSaveRequestOverwrites;
};
KWebWallet::KWebWalletPrivate::KWebWalletPrivate(KWebWallet *parent)
:wid (0), q(parent)
{
}
KWebWallet::WebFormList KWebWallet::KWebWalletPrivate::parseFormData(QWebFrame *frame, bool fillform, bool ignorepasswd)
{
Q_ASSERT(frame);
KWebWallet::WebFormList list;
const QVariant result (frame->evaluateJavaScript(QL1S(FILLABLE_FORM_ELEMENT_EXTRACTOR_JS)));
const QVariantList results (result.toList());
Q_FOREACH (const QVariant &formVariant, results) {
QVariantMap map = formVariant.toMap();
KWebWallet::WebForm form;
form.url = urlForFrame(frame);
form.name = map[QL1S("name")].toString();
form.index = map[QL1S("index")].toString();
bool formHasPasswords = false;
const QVariantList elements = map[QL1S("elements")].toList();
QList<KWebWallet::WebForm::WebField> inputFields;
Q_FOREACH (const QVariant &element, elements) {
QVariantMap elementMap (element.toMap());
const QString name (elementMap[QL1S("name")].toString());
const QString value (ignorepasswd ? QString() : elementMap[QL1S("value")].toString());
if (name.isEmpty()) {
continue;
}
if (fillform && elementMap[QL1S("readonly")].toBool()) {
continue;
}
if (elementMap[QL1S("type")].toString().compare(QL1S("password"), Qt::CaseInsensitive) == 0) {
if (!fillform && value.isEmpty())
continue;
formHasPasswords = true;
}
inputFields.append(qMakePair(name, value));
}
// Only add the input fields on form save requests...
if (formHasPasswords || fillform) {
form.fields = inputFields;
}
// Add the form to the list if we are saving it or it has cached data.
if ((fillform && q->hasCachedFormData(form)) || (!fillform && !form.fields.isEmpty()))
list << form;
}
return list;
}
void KWebWallet::KWebWalletPrivate::fillDataFromCache(KWebWallet::WebFormList &formList)
{
if (!wallet) {
kWarning(800) << "Unable to retrieve form data from wallet";
return;
}
QString lastKey;
QMap<QString, QString> cachedValues;
QMutableListIterator <WebForm> formIt (formList);
while (formIt.hasNext()) {
KWebWallet::WebForm &form = formIt.next();
const QString key (walletKey(form));
if (key != lastKey && wallet->readMap(key, cachedValues) != 0) {
kWarning(800) << "Unable to read form data for key:" << key;
continue;
}
for (int i = 0, count = form.fields.count(); i < count; ++i) {
form.fields[i].second = cachedValues.value(form.fields[i].first);
}
lastKey = key;
}
}
void KWebWallet::KWebWalletPrivate::saveDataToCache(const QString &key)
{
// Make sure the specified keys exists before acting on it. See BR# 270209.
if (!pendingSaveRequests.contains(key)) {
return;
}
bool success = false;
const QUrl url = pendingSaveRequests.value(key).first().url;
if (wallet) {
int count = 0;
const KWebWallet::WebFormList list = pendingSaveRequests.value(key);
QListIterator<KWebWallet::WebForm> formIt (list);
while (formIt.hasNext()) {
QMap<QString, QString> values, storedValues;
const KWebWallet::WebForm form = formIt.next();
const QString accessKey = walletKey(form);
if (confirmSaveRequestOverwrites.contains(url)) {
confirmSaveRequestOverwrites.remove(url);
const int status = wallet->readMap(accessKey, storedValues);
if (status == 0 && storedValues.count()) {
QListIterator<KWebWallet::WebForm::WebField> fieldIt (form.fields);
while (fieldIt.hasNext()) {
const KWebWallet::WebForm::WebField field = fieldIt.next();
if (storedValues.contains(field.first) &&
storedValues.value(field.first) != field.second) {
emit q->saveFormDataRequested(key, url);
return;
}
}
// If we got here it means the new credential is exactly
// the same as the one already cached ; so skip the
// re-saving part...
success = true;
continue;
}
}
QListIterator<KWebWallet::WebForm::WebField> fieldIt (form.fields);
while (fieldIt.hasNext()) {
const KWebWallet::WebForm::WebField field = fieldIt.next();
values.insert(field.first, field.second);
}
if (wallet->writeMap(accessKey, values) == 0)
count++;
else
kWarning(800) << "Unable to write form data to wallet";
}
if (list.isEmpty() || count > 0)
success = true;
pendingSaveRequests.remove(key);
} else {
kWarning(800) << "NULL KWallet instance!";
}
emit q->saveFormDataCompleted(url, success);
}
void KWebWallet::KWebWalletPrivate::openWallet()
{
if (!wallet.isNull()) {
return;
}
wallet.reset(KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
wid, KWallet::Wallet::Asynchronous));
if (wallet.isNull()) {
return;
}
connect(wallet.data(), SIGNAL(walletOpened(bool)), q, SLOT(_k_openWalletDone(bool)));
connect(wallet.data(), SIGNAL(walletClosed()), q, SLOT(_k_walletClosed()));
}
void KWebWallet::KWebWalletPrivate::removeDataFromCache(const WebFormList &formList)
{
if (!wallet) {
kWarning(800) << "NULL KWallet instance!";
return;
}
QListIterator<WebForm> formIt (formList);
while (formIt.hasNext())
wallet->removeEntry(walletKey(formIt.next()));
}
void KWebWallet::KWebWalletPrivate::_k_openWalletDone(bool ok)
{
Q_ASSERT (wallet);
if (ok &&
(wallet->hasFolder(KWallet::Wallet::FormDataFolder()) ||
wallet->createFolder(KWallet::Wallet::FormDataFolder())) &&
wallet->setFolder(KWallet::Wallet::FormDataFolder())) {
// Do pending fill requests...
if (!pendingFillRequests.isEmpty()) {
KUrl::List urlList;
QMutableHashIterator<KUrl, FormsData> requestIt (pendingFillRequests);
while (requestIt.hasNext()) {
requestIt.next();
KWebWallet::WebFormList list = requestIt.value().forms;
fillDataFromCache(list);
q->fillWebForm(requestIt.key(), list);
}
pendingFillRequests.clear();
}
// Do pending save requests...
if (!pendingSaveRequests.isEmpty()) {
QListIterator<QString> keysIt (pendingSaveRequests.keys());
while (keysIt.hasNext())
saveDataToCache(keysIt.next());
}
// Do pending remove requests...
if (!pendingRemoveRequests.isEmpty()) {
removeDataFromCache(pendingRemoveRequests);
pendingRemoveRequests.clear();
}
} else {
// Delete the wallet if opening the wallet failed or we were unable
// to change to the folder we wanted to change to.
delete wallet.take();
}
}
void KWebWallet::KWebWalletPrivate::_k_walletClosed()
{
if (wallet)
wallet.take()->deleteLater();
emit q->walletClosed();
}
KWebWallet::KWebWallet(QObject *parent, WId wid)
:QObject(parent), d(new KWebWalletPrivate(this))
{
if (!wid) {
// If wid is 0, make a best effort attempt to discern it from our
// parent object.
QWidget* widget = topLevelWindow(parent);
if (widget) {
wid = widget->winId();
}
}
d->wid = wid;
}
KWebWallet::~KWebWallet()
{
delete d;
}
KWebWallet::WebFormList KWebWallet::formsWithCachedData(QWebFrame* frame, bool recursive) const
{
WebFormList list;
if (frame) {
list << d->parseFormData(frame);
if (recursive) {
QList<QWebFrame*> childFrameList;
collectAllChildFrames(frame, childFrameList);
QListIterator <QWebFrame *> framesIt (childFrameList);
while (framesIt.hasNext()) {
list << d->parseFormData(framesIt.next());
}
}
}
return list;
}
void KWebWallet::fillFormData(QWebFrame *frame, bool recursive)
{
if (!frame)
return;
KUrl::List urlList;
WebFormList formsList = d->parseFormData(frame);
if (!formsList.isEmpty()) {
const QUrl url (urlForFrame(frame));
if (d->pendingFillRequests.contains(url)) {
kWarning(800) << "Duplicate request rejected!";
} else {
KWebWalletPrivate::FormsData data;
data.frame = QWeakPointer<QWebFrame>(frame);
data.forms << formsList;
d->pendingFillRequests.insert(url, data);
urlList << url;
}
}
if (recursive) {
QList<QWebFrame*> childFrameList;
collectAllChildFrames(frame, childFrameList);
QListIterator<QWebFrame*> frameIt (childFrameList);
while (frameIt.hasNext()) {
QWebFrame *childFrame = frameIt.next();
formsList = d->parseFormData(childFrame);
if (formsList.isEmpty())
continue;
const QUrl url (childFrame->url());
if (d->pendingFillRequests.contains(url)) {
kWarning(800) << "Duplicate request rejected!!!";
} else {
KWebWalletPrivate::FormsData data;
data.frame = QWeakPointer<QWebFrame>(childFrame);
data.forms << formsList;
d->pendingFillRequests.insert(url, data);
urlList << url;
}
}
}
if (!urlList.isEmpty())
fillFormDataFromCache(urlList);
}
static void createSaveKeyFor(QWebFrame* frame, QString* key)
{
QUrl frameUrl(urlForFrame(frame));
frameUrl.setPassword(QString());
frameUrl.setPassword(QString());
QString keyStr = frameUrl.toString();
if (!frame->frameName().isEmpty())
keyStr += frame->frameName();
*key = QString::number(qHash(keyStr), 16);
}
void KWebWallet::saveFormData(QWebFrame *frame, bool recursive, bool ignorePasswordFields)
{
if (!frame)
return;
QString key;
createSaveKeyFor(frame, &key);
if (d->pendingSaveRequests.contains(key))
return;
WebFormList list = d->parseFormData(frame, false, ignorePasswordFields);
if (recursive) {
QList<QWebFrame*> childFrameList;
collectAllChildFrames(frame, childFrameList);
QListIterator<QWebFrame*> frameIt (childFrameList);
while (frameIt.hasNext())
list << d->parseFormData(frameIt.next(), false, ignorePasswordFields);
}
if (list.isEmpty())
return;
d->pendingSaveRequests.insert(key, list);
QMutableListIterator<WebForm> it (list);
while (it.hasNext()) {
const WebForm form (it.next());
if (hasCachedFormData(form))
it.remove();
}
if (list.isEmpty()) {
d->confirmSaveRequestOverwrites.insert(urlForFrame(frame));
saveFormDataToCache(key);
return;
}
emit saveFormDataRequested(key, urlForFrame(frame));
}
void KWebWallet::removeFormData(QWebFrame *frame, bool recursive)
{
if (frame)
removeFormDataFromCache(formsWithCachedData(frame, recursive));
}
void KWebWallet::removeFormData(const WebFormList &forms)
{
d->pendingRemoveRequests << forms;
removeFormDataFromCache(forms);
}
void KWebWallet::acceptSaveFormDataRequest(const QString &key)
{
saveFormDataToCache(key);
}
void KWebWallet::rejectSaveFormDataRequest(const QString & key)
{
d->pendingSaveRequests.remove(key);
}
void KWebWallet::fillWebForm(const KUrl &url, const KWebWallet::WebFormList &forms)
{
QWeakPointer<QWebFrame> frame = d->pendingFillRequests.value(url).frame;
if (!frame)
return;
QString script;
bool wasFilled = false;
Q_FOREACH (const KWebWallet::WebForm& form, forms) {
Q_FOREACH(const KWebWallet::WebForm::WebField& field, form.fields) {
QString value = field.second;
value.replace(QL1C('\\'), QL1S("\\\\"));
script += QString::fromLatin1("if (document.forms[\"%1\"].elements[\"%2\"]) document.forms[\"%1\"].elements[\"%2\"].value=\"%3\";\n")
.arg((form.name.isEmpty() ? form.index : form.name))
.arg(field.first).arg(value);
}
}
if (!script.isEmpty()) {
wasFilled = true;
frame.data()->evaluateJavaScript(script);
}
emit fillFormRequestCompleted(wasFilled);
}
KWebWallet::WebFormList KWebWallet::formsToFill(const KUrl &url) const
{
return d->pendingFillRequests.value(url).forms;
}
KWebWallet::WebFormList KWebWallet::formsToSave(const QString &key) const
{
return d->pendingSaveRequests.value(key);
}
bool KWebWallet::hasCachedFormData(const WebForm &form) const
{
return !KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(),
KWallet::Wallet::FormDataFolder(),
walletKey(form));
}
void KWebWallet::fillFormDataFromCache(const KUrl::List &urlList)
{
if (d->wallet) {
QListIterator<KUrl> urlIt (urlList);
while (urlIt.hasNext()) {
const KUrl url = urlIt.next();
WebFormList list = formsToFill(url);
d->fillDataFromCache(list);
fillWebForm(url, list);
}
d->pendingFillRequests.clear();
}
d->openWallet();
}
void KWebWallet::saveFormDataToCache(const QString &key)
{
if (d->wallet) {
d->saveDataToCache(key);
return;
}
d->openWallet();
}
void KWebWallet::removeFormDataFromCache(const WebFormList &forms)
{
if (d->wallet) {
d->removeDataFromCache(forms);
d->pendingRemoveRequests.clear();
return;
}
d->openWallet();
}
#include "moc_kwebwallet.cpp"

View file

@ -1,320 +0,0 @@
/*
* This file is part of the KDE project.
*
* Copyright (C) 2009 Dawit Alemayehu <adawit@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef KWEBWALLET_H
#define KWEBWALLET_H
#include <kdewebkit_export.h>
#include <kurl.h>
#include <QtCore/QObject>
#include <QtCore/QPair>
#include <QtGui/QWidget>
class QWebFrame;
class QWebPage;
/**
* @short A class that provides KDE wallet integration for QWebFrame.
*
* Normally, you will use this class via KWebPage. In this case, you need to
* connect to the saveFormDataRequested signal and call either
* acceptSaveFormDataRequest or rejectSaveFormDataRequest, typically after
* asking the user whether they want to save the form data.
*
* You will also need to call fillFormData when a QWebFrame has finished
* loading. To do this, connect to QWebPage::loadFinished and, if the page was
* loaded successfully, call
* @code
* page->wallet()->fillFormData(page->mainFrame());
* @endcode
*
* If you wish to use this directly with a subclass of QWebPage, you should call
* saveFormData from QWebPage::acceptNavigationRequest when a user submits a
* form.
*
* @see KWebPage
*
* @author Dawit Alemayehu <adawit @ kde.org>
* @since 4.4
*/
class KDEWEBKIT_EXPORT KWebWallet : public QObject
{
Q_OBJECT
public:
/**
* Holds data from a HTML &lt;form&gt; element.
*/
struct WebForm
{
/**
* A typedef for storing the name and value attributes of HTML &lt;input&gt;
* elements.
*/
typedef QPair<QString, QString> WebField;
/** The URL the form was found at. */
QUrl url;
/** The name attribute of the form. */
QString name;
/** The position of the form on the web page, relative to other forms. */
QString index;
/** The name and value attributes of each input element in the form. */
QList<WebField> fields;
};
/**
* A list of web forms
*/
typedef QList<WebForm> WebFormList;
/**
* Constructs a KWebWallet
*
* @p parent is usually the QWebPage this wallet is being used for.
*
* The @p wid parameter is used to tell KDE's wallet manager which window
* is requesting access to the wallet.
*
* @param parent the owner of this wallet
* @param wid the window ID of the window the web page will be
* embedded in
*/
explicit KWebWallet(QObject* parent = 0, WId wid = 0);
/**
* Destructor
*/
virtual ~KWebWallet();
/**
* Returns a list of forms in @p frame that have cached data in the
* peristent storage.
*
* If @p recursive is set to true, the default, then this function will
* will also return the cached form data for all the children frames of
* @p frame.
*
* If the site currently rendered in @p frame does not contain any forms
* or there is no cached data for the forms found in @p frame, then this
* function will return an empty list.
*
* Note that this function will only return the information about the forms
* in @p frame and not their cached data, i.e. the fields member variable in
* the returned @ref WebForm list will always be empty.
*/
WebFormList formsWithCachedData(QWebFrame* frame, bool recursive = true) const;
/**
* Attempts to save the form data from @p frame and its children frames.
*
* If @p recursive is set to true, the default, then form data from all
* the child frames of @p frame will be saved. Set @p ignorePasswordFields
* to true if you do not want data from password fields to not be saved.
*
* You must connect to the @ref saveFormDataRequested signal and call either
* @ref rejectSaveFormDataRequest or @ref acceptSaveFormDataRequest signals
* in order to complete the save request. Otherwise, you request will simply
* be ignored.
*/
void saveFormData(QWebFrame *frame, bool recursive = true, bool ignorePasswordFields = false);
/**
* Attempts to fill forms contained in @p frame with cached data.
*
* If @p recursive is set to true, the default, then this function will
* attempt to fill out forms in the specified frame and all its children
* frames.
*/
void fillFormData(QWebFrame *frame, bool recursive = true);
/**
* Removes the form data specified by @p forms from the persistent storage.
*
* This function is provided for convenience and simply calls @ref formsWithCachedData
* and @ref removeFormData(WebFormList). Note that this function will remove all cached
* data for forms found in @p frame. If @p recursive is set to true, then
* all cached data for all of the child frames of @p frame will be removed
* from the persistent storage as well.
*
* @see formsWithCachedData
* @see removeFormData
*/
void removeFormData (QWebFrame *frame, bool recursive);
/**
* Removes the form data specified by @p forms from the persistent storage.
*
* Call @ref formsWithCachedData to obtain a list of forms with data cached
* in persistent storage.
*
* @see formsWithCachedData
*/
void removeFormData(const WebFormList &forms);
public Q_SLOTS:
/**
* Accepts the save form data request associated with @p key.
*
* The @p key parameter is the one sent through the @ref saveFormDataRequested
* signal.
*
* You must always call this function or @ref rejectSaveFormDataRequest in
* order to complete the save form data request. Otherwise, the request will
* simply be ignored.
*
* @see saveFormDataRequested.
*/
void acceptSaveFormDataRequest(const QString &key);
/**
* Rejects the save form data request associated with @p key.
*
* The @p key parameter is the one sent through the @ref saveFormDataRequested
* signal.
*
* @see saveFormDataRequested.
*/
void rejectSaveFormDataRequest(const QString &key);
Q_SIGNALS:
/**
* This signal is emitted whenever a save form data request is received.
*
* Unless you connect to this signal and and call @ref acceptSaveFormDataRequest
* or @ref rejectSaveFormDataRequest slots, the save form data requested through
* @ref saveFormData will simply be ignored.
*
* @p key is a value that uniquely identifies the save request and @p url
* is the address for which the form data is being saved.
*
* @see acceptSaveFormDataRequest
* @see rejectSaveFormDataRequest
*/
void saveFormDataRequested(const QString &key, const QUrl &url);
/**
* This signal is emitted whenever a save form data request is completed.
*
* @p ok will be set to true if the save form data request for @p url was
* completed successfully.
*
* @see saveFormDataRequested
*/
void saveFormDataCompleted(const QUrl &url, bool ok);
/**
* This signal is emitted whenever a fill form data request is completed.
*
* @p ok will be set to true if any forms were successfully filled with
* cached data from the persistent storage.
*
* @see fillFormData
* @since 4.5
*/
void fillFormRequestCompleted(bool ok);
/**
* This signal is emitted whenever the current wallet is closed.
*/
void walletClosed();
protected:
/**
* Returns a list of forms for @p url that are waiting to be filled.
*
* This function returns an empty list if there is no pending requests
* for filling forms associated with @p url.
*/
WebFormList formsToFill(const KUrl &url) const;
/**
* Returns a list of for @p key that are waiting to be saved.
*
* This function returns an empty list if there are no pending requests
* for saving forms associated with @p key.
*/
WebFormList formsToSave(const QString &key) const;
/**
* Returns forms to be removed from persistent storage.
*/
WebFormList formsToDelete() const;
/**
* Returns true when there is data associated with @p form in the
* persistent storage.
*/
virtual bool hasCachedFormData(const WebForm &form) const;
/**
* Fills the web forms in frame that point to @p url with data from @p forms.
*
* @see fillFormDataFromCache.
*/
void fillWebForm(const KUrl &url, const WebFormList &forms);
/**
* Fills form data from persistent storage.
*
* If you reimplement this function, call @ref formsToFill to obtain
* the list of forms pending to be filled. Once you fill the list with
* the cached data from the persistent storage, you must call @p fillWebForm
* to fill out the actual web forms.
*
* @see formsToFill
*/
virtual void fillFormDataFromCache(const KUrl::List &list);
/**
* Stores form data associated with @p key to a persistent storage.
*
* If you reimplement this function, call @ref formsToSave to obtain the
* list of form data pending to be saved to persistent storage.
*
*@see formsToSave
*/
virtual void saveFormDataToCache(const QString &key);
/**
* Removes all cached form data associated with @p forms from persistent storage.
*
* If you reimplement this function, call @ref formsToDelete to obtain the
* list of form data pending to be removed from persistent storage.
*
*@see formsToDelete
*/
virtual void removeFormDataFromCache(const WebFormList &forms);
private:
class KWebWalletPrivate;
friend class KWebWalletPrivate;
KWebWalletPrivate * const d;
Q_PRIVATE_SLOT(d, void _k_openWalletDone(bool))
Q_PRIVATE_SLOT(d, void _k_walletClosed())
};
#endif // KWEBWALLET_H

View file

@ -40,25 +40,5 @@ if(QT_QTDESIGNER_FOUND)
TARGETS kdewidgets
DESTINATION ${PLUGIN_INSTALL_DIR}/kde4/plugins/designer
)
if(QT_QTWEBKIT_FOUND)
include_directories(
${CMAKE_SOURCE_DIR}/kdewebkit
${CMAKE_BINARY_DIR}/kdewebkit
)
kde4_add_widget(kdewebkitwidgets_SRCS kdewebkit.widgets)
qt4_add_resources(kdewebkitwidgets_SRCS kdewebkitwidgets.qrc)
kde4_add_plugin(kdewebkitwidgets ${kdewebkitwidgets_SRCS})
target_link_libraries(kdewebkitwidgets ${KDE4_KDEWEBKIT_LIBS})
install(
TARGETS kdewebkitwidgets
DESTINATION ${PLUGIN_INSTALL_DIR}/kde4/plugins/designer
)
endif()
endif(QT_QTDESIGNER_FOUND)

View file

@ -1,10 +0,0 @@
[Global]
PluginName=KDEWebKitWidgets
Includes=kcomponentdata.h
Init=new KComponentData("kdewidgets");
[KWebView]
IncludeFile=kwebview.h
ToolTip=KDE WebKit View
WhatsThis=A WebKit view with KDE integration.
Group=Views (KDE)

View file

@ -1,4 +0,0 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
</qresource>
</RCC>

View file

@ -1,15 +1,10 @@
if(KDE_PLATFORM_FEATURE_BINARY_COMPATIBLE_FEATURE_REDUCTION)
set(PLASMA_NO_KDEWEBKIT TRUE)
set(PLASMA_NO_SOLID TRUE)
set(PLASMA_NO_KIO TRUE)
set(PLASMA_NO_KUTILS TRUE)
set(PLASMA_NO_GLOBAL_SHORTCUTS TRUE)
endif()
if(NOT QT_QTWEBKIT_FOUND)
set(PLASMA_NO_KDEWEBKIT TRUE)
endif()
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
${KDE4_KDECORE_INCLUDES}
@ -19,7 +14,6 @@ include_directories(
${CMAKE_SOURCE_DIR}/plasma/extenders
# for the export headers
${CMAKE_BINARY_DIR}/kutils
${CMAKE_BINARY_DIR}/kdewebkit
)
if(NOT PLASMA_NO_KIO)
@ -27,11 +21,6 @@ if(NOT PLASMA_NO_KIO)
set(PLASMA_EXTRA_LIBS ${PLASMA_EXTRA_LIBS} ${KDE4_KIO_LIBS})
endif()
if(NOT PLASMA_NO_KDEWEBKIT)
include_directories(${CMAKE_SOURCE_DIR}/kdewebkit/)
set(PLASMA_EXTRA_LIBS ${PLASMA_EXTRA_LIBS} ${KDE4_KDEWEBKIT_LIBS})
endif()
if(NOT PLASMA_NO_SOLID)
include_directories(${CMAKE_BINARY_DIR}/solid/)
include_directories(${CMAKE_SOURCE_DIR}/solid/)
@ -172,15 +161,6 @@ set(plasma_LIB_SRCS
widgets/textedit.cpp
)
if(QT_QTWEBKIT_FOUND)
set(plasma_LIB_SRCS
${plasma_LIB_SRCS}
private/animablegraphicswebview.cpp
private/animablegraphicswebview_p.h
widgets/webview.cpp
)
endif()
kde4_add_kcfg_files(plasma_LIB_SRCS
data/kconfigxt/libplasma-theme-global.kcfgc
)
@ -298,7 +278,6 @@ install(
widgets/textbrowser.h
widgets/treeview.h
widgets/textedit.h
widgets/webview.h
DESTINATION ${INCLUDE_INSTALL_DIR}/plasma/widgets
COMPONENT Devel
)

View file

@ -1,4 +1,3 @@
#cmakedefine PLASMA_NO_KDEWEBKIT
#cmakedefine PLASMA_NO_SOLID
#cmakedefine PLASMA_NO_KIO
#cmakedefine PLASMA_NO_KUTILS

View file

@ -1,193 +0,0 @@
/*
* Copyright 2006-2007 Aaron Seigo <aseigo@kde.org>
* Copyright 2010 Davide Bettio <davide.bettio@kdemail.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "animablegraphicswebview_p.h"
#include <QtGui/QApplication>
#include <QtGui/qevent.h>
#include <QtGui/qgesture.h>
#include <QtWebKit/QWebFrame>
#include <qwebpage.h>
#include <kglobalsettings.h>
using namespace Plasma;
AnimableGraphicsWebView::AnimableGraphicsWebView(QGraphicsItem * parent)
: GraphicsWebViewBase(parent)
{
setAcceptTouchEvents(true);
m_dragToScroll = false;
}
void AnimableGraphicsWebView::setDragToScroll(bool enable)
{
m_dragToScroll = enable;
}
bool AnimableGraphicsWebView::dragToScroll() const
{
return m_dragToScroll;
}
QSizeF AnimableGraphicsWebView::contentsSize() const
{
if (!page()) {
return QSizeF();
} else {
return page()->mainFrame()->contentsSize();
}
}
void AnimableGraphicsWebView::setScrollPosition(const QPointF &position)
{
if (!page()) {
return;
} else {
page()->mainFrame()->setScrollPosition(position.toPoint());
}
}
QPointF AnimableGraphicsWebView::scrollPosition() const
{
if (!page() || !page()->mainFrame()) {
return QPointF();
} else {
return page()->mainFrame()->scrollPosition();
}
}
qreal AnimableGraphicsWebView::zoom() const
{
return GraphicsWebViewBase::zoomFactor();
}
void AnimableGraphicsWebView::setZoom(const qreal zoom)
{
GraphicsWebViewBase::setZoomFactor(zoom);
}
QRectF AnimableGraphicsWebView::viewportGeometry() const
{
QRectF result;
if (!page()) {
return result;
} else {
return page()->mainFrame()->geometry();
}
}
void AnimableGraphicsWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (!page()) {
GraphicsWebViewBase::mouseMoveEvent(event);
return;
}
if (m_dragToScroll) {
return;
}
QMouseEvent me(QEvent::MouseMove, event->pos().toPoint(), event->button(),
event->buttons(), event->modifiers());
page()->event(&me);
if (me.isAccepted()) {
event->accept();
}
}
void AnimableGraphicsWebView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (!page()) {
GraphicsWebViewBase::mousePressEvent(event);
return;
}
m_lastScrollPosition = scrollPosition();
setFocus();
QMouseEvent me(QEvent::MouseButtonPress, event->pos().toPoint(),
event->button(), event->buttons(), event->modifiers());
page()->event(&me);
if (me.isAccepted() && !m_dragToScroll) {
event->accept();
}
}
void AnimableGraphicsWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (!page()) {
GraphicsWebViewBase::mouseReleaseEvent(event);
return;
}
QMouseEvent me(QEvent::MouseButtonRelease, event->pos().toPoint(),
event->button(),event->buttons(), event->modifiers());
if (!m_dragToScroll || (scrollPosition() - m_lastScrollPosition).manhattanLength() < KGlobalSettings::dndEventDelay()) {
page()->event(&me);
}
if (me.isAccepted() && !m_dragToScroll) {
event->accept();
}
}
void AnimableGraphicsWebView::wheelEvent(QGraphicsSceneWheelEvent *event)
{
if (!page()) {
GraphicsWebViewBase::wheelEvent(event);
return;
}
QWheelEvent we(event->pos().toPoint(), event->delta(), event->buttons(),
event->modifiers(), event->orientation());
page()->event(&we);
event->setAccepted(!m_dragToScroll);
}
qreal AnimableGraphicsWebView::scrollPositionX() const
{
return page()->mainFrame()->scrollPosition().x();
}
void AnimableGraphicsWebView::setScrollPositionX(qreal position)
{
QPointF pt(position, scrollPositionY());
setScrollPosition(pt);
}
qreal AnimableGraphicsWebView::scrollPositionY() const
{
return page()->mainFrame()->scrollPosition().y();
}
void AnimableGraphicsWebView::setScrollPositionY(qreal position)
{
QPointF pt(scrollPositionX(), position);
setScrollPosition(pt);
}
#include "moc_animablegraphicswebview_p.cpp"

View file

@ -1,80 +0,0 @@
/*
* Copyright 2006-2007 Aaron Seigo <aseigo@kde.org>
* Copyright 2010 Davide Bettio <davide.bettio@kdemail.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef ANIMABLEWEBVIEW_P_H
#define ANIMABLEWEBVIEW_P_H
#include <QtGui/qgraphicssceneevent.h>
#include <QtGui/QGraphicsView>
#include <config-plasma.h>
#ifndef PLASMA_NO_KDEWEBKIT
#include <kgraphicswebview.h>
#define GraphicsWebViewBase KGraphicsWebView
#else
#include <qgraphicswebview.h>
#define GraphicsWebViewBase QGraphicsWebView
#endif
namespace Plasma
{
class AnimableGraphicsWebView : public GraphicsWebViewBase
{
Q_OBJECT
Q_PROPERTY(qreal zoomFactor READ zoom WRITE setZoom)
Q_PROPERTY(QPointF scrollPosition READ scrollPosition WRITE setScrollPosition)
Q_PROPERTY(qreal scrollPositionX READ scrollPositionX WRITE setScrollPositionX)
Q_PROPERTY(qreal scrollPositionY READ scrollPositionY WRITE setScrollPositionY)
Q_PROPERTY(QSizeF contentsSize READ contentsSize)
Q_PROPERTY(QRectF viewportGeometry READ viewportGeometry)
public:
AnimableGraphicsWebView(QGraphicsItem * parent = 0);
QPointF scrollPosition() const;
void setScrollPosition(const QPointF &position);
qreal scrollPositionX() const;
void setScrollPositionX(qreal position);
qreal scrollPositionY() const;
void setScrollPositionY(qreal position);
QSizeF contentsSize() const;
QRectF viewportGeometry() const;
void setDragToScroll(bool enable);
bool dragToScroll() const;
qreal zoom() const;
void setZoom(const qreal zoom);
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void wheelEvent(QGraphicsSceneWheelEvent *event);
private:
bool m_dragToScroll;
QPointF m_lastScrollPosition;
};
}
#endif

View file

@ -1,257 +0,0 @@
/*
* Copyright 2006-2007 Aaron Seigo <aseigo@kde.org>
* Copyright 2010 Davide Bettio <davide.bettio@kdemail.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QtGui/QApplication>
#include <QtGui/qstyleoption.h>
#include <fixx11h.h>
#include <QtWebKit/QWebFrame>
#include <QtWebKit/QWebPage>
#include <QtCore/QTimer>
#include <config-plasma.h>
#ifndef PLASMA_NO_KIO
#include <kio/accessmanager.h>
#endif
#include <kdebug.h>
#include "animator.h"
#include "plasma.h"
#include "widgets/webview.h"
#include "widgets/scrollwidget.h"
#include "private/animablegraphicswebview_p.h"
namespace Plasma
{
class WebViewPrivate
{
public:
WebViewPrivate(WebView *parent)
: q(parent)
{
}
void loadingFinished(bool success);
void dragTimeoutExpired();
WebView *q;
AnimableGraphicsWebView *webView;
ScrollWidget *scrollWidget;
bool loaded;
};
WebView::WebView(QGraphicsItem *parent)
: QGraphicsWidget(parent),
d(new WebViewPrivate(this))
{
d->loaded = false;
setAcceptTouchEvents(true);
setAcceptHoverEvents(true);
setFlags(QGraphicsItem::ItemIsFocusable);
d->scrollWidget = new Plasma::ScrollWidget(this);
d->webView = new AnimableGraphicsWebView(d->scrollWidget);
d->scrollWidget->setWidget(d->webView);
d->scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
d->scrollWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setDragToScroll(false);
QPalette palette = qApp->palette();
palette.setBrush(QPalette::Base, Qt::transparent);
d->webView->page()->setPalette(palette);
#ifndef PLASMA_NO_KIO
d->webView->page()->setNetworkAccessManager(new KIO::AccessManager(d->webView->page()));
#endif
connect(d->webView, SIGNAL(loadProgress(int)),
this, SIGNAL(loadProgress(int)));
connect(d->webView, SIGNAL(loadFinished(bool)),
this, SLOT(loadingFinished(bool)));
connect(d->webView, SIGNAL(urlChanged(QUrl)),
this, SIGNAL(urlChanged(QUrl)));
}
WebView::~WebView()
{
delete d;
}
void WebView::setUrl(const KUrl &url)
{
d->loaded = false;
d->webView->load(url);
}
KUrl WebView::url() const
{
return d->webView->url();
}
void WebView::setHtml(const QByteArray &html, const KUrl &baseUrl)
{
d->loaded = false;
d->webView->setContent(html, QString(), baseUrl);
}
void WebView::setHtml(const QString &html, const KUrl &baseUrl)
{
d->loaded = false;
d->webView->setHtml(html, baseUrl);
}
QString WebView::html() const
{
return d->webView->page()->mainFrame()->toHtml();
}
QRectF WebView::geometry() const
{
if (d->loaded) {
return QRectF(pos(), d->webView->page()->mainFrame()->geometry().size());
} else {
return QGraphicsWidget::geometry();
}
}
QSizeF WebView::contentsSize() const
{
return d->webView->page()->mainFrame()->contentsSize();
}
void WebView::setScrollPosition(const QPointF &position)
{
d->webView->setScrollPosition(position);
}
QPointF WebView::scrollPosition() const
{
return d->webView->scrollPosition();
}
QRectF WebView::viewportGeometry() const
{
return d->webView->page()->mainFrame()->geometry();
}
qreal WebView::zoomFactor() const
{
return d->webView->zoomFactor();
}
void WebView::setZoomFactor(const qreal zoom)
{
d->webView->setZoomFactor(zoom);
}
void WebView::setPage(QWebPage *page)
{
d->webView->setPage(page);
}
QWebPage *WebView::page() const
{
return d->webView->page();
}
QWebFrame *WebView::mainFrame() const
{
return d->webView->page()->mainFrame();
}
void WebView::setDragToScroll(bool drag)
{
// enable / disable scrollbars
if (drag) {
mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
} else {
mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAsNeeded);
mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAsNeeded);
}
d->webView->setDragToScroll(drag);
d->scrollWidget->setFiltersChildEvents(drag);
}
bool WebView::dragToScroll()
{
return d->webView->dragToScroll();
}
void WebView::back()
{
d->webView->back();
}
void WebView::forward()
{
d->webView->forward();
}
void WebView::reload()
{
d->webView->reload();
}
void WebView::stop()
{
d->webView->stop();
}
QVariant WebView::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == QGraphicsItem::ItemSceneHasChanged) {
//FIXME: QWebPage _requires_ a QWidget view to not crash in places such as
// WebCore::PopupMenu::show() due to hostWindow()->platformPageClient() == NULL
// because QWebPage::d->client is NULL
//d->webView->page()->setView(viewFor(this));
}
return QGraphicsWidget::itemChange(change, value);
}
void WebView::setGeometry(const QRectF &geometry)
{
QGraphicsWidget::setGeometry(geometry);
d->scrollWidget->setGeometry(QRectF(0, 0, geometry.width(), geometry.height()));
d->webView->setGeometry(d->scrollWidget->viewportGeometry());
}
QSizeF WebView::sizeHint(Qt::SizeHint which, const QSizeF & constraint) const
{
if (which == Qt::PreferredSize) {
return d->webView->page()->mainFrame()->contentsSize();
} else {
return QGraphicsWidget::sizeHint(which, constraint);
}
}
void WebViewPrivate::loadingFinished(bool success)
{
loaded = success;
q->updateGeometry();
emit q->loadFinished(success);
q->update();
}
} // namespace Plasma
#include "moc_webview.cpp"

View file

@ -1,242 +0,0 @@
/*
* Copyright 2006-2007 Aaron Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PLASMA_WEBVIEW_H
#define PLASMA_WEBVIEW_H
#include <plasma/plasma_export.h>
#include <QtGui/QGraphicsWidget>
#include <kurl.h>
class QWebPage;
class QWebFrame;
#include <QKeyEvent>
#include <QGraphicsSceneDragDropEvent>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneWheelEvent>
#include <QRect>
namespace Plasma
{
class WebViewPrivate;
/**
* @class WebView plasma/widgets/webview.h <Plasma/Widgets/WebView>
*
* @short Provides a widget to display html content in Plasma.
*/
class PLASMA_EXPORT WebView : public QGraphicsWidget
{
Q_OBJECT
Q_PROPERTY(KUrl url READ url WRITE setUrl)
Q_PROPERTY(QString html READ html WRITE setHtml)
Q_PROPERTY(bool dragToScroll READ dragToScroll WRITE setDragToScroll)
Q_PROPERTY(QPointF scrollPosition READ scrollPosition WRITE setScrollPosition)
Q_PROPERTY(QSizeF contentsSize READ contentsSize)
Q_PROPERTY(QRectF viewportGeometry READ viewportGeometry)
Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor)
public:
explicit WebView(QGraphicsItem *parent = 0);
~WebView();
/**
* Sets the URL to display. Loading may happen asynchronously.
*
* @param url the location of the content to load.
*/
void setUrl(const KUrl &url);
/**
* @return the html content of the page
*/
KUrl url() const;
/**
* Sets the html to be shown along with a base URL to be used
* to resolve relative references.
*
* @param html the html (in utf8) to display in the content area
* @param baseUrl the base url for relative references
*/
void setHtml(const QByteArray &html, const KUrl &baseUrl = KUrl());
/**
* @return the html content of the page
*/
QString html() const;
/**
* Sets the html to be shown along with a base URL to be used
* to resolve relative references.
*
* @param html the html (in utf8) to display in the content area
* @param baseUrl the base url for relative references
*/
void setHtml(const QString &html, const KUrl &baseUrl = KUrl());
/**
* Reimplementation
*/
QRectF geometry() const;
/**
* @return the size of the internal widget
* @since 4.4
*/
QSizeF contentsSize() const;
/**
* Sets the position of the webpage relative to this widget
* @since 4.4
*/
void setScrollPosition(const QPointF &position);
/**
* @return the position of the webpage relative to this widget
* @since 4.4
*/
QPointF scrollPosition() const;
/**
* The geometry of the area that actually displays the web page
* @since 4.4
*/
QRectF viewportGeometry() const;
/**
* The zoom factor of the page
*
* @since 4.4
*/
qreal zoomFactor() const;
/**
* Sets the zoom factor of the page
*
* @since 4.4
*/
void setZoomFactor(const qreal zoom);
/**
* Sets the page to use in this item. The owner of the webpage remains,
* however if this WebView object is the owner of the current page,
* then the current page is deleted
*
* @param page the page to set in this view
*/
void setPage(QWebPage *page);
/**
* The QWebPage associated with this item. Useful when more
* of the features of the full QWebPage object need to be accessed.
*/
QWebPage *page() const;
/**
* The main web frame associated with this item.
*/
QWebFrame *mainFrame() const;
/**
* Sets if the page can be scrolled around by dragging the contents with the mouse
* @since 4.3
*/
void setDragToScroll(bool drag);
/**
* @return true if the page can be scrolled by dragging the mouse
* @since 4.3
*/
bool dragToScroll();
/**
* Reimplementation
*/
void setGeometry(const QRectF &geometry);
public Q_SLOTS:
/**
* Loads the previous document in the list of documents built by navigating links.
* @since 4.6
*/
void back();
/**
* Loads the next document in the list of documents built by navigating links.
* @since 4.6
*/
void forward();
/**
* Reloads the current document.
* @since 4.6
*/
void reload();
/**
* Stops loading the document.
* @since 4.6
*/
void stop();
Q_SIGNALS:
/**
* During loading progress, this signal is emitted. The values
* are always between 0 and 100, inclusive.
*
* @param percent the estimated amount the loading is complete
*/
void loadProgress(int percent);
/**
* This signal is emitted when loading is completed.
*
* @param success true if the content was loaded successfully,
* otherwise false
*/
void loadFinished(bool success);
/**
* url displayed by the web page changed
* @since 4.6
*/
void urlChanged(const QUrl &url);
protected:
/**
* Reimplementation
*/
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const;
private:
Q_PRIVATE_SLOT(d, void loadingFinished(bool success))
WebViewPrivate * const d;
friend class WebViewPrivate;
};
} // namespace Plasma
#endif // Multiple incluson guard