diff --git a/.gitignore b/.gitignore index 2c0d7db7..9d28a012 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ ms_print.* doc/ .qmake.stash build +.vscode \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..b90881a8 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tools/htmlToXBel"] + path = tools/htmlToXBel + url = https://gitlab.com/EndorphinBrowser/tools/htmlToXBel.git diff --git a/BUILDING.md b/BUILDING.md index cf4eb33b..376252a1 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -5,14 +5,13 @@ Endorphin is still in development, which means that there are no compiled instal ### Step 1: Make sure git is installed. To see if git is installed, open up a terminal window and type `git`. If it is not installed, the terminal will report back command not found. If it is installed, you'll receive the git help text. To install git: [Windows](https://gitforwindows.org/), [Mac](https://git-scm.com/download/mac), and for Linux, use your distro's package manager. -### Step 2: Download and install Qt 5.14 or greater. -If you already have **Qt 5.14** or greater installed, you can skip this step. -To install Qt 5.14, visit the [Download Page](https://www.qt.io/download) or use your distro's package manager on Linux. Be sure to add the correct PATH variable if required in the official install instructions. When you're done, skip the alternative method section, and move onto Step 3. +### Step 2: Download and install Qt 5.15. +If you already have **Qt 5.15** or greater installed, you can skip this step. To install Qt 5.15, visit the [Download Page](https://www.qt.io/download) or use your distro's package manager on Linux. Be sure to add the correct PATH variable if required in the official install instructions. When you're done, skip the alternative method section, and move onto Step 3. ### Step 3: Download and compile the latest Endorphin. Now we will download the latest tree of Endorphin. Issue these commands: ``` -$ git clone git://github.com/EndorphinBrowser/browser.git +$ git clone https://gitlab.com/EndorphinBrowser/browser.git --recursive $ cd browser $ mkdir build && cd build $ cmake .. diff --git a/ChangeLog b/CHANGELOG.arora.md similarity index 77% rename from ChangeLog rename to CHANGELOG.arora.md index b48bb743..5acbf78b 100644 --- a/ChangeLog +++ b/CHANGELOG.arora.md @@ -1,131 +1,82 @@ -UNRELEASED: - -Fixed issues: - endorphin-placesimport sometimes resulted in an "Invalid cross-device link" error. - -Behind the scene: - Add alternative CMake build system - This is not final yet, and currently only works on Linux. - When it is finished, it will replace qmake. - CMake currently reduces the size of endorphin-placesimport from about 2 MB to about 250 KB. - This improvement will be added to QMake later. - -Other: - Remove ClickToFlash - Flash will reach its end-of-life soon, and shouldn't be used at all, so this feature was removed. - Remove usage of some deprecated QT features - -Fixed issues: - Fix many "invalid certificate" errors - -0.12.1 - -Interface: - Add note about this being an inofficial fork - Update included user agents - Improve placeholder text of the searchbox on the front page - -Fixed issues: - Fix language fallback - -0.12.0 - -Interface: - Show the number of downloads in the download manager dialog title - -Fixed issues: - When the 'delete' button is pressed, the downloaded item count was not updated. - Issue: 912: Autofill manager was always storing forms. - Issue: 915: Fixed ssl certificate problem with sites like https://webmail.us.army.mil - By default QSSLConfiguration was only accepting SSLv3 while we want to - accept all of them. - Issue: 918: "Autofill webforms" in Preferences was always checked. - Issue: 931: Fix for fullscreen on Mac - Issue: 957: Workaround for a bug in QCompleter - -Behind the scene: - Support persistent data storage (HTML5 localStorage) - Update to QT5 & latest WebKit to fix many issues with modern websites - Update some internal pages to HTML5 - Code cleanup - -Other: - Remove OS2 support - -This is not an official update to this browser. - -0.11.0 -Interface: - When the privacy indicator is visible clicking on it will result in private mode being turned off. - Add a way to modify the user agent string from within the application. - Support arguments for the external download program - Tweak the adblock dialog spacing and size. - Change the AdBlock dialog to use a simple check box instead of a group box. - Replace Stopped with Download Complete (like in ffx it's less confusing ) - Update the copyright year in the about dialog to include 2010 - Issue: 768: Fix spelling mistake - Issue: 821: Sort columns in cookie dialog by data values instead of string value. This fixes the dates being alphanumerically sorted. - -Behind the scene: - Issue: 891: Fix Text Encoding to work correctly - Issue: 826: Correctly save the history state of a tab when using Qt 4.6 - Fix build breakage with QtWebKit 2.0. - Remove remnant of delayed QWebView creation. Fixes tab restore again. - Style fix: convert tabs to spaces. - -Build system: - Add an application icon for os2. - For finding the locale tools on os2 behave like win32 - When building in debug mode on OS2 just like with Windows enable the console. - Move Endorphin's hooks to the git-hooks format to utilize git-hooks (See: http://github.com/icefox/git-hooks) - Default to lrelease and not lrelease-qt4 on non unix platforms. - QMAKE_EXTRA_UNIX_TARGETS is deprecated; use QMAKE_EXTRA_TARGETS instead. - Enable the raster graphics system by default for X11 - -Translation: - Make "Show Hidden Files" translatable. - Issue: 811: Fix typos in the German translation - Replaced "leichtgewichtiger" with "schlanker" in translation with source "Lightweight WebKit-based wen browser" - Fixed capitalization typo whare the word "Tab" began with a lowercase "t" - Renamed Dutch translation file from nl_BE to nl. - - -0.10.2 -The major issues: - - When compiling with Qt 4.6 Endorphin had been using some API that changes +# Arora Changelog + +This is the changelog of the Arora browser. Arora had a different issue log (not accessible anymore) +and it might be confusing if we used the Endorphin and Arora issue log in the changelog, so the Changelog +was moved to another file. + +## 0.11.0 + +### Interface +- When the privacy indicator is visible clicking on it will result in private mode being turned off. +- Add a way to modify the user agent string from within the application. +- Support arguments for the external download program +- Tweak the adblock dialog spacing and size. +- Change the AdBlock dialog to use a simple check box instead of a group box. +- Replace Stopped with Download Complete (like in ffx it's less confusing ) +- Update the copyright year in the about dialog to include 2010 +- Issue: 768: Fix spelling mistake +- Issue: 821: Sort columns in cookie dialog by data values instead of string value. This fixes the dates being alphanumerically sorted. + +### Behind the scene +- Issue: 891: Fix Text Encoding to work correctly +- Issue: 826: Correctly save the history state of a tab when using Qt 4.6 +- Fix build breakage with QtWebKit 2.0. +- Remove remnant of delayed QWebView creation. Fixes tab restore again. +- Style fix: convert tabs to spaces. + +#### Build system +- Add an application icon for os2. +- For finding the locale tools on os2 behave like win32 +- When building in debug mode on OS2 just like with Windows enable the console. +- Move Arora's hooks to the git-hooks format to utilize git-hooks (See: http://github.com/icefox/git-hooks) +- Default to lrelease and not lrelease-qt4 on non unix platforms. +- QMAKE_EXTRA_UNIX_TARGETS is deprecated; use QMAKE_EXTRA_TARGETS instead. +- Enable the raster graphics system by default for X11 + +### Translation +- Make "Show Hidden Files" translatable. +- Issue: 811: Fix typos in the German translation +- Replaced "leichtgewichtiger" with "schlanker" in translation with source "Lightweight WebKit-based wen browser" +- Fixed capitalization typo whare the word "Tab" began with a lowercase "t" +- Renamed Dutch translation file from nl_BE to nl. + + +## 0.10.2 +### The major issues +- When compiling with Qt 4.6 Arora had been using some API that changes shortly before the release of Qt 4.6.0 after an API review was done for the new API in QtWebKit. This release changes the code to build with the final API that is found in Qt 4.6.0 - - A segfault that could occur when opening a URL on a new window from the command-line. +- A segfault that could occur when opening a URL on a new window from the command-line. -0.10.1 -The major issues: - Issue: 666 Sites were showing a "SSL handshake failure". With the new NetworkAccessManagerProxy the signals were being sent to the proxy and not the primary networkaccessmanager. - Issue: 683: Endorphin crashes when using privacy mode. +## 0.10.1 +### The major issues +- Issue: 666 Sites were showing a "SSL handshake failure". With the new NetworkAccessManagerProxy the signals were being sent to the proxy and not the primary networkaccessmanager. +- Issue: 683: Arora crashes when using privacy mode. When switching to private mode the primary networkaccessmanagers swaps cookiejar's which caused a segfault. Introduce a CookieJarProxy class which will pass the cookie requests to the primary networkaccessmanager's cookiejar. -Translations: - Add Portuguese translation from Américo Monteiro - Updated Turkish translation from Mehmet Nur Olcay - Issue: 682,677 Fix several FR spelling mistakes. - -Fixed Issues: - Issue: 79 Only tab down the completer when the popup is visible. - Issue: 221 When using Qt 4.6 hardcode a webpage to have a white background even when using a dark theme. - Issue: 472 Set the url on the location bar that matches the webview that we are loading the url in, not in the current location bar which might not be the correct one. - Issue: 637 Startup Crash with Qt 4.5.0 (not with any other version) - Issue: 679 Selecting Show only one close button instead of one for each tab requires an application restart to be applied. - Issue: 676 Fix openstreetmap.org's login saving and improve the Wallet password dialog when finding the login name. +### Translations +- Add Portuguese translation from Américo Monteiro +- Updated Turkish translation from Mehmet Nur Olcay +- Issue: 682,677 Fix several FR spelling mistakes. + +### Fixed Issues +- Issue: 79 Only tab down the completer when the popup is visible. +- Issue: 221 When using Qt 4.6 hardcode a webpage to have a white background even when using a dark theme. +- Issue: 472 Set the url on the location bar that matches the webview that we are loading the url in, not in the current location bar which might not be the correct one. +- Issue: 637 Startup Crash with Qt 4.5.0 (not with any other version) +- Issue: 679 Selecting Show only one close button instead of one for each tab requires an application restart to be applied. +- Issue: 676 Fix openstreetmap.org's login saving and improve the Wallet password dialog when finding the login name. Rather than using the document.form[0].name use document.form[0].elements["name"] this allows the name to contain things such as []'s without causing a problem. -Other issues / changes - Add support for the home, favorites, search, and openurl multimedia keys found on some keyboards - Turn on AutoFill by default - Remove the accidental 100MB limit on the disk cache size in the settings dialog. - Make source viewer remember the window size and not block access to the main window +### Other issues / changes +- Add support for the home, favorites, search, and openurl multimedia keys found on some keyboards +- Turn on AutoFill by default +- Remove the accidental 100MB limit on the disk cache size in the settings dialog. +- Make source viewer remember the window size and not block access to the main window -0.10.0 +## 0.10.0 Interface - Issue #24: Add support for AdBlock - Issue #40: Support several common modifiers in the location bar for modifying the typed in url. @@ -140,30 +91,30 @@ Interface - Issue #650: Save the toolbar location allowing the toolbars to be next to each other - Add ctrl-z shortcut to undo the closing of the last tab. - Behave better when access keys are enabled by adding a slight delay to make sure that the ctrl is actually for access keys and not for another shortcut such as ctrl-tab or ctrl-a -- When endorphin crashed on the previous startup give the user a way to bypass the failsafe and restore their session if they really want. +- When Arora crashed on the previous startup give the user a way to bypass the failsafe and restore their session if they really want. - Add the ability to set the length of a session cookie - Enable DNS prefetching and WebKit version in the about dialog when building against Qt 4.6. - Remember what tab you were on when you close the settings dialog - Add a browse button next to the style sheet line edit to help users find files and automatically translate them into url's. - Add icons to the menu actions on freedesktop systems. - Show the configure search engines action in the tools menu -- Change default bookmarks to only have a link to htpp://endorphin-browser.org +- Change default bookmarks to only have a link to htpp://Arora-browser.org Removed all of Qt development type entries - From discussion on http://endorphinbrowser.blogspot.com/2009/08/endorphin-090.html and also the Kubuntu guys strip the bookmarks in their release so it make sense. + From discussion on http://Arorabrowser.blogspot.com/2009/08/Arora-090.html and also the Kubuntu guys strip the bookmarks in their release so it make sense. - Move the Preferences menu item to Tools|Options - Set placeholder text for the start page search box - Add a checkbox to hide/show hidden files in the directory listing. - Change the about dialog text so it can be selected with a mouse so users can copy the application version. - Allow urls to be dropped on the bookmark bar and bookmark menu -Behind the scenes +### Behind the scenes - Force the history completer to be LTR: same as the url line. - Create a new stills class, NetworkAcessManagerProxy that is useful for tracking what QWebPage a QWebReply came from. - Load QWebView settings when the View is created so m_enableAccessKeys will be read from settings - Rename lineedit -> locationbar functions & variables - Enhance SingleApplication so that the host can send messages back to the second application. On Windows this is used to send the window id back to the application that was just started - so it can raise the endorphin window to the front. + so it can raise the Arora window to the front. - Fix some old MSVC compile warnings - Make it possible to retranslate the bookmarks toolbar title - Set the maximumPagesInCache to 3 (default is 0) and provide a way for users to set this value through QSettings. @@ -181,7 +132,7 @@ Behind the scenes - Fix character encoding in directory listing. - Clean up the private browsing message box to make it easier to translate. -Build system +#### Build system - Allow building against a shadow-built WebKit trunk - Ignore more misc generated build files on windows - Add Git hook to check commits for the proper copyright year @@ -190,17 +141,18 @@ Build system - Re-enable sharing the temporary compilation objects for all subprojects. Use the 'ordered' configuration to make sure that we walk through the subdirectories one by one and not all simultaneously when building in parallel. -0.9.0 +## 0.9.0 + Drop support for Qt 4.4. -Interface -FEATURES: +### Interface +#### Features - Add support for search keywords in the location bar. - POST support for OpenSearch suggestion requests. - Add WebKit version to the About dialog [WebKit trunk only]. - Use HTTP pipelining for all network requests [Qt 4.6 only]. -IMPROVEMENTS: +#### Improvements - Remember last used save directory. - Added file dialog to download location settings. - Restrict drag and drop to the same page unless a QWebView accepts it. @@ -214,7 +166,7 @@ IMPROVEMENTS: - Add Planet Qt to the default set of bookmarks. - Remove the text wrapping option from the source viewer's menu and instead enable it by default. -BUGFIXES: +### Bug fixes - Avoid duplicated and contradictory rules on the cookie rule list. - Change the shortcut for showing the bookmark toolbar as it was conflicting with the show bookmark dialog shortcut. - Encode the user input before inserting it into an URL template. @@ -237,7 +189,7 @@ BUGFIXES: - Avoid overwriting the user agent string in the WebPage autotest. - Fix non-ASCII characters displayed garbled for Authors. -Behind the scenes +### Behind the scenes - Merge two blocks of code that deals with oneCloseButton policy. - Make parentWindow() prettier. - Simplify updates of actions in view menu. @@ -245,14 +197,14 @@ Behind the scenes - Save UI changes in the active window before creating a new one. - Move all network related files into one directory. -Build system +#### Build system - When building on osx use qmake -r. - Ignore generated files built on windows. -0.8.0 -Interface -FEATURES: +## 0.8.0 +### Interface +#### Features - When the ctrl key is pressed show keyboard accelerators on the screen. [Qt 4.6 only]. - Location bar: implement full text search and more accurate sorting. - Add a simple start page with a search box pointing at the active search engine. @@ -263,7 +215,7 @@ FEATURES: - Add a checkable push button to the search bar that allows to highlight a specific string in a website [Qt 4.6 only]. - Add a setting that specifies if the url supplied by the user should be forwarded to the default search engine if it isn't valid. -IMPROVEMENTS: +#### Improvements - Show a more verbose message when the htmlToXBel tool is not installed. - Show the complete tab title as tool tip to improve GUI usability for long website titles. - Download manager: Create the download directory as needed. @@ -274,7 +226,7 @@ IMPROVEMENTS: - When creating new windows, use the startup setting to decide if the homepage should be loaded. - Remove the network monitor tool as the current Inspector now lets you see request headers and response headers. -BUGFIXES: +### Bug fixes - Fix several memory leaks: set the Qt::WA_DeleteOnClose flag on dialogs that are executed asynchronously. - Download manager: Fix displaying file size when downloading huge files. - Download manager: Give correct name to downloaded files with no suffix. @@ -282,7 +234,7 @@ BUGFIXES: - Bookmarks manager: Don't allow to edit the url in any nodes but normal bookmarks. - Private browsing now disables the disk cache. -Behind the scenes +### Behind the scenes - Added custom network scheme handlers, i.e. a single one for listing local directories. - Add a setting so the user can swap the location of the new and close tab buttons. - Add the ability for a user to specify the userAgent through QSettings. @@ -294,19 +246,21 @@ Behind the scenes - Tweak the certToFormattedString() function. - OpenSearch: localization improvements. -Build system -- Include an additional XML file in the installation, which will make Endorphin appear in Gnome Control Center on the list of available web browsers that can be set as default. +#### Build system +- Include an additional XML file in the installation, which will make Arora appear in Gnome Control Center on the list of available web browsers that can be set as default. - Add man pages for the tools. - webkit.pri now supports building QtWebKit as a framework on mac. -0.7.1 -Fix Windows build. -Fix building in parallel (make -jX). +## 0.7.1 +### Behind the scenes +#### Build system +- Fix Windows build. +- Fix building in parallel (make -jX). -0.7.0 -Interface +## 0.7.0 +### Interface - Add support for OpenSearch to the toolbar search - Add the ability to search from the webpage context menu - Remember the boxes checked in the Clear Private Data dialog @@ -317,7 +271,7 @@ Interface - Add a setting specifying if the application should quit when last tab is closed. - Revert the check for the Oxygen style so when under KDE4 Oxygen will be used even if it has issues. -- Fix mid click to paste urls into Endorphin to have them be loaded +- Fix mid click to paste urls into Arora to have them be loaded - Fix crash in Clear Privacy Dialog when cache is disabled - In the download manager change the "Ok" Button to "Close" - Fix the positioning of new tab and close tab buttons. Comparing to 0.6 they are just swapped now. @@ -345,10 +299,10 @@ used even if it has issues. - Add subdomain checking, eg when the policy says 'block def.com', then it will block cookies from 'def.com', 'www.def.com' but not from 'abcdef.com' - Handle cookie rules with starting dot correctly -Behind the scenes +### Behind the scenes - Add a subclass of QWebPluginFactory that can be used for managing QWebPlugin's - Add a static BrowserMainWindow::parentWindow(QWidget *) method that returns a main window being one of the passed widget's parents. -- Move QTRY functions into their own header file as it has no dependency on Endorphin and can be used by tests that don't require BrowserApplication +- Move QTRY functions into their own header file as it has no dependency on Arora and can be used by tests that don't require BrowserApplication - Mark strings as not translatable where it doesn't make sense - Move location bar site icon class into its own file - Move the privacy indicator out into its own class and file @@ -366,27 +320,27 @@ Behind the scenes - Add WebPage::linkedResources(const QString&) method that returns a list of resources attached to the main document - BrowserApplication::mainWindow() returns the currently active window -Build system +#### Build system - Remove one second punishment because it didn't work and I didn't make autotests when I was punished - Add foreach() style error to look for and fix existing occurences. - When building by default don't have lrelase be verbose as it du/mps a lot of junk on the console - Add commit hook to do basic style checking on the files being commited - unset GIT_DIR to fix warnings that are printed to the console -- When building Endorphin also don't allow casts to ascii to detect bugs. -- Share compiled object files with the main endorphin binary to reduce build times +- When building Arora also don't allow casts to ascii to detect bugs. +- Share compiled object files with the main Arora binary to reduce build times -0.6.1 -When using Endorphin with Qt 4.5.1 after a little while pages will stop rendering. +## 0.6.1 +When using Arora with Qt 4.5.1 after a little while pages will stop rendering. This is because of a bug in 4.5.1 where renaming a file will cause the file descriptor to not be closed. QNetworkDiskCache is a simple cache and uses QTemporaryFile's for each new cached file and eventually the kernel wont let QNetworkDiskCache open a cache file because all of the previous files were not -closed. When running against Qt 4.5.1 Endorphin will now disable the disk cache. +closed. When running against Qt 4.5.1 Arora will now disable the disk cache. -0.6 -Interface +## 0.6 +### Interface - Save more of the main window state, window's fullscreen status, maximized status, menu bar visibility, normal size, and ensure that the menu bar and status bar are returned to their proper states if saving while the window is fullscreen. - Open a downloaded file instead of the containing directory - Add check for the Oxygen style and switch to Plastique unless the user specifies oxygen on the command line @@ -406,7 +360,7 @@ Interface - Allow to close the browser with more than one window opened, which was previously impossible (it might be useful when you restore session on startup). - Revert to the default tab selection behavior after closing a tab to match other browsers - Middle button role should be inverted when "Select tabs and windows as they created" is selected -- Add support for MidClick/Ctrl-Click/Shift-Ctrl-Click to all urls in Endorphin. Be it in menus, toolbars, links and javascript links. +- Add support for MidClick/Ctrl-Click/Shift-Ctrl-Click to all urls in Arora. Be it in menus, toolbars, links and javascript links. - Add support for XButton1 and XButton2 to be back/forward on the webview - Add the ability to turn pop-up blocking off - More control to the users! Added a possibility to control where target="_blank" links will be opened and default to a new tab. @@ -428,18 +382,20 @@ Interface - Several spelling errors in the interface and code. -Behind the scenes --Upgrade the SearchLineEdit class +### Behind the scenes +#### Upgrade the SearchLineEdit class - Rather then using a QMenu use QCompleter now that LineEdit can let you set the text margin and the completer popup takes up the whole width. - Re-code searchlineedit to just be a LineEdit subclass that has a search button and a clear button and nothing more. - Re-code the SearchButton to use the QCompleter, take up less width when there isn't one and use a QImage. - Update the toolbar search widget to use the completer rather then the old QMenu -- Significantly improve the startup time of Endorphin. + +#### Other improvementsv behind the scenes +- Significantly improve the startup time of Arora. - Add new access functions to the DownloadItem data. - Move the ClearButton and SearchButton class into its own file - Fix searchbar for special chars such as '+'. This seems a bug in Qt's addQueryItem. Workaround is to use addEncodedQueryItem. - delete the root bookmark node on exit to not generate errors in valgrind -- fix memory leaks in the autotest to confirm that Endorphin's xbel doesn't have any leaks +- fix memory leaks in the autotest to confirm that Arora's xbel doesn't have any leaks - Only clear the cookies if we have loaded them - In ModelMenu rather then all submenu's being QMenu let them be specified by the implementation and as the default use ModelMenu. - Add new menumodel manualtest @@ -454,7 +410,7 @@ Behind the scenes - Remove executable bit from html not found file - Be more vigilant about always using encoded urls when storing them in QString -Build system +#### Build system - Ignore generated files on Windows - Add a common way to install binaries and install the tools - Add commit hook commit-msg with support for aspell to check the spelling of the commit message @@ -465,8 +421,8 @@ Build system - Improve the build times of the manualtests by sharing object files and simplifying the includes -0.5 -Interface +## 0.5 +### Interface - Add new Network Access Monitor tool that shows each network request as it passes. - Added option for showing only one close Button - Don't add empty tabs if closed to recently closed tabs menu. @@ -494,7 +450,7 @@ Interface - Refined drag & drop handling in bookmarks toolbar. Fixed a bug, when page was assigned to inappropriate folder due to more than one folder having same name. - Implement simple context menu in bookmarks toolbar. Let user change bookmark URL in Add Bookmark dialog. -Behind the scenes +### Behind the scenes - Brand new more compliant, faster cookie jar - Brand new Language Manager which selects the correct language on start and lets you choose a different language via the Help menu. - Separate the cookie classes into separate files. @@ -503,23 +459,23 @@ Behind the scenes - The error web pages are now translatable. - Encode urls rather then use toString in various places to prevent loss of url data. - When using foreach try to use a const reference so a copy isn't made (slower) compared to the reference (faster). -- Add a new tool to convert bookmarks that are in the html format into the XBel format (not used in Endorphin yet). +- Add a new tool to convert bookmarks that are in the html format into the XBel format (not used in Arora yet). - Various code style and general keeping the code clean fixes - Add Implementation to get the current username on Windows for the single application -Build system +#### Build system - Add script to build OS X package using the new macdeployqt tool in Qt 4.5 - Building with QT_STRICT_ITERATORS to catch errors. - Enhance support for building with multiple WebKit trunk branches - Adds the ability to generate code documentation with doxygen -0.4 -Interface +## 0.4 +### Interface - New source viewer with search and syntax highlighting. - Make middle click on bookmarks menus open the user in a new tab. - Added the ability to change the language from the Help menu. - Double left click location bar selects all of the text. -- Incorporate Jens Explorer style into Endorphin on Window for a better look and feel on XP and Vista. http://labs.trolltech.com/blogs/2007/06/08/explorer-style-toolbars/ +- Incorporate Jens Explorer style into Arora on Window for a better look and feel on XP and Vista. http://labs.trolltech.com/blogs/2007/06/08/explorer-style-toolbars/ - Change the "icon" on the next/prev search for RTL desktops: next points to the right, and previous points to the right - Various RightToLeft fixes for for Mozilla's bug https://bugzilla.mozilla.org/show_bug.cgi?id=219070 - When the url scheme is https make the location bar background turn yellow. @@ -531,20 +487,21 @@ Interface - When dropping text on the webpage load the url - When the location bar has focus don't change the text. -Behind the scenes +### Behind the scenes - Make a dedicated SingleApplication class - Tweak HistoryManager API to be easier to read. - Improvements to the code style to be more consistent - Move the binaries for autotests and manual tests into the .gitignore in that directory rather then all in one file at the top. - Update manualtest for the location bar now that the urllineedit class has become the new location bar class and add a new git hook to make sure manual tests build. -Build system +### Build system - Move locale build instructions to its own pri file in the locale directory - Correctly detect qt3's qmake on Debian - Enhance support for building with WebKit trunk -0.3 +## 0.3 +### Interface - With Qt 4.5 use movable tabs - With Qt 4.5 use disk cache - Created a new LineEdit that handles adding side widgets in a clean, simple and elegant way. @@ -566,23 +523,23 @@ Build system - Improve a number of the strings (feedback from MentalMaelstrom) - Tweak action accelerators (the same ones were being used) -Build system -- Allow building Endorphin with both Debug/Release of WebKit trunk +### Build system +- Allow building Arora with both Debug/Release of WebKit trunk - Only include the sha1 and change number in the version when using git. -- Create utils directory to contain non-Endorphin specific classes +- Create utils directory to contain non-Arora specific classes - Run desktop file through desktop-file-validate and correct the errors -Autotests +#### Autotests - Add QTRY_COMPARE and QTRY_VERIFY for the autotests to use. -- add AUTOTESTS define when running autotests to prevent accessing running endorphin's and sending url's to it -- Fix autotest failures (test related, not endorphin) +- add AUTOTESTS define when running autotests to prevent accessing running Arora's and sending url's to it +- Fix autotest failures (test related, not Arora) - Detect which version of qmake to use when building the autotests - Give a 1 second punishment if there is no autotest for the source file that was changed - Emit a warning of a file doesn't have a matching autotest - Update modeltest code to match Trolltech's svn -0.2 +## 0.2 - Many Bug fixes and improvements. - Add make install on unix - Improved tabs @@ -590,6 +547,6 @@ Autotests - New reset dialog - New about dialog - Add search banner - - Rename to Endorphin and a new application icon + - Rename to Arora and a new application icon - Project specific git hooks - Branch from the Qt demo browser with new autotests and manualtests diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..69eda065 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,55 @@ +## Changelog + +## 0.13.0 + +The first official Endorphin release. Contains many new features, a new engine, and bug fixes. +**Not released yet.** + +### Fixed issues +- endorphin-placesimport sometimes resulted in an "Invalid cross-device link" error. + +### Behind the scene +- Port to CMake +- Update the Engine from WebKit to WebEngine + +### Other +- Remove ClickToFlash: Flash is no longer supported +- Prepare for Qt6 + +## 0.12.1 + +This release contained some small changes to 0.12.0. + +### Interface +- Add note about this being an inofficial fork +- Update included user agents +- Improve placeholder text of the searchbox on the front page + +### Fixed issues + Fix language fallback + +## 0.12.0 + +An update that contains all changes that were made to Arora after 0.11.0, and QT5 support. + +### Interface +- Show the number of downloads in the download manager dialog title + +### Fixed issues +- When the 'delete' button is pressed, the downloaded item count was not updated. +- Issue: 912: Autofill manager was always storing forms. +- Issue: 915: Fixed ssl certificate problem with sites like https://webmail.us.army.mil: + By default QSSLConfiguration was only accepting SSLv3 while we want to + accept all of them. +- Issue: 918: "Autofill webforms" in Preferences was always checked. +- Issue: 931: Fix for fullscreen on Mac +- Issue: 957: Workaround for a bug in QCompleter + +### Behind the scene +- Support persistent data storage (HTML5 localStorage) +- Update to QT5 & latest WebKit +- Update some internal pages to HTML5 +- Code cleanup + +### Other +- Remove OS2 support \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f1c34a3..ebc041f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,12 @@ project(Endorphin) cmake_minimum_required(VERSION 3.16) +include(CTest) +include(definitions.cmake) +include(src/bookmarks/xbel/libxbel.cmake) +include(endorphinbase.cmake) +if(BUILD_TESTING) + add_subdirectory(autotests) +endif() set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) diff --git a/GPLHEADER b/GPLHEADER index b932cb3d..9b16c98c 100644 --- a/GPLHEADER +++ b/GPLHEADER @@ -1,5 +1,5 @@ /* - * Copyright 2008 Name + * Copyright 2020 Name * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..4ef1e630 --- /dev/null +++ b/LICENSE @@ -0,0 +1,351 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 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. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, 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 software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, 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 redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +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 give any other recipients of the Program a copy of this License +along with the Program. + +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 Program or any portion +of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +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 Program, 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 Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) 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; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, 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 executable. 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. + +If distribution of executable or 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 counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program 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. + + 5. 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 Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program 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. + + 7. 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 Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program 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 Program. + +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. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program 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. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 Program +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 Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, 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 + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), 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 Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. 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. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; 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. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + +------------------------------------------------------------------------- + +In addition, as a special exception, permission is given to link the +code of its release with the OpenSSL project's "OpenSSL" library (or +modified versions of it that use the same license as the "OpenSSL" +library), and distribute the linked executables. You must comply with the GNU +General Public License version 2 or the GNU General Public License version 3 +in all respects for all of the code used other than the "OpenSSL" code. If +you modify this file, you may extend this exception to your version of the +file, but you are not obligated to do so. If you do not wish to do so, +delete this exception statement from your version of this file. \ No newline at end of file diff --git a/README.md b/README.md index 88a4f7d2..df7ce330 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,12 @@ Endorphin is a cross platform web browser built using Qt and WebKit. This is a fork of the [Arora browser](https://github.com/Arora/arora). -This fork was created by Aaron Dewes. +This fork was created by Aaron Dewes with the goal of contnuing the development of this old browser and further improving it. -## Contributing +### Contributing If you want to contribute, feel free to open an issue or a PR. - ### Building -Endorphin uses the cmake build system. If you already have Qt 5.14 or newer on your system building is as easy as running the command 'cmake' and then 'make'. +Endorphin uses the cmake build system. If you already have Qt 5.15 or newer on your system building is as easy as running the command 'cmake' and then 'make'. For more detailed information see the [Building guide](BUILDING.md). diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt new file mode 100644 index 00000000..c981becf --- /dev/null +++ b/autotests/CMakeLists.txt @@ -0,0 +1,19 @@ +project(autotests) +add_subdirectory(addbookmarkdialog) +add_subdirectory(autosaver) +add_subdirectory(bookmarknode) +#add_subdirectory(downloadmanager) +add_subdirectory(historyfiltermodel) +add_subdirectory(historymanager) +add_subdirectory(modeltoolbar) +add_subdirectory(opensearchengine) +add_subdirectory(opensearchmanager) +add_subdirectory(opensearchreader) +add_subdirectory(opensearchwriter) +add_subdirectory(searchlineedit) +add_subdirectory(tabbar) +add_subdirectory(tabwidget) +add_subdirectory(utils) +add_subdirectory(webactionmapper) +#add_subdirectory(webpage) +add_subdirectory(xbel) \ No newline at end of file diff --git a/autotests/adblock/adblock.pro b/autotests/adblock/adblock.pro deleted file mode 100644 index e00136d1..00000000 --- a/autotests/adblock/adblock.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - adblockmanager \ - adblocknetwork \ - adblockpage \ - adblockrule \ - adblocksubscription - -CONFIG += ordered diff --git a/autotests/adblock/adblockmanager/.gitignore b/autotests/adblock/adblockmanager/.gitignore deleted file mode 100644 index 956108dc..00000000 --- a/autotests/adblock/adblockmanager/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblockmanager diff --git a/autotests/adblock/adblockmanager/adblockmanager.pro b/autotests/adblock/adblockmanager/adblockmanager.pro deleted file mode 100644 index 025c3a5a..00000000 --- a/autotests/adblock/adblockmanager/adblockmanager.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES += tst_adblockmanager.cpp -HEADERS += diff --git a/autotests/adblock/adblockmanager/tst_adblockmanager.cpp b/autotests/adblock/adblockmanager/tst_adblockmanager.cpp deleted file mode 100644 index 658b9f6f..00000000 --- a/autotests/adblock/adblockmanager/tst_adblockmanager.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 - -#include "adblockdialog.h" -#include "adblockmanager.h" -#include "adblocksubscription.h" - -#include -#include -#include -#include - - -class tst_AdBlockManager : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void adblockmanager_data(); - void adblockmanager(); - - void addSubscription(); - void customRules(); - void isEnabled_data(); - void isEnabled(); - void load(); - void removeSubscription(); - void showDialog(); - void rulesChanged(); -}; - -// Subclass that exposes the protected functions. -class SubAdBlockManager : public AdBlockManager -{ -public: - ~SubAdBlockManager() { - QList list = subscriptions(); - foreach (AdBlockSubscription *s, list) - removeSubscription(s); - setEnabled(false); - } - - void call_rulesChanged() - { return SubAdBlockManager::rulesChanged(); } -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_AdBlockManager::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_AdBlockManager::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_AdBlockManager::init() -{ -} - -// This will be called after every test function. -void tst_AdBlockManager::cleanup() -{ -} - -void tst_AdBlockManager::adblockmanager_data() -{ -} - -void tst_AdBlockManager::adblockmanager() -{ - SubAdBlockManager manager; - manager.addSubscription((AdBlockSubscription*)0); - QVERIFY(manager.customRules()); - QVERIFY(manager.instance() != (AdBlockManager*)0); - QCOMPARE(manager.isEnabled(), true); - manager.load(); - QVERIFY(manager.network()); - QVERIFY(manager.page()); - manager.removeSubscription((AdBlockSubscription*)0); - manager.setEnabled(false); - QVERIFY(manager.showDialog()); - QList list; - list.append(manager.customRules()); - QCOMPARE(manager.subscriptions(), list); -} - -// public void addSubscription(AdBlockSubscription *subscription) -void tst_AdBlockManager::addSubscription() -{ - SubAdBlockManager manager; - - QList list = manager.subscriptions(); - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), &manager); - manager.addSubscription(subscription); - QCOMPARE(manager.subscriptions(), (list += subscription)); - - QCOMPARE(spy0.count(), 1); -} - -// public AdBlockSubscription *customRules() -void tst_AdBlockManager::customRules() -{ - SubAdBlockManager manager; - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - AdBlockSubscription *subscription = manager.customRules(); - QVERIFY(subscription); - QVERIFY(!subscription->title().isEmpty()); - QVERIFY(subscription->allRules().isEmpty()); - - QCOMPARE(spy0.count(), 1); - - subscription = manager.customRules(); - QCOMPARE(spy0.count(), 1); -} - -void tst_AdBlockManager::isEnabled_data() -{ - QTest::addColumn("isEnabled"); - QTest::newRow("true") << true; - QTest::newRow("false") << false; -} - -// public bool isEnabled() const -void tst_AdBlockManager::isEnabled() -{ - QFETCH(bool, isEnabled); - - SubAdBlockManager manager; - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - bool before = manager.isEnabled(); - - manager.setEnabled(isEnabled); - manager.setEnabled(isEnabled); - QCOMPARE(manager.isEnabled(), isEnabled); - - QCOMPARE(spy0.count(), before == isEnabled ? 0 : 1); -} - -// public void load() -void tst_AdBlockManager::load() -{ - SubAdBlockManager manager; - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - manager.load(); - - QCOMPARE(spy0.count(), 0); -} - -// public void removeSubscription(AdBlockSubscription *subscription) -void tst_AdBlockManager::removeSubscription() -{ - SubAdBlockManager manager; - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - QList list = manager.subscriptions(); - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), &manager); - manager.addSubscription(subscription); - manager.removeSubscription(subscription); - QCOMPARE(manager.subscriptions(), list); - - QCOMPARE(spy0.count(), 2); -} - - -// public AdBlockDialog *showDialog() -void tst_AdBlockManager::showDialog() -{ - SubAdBlockManager manager; - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - AdBlockDialog *dialog = manager.showDialog(); - QVERIFY(dialog); - QTRY_VERIFY(dialog->isVisible()); -} - -void tst_AdBlockManager::rulesChanged() -{ - SubAdBlockManager manager; - - QSignalSpy spy0(&manager, SIGNAL(rulesChanged())); - - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), &manager); - manager.addSubscription(subscription); - subscription->setEnabled(true); - subscription->addRule(AdBlockRule()); - - QCOMPARE(spy0.count(), 3); -} - -QTEST_MAIN(tst_AdBlockManager) -#include "tst_adblockmanager.moc" - diff --git a/autotests/adblock/adblocknetwork/.gitignore b/autotests/adblock/adblocknetwork/.gitignore deleted file mode 100644 index dcb473fd..00000000 --- a/autotests/adblock/adblocknetwork/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblocknetwork diff --git a/autotests/adblock/adblocknetwork/adblocknetwork.pro b/autotests/adblock/adblocknetwork/adblocknetwork.pro deleted file mode 100644 index 2ae14cc2..00000000 --- a/autotests/adblock/adblocknetwork/adblocknetwork.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES += tst_adblocknetwork.cpp -HEADERS += diff --git a/autotests/adblock/adblocknetwork/tst_adblocknetwork.cpp b/autotests/adblock/adblocknetwork/tst_adblocknetwork.cpp deleted file mode 100644 index 9ade541f..00000000 --- a/autotests/adblock/adblocknetwork/tst_adblocknetwork.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 - -#include "adblocknetwork.h" -#include "adblockmanager.h" -#include "adblocksubscription.h" -#include "adblockrule.h" - -#include - -class tst_AdBlockNetwork : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void adblocknetwork_data(); - void adblocknetwork(); - - void data(); - - void enabled_data(); - void enabled(); - - void block_data(); - void block(); -}; - -// Subclass that exposes the protected functions. -class SubAdBlockNetwork : public AdBlockNetwork -{ -public: - -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_AdBlockNetwork::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_AdBlockNetwork::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_AdBlockNetwork::init() -{ -} - -// This will be called after every test function. -void tst_AdBlockNetwork::cleanup() -{ - AdBlockManager *manager = AdBlockManager::instance(); - QList list = manager->subscriptions(); - foreach (AdBlockSubscription *s, list) - manager->removeSubscription(s); -} - -void tst_AdBlockNetwork::adblocknetwork_data() -{ -} - -void tst_AdBlockNetwork::adblocknetwork() -{ - SubAdBlockNetwork network; - QCOMPARE(network.block(QNetworkRequest()), (QNetworkReply*)0); -} - -void tst_AdBlockNetwork::data() -{ - SubAdBlockNetwork network; - - AdBlockManager *manager = AdBlockManager::instance(); - manager->setEnabled(true); - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), manager); - subscription->setEnabled(true); - manager->addSubscription(subscription); - - AdBlockRule rule("/"); - rule.setEnabled(true); - subscription->addRule(rule); - - QNetworkReply *reply = 0; - QNetworkRequest request = QNetworkRequest(QUrl("data://foobar")); - - reply = network.block(request); - QVERIFY(!reply); -} - -void tst_AdBlockNetwork::enabled_data() -{ - QTest::addColumn("enableManager"); - QTest::addColumn("enableSubscription"); - QTest::addColumn("enableRule"); - QTest::addColumn("block"); - QTest::newRow("null") << true << true << true << true; - QTest::newRow("m") << false << true << true << false; - QTest::newRow("s") << true << false << true << false; - QTest::newRow("r") << true << true << false << false; -} - -void tst_AdBlockNetwork::enabled() -{ - QFETCH(bool, enableManager); - QFETCH(bool, enableSubscription); - QFETCH(bool, enableRule); - QFETCH(bool, block); - - SubAdBlockNetwork network; - - AdBlockManager *manager = AdBlockManager::instance(); - manager->setEnabled(enableManager); - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), manager); - subscription->setEnabled(enableSubscription); - manager->addSubscription(subscription); - - AdBlockRule rule("/"); - rule.setEnabled(enableRule); - subscription->addRule(rule); - - QNetworkReply *reply = 0; - QNetworkRequest grequest = QNetworkRequest(QUrl("http://www.google.com")); - - reply = network.block(grequest); - QCOMPARE((reply != 0), block); -} - -// check that block block and !block blocks other sites -void tst_AdBlockNetwork::block_data() -{ - QTest::addColumn("ruleList"); - QTest::addColumn("url"); - QTest::addColumn("block"); - - QTest::newRow("null") << QString() - << QUrl() - << false; - - QUrl google("http://www.google.com"); - QTest::newRow("google") << QString("/") - << google - << true; - - // defining exception rules - QTest::newRow("exception0") << QString("@@advice,advice") - << QUrl("http://example.com/advice.html") - << false; - QTest::newRow("exception1") << QString("@@|http://example.com") - << QUrl("http://example.com/advice.html") - << false; - QTest::newRow("exception2") << QString("@@http://example.com") - << QUrl("http://example.com/advice.html") - << false; - - QTest::newRow("order0") << QString("advice,@@advice") - << QUrl("http://example.com/advice.html") - << false; -} - -// public QNetworkReply *block(QNetworkRequest const &request) -void tst_AdBlockNetwork::block() -{ - QFETCH(QString, ruleList); - QFETCH(QUrl, url); - QFETCH(bool, block); - - SubAdBlockNetwork network; - - AdBlockManager *manager = AdBlockManager::instance(); - manager->setEnabled(true); - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), manager); - subscription->setEnabled(true); - manager->addSubscription(subscription); - - QStringList rules = ruleList.split(","); - foreach (const QString &rule, rules) - subscription->addRule(AdBlockRule(rule)); - - QNetworkReply *reply = network.block(QNetworkRequest(url)); - bool blocked = (reply != 0); - QCOMPARE(blocked, block); -} - -QTEST_MAIN(tst_AdBlockNetwork) -#include "tst_adblocknetwork.moc" - diff --git a/autotests/adblock/adblockpage/.gitignore b/autotests/adblock/adblockpage/.gitignore deleted file mode 100644 index ed880152..00000000 --- a/autotests/adblock/adblockpage/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblockpage diff --git a/autotests/adblock/adblockpage/adblockpage.pro b/autotests/adblock/adblockpage/adblockpage.pro deleted file mode 100644 index a6a6b207..00000000 --- a/autotests/adblock/adblockpage/adblockpage.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES += tst_adblockpage.cpp -HEADERS += diff --git a/autotests/adblock/adblockpage/test.html b/autotests/adblock/adblockpage/test.html deleted file mode 100644 index 39cb99d1..00000000 --- a/autotests/adblock/adblockpage/test.html +++ /dev/null @@ -1,8 +0,0 @@ - -
Cheapest tofu, only here and now!
-
Really cheap tofu, click here!
-Only here you get the best tofu! -
tofu!
-
Cheapest tofu, only here and now!
-
Cheapest tofu, only here and now!
-
tofu!
diff --git a/autotests/adblock/adblockpage/tst_adblockpage.cpp b/autotests/adblock/adblockpage/tst_adblockpage.cpp deleted file mode 100644 index a8071830..00000000 --- a/autotests/adblock/adblockpage/tst_adblockpage.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include -#include - -#include "adblockpage.h" - -#include "adblockmanager.h" -#include "adblocksubscription.h" -#include "adblockrule.h" - -#include -#include -#include -#include - -class tst_AdBlockPage : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void adblockpage_data(); - void adblockpage(); - - void applyRulesToPage_data(); - void applyRulesToPage(); -}; - -// Subclass that exposes the protected functions. -class SubAdBlockPage : public AdBlockPage -{ -public: - -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_AdBlockPage::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_AdBlockPage::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_AdBlockPage::init() -{ -} - -// This will be called after every test function. -void tst_AdBlockPage::cleanup() -{ - AdBlockManager *manager = AdBlockManager::instance(); - QList list = manager->subscriptions(); - foreach (AdBlockSubscription *s, list) - manager->removeSubscription(s); -} - -void tst_AdBlockPage::adblockpage_data() -{ -} - -void tst_AdBlockPage::adblockpage() -{ - SubAdBlockPage page; - page.applyRulesToPage((QWebPage*)0); -} - -void tst_AdBlockPage::applyRulesToPage_data() -{ - QTest::addColumn("ruleList"); - QTest::addColumn("count"); - - int start = 7; - QTest::newRow("null") << QString() << start; - - //Examples taken from http://adblockplus.org/en/filters - - QTest::newRow("basic-0") << QString("##div.textad") << start - 1; - QTest::newRow("basic-1") << QString("##div#sponsorad") << start - 1; - QTest::newRow("basic-2") << QString("##*#sponsorad") << start - 1; - QTest::newRow("basic-3") << QString("##textad") << start -1; - - // Attribute selectors - QTest::newRow("attribute-0") << QString("##table[width=\"80%\"]") << start - 2; - QTest::newRow("attribute-1") << QString("##table[width=\"80%\"][bgcolor=\"white\"]") << start - 1; - QTest::newRow("attribute-2") << QString("##div[title*=\"adv\"]") << start - 2; - QTest::newRow("attribute-3") << QString("##div[title^=\"adv\"][title$=\"ert\"]") << start - 1; - - // Advanced selectors -} - -// public void applyRulesToPage(QWebPage *page) -void tst_AdBlockPage::applyRulesToPage() -{ - QFETCH(QString, ruleList); - QFETCH(int, count); - - AdBlockManager *manager = AdBlockManager::instance(); - manager->setEnabled(true); - - AdBlockSubscription *subscription = new AdBlockSubscription(QUrl(), manager); - subscription->setEnabled(true); - manager->addSubscription(subscription); - - QStringList rules = ruleList.split(","); - foreach (const QString &rule, rules) - subscription->addRule(AdBlockRule(rule)); - - QWebView view; - QSignalSpy spy1(view.page(), SIGNAL(loadFinished(bool))); - view.load(QUrl::fromLocalFile(QDir::currentPath() + "/test.html")); - QTRY_COMPARE(spy1.count(), 1); - - SubAdBlockPage page; - page.applyRulesToPage(view.page()); - if (view.page()->mainFrame()->toHtml().count("tofu") != count) - qDebug() << view.page()->mainFrame()->toHtml(); - QCOMPARE(view.page()->mainFrame()->toHtml().count("tofu"), count); -} - -QTEST_MAIN(tst_AdBlockPage) -#include "tst_adblockpage.moc" - diff --git a/autotests/adblock/adblockrule/.gitignore b/autotests/adblock/adblockrule/.gitignore deleted file mode 100644 index 3b9e3229..00000000 --- a/autotests/adblock/adblockrule/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblockrule diff --git a/autotests/adblock/adblockrule/adblockrule.pro b/autotests/adblock/adblockrule/adblockrule.pro deleted file mode 100644 index 52435394..00000000 --- a/autotests/adblock/adblockrule/adblockrule.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES += tst_adblockrule.cpp -HEADERS += diff --git a/autotests/adblock/adblockrule/tst_adblockrule.cpp b/autotests/adblock/adblockrule/tst_adblockrule.cpp deleted file mode 100644 index 25896c2a..00000000 --- a/autotests/adblock/adblockrule/tst_adblockrule.cpp +++ /dev/null @@ -1,385 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * Copyright 2009 Zsombor Gegesy - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include - -#include "adblockrule.h" - -#include -#include - -class tst_AdBlockRule : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void regexpCreation_data(); - void regexpCreation(); - void networkMatch_data(); - void networkMatch(); - -}; - -// Subclass that exposes the protected functions. -class SubAdBlockRule : public AdBlockRule -{ -public: - SubAdBlockRule(const QString &filter); -}; - -SubAdBlockRule::SubAdBlockRule(const QString &filter) - : AdBlockRule(filter) -{ -} - -// This will be called before the first test function is executed. -// It is only called once. -void tst_AdBlockRule::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_AdBlockRule::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_AdBlockRule::init() -{ -} - -// This will be called after every test function. -void tst_AdBlockRule::cleanup() -{ -} - -void tst_AdBlockRule::networkMatch_data() -{ - QTest::addColumn("filter"); - QTest::addColumn("url"); - QTest::addColumn("networkMatch"); - QTest::newRow("null") << QString() << QUrl() << false; - - //Examples taken from http://adblockplus.org/en/filters - - // Basic filter rules - QTest::newRow("basic0") << QString("http://example.com/ads/banner123.gif") - << QUrl("http://example.com/ads/banner123.gif") - << true; - QTest::newRow("basic1") << QString("http://example.com/ads/banner*.gif") - << QUrl("http://example.com/ads/banner123.gif") - << true; - QTest::newRow("basic2") << QString("http://example.com/ads/*") - << QUrl("http://example.com/ads/banner123.gif") - << true; - QTest::newRow("basic3") << QString("http://example.com/*") - << QUrl("http://example.com/ads/banner123.gif") - << true; - - // defining exception rules - QTest::newRow("exception0") << QString("@@advice") - << QUrl("http://example.com/advice.html") - << true; - QTest::newRow("exception1") << QString("@@|http://example.com") - << QUrl("http://example.com/advice.html") - << true; - QTest::newRow("exception2") << QString("@@http://example.com") - << QUrl("http://example.com/advice.html") - << true; - - // matching at beginning/end of an address - QTest::newRow("m0") << QString("ad") - << QUrl("http://example.com/advice.html") - << true; - QTest::newRow("m1") << QString("*ad*") - << QUrl("http://example.com/advice.html") - << true; - QTest::newRow("m2") << QString("swf") - << QUrl("http://example.com/swf/index.html") - << true; - QTest::newRow("m3") << QString("swf|") - << QUrl("http://example.com/annoyingflash.swf") - << true; - QTest::newRow("m4") << QString("swf|") - << QUrl("http://example.com/swf/index.html") - << false; - - QTest::newRow("m5") << QString("http://baddomain.example/") - << QUrl("http://baddomain.example/banner.gif") - << true; - QTest::newRow("m6") << QString("http://baddomain.example/") - << QUrl("http://gooddomain.example/analyze?http://baddomain.example.") - << false; - - QTest::newRow("m7") << QString("||example.com/banner.gif") - << QUrl("http://example.com/banner.gif") - << true; - QTest::newRow("m8") << QString("||example.com/banner.gif") - << QUrl("https://example.com/banner.gif") - << true; - QTest::newRow("m9") << QString("||example.com/banner.gif") - << QUrl("http://www.example.com/banner.gif") - << true; - - QTest::newRow("m10") << QString("||example.com/banner.gif") - << QUrl("http://badexample.com/banner.gif") - << false; - QTest::newRow("m10") << QString("||example.com/banner.gif") - << QUrl("http://gooddomain.example/analyze?http://example.com/banner.gif") - << false; - - QTest::newRow("m11") << QString("/getad.php|") - << QUrl("http://adblockplus.mozdev.org/easylist/easylist.txt") - << false; - - // Matching separators - QTest::newRow("sep_1") << QString("a^") - << QUrl("a/") - << true; - QTest::newRow("sep_2") << QString("a^") - << QUrl("a:") - << true; - QTest::newRow("sep_3") << QString("a^") - << QUrl("a.") - << false; - QTest::newRow("sep_4") << QString("a^") - << QUrl("a?") - << true; - QTest::newRow("sep_5") << QString("a^") - << QUrl("a=") - << true; - QTest::newRow("sep_6") << QString("a^") - << QUrl("a&") - << true; - - QTest::newRow("s1_s") << QString("com^") - << QUrl("com:") - << true; - QTest::newRow("s2_s") << QString("ab^cd") - << QUrl("ab.cd") - << false; - - // Marking separate characters - QTest::newRow("s0") << QString("http://example.com^") - << QUrl("http://example.com/") - << true; - QTest::newRow("s1") << QString("http://example.com^") - << QUrl("http://example.com:8000/") - << true; - QTest::newRow("s2") << QString("http://example.com^") - << QUrl("http://example.com.ar/") - << false; - QTest::newRow("s3") << QString("^example.com^") - << QUrl("http://example.com:8000/foo.bar?a=12&b=%D1%82%D0%B5%D1%81%D1%82") - << true; - QTest::newRow("s4") << QString("^%D1^") - << QUrl::fromEncoded("http://example.com:8000/foo.bar?a=12&b=%D1") - << true; - QTest::newRow("s5") << QString("^foo.bar^") - << QUrl("http://example.com:8000/foo.bar?a=12&b=%D1%82%D0%B5%D1%81%D1%82") - << true; - QTest::newRow("s6") << QString("^%D1%82%D0%B5%D1%81%D1%82^") - << QUrl::fromEncoded("http://example.com:8000/foo.bar?a=12&b=%D1%82%D0%B5%D1%81%D1%82") - << true; - // Comments - QTest::newRow("c0") << QString("!foo.bar") - << QUrl("!foo.bar") - << false; - QTest::newRow("c1") << QString("!foo.bar") - << QUrl("foo.bar") - << false; - - // Specifying filter options - // type - QTest::newRow("o0") << QString("*/ads/*$script,image,background,stylesheet,object,xbl,ping,xmlhttprequest,object-subrequest,object-subrequest,dtd,subdocument,document,other") - << QUrl("foo.bar/ads/foo.jpg") - << false; - // Inverse type - QTest::newRow("o1") << QString("*/ads/*$~script, ~image, ~background, ~stylesheet, ~object, ~xbl, ~ping, ~xmlhttprequest, ~object-subrequest, ~dtd, ~subdocument, ~document, ~other") - << QUrl("foo.bar/ads/foo.jpg") - << false; - // Restriction to third-party/first-party requests - QTest::newRow("o2") << QString("*/ads/*$third-party") - << QUrl("foo.bar/ads/foo.jpg") - << false; - QTest::newRow("o3") << QString("*/ads/*$first-party") - << QUrl("foo.bar/ads/foo.jpg") - << false; - // Domain restrictions - QTest::newRow("o4") << QString("*/ads/*$domain=example.com|example.net") - << QUrl("http://example.com/ads/foo.jpg") - << true; - QTest::newRow("o5") << QString("*/ads/*$domain=example.com") - << QUrl("http://foo.com/ads/foo.jpg") - << false; - - QTest::newRow("o6") << QString("*/ads/*$domain=~example.com") - << QUrl("http://foo.com/ads/foo.jpg") - << true; - QTest::newRow("o7") << QString("*/ads/*$domain=~example.com") - << QUrl("http://example.com/ads/foo.jpg") - << false; - QTest::newRow("o8") << QString("*/ads/*$domain=example.com|~foo.example.com") - << QUrl("http://example.com/ads/foo.jpg") - << true; - QTest::newRow("o9") << QString("*/ads/*$domain=example.com|~foo.example.com") - << QUrl("http://foo.example.com/ads/foo.jpg") - << false; - QTest::newRow("o10") << QString("*/ads/*$domain=example.com|~foo.example.com") - << QUrl("http://bar.example.com/ads/foo.jpg") - << true; - // match-case - QTest::newRow("o11") << QString("*/BannerAd.gif$match-case") - << QUrl("http://example.com/BannerAd.gif") - << true; - QTest::newRow("o12") << QString("*/BannerAd.gif$match-case") - << QUrl("http://example.com/bannerad.gif") - << false; - // collapse - // TODO test collapse somehow - QTest::newRow("o13") << QString("*/BannerAd.gif$collapse") - << QUrl("http://example.com/bannerad.gif") - << false; - QTest::newRow("o14") << QString("*/BannerAd.gif$~collapse") - << QUrl("http://example.com/bannerad.gif") - << false; - // Regular expressions - QTest::newRow("r0") << QString("/banner\\d+/") - << QUrl("banner123") - << true; - QTest::newRow("r1") << QString("/banner\\d+/") - << QUrl("banner321") - << true; - QTest::newRow("r2") << QString("/banner\\d+/") - << QUrl("banners") - << false; - - // See the AdBlockPage autotest for CSS testing - // Basic Element hiding the network matching should never pass - QTest::newRow("e0") << QString("##div.textad") - << QUrl() - << false; - QTest::newRow("e1") << QString("##div#sponsorad") - << QUrl() - << false; - QTest::newRow("e1") << QString("##*#sponsorad") - << QUrl() - << false; - QTest::newRow("e1") << QString("##textad") - << QUrl() - << false; - QTest::newRow("e1") << QString("example.com##*.sponsor") - << QUrl("example.com") - << false; - QTest::newRow("e1") << QString("example.com,example.net##*.sponsor") - << QUrl("example.com") - << false; - - // Seen on the internet - QTest::newRow("i0") << QString("||snap.com^$third-party") - << QUrl("http://spa.snap.com/snap_preview_anywhere.js?ap=1&key=89743df349c6c38afc3094e9566cb98e&sb=1&link_icon=off&domain=pub-6332280-www.techcrunch.com") - << true; - - QTest::newRow("i1") << QString("|http://ads.") - << QUrl("http://ads.cnn.com/html.ng/site=cnn&cnn_pagetype=main&cnn_position=336x280_adlinks&cnn_rollup=homepage&page.allowcompete=yes¶ms.styles=fs&tile=8837285713521&domId=463050") - << true; - - QTest::newRow("i2") << QString("/adverti$~object_subrequest,~stylesheet,domain=~advertise4free.org|~amarillas.cl|~bnet.com|~catalysttelecom.com|~cod4central.com|~scansource.com|~scansourcecommunications.com|~scansourcesecurity.com") - << QUrl("http://i2.cdn.turner.com/cnn/.element/img/2.0/content/ads/advertisement.gif") - << true; - - QTest::newRow("i3") << QString("/adspace") - << QUrl("http://i.cdn.turner.com/cnn/cnn_adspaces/cnn_adspaces.js") - << false; -} - -// public bool networkMatch(const QUrl &url) const -void tst_AdBlockRule::networkMatch() -{ - QFETCH(QString, filter); - QFETCH(QUrl, url); - QFETCH(bool, networkMatch); - - SubAdBlockRule AdBlockRule(filter); - bool result = AdBlockRule.networkMatch(url.toEncoded()); - if (result != networkMatch) { - qDebug() << "Match error."; - qDebug() << "\tFilter:" << filter; - qDebug() << "\tUrl: " << url; - qDebug() << "\tResult : " << (result ? "match" : "NOT match"); - } - QCOMPARE(AdBlockRule.networkMatch(url.toEncoded()), networkMatch); -} - -void tst_AdBlockRule::regexpCreation_data() -{ - QTest::addColumn("input"); - QTest::addColumn("output"); - - QTest::newRow("null") << QString("test") << QString("test"); - QTest::newRow("m1") << QString("abc*") << QString("abc"); - QTest::newRow("m2") << QString("*abc*") << QString("abc"); - QTest::newRow("m3") << QString("abc**") << QString("abc"); - QTest::newRow("m4") << QString("abc***") << QString("abc"); - QTest::newRow("m5") << QString("**abc**") << QString("abc"); - QTest::newRow("m6") << QString("**a*bc**") << QString("a.*bc"); - QTest::newRow("h1") << QString("abc.com") << QString("abc\\.com"); - - QTest::newRow("a2") << QString("abc^|def") << QString("abc(?:[^\\w\\d\\-.%]|$)\\|def"); - QTest::newRow("a3") << QString("^|def") << QString("(?:[^\\w\\d\\-.%]|$)\\|def"); - - QTest::newRow("s1") << QString("de|f") << QString("de\\|f"); - - QTest::newRow("e1") << QString("|abc") << QString("^abc"); - QTest::newRow("e2") << QString("d|abc") << QString("d\\|abc"); - QTest::newRow("e3") << QString("abc|") << QString("abc$"); - - QTest::newRow("z1") << QString("^abc") << QString("(?:[^\\w\\d\\-.%]|$)abc"); - QTest::newRow("z2") << QString("a^bc") << QString("a(?:[^\\w\\d\\-.%]|$)bc"); - QTest::newRow("z3") << QString("abc^|") << QString("abc(?:[^\\w\\d\\-.%]|$)"); - QTest::newRow("z4") << QString("http://example.com^") - << QString("http\\:\\/\\/example\\.com(?:[^\\w\\d\\-.%]|$)"); - - - QTest::newRow("d0") << QString("||example.com") - << QString("^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?example\\.com"); - QTest::newRow("d1") << QString("||example.com/banner.gif") - << QString("^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?example\\.com\\/banner\\.gif"); -} - -void tst_AdBlockRule::regexpCreation() -{ - QFETCH(QString, input); - QFETCH(QString, output); - - SubAdBlockRule rule(input); - QCOMPARE(rule.regExpPattern(), output); -} - -QTEST_MAIN(tst_AdBlockRule) -#include "tst_adblockrule.moc" - diff --git a/autotests/adblock/adblocksubscription/.gitignore b/autotests/adblock/adblocksubscription/.gitignore deleted file mode 100644 index aea23ae2..00000000 --- a/autotests/adblock/adblocksubscription/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -adblocksubscription -rules2.txt diff --git a/autotests/adblock/adblocksubscription/adblocksubscription.pro b/autotests/adblock/adblocksubscription/adblocksubscription.pro deleted file mode 100644 index 2ad5e053..00000000 --- a/autotests/adblock/adblocksubscription/adblocksubscription.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES += tst_adblocksubscription.cpp -HEADERS += diff --git a/autotests/adblock/adblocksubscription/rules.txt b/autotests/adblock/adblocksubscription/rules.txt deleted file mode 100644 index 6a13a94c..00000000 --- a/autotests/adblock/adblocksubscription/rules.txt +++ /dev/null @@ -1,3 +0,0 @@ -[Adblock Plus 0.7.1] -http://example.com/ads/* -@@advice diff --git a/autotests/adblock/adblocksubscription/tst_adblocksubscription.cpp b/autotests/adblock/adblocksubscription/tst_adblocksubscription.cpp deleted file mode 100644 index 475ee467..00000000 --- a/autotests/adblock/adblocksubscription/tst_adblocksubscription.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include -#include - -#include - -#include - -class tst_AdBlockSubscription : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void adblocksubscription_data(); - void adblocksubscription(); - - void isEnabled_data(); - void isEnabled(); - void location_data(); - void location(); - void saveRules_data(); - void saveRules(); - void title_data(); - void title(); - void updateNow_data(); - void updateNow(); - void allow_data(); - void allow(); - void block_data(); - void block(); - void addRule(); - void removeRule(); -}; - -// Subclass that exposes the protected functions. -class SubAdBlockSubscription : public AdBlockSubscription -{ -public: - SubAdBlockSubscription(const QUrl &url = QUrl()) : AdBlockSubscription(url) {} - -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_AdBlockSubscription::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_AdBlockSubscription::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_AdBlockSubscription::init() -{ -} - -// This will be called after every test function. -void tst_AdBlockSubscription::cleanup() -{ -} - -void tst_AdBlockSubscription::adblocksubscription_data() -{ - QTest::addColumn("url"); - QTest::addColumn("title"); - QTest::addColumn("location"); - QTest::addColumn("enabled"); - QTest::addColumn("lastUpdate"); - QTest::newRow("basic0") << QUrl::fromEncoded("abp:subscribe?location=http://easylist.adblockplus.org/easylist.txt&title=EasyList") - << "EasyList" - << QUrl("http://easylist.adblockplus.org/easylist.txt") - << true - << QDateTime(); - - - QTest::addColumn("url"); - QTest::addColumn("title"); - QTest::addColumn("location"); - QTest::addColumn("enabled"); - QTest::addColumn("lastUpdate"); - QTest::newRow("basic1") << QUrl::fromEncoded("abp:subscribe?location=http://easylist.adblockplus.org/easylist.txt&title=EasyList&enabled=false&lastUpdate=2009-01-16T12%3A10%3A55") - << "EasyList" - << QUrl("http://easylist.adblockplus.org/easylist.txt") - << false - << QDateTime(QDate(2009, 1, 16), QTime(12, 10, 55)); -} - -void tst_AdBlockSubscription::adblocksubscription() -{ - QFETCH(QUrl, url); - QFETCH(QString, title); - QFETCH(QUrl, location); - QFETCH(bool, enabled); - QFETCH(QDateTime, lastUpdate); - - SubAdBlockSubscription subscription(url); - QCOMPARE(subscription.title(), title); - QCOMPARE(subscription.location(), location); - QCOMPARE(subscription.isEnabled(), enabled); - QCOMPARE(subscription.lastUpdate(), lastUpdate); - QVERIFY(subscription.url().isValid()); - //QCOMPARE(subscription.url(), url); - QCOMPARE(subscription.block(QString()), (AdBlockRule const*)0); - subscription.saveRules(); - subscription.setEnabled(false); - subscription.setLocation(QUrl()); - subscription.setTitle(QString()); - subscription.updateNow(); - subscription.allRules(); - subscription.removeRule(-1); - subscription.removeRule(0); - subscription.removeRule(1); - subscription.addRule(AdBlockRule()); -} - -Q_DECLARE_METATYPE(AdBlockRule const*) -void tst_AdBlockSubscription::allow_data() -{ - QTest::addColumn("url"); - QTest::addColumn("allow"); - QTest::newRow("block") << QUrl("http://example.com/ads/banner123.gif") << false; - QTest::newRow("allow") << QUrl("http://example.com/ads/advice.html") << true; -} - -// public AdBlockRule const *block(QString const &urlString) const -void tst_AdBlockSubscription::allow() -{ - QFETCH(QUrl, url); - QFETCH(bool, allow); - - SubAdBlockSubscription subscription; - subscription.setLocation(QUrl::fromLocalFile(QDir::currentPath() + "/rules.txt")); - subscription.setEnabled(true); - subscription.updateNow(); - - const AdBlockRule *rule = subscription.allow(QString::fromUtf8(url.toEncoded())); - if (rule) - QVERIFY(rule->isException()); - QCOMPARE((0 != rule), allow); -} - -void tst_AdBlockSubscription::block_data() -{ - QTest::addColumn("url"); - QTest::addColumn("block"); - QTest::newRow("block") << QUrl("http://example.com/ads/banner123.gif") << true; - QTest::newRow("allow") << QUrl("http://example.com/ads/advice.html") << true; -} - -// public AdBlockRule const *block(QString const &urlString) const -void tst_AdBlockSubscription::block() -{ - QFETCH(QUrl, url); - QFETCH(bool, block); - - SubAdBlockSubscription subscription; - subscription.setLocation(QUrl::fromLocalFile(QDir::currentPath() + "/rules.txt")); - subscription.setEnabled(true); - subscription.updateNow(); - - const AdBlockRule *rule = subscription.block(QString::fromUtf8(url.toEncoded())); - if (rule) - QVERIFY(!rule->isException()); - QCOMPARE((0 != rule), block); -} - -void tst_AdBlockSubscription::isEnabled_data() -{ - QTest::addColumn("isEnabled"); - QTest::newRow("true") << true; - QTest::newRow("false") << false; -} - -// public bool isEnabled() const -void tst_AdBlockSubscription::isEnabled() -{ - QFETCH(bool, isEnabled); - - SubAdBlockSubscription subscription; - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - bool changed = subscription.isEnabled() != isEnabled; - subscription.setEnabled(isEnabled); - QCOMPARE(subscription.isEnabled(), isEnabled); - - QCOMPARE(spy0.count(), 0); - QCOMPARE(spy1.count(), changed ? 1 : 0); -} - -void tst_AdBlockSubscription::location_data() -{ - QTest::addColumn("location"); - QTest::newRow("null") << QUrl(); - QTest::newRow("x") << QUrl("x"); -} - -// public QUrl location() const -void tst_AdBlockSubscription::location() -{ - QFETCH(QUrl, location); - - SubAdBlockSubscription subscription(QUrl("abp:subscribe")); - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - bool changed = location != subscription.location(); - subscription.setLocation(location); - QCOMPARE(subscription.location(), location); - QCOMPARE(subscription.url(), QUrl(QString("abp:subscribe?location=%1&title=").arg(location.toString()))); - - QCOMPARE(spy0.count(), 0); - QCOMPARE(spy1.count(), changed ? 1 : 0); -} - -void tst_AdBlockSubscription::saveRules_data() -{ - QTest::addColumn("location"); - QTest::newRow("file") << QUrl::fromLocalFile(QDir::currentPath() + "/rules2.txt"); -} - -// public void saveRules() -void tst_AdBlockSubscription::saveRules() -{ - QFETCH(QUrl, location); - SubAdBlockSubscription subscription; - subscription.setLocation(location); - - subscription.addRule(AdBlockRule()); - subscription.saveRules(); - subscription.removeRule(0); - subscription.updateNow(); - QCOMPARE(subscription.allRules().count(), 1); -} - -void tst_AdBlockSubscription::title_data() -{ - QTest::addColumn("title"); - QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); -} - -// public QString title() const -void tst_AdBlockSubscription::title() -{ - QFETCH(QString, title); - - SubAdBlockSubscription subscription; - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - bool changed = title != subscription.title(); - subscription.setTitle(title); - QCOMPARE(subscription.title(), title); - - QCOMPARE(spy0.count(), 0); - QCOMPARE(spy1.count(), changed ? 1 : 0); -} - -void tst_AdBlockSubscription::updateNow_data() -{ - QTest::addColumn("location"); - QTest::newRow("file") << QUrl::fromLocalFile(QDir::currentPath() + "/rules.txt"); -} - -// public void updateNow() -void tst_AdBlockSubscription::updateNow() -{ - QFETCH(QUrl, location); - - SubAdBlockSubscription subscription; - subscription.setLocation(location); - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - subscription.updateNow(); - - QTRY_COMPARE(spy0.count(), 1); - QCOMPARE(spy1.count(), 1); - QVERIFY(subscription.lastUpdate() != QDateTime()); - QCOMPARE(subscription.allRules().count(), 2); -} - -void tst_AdBlockSubscription::addRule() -{ - SubAdBlockSubscription subscription; - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - subscription.addRule(AdBlockRule()); - subscription.addRule(AdBlockRule("/test")); - - QTRY_COMPARE(spy0.count(), 2); - QCOMPARE(spy1.count(), 0); - QCOMPARE(subscription.allRules().count(), 2); -} - -void tst_AdBlockSubscription::removeRule() -{ - SubAdBlockSubscription subscription; - - QSignalSpy spy0(&subscription, SIGNAL(rulesChanged())); - QSignalSpy spy1(&subscription, SIGNAL(changed())); - - subscription.addRule(AdBlockRule("/test")); - subscription.removeRule(0); - - QTRY_COMPARE(spy0.count(), 2); - QCOMPARE(spy1.count(), 0); - QCOMPARE(subscription.allRules().count(), 0); -} - - -QTEST_MAIN(tst_AdBlockSubscription) -#include "tst_adblocksubscription.moc" - diff --git a/autotests/addbookmarkdialog/CMakeLists.txt b/autotests/addbookmarkdialog/CMakeLists.txt new file mode 100644 index 00000000..3e0db452 --- /dev/null +++ b/autotests/addbookmarkdialog/CMakeLists.txt @@ -0,0 +1,7 @@ +project(test-addbookmarkdialog) +find_package(Qt5Test REQUIRED) + +QT5_WRAP_UI(UIS ../../src/bookmarks/addbookmarkdialog.ui) + +add_executable(test-addbookmarkdialog tst_addbookmarkdialog.cpp ${UIS}) +target_link_libraries(test-addbookmarkdialog endorphin-base Qt5::Test) diff --git a/autotests/addbookmarkdialog/addbookmarkdialog.pro b/autotests/addbookmarkdialog/addbookmarkdialog.pro deleted file mode 100644 index b23b95df..00000000 --- a/autotests/addbookmarkdialog/addbookmarkdialog.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_addbookmarkdialog.cpp diff --git a/autotests/addbookmarkdialog/tst_addbookmarkdialog.cpp b/autotests/addbookmarkdialog/tst_addbookmarkdialog.cpp index 0f2e6d49..500d5950 100644 --- a/autotests/addbookmarkdialog/tst_addbookmarkdialog.cpp +++ b/autotests/addbookmarkdialog/tst_addbookmarkdialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,20 +24,20 @@ #include "bookmarknode.h" #include "browserapplication.h" -#include -#include +#include +#include class tst_AddBookmarkDialog : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void addbookmarkdialog_data(); void addbookmarkdialog(); }; diff --git a/autotests/autosaver/CMakeLists.txt b/autotests/autosaver/CMakeLists.txt new file mode 100644 index 00000000..fa885fbc --- /dev/null +++ b/autotests/autosaver/CMakeLists.txt @@ -0,0 +1,5 @@ +project(test-autosaver) +find_package(Qt5Test REQUIRED) + +add_executable(test-autosaver tst_autosaver.cpp) +target_link_libraries(test-autosaver endorphin-base Qt5::Test) diff --git a/autotests/autosaver/autosaver.pro b/autotests/autosaver/autosaver.pro deleted file mode 100644 index 2ca5ec4f..00000000 --- a/autotests/autosaver/autosaver.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES = tst_autosaver.cpp autosaver.cpp -HEADERS = autosaver.h diff --git a/autotests/autosaver/tst_autosaver.cpp b/autotests/autosaver/tst_autosaver.cpp index 5e942746..9119c399 100644 --- a/autotests/autosaver/tst_autosaver.cpp +++ b/autotests/autosaver/tst_autosaver.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,7 +24,7 @@ class tst_AutoSaver : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); @@ -32,7 +32,7 @@ public slots: void save(); -private slots: +private Q_SLOTS: void AutoSaver_data(); void AutoSaver(); void changeOccurred_data(); @@ -53,7 +53,7 @@ class TestClass : public QObject { Q_OBJECT -signals: +Q_SIGNALS: void saveCalled(); public: @@ -68,9 +68,9 @@ Q_OBJECT SubAutoSaver *AutoSaver; -public slots: +public Q_SLOTS: void save() { - emit saveCalled(); + Q_EMIT saveCalled(); } }; diff --git a/autotests/autotests.pri b/autotests/autotests.pri deleted file mode 100644 index f72584ad..00000000 --- a/autotests/autotests.pri +++ /dev/null @@ -1,21 +0,0 @@ -win32: CONFIG += console -mac:CONFIG -= app_bundle - -CONFIG += qtestlib - -include($$PWD/../src/src.pri) -include($$PWD/modeltest/modeltest.pri) - -HEADERS += qtest_endorphin.h - -DEFINES += AUTOTESTS - -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD - -RCC_DIR = $$PWD/.rcc -UI_DIR = $$PWD/.ui -MOC_DIR = $$PWD/.moc -OBJECTS_DIR = $$PWD/.obj - - diff --git a/autotests/autotests.pro b/autotests/autotests.pro deleted file mode 100644 index fdd32901..00000000 --- a/autotests/autotests.pro +++ /dev/null @@ -1,23 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - adblock \ - addbookmarkdialog \ - autosaver \ - bookmarknode \ - cookiejar \ - historyfiltermodel \ - historymanager \ - modeltoolbar \ - opensearchengine \ - opensearchmanager \ - opensearchreader \ - opensearchwriter \ - searchlineedit \ - tabbar \ - tabwidget \ - utils \ - webactionmapper \ - webpage \ - xbel - -CONFIG += ordered diff --git a/autotests/bookmarknode/CMakeLists.txt b/autotests/bookmarknode/CMakeLists.txt new file mode 100644 index 00000000..88295a9b --- /dev/null +++ b/autotests/bookmarknode/CMakeLists.txt @@ -0,0 +1,6 @@ +project(test-bookmarknode) +find_package(Qt5Test REQUIRED) + +add_executable(test-bookmarknode tst_bookmarknode.cpp) +target_link_libraries(test-bookmarknode endorphin-base Qt5::Test) + diff --git a/autotests/bookmarknode/bookmarknode.pro b/autotests/bookmarknode/bookmarknode.pro deleted file mode 100644 index b796c019..00000000 --- a/autotests/bookmarknode/bookmarknode.pro +++ /dev/null @@ -1,14 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../autotests.pri) - -QT = core - -# Input -SOURCES = bookmarknode.cpp tst_bookmarknode.cpp -HEADERS = bookmarknode.h -FORMS = -RESOURCE = diff --git a/autotests/bookmarknode/tst_bookmarknode.cpp b/autotests/bookmarknode/tst_bookmarknode.cpp index 15cdda19..8bf77ac1 100644 --- a/autotests/bookmarknode/tst_bookmarknode.cpp +++ b/autotests/bookmarknode/tst_bookmarknode.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Aaron Dewes + * Copyright (c) 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -33,13 +33,13 @@ class tst_BookmarkNode : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void bookmarknode_data(); void bookmarknode(); diff --git a/autotests/cookiejar/.gitignore b/autotests/cookiejar/.gitignore deleted file mode 100644 index b4440a70..00000000 --- a/autotests/cookiejar/.gitignore +++ /dev/null @@ -1 +0,0 @@ -cookiejar diff --git a/autotests/cookiejar/cookiejar.pro b/autotests/cookiejar/cookiejar.pro deleted file mode 100644 index bc4d22b0..00000000 --- a/autotests/cookiejar/cookiejar.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_cookiejar.cpp -HEADERS += diff --git a/autotests/cookiejar/tst_cookiejar.cpp b/autotests/cookiejar/tst_cookiejar.cpp deleted file mode 100644 index e7a99a67..00000000 --- a/autotests/cookiejar/tst_cookiejar.cpp +++ /dev/null @@ -1,556 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include - -class tst_CookieJar : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void cookiejar_data(); - void cookiejar(); - - void acceptPolicy_data(); - void acceptPolicy(); - void allowedCookies_data(); - void allowedCookies(); - void allowForSessionCookies_data(); - void allowForSessionCookies(); - void blockedCookies_data(); - void blockedCookies(); - void clear_data(); - void clear(); - void cookiesForUrl_data(); - void cookiesForUrl(); - void keepPolicy_data(); - void keepPolicy(); - void loadSettings_data(); - void loadSettings(); - void setAcceptPolicy_data(); - void setAcceptPolicy(); - void setAllowedCookies_data(); - void setAllowedCookies(); - void setAllowForSessionCookies_data(); - void setAllowForSessionCookies(); - void setBlockedCookies_data(); - void setBlockedCookies(); - void setCookiesFromUrl_data(); - void setCookiesFromUrl(); - void setKeepPolicy_data(); - void setKeepPolicy(); - void cookiesChanged_data(); - void cookiesChanged(); - void isOnDomainList_data(); - void isOnDomainList(); -}; - -// Subclass that exposes the protected functions. -class SubCookieJar : public CookieJar -{ -public: - void call_cookiesChanged() - { return SubCookieJar::cookiesChanged(); } - - static bool call_isOnDomainList(QStringList const &list, QString const &domain) - { return SubCookieJar::isOnDomainList(list, domain); } -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_CookieJar::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_CookieJar::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_CookieJar::init() -{ -} - -// This will be called after every test function. -void tst_CookieJar::cleanup() -{ -} - -void tst_CookieJar::cookiejar_data() -{ -} - -void tst_CookieJar::cookiejar() -{ - SubCookieJar jar; -#if 0 - QCOMPARE(jar.acceptPolicy(), CookieJar::AcceptPolicy); - QCOMPARE(jar.allowedCookies(), QStringList); - QCOMPARE(jar.allowForSessionCookies(), QStringList); - QCOMPARE(jar.blockedCookies(), QStringList); - jar.clear(); - QCOMPARE(jar.cookiesForUrl(QUrl()), QList()); - QCOMPARE(jar.keepPolicy(), CookieJar::KeepPolicy); - jar.loadSettings(); - jar.setAcceptPolicy(CookieJar::AcceptPolicy); - jar.setAllowedCookies(QStringList()); - jar.setAllowForSessionCookies(QStringList()); - jar.setBlockedCookies(QStringList()); - QCOMPARE(jar.setCookiesFromUrl(QList(), QUrl()), false); - jar.setKeepPolicy(CookieJar::KeepPolicy); - jar.call_cookiesChanged(); - QCOMPARE(jar.call_isOnDomainList(QStringList(), QString()), false); -#endif - QSKIP("Test is not implemented."); -} - -Q_DECLARE_METATYPE(CookieJar::AcceptPolicy) -void tst_CookieJar::acceptPolicy_data() -{ -#if 0 - QTest::addColumn("acceptPolicy"); - QTest::newRow("null") << CookieJar::AcceptPolicy(); -#endif -} - -// public CookieJar::AcceptPolicy acceptPolicy() const -void tst_CookieJar::acceptPolicy() -{ -#if 0 - QFETCH(CookieJar::AcceptPolicy, acceptPolicy); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.acceptPolicy(), acceptPolicy); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::allowedCookies_data() -{ -#if 0 - QTest::addColumn("allowedCookies"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public QStringList allowedCookies() const -void tst_CookieJar::allowedCookies() -{ -#if 0 - QFETCH(QStringList, allowedCookies); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.allowedCookies(), allowedCookies); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::allowForSessionCookies_data() -{ -#if 0 - QTest::addColumn("allowForSessionCookies"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public QStringList allowForSessionCookies() const -void tst_CookieJar::allowForSessionCookies() -{ -#if 0 - QFETCH(QStringList, allowForSessionCookies); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.allowForSessionCookies(), allowForSessionCookies); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::blockedCookies_data() -{ -#if 0 - QTest::addColumn("blockedCookies"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public QStringList blockedCookies() const -void tst_CookieJar::blockedCookies() -{ -#if 0 - QFETCH(QStringList, blockedCookies); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.blockedCookies(), blockedCookies); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::clear_data() -{ - QTest::addColumn("foo"); - QTest::newRow("0") << 0; - QTest::newRow("-1") << -1; -} - -// public void clear() -void tst_CookieJar::clear() -{ -#if 0 - QFETCH(int, foo); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.clear(); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::cookiesForUrl_data() -{ -#if 0 - QTest::addColumn("url"); - QTest::addColumn>("cookiesForUrl"); - QTest::newRow("null") << QUrl() << QList(); -#endif -} - -// public QList cookiesForUrl(QUrl const &url) const -void tst_CookieJar::cookiesForUrl() -{ -#if 0 - QFETCH(QUrl, url); - QFETCH(QList, cookiesForUrl); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.cookiesForUrl(url), cookiesForUrl); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -Q_DECLARE_METATYPE(CookieJar::KeepPolicy) -void tst_CookieJar::keepPolicy_data() -{ -#if 0 - QTest::addColumn("keepPolicy"); - QTest::newRow("null") << CookieJar::KeepPolicy(); -#endif -} - -// public CookieJar::KeepPolicy keepPolicy() const -void tst_CookieJar::keepPolicy() -{ -#if 0 - QFETCH(CookieJar::KeepPolicy, keepPolicy); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.keepPolicy(), keepPolicy); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::loadSettings_data() -{ - QTest::addColumn("foo"); - QTest::newRow("0") << 0; - QTest::newRow("-1") << -1; -} - -// public void loadSettings() -void tst_CookieJar::loadSettings() -{ -#if 0 - QFETCH(int, foo); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.loadSettings(); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setAcceptPolicy_data() -{ -#if 0 - QTest::addColumn("policy"); - QTest::newRow("null") << CookieJar::AcceptPolicy(); -#endif -} - -// public void setAcceptPolicy(CookieJar::AcceptPolicy policy) -void tst_CookieJar::setAcceptPolicy() -{ -#if 0 - QFETCH(CookieJar::AcceptPolicy, policy); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.setAcceptPolicy(policy); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setAllowedCookies_data() -{ -#if 0 - QTest::addColumn("list"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public void setAllowedCookies(QStringList const &list) -void tst_CookieJar::setAllowedCookies() -{ -#if 0 - QFETCH(QStringList, list); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.setAllowedCookies(list); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setAllowForSessionCookies_data() -{ -#if 0 - QTest::addColumn("list"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public void setAllowForSessionCookies(QStringList const &list) -void tst_CookieJar::setAllowForSessionCookies() -{ -#if 0 - QFETCH(QStringList, list); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.setAllowForSessionCookies(list); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setBlockedCookies_data() -{ -#if 0 - QTest::addColumn("list"); - QTest::newRow("null") << QStringList(); -#endif -} - -// public void setBlockedCookies(QStringList const &list) -void tst_CookieJar::setBlockedCookies() -{ -#if 0 - QFETCH(QStringList, list); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.setBlockedCookies(list); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setCookiesFromUrl_data() -{ -#if 0 - QTest::addColumn>("cookieList"); - QTest::addColumn("url"); - QTest::addColumn("setCookiesFromUrl"); - QTest::newRow("null") << QList() << QUrl() << false; -#endif -} - -// public bool setCookiesFromUrl(QList const &cookieList, QUrl const &url) -void tst_CookieJar::setCookiesFromUrl() -{ -#if 0 - QFETCH(QList, cookieList); - QFETCH(QUrl, url); - QFETCH(bool, setCookiesFromUrl); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - QCOMPARE(jar.setCookiesFromUrl(cookieList, url), setCookiesFromUrl); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::setKeepPolicy_data() -{ -#if 0 - QTest::addColumn("policy"); - QTest::newRow("null") << CookieJar::KeepPolicy(); -#endif -} - -// public void setKeepPolicy(CookieJar::KeepPolicy policy) -void tst_CookieJar::setKeepPolicy() -{ -#if 0 - QFETCH(CookieJar::KeepPolicy, policy); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.setKeepPolicy(policy); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::cookiesChanged_data() -{ - QTest::addColumn("foo"); - QTest::newRow("0") << 0; - QTest::newRow("-1") << -1; -} - -// protected void cookiesChanged() -void tst_CookieJar::cookiesChanged() -{ -#if 0 - QFETCH(int, foo); - - SubCookieJar jar; - - QSignalSpy spy0(&jar, SIGNAL(cookiesChanged())); - - jar.call_cookiesChanged(); - - QCOMPARE(spy0.count(), 0); -#endif - QSKIP("Test is not implemented."); -} - -void tst_CookieJar::isOnDomainList_data() -{ - QTest::addColumn("list"); - QTest::addColumn("domain"); - QTest::addColumn("isOnDomainList"); - - QTest::newRow("null") << QStringList() << QString() << false; - QTest::newRow("exact-match") << (QStringList() << "foo.com") << "foo.com" << true; - - QTest::newRow("check-0") << (QStringList() << "foo.com") << "foo.com" << true; - QTest::newRow("check-1") << (QStringList() << "foo.com") << ".foo.com" << true; - QTest::newRow("check-2") << (QStringList() << ".foo.com") << "foo.com" << true; - QTest::newRow("check-3") << (QStringList() << ".foo.com") << ".foo.com" << true; - QTest::newRow("check-4") << (QStringList() << "foo.com") << "abcfoo.com" << false; - QTest::newRow("check-5") << (QStringList() << "foo.com") << "abc.foo.com" << true; - QTest::newRow("check-6") << (QStringList() << ".foo.com") << "abcfoo.com" << false; - QTest::newRow("check-7") << (QStringList() << ".foo.com") << "abc.foo.com" << true; - - QTest::newRow("check-4") << (QStringList() << "abc.foo.com") << "foo.com" << false; - QTest::newRow("check-5") << (QStringList() << "abc.foo.com") << ".foo.com" << false; - - - QTest::newRow("edgecheck-0") << (QStringList() << "") << ".foo.com" << false; - QTest::newRow("edgecheck-1") << (QStringList() << "") << "foo.com" << false; - QTest::newRow("edgecheck-2") << (QStringList() << ".") << ".foo.com" << false; - QTest::newRow("edgecheck-3") << (QStringList() << ".") << "foo.com" << false; - QTest::newRow("edgecheck-4") << (QStringList() << "abc.foo.com") << "" << false; - QTest::newRow("edgecheck-5") << (QStringList() << "a") << "ab" << false; -} - -// protected static bool isOnDomainList(QStringList const &list, QString const &domain) -void tst_CookieJar::isOnDomainList() -{ - QFETCH(QStringList, list); - QFETCH(QString, domain); - QFETCH(bool, isOnDomainList); - - SubCookieJar jar; - - QCOMPARE(jar.call_isOnDomainList(list, domain), isOnDomainList); -} - -QTEST_MAIN(tst_CookieJar) -#include "tst_cookiejar.moc" - diff --git a/autotests/downloadmanager/CMakeLists.txt b/autotests/downloadmanager/CMakeLists.txt new file mode 100644 index 00000000..f1bfdcae --- /dev/null +++ b/autotests/downloadmanager/CMakeLists.txt @@ -0,0 +1,5 @@ +project(test-downloadmanager) +find_package(Qt5Test REQUIRED) + +add_executable(test-downloadmanager tst_downloadmanager.cpp) +target_link_libraries(test-downloadmanager endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/downloadmanager/downloadmanager.pro b/autotests/downloadmanager/downloadmanager.pro deleted file mode 100644 index f53cddff..00000000 --- a/autotests/downloadmanager/downloadmanager.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_downloadmanager.cpp -HEADERS += diff --git a/autotests/downloadmanager/tst_downloadmanager.cpp b/autotests/downloadmanager/tst_downloadmanager.cpp index 6e142f6c..69d080e0 100644 --- a/autotests/downloadmanager/tst_downloadmanager.cpp +++ b/autotests/downloadmanager/tst_downloadmanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,21 +22,21 @@ #include #include "downloadmanager.h" -#define BIGFILE "http://10.0.0.3/~ben/distccKNOPPIX-1.3-2004-08-20-gcc-3.3.iso" -#define BIGFILENAME "distccKNOPPIX-1.3-2004-08-20-gcc-3.3.iso" -#define BIGFILENAME2 "distccKNOPPIX-1.3-2004-08-20-gcc-3.3-1.iso" +#define BIGFILE "http://ftp.uni-kl.de/pub/linux/knoppix/KNOPPIX_V7.2.0CD-2013-06-16-DE.iso" +#define BIGFILENAME "KNOPPIX_V7.2.0CD-2013-06-16-DE.iso" +#define BIGFILENAME2 "KNOPPIX_V7.2.0CD-2013-06-16-DE.iso" class tst_DownloadManager : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void downloadmanager_data(); void downloadmanager(); void cleanupButton_data(); diff --git a/autotests/historyfiltermodel/CMakeLists.txt b/autotests/historyfiltermodel/CMakeLists.txt new file mode 100644 index 00000000..224d5055 --- /dev/null +++ b/autotests/historyfiltermodel/CMakeLists.txt @@ -0,0 +1,6 @@ +project(test-historyfiltermodel) +find_package(Qt5Test REQUIRED) +QT5_WRAP_UI(UIS ../../src/history/history.ui) + +add_executable(test-historyfiltermodel tst_historyfiltermodel.cpp ${UIS}) +target_link_libraries(test-historyfiltermodel endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/historyfiltermodel/historyfiltermodel.pro b/autotests/historyfiltermodel/historyfiltermodel.pro deleted file mode 100644 index 2315b830..00000000 --- a/autotests/historyfiltermodel/historyfiltermodel.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_historyfiltermodel.cpp -HEADERS += diff --git a/autotests/historyfiltermodel/tst_historyfiltermodel.cpp b/autotests/historyfiltermodel/tst_historyfiltermodel.cpp index b753239f..4fe37db7 100644 --- a/autotests/historyfiltermodel/tst_historyfiltermodel.cpp +++ b/autotests/historyfiltermodel/tst_historyfiltermodel.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,7 +17,8 @@ * Boston, MA 02110-1301 USA */ -#include +#include +#include #include #include @@ -25,13 +26,13 @@ class tst_HistoryFilterModel : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void historyfiltermodel_data(); void historyfiltermodel(); @@ -111,14 +112,14 @@ HistoryList makeHistoryList(int count) QDateTime dateTime = QDateTime::currentDateTime(); for (int i = 0; i < count; ++i) { HistoryEntry item; - QString url = QString("http://%1host-%2.com/") - .arg(qrand() % 2 ? "www." : "") + QString url = QStringLiteral("http://%1host-%2.com/") + .arg(QRandomGenerator::global()->generate() % 2 ? "www." : "") .arg(QString::number(i)); item.url = url; - item.title = QString("title %1").arg(i); + item.title = QStringLiteral("title %1").arg(i); item.dateTime = dateTime; list.append(item); - dateTime = dateTime.addSecs(-1 * qrand() % (60 * 60)); + dateTime = dateTime.addSecs(-1 * QRandomGenerator::global()->generate() % (60 * 60)); } return list; } @@ -129,7 +130,7 @@ void tst_HistoryFilterModel::historyContains_data() QTest::addColumn("url"); QTest::addColumn("historyContains"); - QTest::newRow("null") << HistoryList() << QString("foo") << false; + QTest::newRow("null") << HistoryList() << QStringLiteral("foo") << false; HistoryList list1 = makeHistoryList(1); QTest::newRow("one") << list1 << list1.at(0).url << true; @@ -138,7 +139,7 @@ void tst_HistoryFilterModel::historyContains_data() QTest::newRow("many-0") << list2 << list2.at(0).url << true; QTest::newRow("many-1") << list2 << list2.at(1).url << true; QTest::newRow("many-2") << list2 << list2.at(4).url << true; - QTest::newRow("many-3") << list2 << QString("foo") << false; + QTest::newRow("many-3") << list2 << QStringLiteral("foo") << false; } // public bool historyContains(QString const &url) const @@ -284,8 +285,8 @@ void tst_HistoryFilterModel::addRow() } if (history.count() > 0) - for (int i = 0; i < qrand() % 15; ++i) - model.history->addHistoryEntry(history[qrand() % history.count()].url); + for (uint i = 0; i < QRandomGenerator::global()->generate() % 15; ++i) + model.history->addHistoryEntry(history[QRandomGenerator::global()->generate() % history.count()].url); QStringList urls; for (int i = 0; i < model.rowCount(); ++i) { QModelIndex idx = model.index(i, 0); diff --git a/autotests/historymanager/CMakeLists.txt b/autotests/historymanager/CMakeLists.txt new file mode 100644 index 00000000..073264b9 --- /dev/null +++ b/autotests/historymanager/CMakeLists.txt @@ -0,0 +1,10 @@ +project(test-historymanager) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) +QT5_WRAP_UI(UIS ../../src/history/history.ui) + +add_executable(test-historymanager tst_historymanager.cpp ../modeltest/modeltest.cpp ${UIS}) +target_link_libraries(test-historymanager endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/historymanager/historymanager.pro b/autotests/historymanager/historymanager.pro deleted file mode 100644 index 92e9c624..00000000 --- a/autotests/historymanager/historymanager.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_historymanager.cpp -HEADERS += diff --git a/autotests/historymanager/tst_historymanager.cpp b/autotests/historymanager/tst_historymanager.cpp index 48d06671..1a3c20cc 100644 --- a/autotests/historymanager/tst_historymanager.cpp +++ b/autotests/historymanager/tst_historymanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,29 +20,29 @@ #include #include "qtest_endorphin.h" -#include -#include -#include +#include "historymanager.h" +#include "history.h" +#include "locationcompleter.h" #include -#include +#include class tst_HistoryManager : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void history_data(); void history(); void addHistoryEntry_data(); void addHistoryEntry(); - void addHistoryEntry_private(); + //void addHistoryEntry_private(); void addHistoryEntry_url(); void updateHistoryEntry_data(); void updateHistoryEntry(); @@ -73,8 +73,6 @@ class SubHistory : public HistoryManager { QWidget w; setParent(&w); - if (QWebHistoryInterface::defaultInterface() == this) - QWebHistoryInterface::setDefaultInterface(0); setParent(0); } @@ -208,7 +206,7 @@ void tst_HistoryManager::addHistoryEntry() QCOMPARE(history.history().count(), expected.count()); QCOMPARE(history.history(), expected); } - +/* void tst_HistoryManager::addHistoryEntry_private() { SubHistory history; @@ -219,7 +217,7 @@ void tst_HistoryManager::addHistoryEntry_private() globalSettings->setAttribute(QWebSettings::PrivateBrowsingEnabled, false); QVERIFY(history.history().isEmpty()); } - +*/ void tst_HistoryManager::addHistoryEntry_url() { SubHistory history; @@ -236,8 +234,8 @@ void tst_HistoryManager::updateHistoryEntry_data() QTest::addColumn("title"); QTest::newRow("null") << HistoryList() << QUrl() << QString(); - QTest::newRow("one") << (HistoryList() << HistoryEntry()) << QUrl() << QString("foo"); - QTest::newRow("two") << (HistoryList() << HistoryEntry() << HistoryEntry("http://foo.com")) << QUrl() << QString("foo"); + QTest::newRow("one") << (HistoryList() << HistoryEntry()) << QUrl() << QStringLiteral("foo"); + QTest::newRow("two") << (HistoryList() << HistoryEntry() << HistoryEntry("http://foo.com")) << QUrl() << QStringLiteral("foo"); } // public void updateHistoryEntry(QUrl const &url, QString const title) @@ -289,7 +287,7 @@ void tst_HistoryManager::daysToExpire() SubHistory history; history.setHistory(list); - qSort(list.begin(), list.end()); + std::sort(list.begin(), list.end()); QCOMPARE(history.history(), list); history.setDaysToExpire(daysToExpire); @@ -434,7 +432,7 @@ void tst_HistoryManager::big() ModelTest test(&model); QCOMPARE(model.rowCount(), bigHistory.count()); - HistoryCompletionModel completionModel; + LocationCompletionModel completionModel; completionModel.setSourceModel(&model); ModelTest test2(&completionModel); QCOMPARE(completionModel.rowCount(), bigHistory.count()); diff --git a/autotests/modeltest/modeltest.cpp b/autotests/modeltest/modeltest.cpp index a107e661..d7170280 100644 --- a/autotests/modeltest/modeltest.cpp +++ b/autotests/modeltest/modeltest.cpp @@ -22,6 +22,7 @@ ****************************************************************************/ #include +#include #include "modeltest.h" @@ -34,44 +35,28 @@ ModelTest::ModelTest(QAbstractItemModel *_model, QObject *parent) : QObject(pare { Q_ASSERT(model); - connect(model, SIGNAL(columnsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(headerDataChanged(Qt::Orientation, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutAboutToBeChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(modelReset ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); + connect(model, &QAbstractItemModel::columnsAboutToBeInserted, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::columnsAboutToBeRemoved, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::columnsInserted, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::columnsRemoved, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::dataChanged, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::headerDataChanged, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::layoutAboutToBeChanged, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::layoutChanged, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::modelReset, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::rowsAboutToBeInserted, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::rowsAboutToBeRemoved, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::rowsInserted, this, &ModelTest::runAllTests); + connect(model, &QAbstractItemModel::rowsRemoved, this, &ModelTest::runAllTests); // Special checks for inserting/removing - connect(model, SIGNAL(layoutAboutToBeChanged()), - this, SLOT(layoutAboutToBeChanged())); - connect(model, SIGNAL(layoutChanged()), - this, SLOT(layoutChanged())); - - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), - this, SLOT(rowsInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsRemoved(const QModelIndex &, int, int))); + connect(model, &QAbstractItemModel::layoutAboutToBeChanged, this, &ModelTest::layoutAboutToBeChanged); + connect(model, &QAbstractItemModel::layoutChanged, this, &ModelTest::layoutChanged); + + connect(model, &QAbstractItemModel::rowsAboutToBeInserted, this, &ModelTest::rowsAboutToBeInserted); + connect(model, &QAbstractItemModel::rowsAboutToBeRemoved, this, &ModelTest::rowsAboutToBeRemoved); + connect(model, &QAbstractItemModel::rowsInserted, this, &ModelTest::rowsInserted); + connect(model, &QAbstractItemModel::rowsRemoved, this, &ModelTest::rowsRemoved); runAllTests(); } @@ -384,50 +369,50 @@ void ModelTest::data() Q_ASSERT(model->index(0, 0).isValid()); // shouldn't be able to set data on an invalid index - Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false); + Q_ASSERT(model->setData(QModelIndex(), QStringLiteral("foo"), Qt::DisplayRole) == false); // General Purpose roles that should return a QString QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole); if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert(variant)); + Q_ASSERT(variant.canConvert(QMetaType::QString)); } variant = model->data(model->index(0, 0), Qt::StatusTipRole); if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert(variant)); + Q_ASSERT(variant.canConvert(QMetaType::QString)); } variant = model->data(model->index(0, 0), Qt::WhatsThisRole); if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert(variant)); + Q_ASSERT(variant.canConvert(QMetaType::QString)); } // General Purpose roles that should return a QSize variant = model->data(model->index(0, 0), Qt::SizeHintRole); if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert(variant)); + Q_ASSERT(variant.canConvert(QMetaType::QSize)); } // General Purpose roles that should return a QFont QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole); if (fontVariant.isValid()) { - Q_ASSERT(qVariantCanConvert(fontVariant)); + Q_ASSERT(fontVariant.canConvert(QMetaType::QFont)); } // Check that the alignment is one we know about QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole); if (textAlignmentVariant.isValid()) { int alignment = textAlignmentVariant.toInt(); - Q_ASSERT(alignment == (alignment & (Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask))); + Q_ASSERT(alignment == (alignment & (Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask))); } // General Purpose roles that should return a QColor QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole); if (colorVariant.isValid()) { - Q_ASSERT(qVariantCanConvert(colorVariant)); + Q_ASSERT(colorVariant.canConvert(QMetaType::QColor)); } colorVariant = model->data(model->index(0, 0), Qt::TextColorRole); if (colorVariant.isValid()) { - Q_ASSERT(qVariantCanConvert(colorVariant)); + Q_ASSERT(colorVariant.canConvert(QMetaType::QColor)); } // Check that the "check state" is one we know about. diff --git a/autotests/modeltest/modeltest.pri b/autotests/modeltest/modeltest.pri deleted file mode 100644 index 358a0778..00000000 --- a/autotests/modeltest/modeltest.pri +++ /dev/null @@ -1,4 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -SOURCES += $$PWD/modeltest.cpp -HEADERS += $$PWD/modeltest.h diff --git a/autotests/modeltoolbar/CMakeLists.txt b/autotests/modeltoolbar/CMakeLists.txt new file mode 100644 index 00000000..2a39ac30 --- /dev/null +++ b/autotests/modeltoolbar/CMakeLists.txt @@ -0,0 +1,10 @@ +project(test-modeltoolbar) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) + + +add_executable(test-modeltoolbar tst_modeltoolbar.cpp) +target_link_libraries(test-modeltoolbar endorphin-base Qt5::Test) diff --git a/autotests/modeltoolbar/modeltoolbar.pro b/autotests/modeltoolbar/modeltoolbar.pro deleted file mode 100644 index 2a63be59..00000000 --- a/autotests/modeltoolbar/modeltoolbar.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -SOURCES += \ - tst_modeltoolbar.cpp diff --git a/autotests/modeltoolbar/tst_modeltoolbar.cpp b/autotests/modeltoolbar/tst_modeltoolbar.cpp index 4682090c..39eb8935 100644 --- a/autotests/modeltoolbar/tst_modeltoolbar.cpp +++ b/autotests/modeltoolbar/tst_modeltoolbar.cpp @@ -24,22 +24,22 @@ #include "browserapplication.h" #include "modelmenu.h" -#include -#include -#include -#include +#include +#include +#include +#include class tst_ModelToolBar : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void modeltoolbar(); void index(); void model(); @@ -56,13 +56,20 @@ class SubModelToolBar : public ModelToolBar { public: void call_activated(QModelIndex const &index) - { return SubModelToolBar::activated(index); } + { + return SubModelToolBar::activated(index); + } void call_build() - { SubModelToolBar::build(); resize(sizeHint()); } + { + SubModelToolBar::build(); + resize(sizeHint()); + } ModelMenu *call_createMenu() - { return SubModelToolBar::createMenu(); } + { + return SubModelToolBar::createMenu(); + } }; class ColorModel : public QAbstractItemModel @@ -274,11 +281,6 @@ void tst_ModelToolBar::activated() if (spy.count()) QCOMPARE(spy.at(0).at(0).value(), bar.index(action)); - if (action) { - QCOMPARE(BrowserApplication::instance()->eventMouseButtons(), Qt::MidButton); - QCOMPARE(BrowserApplication::instance()->eventKeyboardModifiers(), Qt::ShiftModifier); - } - spy.clear(); point.setX(point.x() + 50); diff --git a/autotests/opensearchengine/CMakeLists.txt b/autotests/opensearchengine/CMakeLists.txt new file mode 100644 index 00000000..0b5f3812 --- /dev/null +++ b/autotests/opensearchengine/CMakeLists.txt @@ -0,0 +1,9 @@ +project(test-opensearchengine) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) + +add_executable(test-opensearchengine tst_opensearchengine.cpp) +target_link_libraries(test-opensearchengine endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/opensearchengine/opensearchengine.pro b/autotests/opensearchengine/opensearchengine.pro deleted file mode 100644 index 9a5b215a..00000000 --- a/autotests/opensearchengine/opensearchengine.pro +++ /dev/null @@ -1,20 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -SOURCES = \ - opensearchengine.cpp \ - opensearchenginedelegate.cpp \ - tst_opensearchengine.cpp - -HEADERS = \ - opensearchengine.h \ - opensearchenginedelegate.h - -FORMS = - -RESOURCES = \ - opensearchengine.qrc diff --git a/autotests/opensearchengine/tst_opensearchengine.cpp b/autotests/opensearchengine/tst_opensearchengine.cpp index 3a3bd205..3f30d64f 100644 --- a/autotests/opensearchengine/tst_opensearchengine.cpp +++ b/autotests/opensearchengine/tst_opensearchengine.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -24,12 +24,12 @@ #include "opensearchenginedelegate.h" #include -#include +#include #include #include -#include -#include -#include +#include +#include +#include typedef OpenSearchEngine::Parameters Parameters; typedef OpenSearchEngine::Parameter Parameter; @@ -38,13 +38,13 @@ class tst_OpenSearchEngine : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void opensearchengine_data(); void opensearchengine(); @@ -90,16 +90,24 @@ class SubOpenSearchEngine : public OpenSearchEngine { public: void call_imageChanged() - { return SubOpenSearchEngine::imageChanged(); } + { + return SubOpenSearchEngine::imageChanged(); + } void call_loadImage() const - { return SubOpenSearchEngine::loadImage(); } + { + return SubOpenSearchEngine::loadImage(); + } QString call_parseTemplate(QString const &searchTerm, QString const &searchTemplate) const - { return SubOpenSearchEngine::parseTemplate(searchTerm, searchTemplate); } + { + return SubOpenSearchEngine::parseTemplate(searchTerm, searchTemplate); + } void call_suggestions(QStringList const &suggestions) - { return SubOpenSearchEngine::suggestions(suggestions); } + { + return SubOpenSearchEngine::suggestions(suggestions); + } }; class SuggestionsTestNetworkReply : public QNetworkReply @@ -146,7 +154,7 @@ class SuggestionsTestNetworkReply : public QNetworkReply { } -private slots: +private Q_SLOTS: void sendSuggestions() { // Publish result @@ -155,10 +163,10 @@ private slots: setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200); setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, QByteArray("Ok")); - emit metaDataChanged(); - emit readyRead(); - emit downloadProgress(expectedResult.size(), expectedResult.size()); - emit finished(); + Q_EMIT metaDataChanged(); + Q_EMIT readyRead(); + Q_EMIT downloadProgress(expectedResult.size(), expectedResult.size()); + Q_EMIT finished(); } private: @@ -285,7 +293,7 @@ void tst_OpenSearchEngine::description_data() { QTest::addColumn("description"); QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString description() const @@ -324,7 +332,7 @@ void tst_OpenSearchEngine::image() QPixmap image(1, 1); image.fill(); image.save(&imageBuffer, "PNG"); - QString imageUrl = QString("data:image/png;base64,").append(imageBuffer.buffer().toBase64()); + QString imageUrl = QStringLiteral("data:image/png;base64,").append(imageBuffer.buffer().toBase64()); engine.setImageUrl(imageUrl); QCOMPARE(engine.image(), QImage()); @@ -346,7 +354,7 @@ void tst_OpenSearchEngine::imageUrl_data() { QTest::addColumn("imageUrl"); QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString imageUrl() const @@ -375,9 +383,9 @@ void tst_OpenSearchEngine::isValid_data() QTest::addColumn("searchUrlTemplate"); QTest::addColumn("isValid"); QTest::newRow("false-0") << QString() << QString() << false; - QTest::newRow("false-1") << QString() << QString("x") << false; - QTest::newRow("false-2") << QString("x") << QString() << false; - QTest::newRow("true") << QString("x") << QString("y") << true; + QTest::newRow("false-1") << QString() << QStringLiteral("x") << false; + QTest::newRow("false-2") << QStringLiteral("x") << QString() << false; + QTest::newRow("true") << QStringLiteral("x") << QStringLiteral("y") << true; } // public bool isValid() const @@ -404,7 +412,7 @@ void tst_OpenSearchEngine::name_data() { QTest::addColumn("name"); QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString name() const @@ -452,13 +460,13 @@ void tst_OpenSearchEngine::operatorequal_data() QTest::newRow("null") << QString() << QString() << QString() << QString() << QString() << Parameters() << Parameters() << true; - QTest::newRow("name") << QString("x") << QString() << QString() << QString() << QString() + QTest::newRow("name") << QStringLiteral("x") << QString() << QString() << QString() << QString() << Parameters() << Parameters() << false; - QTest::newRow("description") << QString() << QString("x") << QString() << QString() << QString() + QTest::newRow("description") << QString() << QStringLiteral("x") << QString() << QString() << QString() << Parameters() << Parameters() << false; - QTest::newRow("imageUrl") << QString() << QString() << QString("x") << QString() << QString() + QTest::newRow("imageUrl") << QString() << QString() << QStringLiteral("x") << QString() << QString() << Parameters() << Parameters() << false; QTest::newRow("parameters") << QString() << QString() << QString() << QString() << QString() @@ -496,7 +504,7 @@ void tst_OpenSearchEngine::providesSuggestions_data() QTest::addColumn("suggestionsUrlTemplate"); QTest::addColumn("providesSuggestions"); QTest::newRow("false") << QString() << false; - QTest::newRow("true") << QString("foo") << true; + QTest::newRow("true") << QStringLiteral("foo") << true; } // public bool providesSuggestions() const @@ -523,9 +531,9 @@ void tst_OpenSearchEngine::requestSuggestions_data() QTest::addColumn("method"); QTest::addColumn("lastOperation"); QTest::newRow("null") << QString() << QString() << QNetworkAccessManager::GetOperation; - QTest::newRow("foo") << QString("foo") << QString("get") << QNetworkAccessManager::GetOperation; - QTest::newRow("bar") << QString("bar") << QString("post") << QNetworkAccessManager::PostOperation; - QTest::newRow("baz") << QString("baz") << QString("put") << QNetworkAccessManager::GetOperation; + QTest::newRow("foo") << QStringLiteral("foo") << QStringLiteral("get") << QNetworkAccessManager::GetOperation; + QTest::newRow("bar") << QStringLiteral("bar") << QStringLiteral("post") << QNetworkAccessManager::PostOperation; + QTest::newRow("baz") << QStringLiteral("baz") << QStringLiteral("put") << QNetworkAccessManager::GetOperation; } Q_DECLARE_METATYPE(QNetworkAccessManager::Operation) @@ -619,13 +627,13 @@ void tst_OpenSearchEngine::searchUrl_data() QTest::addColumn("parameters"); QTest::addColumn("searchUrl"); QTest::newRow("null") << QString() << QString() << Parameters() << QUrl(); - QTest::newRow("foo") << QString("foo") << QString("http://foobar.baz/?q={searchTerms}") - << Parameters() << QUrl(QString("http://foobar.baz/?q=foo")); - QTest::newRow("empty") << QString() << QString("http://foobar.baz/?q={searchTerms}") - << Parameters() << QUrl(QString("http://foobar.baz/?q=")); - QTest::newRow("parameters") << QString("baz") << QString("http://foobar.baz/?q={searchTerms}") + QTest::newRow("foo") << QStringLiteral("foo") << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << Parameters() << QUrl(QStringLiteral("http://foobar.baz/?q=foo")); + QTest::newRow("empty") << QString() << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << Parameters() << QUrl(QStringLiteral("http://foobar.baz/?q=")); + QTest::newRow("parameters") << QStringLiteral("baz") << QStringLiteral("http://foobar.baz/?q={searchTerms}") << (Parameters() << Parameter("abc", "{searchTerms}") << Parameter("x", "yz")) - << QUrl(QString("http://foobar.baz/?q=baz&abc=baz&x=yz")); + << QUrl(QStringLiteral("http://foobar.baz/?q=baz&abc=baz&x=yz")); } // public QUrl searchUrl(QString const &searchTerm) const @@ -647,7 +655,7 @@ void tst_OpenSearchEngine::searchUrlTemplate_data() { QTest::addColumn("searchUrlTemplate"); QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString searchUrlTemplate() const @@ -702,13 +710,13 @@ void tst_OpenSearchEngine::suggestionsUrl_data() QTest::addColumn("parameters"); QTest::addColumn("suggestionsUrl"); QTest::newRow("null") << QString() << QString() << Parameters() << QUrl(); - QTest::newRow("foo") << QString("foo") << QString("http://foobar.baz/?q={searchTerms}") - << Parameters() << QUrl(QString("http://foobar.baz/?q=foo")); - QTest::newRow("empty") << QString() << QString("http://foobar.baz/?q={searchTerms}") - << Parameters() << QUrl(QString("http://foobar.baz/?q=")); - QTest::newRow("parameters") << QString("baz") << QString("http://foobar.baz/?q={searchTerms}") + QTest::newRow("foo") << QStringLiteral("foo") << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << Parameters() << QUrl(QStringLiteral("http://foobar.baz/?q=foo")); + QTest::newRow("empty") << QString() << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << Parameters() << QUrl(QStringLiteral("http://foobar.baz/?q=")); + QTest::newRow("parameters") << QStringLiteral("baz") << QStringLiteral("http://foobar.baz/?q={searchTerms}") << (Parameters() << Parameter("a", "bc")) - << QUrl(QString("http://foobar.baz/?q=baz&a=bc")); + << QUrl(QStringLiteral("http://foobar.baz/?q=baz&a=bc")); } // public QUrl suggestionsUrl(QString const &searchTerm) const @@ -730,7 +738,7 @@ void tst_OpenSearchEngine::suggestionsUrlTemplate_data() { QTest::addColumn("suggestionsUrlTemplate"); QTest::newRow("null") << QString(); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString suggestionsUrlTemplate() const @@ -752,33 +760,33 @@ void tst_OpenSearchEngine::suggestionsUrlTemplate() void tst_OpenSearchEngine::parseTemplate_data() { - QString lang = QLocale().name().replace(QLatin1Char('_'), QLatin1Char('-')); + QString lang = QLocale().name().replace(QChar('_'), QChar('-')); QTest::addColumn("searchTerm"); QTest::addColumn("searchTemplate"); QTest::addColumn("parseTemplate"); QTest::addColumn("valid"); QTest::newRow("null") << QString() << QString() << QString() << false; - QTest::newRow("foo") << QString("foo") << QString("http://foobar.baz/?q={searchTerms}") - << QString("http://foobar.baz/?q=foo") << true; - QTest::newRow("allParameters") << QString("bar") - << QString("http://foobar.baz/?st={searchTerms}&c={count}" + QTest::newRow("foo") << QStringLiteral("foo") << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << QStringLiteral("http://foobar.baz/?q=foo") << true; + QTest::newRow("allParameters") << QStringLiteral("bar") + << QStringLiteral("http://foobar.baz/?st={searchTerms}&c={count}" "&si={startIndex}&sp={startPage}&l={language}" "&ie={inputEncoding}&oe={outputEncoding}") - << QString("http://foobar.baz/?st=bar&c=20&si=0&" + << QStringLiteral("http://foobar.baz/?st=bar&c=20&si=0&" "sp=0&l=%1&ie=UTF-8&oe=UTF-8").arg(lang) << true; - QTest::newRow("tricky") << QString("{count}") << QString("http://foobar.baz/q={searchTerms}&count={count}") - << QString("http://foobar.baz/q=%7Bcount%7D&count=20") << true; - QTest::newRow("multiple") << QString("abc") << QString("http://foobar.baz/?q={searchTerms}&x={searchTerms}") - << QString("http://foobar.baz/?q=abc&x=abc") << true; - QTest::newRow("referrer") << QString("foo") - << QString("http://foobar.baz/?q={searchTerms}&a={source}&b={ref:source}&c={referrer:source?}") - << QString("http://foobar.baz/?q=foo&a=tst_opensearchengine" + QTest::newRow("tricky") << QStringLiteral("{count}") << QStringLiteral("http://foobar.baz/q={searchTerms}&count={count}") + << QStringLiteral("http://foobar.baz/q=%7Bcount%7D&count=20") << true; + QTest::newRow("multiple") << QStringLiteral("abc") << QStringLiteral("http://foobar.baz/?q={searchTerms}&x={searchTerms}") + << QStringLiteral("http://foobar.baz/?q=abc&x=abc") << true; + QTest::newRow("referrer") << QStringLiteral("foo") + << QStringLiteral("http://foobar.baz/?q={searchTerms}&a={source}&b={ref:source}&c={referrer:source?}") + << QStringLiteral("http://foobar.baz/?q=foo&a=tst_opensearchengine" "&b=tst_opensearchengine&c=tst_opensearchengine") << true; - QTest::newRow("inputEncoding") << QString("c++") << QString("http://foobar.baz/?q={searchTerms}") - << QString("http://foobar.baz/?q=c%2B%2B") << true; + QTest::newRow("inputEncoding") << QStringLiteral("c++") << QStringLiteral("http://foobar.baz/?q={searchTerms}") + << QStringLiteral("http://foobar.baz/?q=c%2B%2B") << true; } // protected QString parseTemplate(QString const &searchTerm, QString const &searchTemplate) const @@ -800,8 +808,8 @@ void tst_OpenSearchEngine::languageCodes_data() QTest::addColumn("languageCode"); QTest::addColumn("url"); - QTest::newRow("es") << QString("es") << QString("http://foobar.baz/?l=es-ES"); - QTest::newRow("pt_BR") << QString("pt_BR") << QString("http://foobar.baz/?l=pt-BR"); + QTest::newRow("es") << QStringLiteral("es") << QStringLiteral("http://foobar.baz/?l=es-ES"); + QTest::newRow("pt_BR") << QStringLiteral("pt_BR") << QStringLiteral("http://foobar.baz/?l=pt-BR"); } void tst_OpenSearchEngine::languageCodes() @@ -812,66 +820,66 @@ void tst_OpenSearchEngine::languageCodes() QLocale::setDefault(QLocale(languageCode)); SubOpenSearchEngine engine; - QCOMPARE(engine.call_parseTemplate(QString("foo"), QString("http://foobar.baz/?l={language}")), url); + QCOMPARE(engine.call_parseTemplate(QStringLiteral("foo"), QStringLiteral("http://foobar.baz/?l={language}")), url); } void tst_OpenSearchEngine::requestMethods() { SubOpenSearchEngine engine; - QCOMPARE(engine.searchMethod(), QString("get")); - QCOMPARE(engine.suggestionsMethod(), QString("get")); + QCOMPARE(engine.searchMethod(), QStringLiteral("get")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("get")); engine.setSearchMethod("post"); - QCOMPARE(engine.searchMethod(), QString("post")); - QCOMPARE(engine.suggestionsMethod(), QString("get")); + QCOMPARE(engine.searchMethod(), QStringLiteral("post")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("get")); engine.setSearchMethod("get"); - QCOMPARE(engine.searchMethod(), QString("get")); - QCOMPARE(engine.suggestionsMethod(), QString("get")); + QCOMPARE(engine.searchMethod(), QStringLiteral("get")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("get")); engine.setSuggestionsMethod("PoSt"); - QCOMPARE(engine.searchMethod(), QString("get")); - QCOMPARE(engine.suggestionsMethod(), QString("post")); + QCOMPARE(engine.searchMethod(), QStringLiteral("get")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("post")); engine.setSearchMethod("foo"); - QCOMPARE(engine.searchMethod(), QString("get")); - QCOMPARE(engine.suggestionsMethod(), QString("post")); + QCOMPARE(engine.searchMethod(), QStringLiteral("get")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("post")); engine.setSuggestionsMethod("bar"); - QCOMPARE(engine.searchMethod(), QString("get")); - QCOMPARE(engine.suggestionsMethod(), QString("post")); + QCOMPARE(engine.searchMethod(), QStringLiteral("get")); + QCOMPARE(engine.suggestionsMethod(), QStringLiteral("post")); } void tst_OpenSearchEngine::delegate() { SubOpenSearchEngine engine; - engine.setName(QString("foo")); - engine.setDescription(QString("bar")); - engine.setSearchUrlTemplate(QString("http://foobar.baz/?q={searchTerms}")); + engine.setName(QStringLiteral("foo")); + engine.setDescription(QStringLiteral("bar")); + engine.setSearchUrlTemplate(QStringLiteral("http://foobar.baz/?q={searchTerms}")); QCOMPARE(engine.delegate(), (Delegate*)0); engine.setDelegate(0); QCOMPARE(engine.delegate(), (Delegate*)0); - engine.requestSearchResults(QString("baz")); + engine.requestSearchResults(QStringLiteral("baz")); Delegate delegate; engine.setDelegate(&delegate); QCOMPARE(engine.delegate(), &delegate); - engine.requestSearchResults(QString("baz")); + engine.requestSearchResults(QStringLiteral("baz")); QCOMPARE(delegate.callsCount, 1); QCOMPARE(delegate.lastOperation, QNetworkAccessManager::GetOperation); QCOMPARE(delegate.lastData, QByteArray()); - QNetworkRequest request(QUrl(engine.call_parseTemplate(QString("baz"), engine.searchUrlTemplate()))); + QNetworkRequest request(QUrl(engine.call_parseTemplate(QStringLiteral("baz"), engine.searchUrlTemplate()))); QCOMPARE(delegate.lastRequest, request); QUrlQuery urlQuery(delegate.lastRequest.url().query()); QVERIFY(urlQuery.hasQueryItem("q")); - QCOMPARE(urlQuery.queryItemValue("q"), QString("baz")); + QCOMPARE(urlQuery.queryItemValue("q"), QStringLiteral("baz")); engine.setSearchParameters(Parameters() << Parameter("a", "b") << Parameter("b", "c")); - engine.requestSearchResults(QString("baz")); + engine.requestSearchResults(QStringLiteral("baz")); QCOMPARE(delegate.callsCount, 2); QCOMPARE(delegate.lastOperation, QNetworkAccessManager::GetOperation); @@ -879,26 +887,26 @@ void tst_OpenSearchEngine::delegate() QUrlQuery q2(delegate.lastRequest.url().query()); QVERIFY(q2.hasQueryItem("a")); - QCOMPARE(q2.queryItemValue("a"), QString("b")); + QCOMPARE(q2.queryItemValue("a"), QStringLiteral("b")); QVERIFY(q2.hasQueryItem("b")); - QCOMPARE(q2.queryItemValue("b"), QString("c")); + QCOMPARE(q2.queryItemValue("b"), QStringLiteral("c")); QVERIFY(q2.hasQueryItem("q")); - QCOMPARE(q2.queryItemValue("q"), QString("baz")); + QCOMPARE(q2.queryItemValue("q"), QStringLiteral("baz")); - QUrl url(engine.call_parseTemplate(QString("baz"), engine.searchUrlTemplate())); + QUrl url(engine.call_parseTemplate(QStringLiteral("baz"), engine.searchUrlTemplate())); QCOMPARE(delegate.lastRequest.url().toString(QUrl::RemoveQuery), url.toString(QUrl::RemoveQuery)); - engine.setSearchMethod(QString("post")); - engine.requestSearchResults(QString("baz")); + engine.setSearchMethod(QStringLiteral("post")); + engine.requestSearchResults(QStringLiteral("baz")); QCOMPARE(delegate.callsCount, 3); QCOMPARE(delegate.lastOperation, QNetworkAccessManager::PostOperation); - request = QNetworkRequest(QUrl(engine.call_parseTemplate(QString("baz"), engine.searchUrlTemplate()))); + request = QNetworkRequest(QUrl(engine.call_parseTemplate(QStringLiteral("baz"), engine.searchUrlTemplate()))); QCOMPARE(delegate.lastRequest, request); QUrlQuery q3(delegate.lastRequest.url().query()); QVERIFY(q3.hasQueryItem("q")); - QCOMPARE(q3.queryItemValue("q"), QString("baz")); + QCOMPARE(q3.queryItemValue("q"), QStringLiteral("baz")); QVERIFY(!delegate.lastData.isEmpty()); QStringList query = QString(delegate.lastData).split('&'); diff --git a/autotests/opensearchmanager/CMakeLists.txt b/autotests/opensearchmanager/CMakeLists.txt new file mode 100644 index 00000000..5d48e071 --- /dev/null +++ b/autotests/opensearchmanager/CMakeLists.txt @@ -0,0 +1,10 @@ +project(test-opensearchmanager) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) + + +add_executable(test-opensearchmanager tst_opensearchmanager.cpp) +target_link_libraries(test-opensearchmanager endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/opensearchmanager/opensearchmanager.pro b/autotests/opensearchmanager/opensearchmanager.pro deleted file mode 100644 index 8ba76ebd..00000000 --- a/autotests/opensearchmanager/opensearchmanager.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -SOURCES += \ - tst_opensearchmanager.cpp \ No newline at end of file diff --git a/autotests/opensearchmanager/tst_opensearchmanager.cpp b/autotests/opensearchmanager/tst_opensearchmanager.cpp index 6f060533..03264af3 100644 --- a/autotests/opensearchmanager/tst_opensearchmanager.cpp +++ b/autotests/opensearchmanager/tst_opensearchmanager.cpp @@ -28,13 +28,13 @@ class tst_OpenSearchManager : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void addRemoveEngine_data(); void addRemoveEngine(); void setCurrentEngine_data(); @@ -68,7 +68,7 @@ void tst_OpenSearchManager::initTestCase() QCoreApplication::setApplicationName("opensearchtest"); SubOpenSearchManager manager; - foreach (const QString &name, manager.allEnginesNames()) + Q_FOREACH (const QString &name, manager.allEnginesNames()) manager.removeEngine(name); QCOMPARE(manager.enginesCount(), 1); } @@ -92,7 +92,7 @@ void tst_OpenSearchManager::init() void tst_OpenSearchManager::cleanup() { SubOpenSearchManager manager; - foreach (const QString &name, manager.allEnginesNames()) + Q_FOREACH (const QString &name, manager.allEnginesNames()) manager.removeEngine(name); QCOMPARE(manager.enginesCount(), 1); } @@ -214,7 +214,7 @@ void tst_OpenSearchManager::restoreDefaults() manager.restoreDefaults(); QCOMPARE(manager.enginesCount(), manager.defaultCount()); - foreach (const QString &name, manager.allEnginesNames()) + Q_FOREACH (const QString &name, manager.allEnginesNames()) manager.removeEngine(name); // Never let the manager have no engines. diff --git a/autotests/opensearchreader/CMakeLists.txt b/autotests/opensearchreader/CMakeLists.txt new file mode 100644 index 00000000..e8360569 --- /dev/null +++ b/autotests/opensearchreader/CMakeLists.txt @@ -0,0 +1,7 @@ +project(test-opensearchreader) +find_package(Qt5Test REQUIRED) + +QT5_ADD_RESOURCES(RSCS opensearchreader.qrc) + +add_executable(test-opensearchreader tst_opensearchreader.cpp ${RSCS}) +target_link_libraries(test-opensearchreader endorphin-base Qt5::Test) \ No newline at end of file diff --git a/autotests/opensearchreader/opensearchreader.pro b/autotests/opensearchreader/opensearchreader.pro deleted file mode 100644 index 392567a3..00000000 --- a/autotests/opensearchreader/opensearchreader.pro +++ /dev/null @@ -1,21 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -SOURCES = \ - opensearchengine.cpp \ - opensearchreader.cpp \ - tst_opensearchreader.cpp - -HEADERS = \ - opensearchengine.h \ - opensearchreader.h - -FORMS = - -RESOURCES = \ - opensearchreader.qrc - diff --git a/autotests/opensearchreader/tst_opensearchreader.cpp b/autotests/opensearchreader/tst_opensearchreader.cpp index 21692a48..dad38752 100644 --- a/autotests/opensearchreader/tst_opensearchreader.cpp +++ b/autotests/opensearchreader/tst_opensearchreader.cpp @@ -26,13 +26,13 @@ class tst_OpenSearchReader : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void read_data(); void read(); }; @@ -74,38 +74,38 @@ void tst_OpenSearchReader::read_data() QTest::addColumn("searchMethod"); QTest::addColumn("suggestionsMethod"); - QTest::newRow("null") << QString(":/doesNotExist") << false << QString() << QString() << QString() << QString() - << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("null") << QStringLiteral(":/doesNotExist") << false << QString() << QString() << QString() << QString() + << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); - QTest::newRow("testfile1") << QString(":/testfile1.xml") << true << QString("Wikipedia (en)") - << QString("Full text search in the English Wikipedia") << QString("http://en.wikipedia.org/bar") - << QString("http://en.wikipedia.org/foo") << QString("http://en.wikipedia.org/favicon.ico") - << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("post") << QString("get"); + QTest::newRow("testfile1") << QStringLiteral(":/testfile1.xml") << true << QStringLiteral("Wikipedia (en)") + << QStringLiteral("Full text search in the English Wikipedia") << QStringLiteral("http://en.wikipedia.org/bar") + << QStringLiteral("http://en.wikipedia.org/foo") << QStringLiteral("http://en.wikipedia.org/favicon.ico") + << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("post") << QStringLiteral("get"); - QTest::newRow("testfile2") << QString(":/testfile2.xml") << false << QString("Wikipedia (en)") - << QString() << QString() << QString("http://en.wikipedia.org/foo") << QString("http://en.wikipedia.org/favicon.ico") - << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("testfile2") << QStringLiteral(":/testfile2.xml") << false << QStringLiteral("Wikipedia (en)") + << QString() << QString() << QStringLiteral("http://en.wikipedia.org/foo") << QStringLiteral("http://en.wikipedia.org/favicon.ico") + << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); - QTest::newRow("testfile3") << QString(":/testfile3.xml") << true << QString("GitHub") << QString("Search GitHub") - << QString("http://github.com/search") << QString("http://github.com/suggestions") << QString() - << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter(QString("q"), QString("{searchTerms}")) - << OpenSearchEngine::Parameter(QString("b"), QString("foo"))) - << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter(QString("bar"), QString("baz"))) - << QString("get") << QString("post"); + QTest::newRow("testfile3") << QStringLiteral(":/testfile3.xml") << true << QStringLiteral("GitHub") << QStringLiteral("Search GitHub") + << QStringLiteral("http://github.com/search") << QStringLiteral("http://github.com/suggestions") << QString() + << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter(QStringLiteral("q"), QStringLiteral("{searchTerms}")) + << OpenSearchEngine::Parameter(QStringLiteral("b"), QStringLiteral("foo"))) + << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter(QStringLiteral("bar"), QStringLiteral("baz"))) + << QStringLiteral("get") << QStringLiteral("post"); - QTest::newRow("testfile4") << QString(":/testfile4.xml") << true << QString("Google") << QString("Google Web Search") - << QString("http://www.google.com/search?bar") << QString("http://suggestqueries.google.com/complete/foo") - << QString("http://www.google.com/favicon.ico") << OpenSearchEngine::Parameters() - << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("testfile4") << QStringLiteral(":/testfile4.xml") << true << QStringLiteral("Google") << QStringLiteral("Google Web Search") + << QStringLiteral("http://www.google.com/search?bar") << QStringLiteral("http://suggestqueries.google.com/complete/foo") + << QStringLiteral("http://www.google.com/favicon.ico") << OpenSearchEngine::Parameters() + << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); - QTest::newRow("testfile5") << QString(":/testfile5.xml") << false << QString() << QString() << QString() << QString() - << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("testfile5") << QStringLiteral(":/testfile5.xml") << false << QString() << QString() << QString() << QString() + << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); - QTest::newRow("testfile6") << QString(":/testfile6.xml") << false << QString() << QString() << QString() << QString() - << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("testfile6") << QStringLiteral(":/testfile6.xml") << false << QString() << QString() << QString() << QString() + << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); - QTest::newRow("testfile7") << QString(":/testfile7.xml") << false << QString() << QString() << QString() << QString() - << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QString("get") << QString("get"); + QTest::newRow("testfile7") << QStringLiteral(":/testfile7.xml") << false << QString() << QString() << QString() << QString() + << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() << QStringLiteral("get") << QStringLiteral("get"); } void tst_OpenSearchReader::read() diff --git a/autotests/opensearchwriter/CMakeLists.txt b/autotests/opensearchwriter/CMakeLists.txt new file mode 100644 index 00000000..0adb0a99 --- /dev/null +++ b/autotests/opensearchwriter/CMakeLists.txt @@ -0,0 +1,7 @@ +project(test-opensearchwriter) +find_package(Qt5Test REQUIRED) + +QT5_ADD_RESOURCES(RSCS opensearchwriter.qrc) + +add_executable(test-opensearchwriter tst_opensearchwriter.cpp ${RSCS}) +target_link_libraries(test-opensearchwriter endorphin-base Qt5::Test) diff --git a/autotests/opensearchwriter/opensearchwriter.pro b/autotests/opensearchwriter/opensearchwriter.pro deleted file mode 100644 index 13ffaff7..00000000 --- a/autotests/opensearchwriter/opensearchwriter.pro +++ /dev/null @@ -1,21 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -SOURCES = \ - opensearchengine.cpp \ - opensearchwriter.cpp \ - tst_opensearchwriter.cpp - -HEADERS = \ - opensearchengine.h \ - opensearchwriter.h - -FORMS = - -RESOURCES = \ - opensearchwriter.qrc - diff --git a/autotests/opensearchwriter/tst_opensearchwriter.cpp b/autotests/opensearchwriter/tst_opensearchwriter.cpp index 4aba40fb..da305381 100644 --- a/autotests/opensearchwriter/tst_opensearchwriter.cpp +++ b/autotests/opensearchwriter/tst_opensearchwriter.cpp @@ -26,13 +26,13 @@ class tst_OpenSearchWriter : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void write_data(); void write(); }; @@ -73,20 +73,20 @@ void tst_OpenSearchWriter::write_data() QTest::addColumn("suggestionsMethod"); QTest::addColumn("fileName"); - QTest::newRow("testfile1") << QString("Foo Bar") << QString("Bar Foo") << QString("http://foobar.barfoo/search") << QString() + QTest::newRow("testfile1") << QStringLiteral("Foo Bar") << QStringLiteral("Bar Foo") << QStringLiteral("http://foobar.barfoo/search") << QString() << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() - << QString() << QString("get") << QString(":/testfile1.xml"); + << QString() << QStringLiteral("get") << QStringLiteral(":/testfile1.xml"); - QTest::newRow("testfile2") << QString("Endorphin!") << QString("a cross platform web browser built using Qt and WebKit") - << QString("http://foobar.barfoo/search") << QString("http://foobar.barfoo/suggest") << QString() + QTest::newRow("testfile2") << QStringLiteral("Endorphin!") << QStringLiteral("a cross platform web browser built using Qt and WebKit") + << QStringLiteral("http://foobar.barfoo/search") << QStringLiteral("http://foobar.barfoo/suggest") << QString() << OpenSearchEngine::Parameters() << OpenSearchEngine::Parameters() - << QString("get") << QString("post") << QString(":/testfile2.xml"); + << QStringLiteral("get") << QStringLiteral("post") << QStringLiteral(":/testfile2.xml"); - QTest::newRow("testile3") << QString("Foo Bar") << QString("Bar Foo") << QString("http://foobar.barfoo/search") - << QString("http://foobar.barfoo/suggest") << QString() + QTest::newRow("testile3") << QStringLiteral("Foo Bar") << QStringLiteral("Bar Foo") << QStringLiteral("http://foobar.barfoo/search") + << QStringLiteral("http://foobar.barfoo/suggest") << QString() << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter("q", "{searchTerms}") << OpenSearchEngine::Parameter("a", "foo")) << (OpenSearchEngine::Parameters() << OpenSearchEngine::Parameter("q", "{searchTerms}")) - << QString("post") << QString("foo") << QString(":/testfile3.xml"); + << QStringLiteral("post") << QStringLiteral("foo") << QStringLiteral(":/testfile3.xml"); } void tst_OpenSearchWriter::write() diff --git a/autotests/qtest_endorphin.h b/autotests/qtest_endorphin.h index fa6bd9db..2312ee40 100644 --- a/autotests/qtest_endorphin.h +++ b/autotests/qtest_endorphin.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/autotests/qtry.h b/autotests/qtry.h index db402728..759fc5a2 100644 --- a/autotests/qtry.h +++ b/autotests/qtry.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008 - 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * diff --git a/autotests/searchlineedit/CMakeLists.txt b/autotests/searchlineedit/CMakeLists.txt new file mode 100644 index 00000000..9fb04fb5 --- /dev/null +++ b/autotests/searchlineedit/CMakeLists.txt @@ -0,0 +1,34 @@ +project(test-searchlineedit) + +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils +) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils + ${RUNTIME_OUTPUT_DIRECTORY} +) +add_definitions(-DNO_BROWSERAPPLICATION) +add_definitions(-DFOR_AUTOTEST) +set(SRCS + tst_searchlineedit.cpp + ../../src/clearbutton.cpp + ../../src/searchbutton.cpp + ../../src/searchlineedit.cpp + ../../src/utils/lineedit.cpp +) + +add_executable(test-searchlineedit ${SRCS} ${UIS} ${MOCS}) +target_link_libraries(test-searchlineedit Qt5::Core Qt5::Test Qt5::Widgets Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/autotests/searchlineedit/searchlineedit.pro b/autotests/searchlineedit/searchlineedit.pro deleted file mode 100644 index 10414922..00000000 --- a/autotests/searchlineedit/searchlineedit.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_searchlineedit.cpp diff --git a/autotests/searchlineedit/tst_searchlineedit.cpp b/autotests/searchlineedit/tst_searchlineedit.cpp index 245249e1..295df24c 100644 --- a/autotests/searchlineedit/tst_searchlineedit.cpp +++ b/autotests/searchlineedit/tst_searchlineedit.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,13 +24,13 @@ class tst_SearchLineEdit : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void searchlineedit_data(); void searchlineedit(); }; @@ -38,7 +38,8 @@ private slots: // Subclass that exposes the protected functions. class SubSearchLineEdit : public SearchLineEdit { -public:}; +public: +}; // This will be called before the first test function is executed. // It is only called once. diff --git a/autotests/tabbar/CMakeLists.txt b/autotests/tabbar/CMakeLists.txt new file mode 100644 index 00000000..67aa5db7 --- /dev/null +++ b/autotests/tabbar/CMakeLists.txt @@ -0,0 +1,6 @@ +project(test-tabbar) +find_package(Qt5Test REQUIRED) + +add_executable(test-tabbar tst_tabbar.cpp) +target_link_libraries(test-tabbar endorphin-base Qt5::Test) + diff --git a/autotests/tabbar/tabbar.pro b/autotests/tabbar/tabbar.pro deleted file mode 100644 index 880ee086..00000000 --- a/autotests/tabbar/tabbar.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../autotests.pri) - -# Input -SOURCES += tst_tabbar.cpp -HEADERS += diff --git a/autotests/tabbar/tst_tabbar.cpp b/autotests/tabbar/tst_tabbar.cpp index aa173062..3e14858c 100644 --- a/autotests/tabbar/tst_tabbar.cpp +++ b/autotests/tabbar/tst_tabbar.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,13 +26,13 @@ class tst_TabBar : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void tabbar_data(); void tabbar(); @@ -48,40 +48,64 @@ class SubTabBar : public TabBar { public: void call_cloneTab(int index) - { return SubTabBar::cloneTab(index); } + { + return SubTabBar::cloneTab(index); + } void call_closeOtherTabs(int index) - { return SubTabBar::closeOtherTabs(index); } + { + return SubTabBar::closeOtherTabs(index); + } void call_closeTab(int index) - { return SubTabBar::closeTab(index); } + { + return SubTabBar::closeTab(index); + } void call_dragEnterEvent(QDragEnterEvent *event) - { return SubTabBar::dragEnterEvent(event); } + { + return SubTabBar::dragEnterEvent(event); + } void call_dropEvent(QDropEvent *event) - { return SubTabBar::dropEvent(event); } + { + return SubTabBar::dropEvent(event); + } void call_mouseMoveEvent(QMouseEvent *event) - { return SubTabBar::mouseMoveEvent(event); } + { + return SubTabBar::mouseMoveEvent(event); + } void call_mousePressEvent(QMouseEvent *event) - { return SubTabBar::mousePressEvent(event); } + { + return SubTabBar::mousePressEvent(event); + } void call_newTab() - { return SubTabBar::newTab(); } + { + return SubTabBar::newTab(); + } void call_reloadAllTabs() - { return SubTabBar::reloadAllTabs(); } + { + return SubTabBar::reloadAllTabs(); + } void call_reloadTab(int index) - { return SubTabBar::reloadTab(index); } + { + return SubTabBar::reloadTab(index); + } void call_tabLayoutChange() - { return SubTabBar::tabLayoutChange(); } + { + return SubTabBar::tabLayoutChange(); + } QSize call_tabSizeHint(int index) const - { return SubTabBar::tabSizeHint(index); } + { + return SubTabBar::tabSizeHint(index); + } }; // This will be called before the first test function is executed. @@ -136,7 +160,7 @@ void tst_TabBar::showTabBarWhenOneTab() bar.setShowTabBarWhenOneTab(showTabBarWhenOneTab); QAction *action = bar.viewTabBarAction(); QVERIFY(action); - QCOMPARE(action->text(), (showTabBarWhenOneTab ? QString("Hide Tab Bar") : QString("Show Tab Bar"))); + QCOMPARE(action->text(), (showTabBarWhenOneTab ? QStringLiteral("Hide Tab Bar") : QStringLiteral("Show Tab Bar"))); QCOMPARE(bar.showTabBarWhenOneTab(), showTabBarWhenOneTab); bar.addTab("one"); @@ -146,14 +170,14 @@ void tst_TabBar::showTabBarWhenOneTab() bar.addTab("two"); QCOMPARE(bar.count(), 2); QCOMPARE(bar.isVisible(), true); - QCOMPARE(action->text(), QString("Hide Tab Bar")); + QCOMPARE(action->text(), QStringLiteral("Hide Tab Bar")); QCOMPARE(action->isEnabled(), false); bar.removeTab(0); QCOMPARE(bar.count(), 1); QCOMPARE(bar.isVisible(), showTabBarWhenOneTab); QCOMPARE(action->isEnabled(), true); - QCOMPARE(action->text(), (showTabBarWhenOneTab ? QString("Hide Tab Bar") : QString("Show Tab Bar"))); + QCOMPARE(action->text(), (showTabBarWhenOneTab ? QStringLiteral("Hide Tab Bar") : QStringLiteral("Show Tab Bar"))); } void tst_TabBar::tabSizeHint_data() diff --git a/autotests/tabwidget/CMakeLists.txt b/autotests/tabwidget/CMakeLists.txt new file mode 100644 index 00000000..ff8ec540 --- /dev/null +++ b/autotests/tabwidget/CMakeLists.txt @@ -0,0 +1,9 @@ +project(test-tabwidget) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) + +add_executable(test-tabwidget tst_tabwidget.cpp) +target_link_libraries(test-tabwidget endorphin-base Qt5::Test) diff --git a/autotests/tabwidget/tabwidget.pro b/autotests/tabwidget/tabwidget.pro deleted file mode 100644 index b8d1e608..00000000 --- a/autotests/tabwidget/tabwidget.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../autotests.pri) - -# Input -SOURCES += tst_tabwidget.cpp -HEADERS += diff --git a/autotests/tabwidget/tst_tabwidget.cpp b/autotests/tabwidget/tst_tabwidget.cpp index a59ee908..8e1d526f 100644 --- a/autotests/tabwidget/tst_tabwidget.cpp +++ b/autotests/tabwidget/tst_tabwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -30,13 +30,13 @@ class tst_TabWidget : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void tabwidget_data(); void tabwidget(); void addWebAction_data(); @@ -78,19 +78,29 @@ class SubTabWidget : public TabWidget { public: void call_linkHovered(QString const &link) - { return SubTabWidget::linkHovered(link); } + { + return SubTabWidget::linkHovered(link); + } void call_loadProgress(int progress) - { return SubTabWidget::loadProgress(progress); } + { + return SubTabWidget::loadProgress(progress); + } void call_setCurrentTitle(QString const &url) - { return SubTabWidget::setCurrentTitle(url); } + { + return SubTabWidget::setCurrentTitle(url); + } void call_showStatusBarMessage(QString const &message) - { return SubTabWidget::showStatusBarMessage(message); } + { + return SubTabWidget::showStatusBarMessage(message); + } void call_tabsChanged() - { return SubTabWidget::tabsChanged(); } + { + return SubTabWidget::tabsChanged(); + } }; // This will be called before the first test function is executed. @@ -122,7 +132,7 @@ void tst_TabWidget::tabwidget_data() void tst_TabWidget::tabwidget() { SubTabWidget widget; - widget.addWebAction((QAction*)0, QWebPage::Back); + widget.addWebAction((QAction*)0, QWebEnginePage::Back); widget.closeTab(); QVERIFY(widget.closeTabAction()); widget.currentWebView(); @@ -138,17 +148,17 @@ void tst_TabWidget::tabwidget() QVERIFY(widget.currentLocationBar()); } -Q_DECLARE_METATYPE(QWebPage::WebAction) +Q_DECLARE_METATYPE(QWebEnginePage::WebAction) void tst_TabWidget::addWebAction_data() { - QTest::addColumn("webAction"); - QTest::newRow("back") << QWebPage::Back; + QTest::addColumn("webAction"); + QTest::newRow("back") << QWebEnginePage::Back; } -// public void addWebAction(QAction *action, QWebPage::WebAction webAction) +// public void addWebAction(QAction *action, QWebEnginePage::WebAction webAction) void tst_TabWidget::addWebAction() { - QFETCH(QWebPage::WebAction, webAction); + QFETCH(QWebEnginePage::WebAction, webAction); SubTabWidget widget; @@ -497,7 +507,7 @@ void tst_TabWidget::recentlyClosedTabsAction() void tst_TabWidget::linkHovered_data() { QTest::addColumn("link"); - QTest::newRow("null") << QString("foo"); + QTest::newRow("null") << QStringLiteral("foo"); } // protected void linkHovered(QString const &link) @@ -563,7 +573,7 @@ void tst_TabWidget::loadProgress(int) void tst_TabWidget::setCurrentTitle_data() { QTest::addColumn("url"); - QTest::newRow("null") << QString("foo"); + QTest::newRow("null") << QStringLiteral("foo"); } // protected void setCurrentTitle(QString const &url) @@ -596,7 +606,7 @@ void tst_TabWidget::setCurrentTitle(const QString &) void tst_TabWidget::showStatusBarMessage_data() { QTest::addColumn("message"); - QTest::newRow("null") << QString("foo"); + QTest::newRow("null") << QStringLiteral("foo"); } // protected void showStatusBarMessage(QString const &message) diff --git a/autotests/utils/CMakeLists.txt b/autotests/utils/CMakeLists.txt new file mode 100644 index 00000000..a17eeb4e --- /dev/null +++ b/autotests/utils/CMakeLists.txt @@ -0,0 +1,5 @@ +project(utils) +add_subdirectory(editlistview) +add_subdirectory(edittreeview) +add_subdirectory(languagemanager) +add_subdirectory(lineedit) \ No newline at end of file diff --git a/autotests/utils/editlistview/CMakeLists.txt b/autotests/utils/editlistview/CMakeLists.txt new file mode 100644 index 00000000..a432a7af --- /dev/null +++ b/autotests/utils/editlistview/CMakeLists.txt @@ -0,0 +1,30 @@ +project(test-editlistview) + +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils +) +INCLUDE_DIRECTORIES( + ../../ + ../../../src/ + ../../../src/utils +) +add_definitions(-DNO_BROWSERAPPLICATION) +add_definitions(-DFOR_AUTOTEST) +set(SRCS + tst_editlistview.cpp + ../../../src/utils/editlistview.cpp +) + +add_executable(test-editlistview ${SRCS} ${UIS} ${MOCS}) +target_link_libraries(test-editlistview Qt5::Core Qt5::Test Qt5::Gui Qt5::Widgets Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/autotests/utils/editlistview/editlistview.pro b/autotests/utils/editlistview/editlistview.pro deleted file mode 100644 index f089b9c8..00000000 --- a/autotests/utils/editlistview/editlistview.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES = tst_editlistview.cpp editlistview.cpp -HEADERS = editlistview.h -FORMS = -RESOURCES = diff --git a/autotests/utils/editlistview/tst_editlistview.cpp b/autotests/utils/editlistview/tst_editlistview.cpp index e3a939da..a2b988c4 100644 --- a/autotests/utils/editlistview/tst_editlistview.cpp +++ b/autotests/utils/editlistview/tst_editlistview.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,13 +26,13 @@ class tst_EditListView : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void editlistview_data(); void editlistview(); diff --git a/autotests/utils/edittreeview/CMakeLists.txt b/autotests/utils/edittreeview/CMakeLists.txt new file mode 100644 index 00000000..ba6d7fd6 --- /dev/null +++ b/autotests/utils/edittreeview/CMakeLists.txt @@ -0,0 +1,30 @@ +project(test-edittreeview) + +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils +) +INCLUDE_DIRECTORIES( + ../../ + ../../../src/ + ../../../src/utils +) +add_definitions(-DNO_BROWSERAPPLICATION) +add_definitions(-DFOR_AUTOTEST) +set(SRCS + tst_edittreeview.cpp + ../../../src/utils/edittreeview.cpp +) + +add_executable(test-edittreeview ${SRCS} ${UIS} ${MOCS}) +target_link_libraries(test-edittreeview Qt5::Core Qt5::Test Qt5::Gui Qt5::Widgets Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/autotests/utils/edittreeview/edittreeview.pro b/autotests/utils/edittreeview/edittreeview.pro deleted file mode 100644 index 00a4dea5..00000000 --- a/autotests/utils/edittreeview/edittreeview.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../../autotests.pri) - -# Input -SOURCES = tst_edittreeview.cpp edittreeview.cpp -HEADERS = edittreeview.h -FORMS = -RESOURCES = diff --git a/autotests/utils/edittreeview/tst_edittreeview.cpp b/autotests/utils/edittreeview/tst_edittreeview.cpp index 8bcfce3f..a1af736c 100644 --- a/autotests/utils/edittreeview/tst_edittreeview.cpp +++ b/autotests/utils/edittreeview/tst_edittreeview.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,19 +20,19 @@ #include #include -#include +#include class tst_EditTreeView : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void edittreeview_data(); void edittreeview(); @@ -56,7 +56,7 @@ class SubEditTreeView : public EditTreeView for (int i = 0; i < 4; ++i) { QStandardItem *item = 0; for (int j = 0; j < 4; ++j) { - item = new QStandardItem(QString("item %0").arg(j)); + item = new QStandardItem(QStringLiteral("item %0").arg(j)); parentItem->appendRow(item); } parentItem = item; diff --git a/autotests/utils/languagemanager/CMakeLists.txt b/autotests/utils/languagemanager/CMakeLists.txt new file mode 100644 index 00000000..950e2ad8 --- /dev/null +++ b/autotests/utils/languagemanager/CMakeLists.txt @@ -0,0 +1,31 @@ +project(test-languagemanager) + +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +find_package(Qt5UiTools REQUIRED) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils +) +INCLUDE_DIRECTORIES( + ../../ + ../../../src/ + ../../../src/utils +) +add_definitions(-DNO_BROWSERAPPLICATION) +add_definitions(-DFOR_AUTOTEST) +set(SRCS + tst_languagemanager.cpp + ../../../src/utils/languagemanager.cpp +) + +add_executable(test-languagemanager ${SRCS} ${UIS} ${MOCS}) +target_link_libraries(test-languagemanager Qt5::Core Qt5::Test Qt5::Gui Qt5::Widgets Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/autotests/utils/languagemanager/languagemanager.pro b/autotests/utils/languagemanager/languagemanager.pro deleted file mode 100644 index 9c0db47f..00000000 --- a/autotests/utils/languagemanager/languagemanager.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../../autotests.pri) -include(../../../src/locale/locale.pri) - -# Input -SOURCES = languagemanager.cpp tst_languagemanager.cpp -HEADERS = languagemanager.h -FORMS = -RESOURCES = diff --git a/autotests/utils/languagemanager/tst_languagemanager.cpp b/autotests/utils/languagemanager/tst_languagemanager.cpp index 09d3a8f6..6fe7c5a9 100644 --- a/autotests/utils/languagemanager/tst_languagemanager.cpp +++ b/autotests/utils/languagemanager/tst_languagemanager.cpp @@ -36,13 +36,13 @@ class tst_LanguageManager : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void languagemanager_data(); void languagemanager(); @@ -59,7 +59,7 @@ class SubLanguageManager : public LanguageManager { public: SubLanguageManager() : LanguageManager() { - addLocaleDirectory(qApp->applicationDirPath() + QLatin1String("/.qm/locale")); + addLocaleDirectory(qApp->applicationDirPath() + QStringLiteral("/.qm/locale")); } }; @@ -168,7 +168,7 @@ void tst_LanguageManager::setCurrentLanguage_data() QTest::addColumn("language"); QTest::addColumn("success"); QTest::addColumn("result"); - QTest::newRow("null-foo") << QString("foo") << false << fallbackLanguage; + QTest::newRow("null-foo") << QStringLiteral("foo") << false << fallbackLanguage; QTest::newRow("null-null") << QString() << false << fallbackLanguage; QString validLanguage = manager.languages().value(0); @@ -187,7 +187,7 @@ void tst_LanguageManager::setCurrentLanguage() SubLanguageManager manager; QString initialLanguage = manager.currentLanguage(); - QSignalSpy spy(&manager, SIGNAL(languageChanged(const QString &))); + QSignalSpy spy(&manager, &LanguageManager::languageChanged); TestWidget widget; widget.retranslate = false; diff --git a/autotests/utils/lineedit/CMakeLists.txt b/autotests/utils/lineedit/CMakeLists.txt new file mode 100644 index 00000000..e991c273 --- /dev/null +++ b/autotests/utils/lineedit/CMakeLists.txt @@ -0,0 +1,31 @@ +project(test-lineedit) + +find_package(Qt5Core REQUIRED) +find_package(Qt5Test REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5Widgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +find_package(Qt5UiTools REQUIRED) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../../src + ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils +) +INCLUDE_DIRECTORIES( + ../../ + ../../../src/ + ../../../src/utils +) +add_definitions(-DNO_BROWSERAPPLICATION) +add_definitions(-DFOR_AUTOTEST) +set(SRCS + tst_lineedit.cpp + ../../../src/utils/lineedit.cpp +) + +add_executable(test-lineedit ${SRCS} ${UIS} ${MOCS}) +target_link_libraries(test-lineedit Qt5::Core Qt5::Test Qt5::Gui Qt5::Widgets Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/autotests/utils/lineedit/lineedit.pro b/autotests/utils/lineedit/lineedit.pro deleted file mode 100644 index d829e9f4..00000000 --- a/autotests/utils/lineedit/lineedit.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES = tst_lineedit.cpp lineedit.cpp -HEADERS = lineedit.h lineedit_p.h -FORMS = -RESOURCES = diff --git a/autotests/utils/lineedit/tst_lineedit.cpp b/autotests/utils/lineedit/tst_lineedit.cpp index f44c71e1..ec44e591 100644 --- a/autotests/utils/lineedit/tst_lineedit.cpp +++ b/autotests/utils/lineedit/tst_lineedit.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,19 +20,19 @@ #include #include -#include +#include class tst_LineEdit : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void lineedit_data(); void lineedit(); @@ -52,7 +52,9 @@ class SubLineEdit : public LineEdit { public: void call_resizeEvent(QResizeEvent *event) - { return SubLineEdit::resizeEvent(event); } + { + return SubLineEdit::resizeEvent(event); + } }; // This will be called before the first test function is executed. @@ -182,7 +184,7 @@ void tst_LineEdit::textMargin() void tst_LineEdit::inactiveText_data() { QTest::addColumn("inactiveText"); - QTest::newRow("foo") << QString("foo"); + QTest::newRow("foo") << QStringLiteral("foo"); } // public QString inactiveText() const diff --git a/autotests/utils/networkaccessmanagerproxy/.gitignore b/autotests/utils/networkaccessmanagerproxy/.gitignore deleted file mode 100644 index 1b40b446..00000000 --- a/autotests/utils/networkaccessmanagerproxy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -networkaccessmanagerproxy diff --git a/autotests/utils/networkaccessmanagerproxy/networkaccessmanagerproxy.pro b/autotests/utils/networkaccessmanagerproxy/networkaccessmanagerproxy.pro deleted file mode 100644 index 125fc571..00000000 --- a/autotests/utils/networkaccessmanagerproxy/networkaccessmanagerproxy.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES = tst_networkaccessmanagerproxy.cpp networkaccessmanagerproxy.cpp webpageproxy.cpp -HEADERS = networkaccessmanagerproxy.h networkaccessmanagerproxy_p.h webpageproxy.h -FORMS = -RESOURCES = diff --git a/autotests/utils/networkaccessmanagerproxy/tst_networkaccessmanagerproxy.cpp b/autotests/utils/networkaccessmanagerproxy/tst_networkaccessmanagerproxy.cpp deleted file mode 100644 index 56c04049..00000000 --- a/autotests/utils/networkaccessmanagerproxy/tst_networkaccessmanagerproxy.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -#include -#include -#include -#include - -class tst_NetworkAccessManagerProxy : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void networkaccessmanagerproxy_data(); - void networkaccessmanagerproxy(); - - void primaryNetworkAccessManager(); - void webPage(); - - void createRequest_data(); - void createRequest(); -}; - -// Subclass that exposes the protected functions. -class SubNetworkAccessManagerProxy : public NetworkAccessManagerProxy -{ -public: - QNetworkReply *call_createRequest(QNetworkAccessManager::Operation op, QNetworkRequest const &request, QIODevice *outgoingData = 0) - { return SubNetworkAccessManagerProxy::createRequest(op, request, outgoingData); } -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_NetworkAccessManagerProxy::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_NetworkAccessManagerProxy::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_NetworkAccessManagerProxy::init() -{ -} - -// This will be called after every test function. -void tst_NetworkAccessManagerProxy::cleanup() -{ -} - -void tst_NetworkAccessManagerProxy::networkaccessmanagerproxy_data() -{ -} - -void tst_NetworkAccessManagerProxy::networkaccessmanagerproxy() -{ - SubNetworkAccessManagerProxy proxy; - QVERIFY(proxy.call_createRequest(QNetworkAccessManager::GetOperation, - QNetworkRequest(), - (QIODevice*)0)); -} - -// public void setPrimaryNetworkAccessManager(NetworkAccessManagerProxy *primaryManager) -void tst_NetworkAccessManagerProxy::primaryNetworkAccessManager() -{ - SubNetworkAccessManagerProxy proxy; - - NetworkAccessManagerProxy primaryManager; - - proxy.setPrimaryNetworkAccessManager(&primaryManager); - QCOMPARE(&primaryManager, proxy.primaryNetworkAccessManager()); - QVERIFY(primaryManager.cookieJar()->parent() == &primaryManager); -} - -// public void setWebPage(WebPageProxy *page) -void tst_NetworkAccessManagerProxy::webPage() -{ - SubNetworkAccessManagerProxy proxy; - - WebPageProxy webPage; - proxy.setWebPage(&webPage); - QCOMPARE(&webPage, proxy.webPage()); -} - -void tst_NetworkAccessManagerProxy::createRequest_data() -{ - QTest::addColumn("primary"); - QTest::newRow("true") << true; - QTest::newRow("false") << false; -} - -// protected QNetworkReply *createRequest(QNetworkAccessManager::Operation op, QNetworkRequest const &request, QIODevice *outgoingData = 0) -void tst_NetworkAccessManagerProxy::createRequest() -{ - QFETCH(bool, primary); - - SubNetworkAccessManagerProxy proxy; - SubNetworkAccessManagerProxy primaryManager; - WebPageProxy webPage; - if (!primary) { - proxy.setPrimaryNetworkAccessManager(&primaryManager); - proxy.setWebPage(&webPage); - } - - QIODevice *outgoingData = 0; - QNetworkRequest request; - QNetworkReply *reply = proxy.call_createRequest(QNetworkAccessManager::GetOperation, request, outgoingData); - QVERIFY(reply); - if (primary) - QCOMPARE(reply->request(), request); - else - QVERIFY(reply->request() != request); -} - -QTEST_MAIN(tst_NetworkAccessManagerProxy) -#include "tst_networkaccessmanagerproxy.moc" - diff --git a/autotests/utils/utils.pro b/autotests/utils/utils.pro deleted file mode 100644 index 08666cd6..00000000 --- a/autotests/utils/utils.pro +++ /dev/null @@ -1,8 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - editlistview \ - edittreeview \ - languagemanager \ - lineedit - -CONFIG += ordered diff --git a/autotests/utils/webpageproxy/.gitignore b/autotests/utils/webpageproxy/.gitignore deleted file mode 100644 index 76350346..00000000 --- a/autotests/utils/webpageproxy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -webpageproxy diff --git a/autotests/utils/webpageproxy/tst_webpageproxy.cpp b/autotests/utils/webpageproxy/tst_webpageproxy.cpp deleted file mode 100644 index e66d6b83..00000000 --- a/autotests/utils/webpageproxy/tst_webpageproxy.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -class tst_WebPageProxy : public QObject -{ - Q_OBJECT - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - void cleanup(); - -private slots: - void webpageproxy_data(); - void webpageproxy(); - - void populateNetworkRequest(); -}; - -// Subclass that exposes the protected functions. -class SubWebPageProxy : public WebPageProxy -{ -public: - void call_populateNetworkRequest(QNetworkRequest &request) - { return SubWebPageProxy::populateNetworkRequest(request); } -}; - -// This will be called before the first test function is executed. -// It is only called once. -void tst_WebPageProxy::initTestCase() -{ -} - -// This will be called after the last test function is executed. -// It is only called once. -void tst_WebPageProxy::cleanupTestCase() -{ -} - -// This will be called before each test function is executed. -void tst_WebPageProxy::init() -{ -} - -// This will be called after every test function. -void tst_WebPageProxy::cleanup() -{ -} - -void tst_WebPageProxy::webpageproxy_data() -{ -} - -void tst_WebPageProxy::webpageproxy() -{ - SubWebPageProxy proxy; - QCOMPARE(proxy.pageAttributeId(), 1100); - QNetworkRequest request; - proxy.call_populateNetworkRequest(request); -} - -// protected void populateNetworkRequest(QNetworkRequest &request) -void tst_WebPageProxy::populateNetworkRequest() -{ - SubWebPageProxy proxy; - - QNetworkRequest emptyRequest; - QNetworkRequest request = emptyRequest; - proxy.call_populateNetworkRequest(request); - - QVERIFY(request != emptyRequest); - QVariant v = request.attribute((QNetworkRequest::Attribute)(proxy.pageAttributeId())); - QVERIFY(v.isValid()); - QWebPage *webPage = (QWebPage*)(v.value()); - QVERIFY(webPage); - QCOMPARE(webPage, &proxy); -} - -QTEST_MAIN(tst_WebPageProxy) -#include "tst_webpageproxy.moc" - diff --git a/autotests/utils/webpageproxy/webpageproxy.pro b/autotests/utils/webpageproxy/webpageproxy.pro deleted file mode 100644 index 2c3b1913..00000000 --- a/autotests/utils/webpageproxy/webpageproxy.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../autotests.pri) - -# Input -SOURCES = tst_webpageproxy.cpp webpageproxy.cpp -HEADERS = webpageproxy.h -FORMS = -RESOURCES = diff --git a/autotests/webactionmapper/CMakeLists.txt b/autotests/webactionmapper/CMakeLists.txt new file mode 100644 index 00000000..61261637 --- /dev/null +++ b/autotests/webactionmapper/CMakeLists.txt @@ -0,0 +1,10 @@ +project(test-webactionmapper) +find_package(Qt5Test REQUIRED) +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/.. + ${CMAKE_CURRENT_SOURCE_DIR}/../modeltest +) + + +add_executable(test-webactionmapper tst_webactionmapper.cpp) +target_link_libraries(test-webactionmapper endorphin-base Qt5::Test) diff --git a/autotests/webactionmapper/tst_webactionmapper.cpp b/autotests/webactionmapper/tst_webactionmapper.cpp index 3622a602..b79ba8c1 100644 --- a/autotests/webactionmapper/tst_webactionmapper.cpp +++ b/autotests/webactionmapper/tst_webactionmapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include #include @@ -32,13 +32,13 @@ class tst_WebActionMapper : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void webactionmapper_data(); void webactionmapper(); void addChild(); @@ -56,7 +56,7 @@ private slots: class SubWebActionMapper : public WebActionMapper { public: - SubWebActionMapper(QAction *root, QWebPage::WebAction webAction, QObject *parent) + SubWebActionMapper(QAction *root, QWebEnginePage::WebAction webAction, QObject *parent) : WebActionMapper(root, webAction, parent) {} }; @@ -89,17 +89,17 @@ void tst_WebActionMapper::webactionmapper_data() void tst_WebActionMapper::webactionmapper() { - SubWebActionMapper mapper(0, QWebPage::Stop, 0); + SubWebActionMapper mapper(0, QWebEnginePage::Stop, 0); mapper.addChild(0); mapper.updateCurrent(0); - QCOMPARE(mapper.webAction(), QWebPage::Stop); + QCOMPARE(mapper.webAction(), QWebEnginePage::Stop); } // public void addChild(QAction *action) void tst_WebActionMapper::addChild() { QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Stop, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Stop, 0); QVERIFY(!root->isEnabled()); QAction *child = new QAction(this); @@ -119,7 +119,7 @@ void tst_WebActionMapper::updateCurrent_data() void tst_WebActionMapper::updateCurrent() { QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Stop, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Stop, 0); QVERIFY(!root->isEnabled()); WebView webView; @@ -138,7 +138,7 @@ void tst_WebActionMapper::updateCurrent() void tst_WebActionMapper::triggerRoot() { QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Reload, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Reload, 0); WebView webView; QAction *childAction = webView.page()->action(mapper.webAction()); @@ -155,7 +155,7 @@ void tst_WebActionMapper::triggerRoot() void tst_WebActionMapper::destroyRoot() { QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Reload, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Reload, 0); WebView webView; QAction *childAction = webView.page()->action(mapper.webAction()); @@ -174,7 +174,7 @@ void tst_WebActionMapper::destroyRoot() void tst_WebActionMapper::destroyCurrent() { QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Reload, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Reload, 0); WebView *webView = new WebView; QAction *childAction = webView->page()->action(mapper.webAction()); @@ -197,7 +197,7 @@ void tst_WebActionMapper::childChanged() { QFETCH(bool, isCurrent); QAction *root = new QAction(this); - SubWebActionMapper mapper(root, QWebPage::Reload, 0); + SubWebActionMapper mapper(root, QWebEnginePage::Reload, 0); WebView webView; QAction *childAction = webView.page()->action(mapper.webAction()); diff --git a/autotests/webactionmapper/webactionmapper.pro b/autotests/webactionmapper/webactionmapper.pro deleted file mode 100644 index 08c7da89..00000000 --- a/autotests/webactionmapper/webactionmapper.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES += tst_webactionmapper.cpp -HEADERS += diff --git a/autotests/webpage/CMakeLists.txt b/autotests/webpage/CMakeLists.txt new file mode 100644 index 00000000..34741181 --- /dev/null +++ b/autotests/webpage/CMakeLists.txt @@ -0,0 +1,5 @@ +project(test-webpage) +find_package(Qt5Test REQUIRED) + +add_executable(test-webpage tst_webpage.cpp) +target_link_libraries(test-webpage endorphin-base Qt5::Test) diff --git a/autotests/webpage/tst_webpage.cpp b/autotests/webpage/tst_webpage.cpp index bf3941e5..5d3e3341 100644 --- a/autotests/webpage/tst_webpage.cpp +++ b/autotests/webpage/tst_webpage.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,9 +19,8 @@ #include #include -#include #include -#include +#include #include #include "qtest_endorphin.h" @@ -30,30 +29,30 @@ class tst_WebPage : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void webpage_data(); void webpage(); void loadSettings_data(); void loadSettings(); - void webPluginFactory_data(); - void webPluginFactory(); - void acceptNavigationRequest_data(); - void acceptNavigationRequest(); - void createPlugin_data(); - void createPlugin(); + //void webPluginFactory_data(); + //void webPluginFactory(); + //void acceptNavigationRequest_data(); + //void acceptNavigationRequest(); + //void createPlugin_data(); + //void createPlugin(); void createWindow_data(); void createWindow(); void handleUnsupportedContent(); - void linkedResources(); - void javaScriptObjects_data(); - void javaScriptObjects(); + //void linkedResources(); + //void javaScriptObjects_data(); + //void javaScriptObjects(); void userAgent(); }; @@ -62,19 +61,26 @@ class SubWebPage : public WebPage { public: QString call_userAgentForUrl(const QUrl &url) const - { return SubWebPage::userAgentForUrl(url); } + { + return SubWebPage::userAgentForUrl(url); + } void call_aboutToLoadUrl(QUrl const &url) - { return SubWebPage::aboutToLoadUrl(url); } - - bool call_acceptNavigationRequest(QWebFrame *frame, QNetworkRequest const &request, NavigationType type) - { return SubWebPage::acceptNavigationRequest(frame, request, type); } - - QObject *call_createPlugin(QString const &classId, QUrl const &url, QStringList const ¶mNames, QStringList const ¶mValues) - { return SubWebPage::createPlugin(classId, url, paramNames, paramValues); } - - QWebPage *call_createWindow(QWebPage::WebWindowType type) - { return SubWebPage::createWindow(type); } + { + return SubWebPage::aboutToLoadUrl(url); + } + + /* + bool call_acceptNavigationRequest(QWebFrame *frame, QNetworkRequest const &request, NavigationType type) + { return SubWebPage::acceptNavigationRequest(frame, request, type); } + + QObject *call_createPlugin(QString const &classId, QUrl const &url, QStringList const ¶mNames, QStringList const ¶mValues) + { return SubWebPage::createPlugin(classId, url, paramNames, paramValues); } + */ + QWebEnginePage *call_createWindow(QWebEnginePage::WebWindowType type) + { + return SubWebPage::createWindow(type); + } }; // This will be called before the first test function is executed. @@ -83,8 +89,8 @@ void tst_WebPage::initTestCase() { QCoreApplication::setApplicationName("tst_webpage"); - QDesktopServices::setUrlHandler(QLatin1String("mailto"), this, "openUrl"); - QDesktopServices::setUrlHandler(QLatin1String("ftp"), this, "openUrl"); + QDesktopServices::setUrlHandler(QStringLiteral("mailto"), this, "openUrl"); + QDesktopServices::setUrlHandler(QStringLiteral("ftp"), this, "openUrl"); } // This will be called after the last test function is executed. @@ -113,11 +119,11 @@ void tst_WebPage::webpage() { SubWebPage page; page.loadSettings(); - QVERIFY(page.webPluginFactory()); + //QVERIFY(page.webPluginFactory()); page.call_aboutToLoadUrl(QUrl()); - QCOMPARE(page.call_acceptNavigationRequest((QWebFrame*)0, QNetworkRequest(), QWebPage::NavigationTypeLinkClicked), true); - QCOMPARE(page.call_createPlugin(QString(), QUrl(), QStringList(), QStringList()), (QObject*)0); - QCOMPARE(page.call_createWindow(QWebPage::WebBrowserWindow), (QWebPage*)0); + // QCOMPARE(page.call_acceptNavigationRequest((QWebFrame*)0, QNetworkRequest(), QWebEnginePage::NavigationTypeLinkClicked), true); + // QCOMPARE(page.call_createPlugin(QString(), QUrl(), QStringList(), QStringList()), (QObject*)0); + QCOMPARE(page.call_createWindow(QWebEnginePage::WebBrowserWindow), (QWebEnginePage*)0); } void tst_WebPage::loadSettings_data() @@ -144,6 +150,7 @@ void tst_WebPage::loadSettings() QSKIP("Test is not implemented."); } +/* // Q_DECLARE_METATYPE(WebPluginFactory*) void tst_WebPage::webPluginFactory_data() { @@ -169,46 +176,49 @@ void tst_WebPage::webPluginFactory() #endif QSKIP("Test is not implemented."); } - -Q_DECLARE_METATYPE(QWebPage::WebWindowType) -Q_DECLARE_METATYPE(QWebPage::NavigationType) +*/ +Q_DECLARE_METATYPE(QWebEnginePage::WebWindowType) +Q_DECLARE_METATYPE(QWebEnginePage::NavigationType) Q_DECLARE_METATYPE(Qt::MouseButton) Q_DECLARE_METATYPE(Qt::KeyboardModifier) +/* void tst_WebPage::acceptNavigationRequest_data() { QTest::addColumn("pressedButton"); QTest::addColumn("pressedKeys"); QTest::addColumn("validFrame"); QTest::addColumn("request"); - QTest::addColumn("type"); + QTest::addColumn("type"); QTest::addColumn("acceptNavigationRequest"); QTest::addColumn("spyCount"); - QTest::newRow("null-noframe") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest() << QWebPage::NavigationTypeLinkClicked << true << 0; - QTest::newRow("null-frame") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest() << QWebPage::NavigationTypeLinkClicked << true << 1; + QTest::newRow("null-noframe") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest() << QWebEnginePage::NavigationTypeLinkClicked << true << 0; + QTest::newRow("null-frame") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest() << QWebEnginePage::NavigationTypeLinkClicked << true << 1; - QTest::newRow("mailto-0") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("mailto:foo@bar.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("mailto-1") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("mailto:foo@bar.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("ftp-0") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("ftp:foo@bar.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("ftp-1") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("ftp:foo@bar.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("mailto-0") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("mailto:foo@bar.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("mailto-1") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("mailto:foo@bar.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("ftp-0") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("ftp:foo@bar.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("ftp-1") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("ftp:foo@bar.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("normal-0") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("http://www.foo.com")) << QWebPage::NavigationTypeLinkClicked << true << 0; - QTest::newRow("normal-1") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebPage::NavigationTypeLinkClicked << true << 1; + QTest::newRow("normal-0") << Qt::NoButton << Qt::NoModifier << false << QNetworkRequest(QUrl("http://www.foo.com")) << QWebEnginePage::NavigationTypeLinkClicked << true << 0; + QTest::newRow("normal-1") << Qt::NoButton << Qt::NoModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebEnginePage::NavigationTypeLinkClicked << true << 1; - QTest::newRow("midclick-0") << Qt::MidButton << Qt::NoModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("midclick-1") << Qt::MidButton << Qt::ShiftModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; - QTest::newRow("midclick-2") << Qt::MidButton << Qt::AltModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebPage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("midclick-0") << Qt::MidButton << Qt::NoModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("midclick-1") << Qt::MidButton << Qt::ShiftModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; + QTest::newRow("midclick-2") << Qt::MidButton << Qt::AltModifier << true << QNetworkRequest(QUrl("http://www.foo.com")) << QWebEnginePage::NavigationTypeLinkClicked << false << 0; } -// protected bool acceptNavigationRequest(QWebFrame *frame, QNetworkRequest const &request, NavigationType type) + +// WebKit: protected bool acceptNavigationRequest(QWebFrame *frame, QNetworkRequest const &request, NavigationType type) +// WebEngine: protected bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) void tst_WebPage::acceptNavigationRequest() { QFETCH(Qt::MouseButton, pressedButton); QFETCH(Qt::KeyboardModifier, pressedKeys); QFETCH(bool, validFrame); QFETCH(QNetworkRequest, request); - QFETCH(QWebPage::NavigationType, type); + QFETCH(QWebEnginePage::NavigationType, type); QFETCH(bool, acceptNavigationRequest); QFETCH(int, spyCount); @@ -224,7 +234,8 @@ void tst_WebPage::acceptNavigationRequest() BrowserApplication::instance()->setEventMouseButtons(Qt::NoButton); BrowserApplication::instance()->setEventKeyboardModifiers(Qt::NoModifier); } - +*/ +/* Q_DECLARE_METATYPE(QStringList) Q_DECLARE_METATYPE(QObject*) void tst_WebPage::createPlugin_data() @@ -259,23 +270,23 @@ void tst_WebPage::createPlugin() #endif QSKIP("Test is not implemented."); } - -Q_DECLARE_METATYPE(QWebPage*) +*/ +Q_DECLARE_METATYPE(QWebEnginePage*) void tst_WebPage::createWindow_data() { #if 0 - QTest::addColumn("type"); - QTest::addColumn("createWindow"); - QTest::newRow("null") << QWebPage::WebWindowType() << QWebPage*(); + QTest::addColumn("type"); + QTest::addColumn("createWindow"); + QTest::newRow("null") << QWebEnginePage::WebWindowType() << QWebEnginePage*(); #endif } -// protected QWebPage *createWindow(QWebPage::WebWindowType type) +// protected QWebEnginePage *createWindow(QWebEnginePage::WebWindowType type) void tst_WebPage::createWindow() { #if 0 - QFETCH(QWebPage::WebWindowType, type); - QFETCH(QWebPage*, createWindow); + QFETCH(QWebEnginePage::WebWindowType, type); + QFETCH(QWebEnginePage*, createWindow); SubWebPage page; @@ -292,10 +303,11 @@ void tst_WebPage::handleUnsupportedContent() { SubWebPage page; QSignalSpy spy(&page, SIGNAL(loadFinished(bool))); - page.mainFrame()->load(QUrl("http://exampletesttesttesttesttesttes.com/test.html")); + page.load(QUrl("http://exampletesttesttesttesttesttes.com/test.html")); QTRY_COMPARE(spy.count(), 1); } +/* void tst_WebPage::linkedResources() { SubWebPage page; @@ -312,25 +324,25 @@ void tst_WebPage::linkedResources() "" ""; - page.mainFrame()->setHtml(html, QUrl("http://foobar.baz/foo/")); + page->setHtml(html, QUrl("http://foobar.baz/foo/")); QList resources = page.linkedResources(); QCOMPARE(resources.count(), 4); - QCOMPARE(resources.at(0).rel, QString("stylesheet")); - QCOMPARE(resources.at(0).type, QString("text/css")); + QCOMPARE(resources.at(0).rel, QStringLiteral("stylesheet")); + QCOMPARE(resources.at(0).type, QStringLiteral("text/css")); QCOMPARE(resources.at(0).href, QUrl("http://foobar.baz/foo/styles/common.css")); QCOMPARE(resources.at(0).title, QString()); - QCOMPARE(resources.at(1).rel, QString("alternate")); - QCOMPARE(resources.at(1).type, QString("application/rss+xml")); + QCOMPARE(resources.at(1).rel, QStringLiteral("alternate")); + QCOMPARE(resources.at(1).type, QStringLiteral("application/rss+xml")); QCOMPARE(resources.at(1).href, QUrl("http://foobar.baz/foo/rss.xml")); QCOMPARE(resources.at(2).href, QUrl("http://foobar.baz/atom.xml")); - QCOMPARE(resources.at(2).title, QString("Feed")); + QCOMPARE(resources.at(2).title, QStringLiteral("Feed")); - QCOMPARE(resources.at(3).rel, QString("search")); - QCOMPARE(resources.at(3).type, QString("application/opensearchdescription+xml")); + QCOMPARE(resources.at(3).rel, QStringLiteral("search")); + QCOMPARE(resources.at(3).type, QStringLiteral("application/opensearchdescription+xml")); QCOMPARE(resources.at(3).href, QUrl("http://external.foo/search.xml")); QString js = "var base = document.createElement('base');" @@ -347,7 +359,8 @@ void tst_WebPage::linkedResources() QCOMPARE(resources.at(2).href, QUrl("http://barbaz.foo/atom.xml")); QCOMPARE(resources.at(3).href, QUrl("http://external.foo/search.xml")); } - +*/ +/* void tst_WebPage::javaScriptObjects_data() { QTest::addColumn("url"); @@ -369,13 +382,13 @@ void tst_WebPage::javaScriptObjects() page.mainFrame()->load(url); QTRY_COMPARE(spy.count(), 1); - QVariant windowExternalVariant = page.mainFrame()->evaluateJavaScript(QLatin1String("window.external")); - QVariant windowEndorphinVariant = page.mainFrame()->evaluateJavaScript(QLatin1String("window.endorphin")); + QVariant windowExternalVariant = page.mainFrame()->evaluateJavaScript(QStringLiteral("window.external")); + QVariant windowEndorphinVariant = page.mainFrame()->evaluateJavaScript(QStringLiteral("window.endorphin")); QCOMPARE(windowExternal, !windowExternalVariant.isNull()); QCOMPARE(windowEndorphin, !windowEndorphinVariant.isNull()); } - +*/ void tst_WebPage::userAgent() { QSettings settings; @@ -388,7 +401,7 @@ void tst_WebPage::userAgent() page.loadSettings(); QString customUserAgent = page.call_userAgentForUrl(QUrl()); QVERIFY(!customUserAgent.isEmpty()); - QCOMPARE(customUserAgent, QString("ben")); + QCOMPARE(customUserAgent, QStringLiteral("ben")); } diff --git a/autotests/webpage/webpage.pro b/autotests/webpage/webpage.pro deleted file mode 100644 index cd99685e..00000000 --- a/autotests/webpage/webpage.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . ../ - -include(../autotests.pri) - -# Input -SOURCES += tst_webpage.cpp -HEADERS += diff --git a/autotests/xbel/CMakeLists.txt b/autotests/xbel/CMakeLists.txt new file mode 100644 index 00000000..3ab96188 --- /dev/null +++ b/autotests/xbel/CMakeLists.txt @@ -0,0 +1,7 @@ +project(test-xbel) +find_package(Qt5Test REQUIRED) + +QT5_ADD_RESOURCES(RSCS xbels.qrc) + +add_executable(test-xbel tst_xbel.cpp ${RSCS}) +target_link_libraries(test-xbel xbel Qt5::Test) diff --git a/autotests/xbel/tst_xbel.cpp b/autotests/xbel/tst_xbel.cpp index d74bda56..1279d9dd 100644 --- a/autotests/xbel/tst_xbel.cpp +++ b/autotests/xbel/tst_xbel.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -27,13 +27,13 @@ class tst_Xbel : public QObject { Q_OBJECT -public slots: +public Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); -private slots: +private Q_SLOTS: void xbelreader_data(); void xbelreader(); @@ -105,9 +105,9 @@ void tst_Xbel::read_data() QTest::addColumn("fileName"); QTest::addColumn("error"); QTest::newRow("null") << QString() << QXmlStreamReader::NoError; - QTest::newRow("frank") << QString("frank.xbel") << QXmlStreamReader::NoError; - QTest::newRow("frank") << QString("all.xbel") << QXmlStreamReader::NoError; - QTest::newRow("bad") << QString("bad.xbel") << QXmlStreamReader::CustomError; + QTest::newRow("frank") << QStringLiteral(":/frank.xbel") << QXmlStreamReader::NoError; + QTest::newRow("frank") << QStringLiteral(":/all.xbel") << QXmlStreamReader::NoError; + QTest::newRow("bad") << QStringLiteral(":/bad.xbel") << QXmlStreamReader::CustomError; } // public BookmarkNode *read(QString const &fileName) @@ -127,7 +127,7 @@ void tst_Xbel::read() void tst_Xbel::readProperly() { SubXbelReader reader; - BookmarkNode *root = reader.read("all.xbel"); + BookmarkNode *root = reader.read(":/all.xbel"); QCOMPARE(reader.error(), QXmlStreamReader::NoError); QListchildren = root->children(); QCOMPARE(children.count(), 4); @@ -145,30 +145,30 @@ void tst_Xbel::readProperly() QCOMPARE(children[1]->type(), BookmarkNode::Folder); QCOMPARE(children[2]->children().count(), 3); - QCOMPARE(children[2]->title, QString("Folder Title")); + QCOMPARE(children[2]->title, QStringLiteral("Folder Title")); QCOMPARE(children[2]->url, QString()); QCOMPARE(children[2]->expanded, false); QCOMPARE(children[2]->type(), BookmarkNode::Folder); { children = children[2]->children(); QCOMPARE(children[0]->children().count(), 0); - QCOMPARE(children[0]->title, QString("Title")); - QCOMPARE(children[0]->url, QString("http://www.foo.com/")); + QCOMPARE(children[0]->title, QStringLiteral("Title")); + QCOMPARE(children[0]->url, QStringLiteral("http://www.foo.com/")); QCOMPARE(children[0]->expanded, false); QCOMPARE(children[0]->type(), BookmarkNode::Bookmark); QCOMPARE(children[1]->children().count(), 0); - QCOMPARE(children[1]->title, QString("Title 2")); - QCOMPARE(children[1]->url, QString("http://www.bar.com/")); + QCOMPARE(children[1]->title, QStringLiteral("Title 2")); + QCOMPARE(children[1]->url, QStringLiteral("http://www.bar.com/")); QCOMPARE(children[1]->expanded, false); QCOMPARE(children[1]->type(), BookmarkNode::Bookmark); - QCOMPARE(children[2]->title, QString("Title 3")); + QCOMPARE(children[2]->title, QStringLiteral("Title 3")); } children = root->children(); QCOMPARE(children[3]->children().count(), 3); - QCOMPARE(children[3]->title, QString("Has SubFolder")); + QCOMPARE(children[3]->title, QStringLiteral("Has SubFolder")); QCOMPARE(children[3]->url, QString()); QCOMPARE(children[3]->expanded, true); QCOMPARE(children[3]->type(), BookmarkNode::Folder); @@ -181,7 +181,7 @@ void tst_Xbel::readProperly() QCOMPARE(children[0]->type(), BookmarkNode::Separator); QCOMPARE(children[1]->children().count(), 3); - QCOMPARE(children[1]->title, QString("SubFolder")); + QCOMPARE(children[1]->title, QStringLiteral("SubFolder")); QCOMPARE(children[1]->url, QString()); QCOMPARE(children[1]->expanded, true); QCOMPARE(children[1]->type(), BookmarkNode::Folder); @@ -212,8 +212,8 @@ void tst_Xbel::xbelwriter() void tst_Xbel::write_data() { QTest::addColumn("readFileName"); - QTest::newRow("frank") << QString("frank.xbel"); - QTest::newRow("all") << QString("all.xbel"); + QTest::newRow("frank") << QStringLiteral(":/frank.xbel"); + QTest::newRow("all") << QStringLiteral(":/all.xbel"); } // public BookmarkNode *read(QString const &fileName) diff --git a/autotests/xbel/xbel.pro b/autotests/xbel/xbel.pro deleted file mode 100644 index d9e417c7..00000000 --- a/autotests/xbel/xbel.pro +++ /dev/null @@ -1,18 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../autotests.pri) - -# Input -SOURCES = \ - tst_xbel.cpp \ - bookmarks/bookmarknode.cpp \ - bookmarks/xbel/xbelreader.cpp \ - bookmarks/xbel/xbelwriter.cpp - -HEADERS = \ - bookmarks/bookmarknode.h \ - bookmarks/xbel/xbelreader.h \ - bookmarks/xbel/xbelwriter.h diff --git a/autotests/xbel/xbels.qrc b/autotests/xbel/xbels.qrc new file mode 100644 index 00000000..ecc40cd4 --- /dev/null +++ b/autotests/xbel/xbels.qrc @@ -0,0 +1,7 @@ + + + all.xbel + frank.xbel + bad.xbel + + \ No newline at end of file diff --git a/debian/copyright b/debian/copyright index d5e2a493..42a9ba8f 100644 --- a/debian/copyright +++ b/debian/copyright @@ -8,20 +8,19 @@ Upstream Author: Aaron Dewes Copyright: - Copyright 1998-1999 Netscape Communications Corporation. All Copyright 2005-2008 Trolltech ASA. All rights reserved. Copyright 2006 Junio C Hamano - Copyright 2007-2009 Aaron Dewes + Copyright 2020 Aaron Dewes Copyright 2008 Ariya Hidayat Copyright 2008-2009 Christian Franke Copyright 2008 Diego Iastrubni, elcuco, at, kde.org Copyright 2008 Jason A. Donenfeld Copyright 2008 Matvey Kozhev - Copyright 2008-2009 Endorphin Developers + Copyright 2008-2020 Endorphin Developers Copyright 2008-2009 Benjamin K. Stuhl Copyright 2008-2009 Jason A. Donenfeld Copyright 2009 Jakub Wieczorek - Copyright 2009 Torch Mobile Inc. http://www.torchmobile.com/ + Copyright 2016 The Qt Company Ltd. License: diff --git a/definitions.cmake b/definitions.cmake new file mode 100644 index 00000000..c450f7f1 --- /dev/null +++ b/definitions.cmake @@ -0,0 +1,101 @@ + +set(ENDORPHIN_SRC_DIR ${CMAKE_SOURCE_DIR}/src) + +set(ENDORPHIN_INCLUDE_DIRS + ${ENDORPHIN_SRC_DIR} + src/utils + src/bookmarks + src/bookmarks/xbel + src/data + src/history + src/htmls + src/locationbar + src/opensearch + src/useragent + src/utils +) + +set(ENDORPHIN_AUTOUIC_SEARCH_PATHS + ${ENDORPHIN_INCLUDE_DIRS} +) + +set(ENDORPHIN_SRCS + src/aboutdialog.cpp + src/acceptlanguagedialog.cpp + src/autosaver.cpp + src/browserapplication.cpp + src/browsermainwindow.cpp + src/clearprivatedata.cpp + src/clearbutton.cpp + src/devtoolswindow.cpp + src/downloadmanager.cpp + src/modelmenu.cpp + src/modeltoolbar.cpp + src/permissionbar.cpp + src/plaintexteditsearch.cpp + src/savepagedialog.cpp + src/searchbar.cpp + src/searchbutton.cpp + src/searchlineedit.cpp + src/settings.cpp + src/tabbar.cpp + src/tabwidget.cpp + src/toolbarsearch.cpp + src/webactionmapper.cpp + src/webpage.cpp + src/webview.cpp + src/webviewsearch.cpp + src/bookmarks/addbookmarkdialog.cpp + src/bookmarks/bookmarksdialog.cpp + src/bookmarks/bookmarksmanager.cpp + src/bookmarks/bookmarksmenu.cpp + src/bookmarks/bookmarksmodel.cpp + src/bookmarks/bookmarkstoolbar.cpp + src/bookmarks/bookmarknode.cpp + src/history/history.cpp + src/locationcompleter.cpp + src/history/historymanager.cpp + src/locationbar/locationbar.cpp + src/locationbar/locationbarsiteicon.cpp + src/locationbar/privacyindicator.cpp + src/opensearch/opensearchdialog.cpp + src/opensearch/opensearchengine.cpp + src/opensearch/opensearchenginedelegate.cpp + src/opensearch/opensearchengineaction.cpp + src/opensearch/opensearchenginemodel.cpp + src/opensearch/opensearchmanager.cpp + src/opensearch/opensearchreader.cpp + src/opensearch/opensearchwriter.cpp + src/useragent/useragentmenu.cpp + src/utils/explorerstyle.cpp + src/utils/editlistview.cpp + src/utils/edittableview.cpp + src/utils/edittreeview.cpp + src/utils/languagemanager.cpp + src/utils/lineedit.cpp + src/utils/singleapplication.cpp + src/utils/squeezelabel.cpp + src/utils/treesortfilterproxymodel.cpp +) + +set(ENDORPHIN_UIS + src/aboutdialog.ui + src/acceptlanguagedialog.ui + src/downloaditem.ui + src/downloads.ui + src/savepagedialog.ui + src/searchbanner.ui + src/settings.ui + src/bookmarks/addbookmarkdialog.ui + src/bookmarks/bookmarksdialog.ui + src/history/history.ui + src/opensearch/opensearchdialog.ui +) + +set(ENDORPHIN_RSCS + src/data/data.qrc + src/data/graphics/graphics.qrc + src/data/searchengines/searchengines.qrc + src/htmls/htmls.qrc + src/useragent/useragents.qrc +) diff --git a/endorphin.pro b/endorphin.pro deleted file mode 100644 index 65480cf7..00000000 --- a/endorphin.pro +++ /dev/null @@ -1,17 +0,0 @@ -lessThan(QT_VERSION, 5.0) { - error("Endorphin requires Qt 5.0 or greater") -} - -TEMPLATE = subdirs -SUBDIRS = src tools -CONFIG += ordered - -unix { - warning("It is recommended to use CMake instead of QMake") - # this is an ugly work around to do .PHONY: doc - doxygen.target = doc dox - doxygen.commands = doxygen Doxyfile - doxygen.depends = Doxyfile - QMAKE_EXTRA_TARGETS += doxygen -} - diff --git a/endorphinbase.cmake b/endorphinbase.cmake new file mode 100644 index 00000000..8eb74402 --- /dev/null +++ b/endorphinbase.cmake @@ -0,0 +1,25 @@ +# Create a base "library" that all tests can link against. Basically the whole browser without entrypoint and translations. +# Used to avoid compiling files twice. + +find_package(Qt5Widgets REQUIRED) +find_package(Qt5Core REQUIRED) +find_package(Qt5Gui REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5Network REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) +find_package(Qt5PrintSupport REQUIRED) +find_package(Qt5LinguistTools REQUIRED) +find_package(Qt5Qml REQUIRED) + +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOMOC ON) + +QT5_WRAP_UI(BASE_UIS ${ENDORPHIN_UIS}) +QT5_ADD_RESOURCES(BASE_RSCS ${ENDORPHIN_RSCS}) + +INCLUDE_DIRECTORIES( + ${ENDORPHIN_INCLUDE_DIRS} +) + +add_library(endorphin-base STATIC ${ENDORPHIN_SRCS} ${BASE_UIS} ${BASE_RSCS} ${BASE_MOCS}) +target_link_libraries(endorphin-base xbel Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Network Qt5::Qml Qt5::PrintSupport Qt5::WebEngine Qt5::WebEngineWidgets) diff --git a/generate_translations.sh b/generate_translations.sh new file mode 100755 index 00000000..7a4e0b83 --- /dev/null +++ b/generate_translations.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +FILES="ast.ts tr_TR.ts de_DE.ts hu_HU.ts es_CR.ts zh_TW.ts cs_CZ.ts sr_RS@latin.ts fr_FR.ts pt_BR.ts es.ts sr_RS.ts ms.ts da_DK.ts sk_SK.ts ru_RU.ts he_IL.ts pt_PT.ts ko_KR.ts fr_CA.ts nl.ts el_GR.ts ca.ts pl_PL.ts nb_NO.ts uk.ts zh_CN.ts gl.ts et_EE.ts fi_FI.ts it_IT.ts ja_JP.ts gl.ts" +for FILE in $FILES; do +/usr/lib/qt5/bin/lupdate @ts_lst_file -ts "src/locale/${FILE}" -noobsolete +done diff --git a/install.pri b/install.pri deleted file mode 100644 index 761010ee..00000000 --- a/install.pri +++ /dev/null @@ -1,13 +0,0 @@ - -unix { - isEmpty(PREFIX) { - PREFIX = /usr/local - } - BINDIR = $$PREFIX/bin - - INSTALLS += target - target.path = $$BINDIR - - DATADIR = $$PREFIX/share -} - diff --git a/manualtests/adblock/adblock.pro b/manualtests/adblock/adblock.pro deleted file mode 100644 index d0811c75..00000000 --- a/manualtests/adblock/adblock.pro +++ /dev/null @@ -1,6 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - adblockdialog \ - adblockmodel - -CONFIG += ordered diff --git a/manualtests/adblock/adblockdialog/.gitignore b/manualtests/adblock/adblockdialog/.gitignore deleted file mode 100644 index ad6f3475..00000000 --- a/manualtests/adblock/adblockdialog/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblockdialog diff --git a/manualtests/adblock/adblockdialog/adblockdialog.pro b/manualtests/adblock/adblockdialog/adblockdialog.pro deleted file mode 100644 index 415d82fc..00000000 --- a/manualtests/adblock/adblockdialog/adblockdialog.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) -include(../../../autotests/modeltest/modeltest.pri) - -# Input -SOURCES += main_adblockdialog.cpp -HEADERS += diff --git a/manualtests/adblock/adblockdialog/main_adblockdialog.cpp b/manualtests/adblock/adblockdialog/main_adblockdialog.cpp deleted file mode 100644 index ede8d54b..00000000 --- a/manualtests/adblock/adblockdialog/main_adblockdialog.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include - -#include "adblockdialog.h" -#include "modeltest.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - AdBlockDialog dialog; - new ModelTest(dialog.treeView->model()); - dialog.show(); - return app.exec(); -} - diff --git a/manualtests/adblock/adblockmodel/.gitignore b/manualtests/adblock/adblockmodel/.gitignore deleted file mode 100644 index c2bb9418..00000000 --- a/manualtests/adblock/adblockmodel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -adblockmodel diff --git a/manualtests/adblock/adblockmodel/adblockmodel.pro b/manualtests/adblock/adblockmodel/adblockmodel.pro deleted file mode 100644 index 453974d1..00000000 --- a/manualtests/adblock/adblockmodel/adblockmodel.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) -include(../../../autotests/modeltest/modeltest.pri) - -# Input -SOURCES += main_adblockmodel.cpp -HEADERS += diff --git a/manualtests/adblock/adblockmodel/main_adblockmodel.cpp b/manualtests/adblock/adblockmodel/main_adblockmodel.cpp deleted file mode 100644 index 6e255a6a..00000000 --- a/manualtests/adblock/adblockmodel/main_adblockmodel.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include - -#include "adblockmodel.h" -#include "modeltest.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - QTreeView view; - AdBlockModel *model = new AdBlockModel; - new ModelTest(model); - view.setModel(model); - view.show(); - return app.exec(); -} - diff --git a/manualtests/bookmarks/.gitignore b/manualtests/bookmarks/.gitignore deleted file mode 100644 index 7e1f6a71..00000000 --- a/manualtests/bookmarks/.gitignore +++ /dev/null @@ -1 +0,0 @@ -bookmarks diff --git a/manualtests/bookmarks/bookmarks.pro b/manualtests/bookmarks/bookmarks.pro deleted file mode 100644 index dcb2e219..00000000 --- a/manualtests/bookmarks/bookmarks.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) -include(../../autotests/modeltest/modeltest.pri) - -# Input -SOURCES += main_bookmarks.cpp -HEADERS += diff --git a/manualtests/bookmarks/main_bookmarks.cpp b/manualtests/bookmarks/main_bookmarks.cpp deleted file mode 100644 index f30c6f00..00000000 --- a/manualtests/bookmarks/main_bookmarks.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include - -#include "addbookmarkdialog.h" -#include "bookmarksdialog.h" -#include "bookmarksmanager.h" -#include "bookmarksmodel.h" -#include "browserapplication.h" -#include "modeltest.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - QCoreApplication::setApplicationName(QLatin1String("endorphin")); - QCoreApplication::setApplicationVersion(QLatin1String("0.1")); - - new ModelTest(BrowserApplication::bookmarksManager()->bookmarksModel()); - BookmarksDialog *dialog = new BookmarksDialog; - dialog->show(); - - QString url("http://www.reddit.com"); - AddBookmarkDialog adddialog; - adddialog.setTitle(QString("Reddit.com: a time drain")); - adddialog.setUrl(url); - //adddialog.show(); - - QMenuBar bar; - QMenu *edit = bar.addMenu(("&Edit")); - edit->addAction(BrowserApplication::bookmarksManager()->undoRedoStack()->createUndoAction(edit)); - edit->addAction(BrowserApplication::bookmarksManager()->undoRedoStack()->createRedoAction(edit)); - return app.exec(); -} - diff --git a/manualtests/downloadmanager/.gitignore b/manualtests/downloadmanager/.gitignore deleted file mode 100644 index 45b3fddc..00000000 --- a/manualtests/downloadmanager/.gitignore +++ /dev/null @@ -1 +0,0 @@ -downloadmanager diff --git a/manualtests/downloadmanager/downloadmanager.pro b/manualtests/downloadmanager/downloadmanager.pro deleted file mode 100644 index 79f26c3f..00000000 --- a/manualtests/downloadmanager/downloadmanager.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) - -# Input -RESOURCES = -SOURCES += main_downloadmanager.cpp -HEADERS += diff --git a/manualtests/downloadmanager/main_downloadmanager.cpp b/manualtests/downloadmanager/main_downloadmanager.cpp deleted file mode 100644 index 50c4dc79..00000000 --- a/manualtests/downloadmanager/main_downloadmanager.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "downloadmanager.h" - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - - DownloadManager manager; - QUrl url("http://10.0.0.3/~ben/distccKNOPPIX-1.3-2004-08-20-gcc-3.3.iso"); - manager.download(url); - manager.show(); - - return application.exec(); -} - diff --git a/manualtests/history/.gitignore b/manualtests/history/.gitignore deleted file mode 100644 index c375d5ba..00000000 --- a/manualtests/history/.gitignore +++ /dev/null @@ -1 +0,0 @@ -history diff --git a/manualtests/history/history.pro b/manualtests/history/history.pro deleted file mode 100644 index 2fa000d9..00000000 --- a/manualtests/history/history.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) -include(../../autotests/modeltest/modeltest.pri) - -# Input -SOURCES += main_history.cpp -HEADERS += diff --git a/manualtests/history/main_history.cpp b/manualtests/history/main_history.cpp deleted file mode 100644 index 1c45c4d9..00000000 --- a/manualtests/history/main_history.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include - -#include -#include -#include -#include -#include - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - QMainWindow w; - - QCoreApplication::setApplicationName("endorphin"); - - HistoryManager history; - - QTabWidget tabWidget; - - QTableView *historyModelView = new QTableView(&tabWidget); - historyModelView->horizontalHeader()->setStretchLastSection(true); - historyModelView->setModel(history.historyModel()); - tabWidget.addTab(historyModelView, "HistoryModel"); - - QTableView *historyFilterModelView = new QTableView(&tabWidget); - historyFilterModelView->horizontalHeader()->setStretchLastSection(true); - historyFilterModelView->setModel(history.historyFilterModel()); - tabWidget.addTab(historyFilterModelView, "HistoryFilterModel"); - - QTreeView *historyTreeModelView = new QTreeView(&tabWidget); - historyTreeModelView->header()->setStretchLastSection(true); - historyTreeModelView->setModel(history.historyTreeModel()); - new ModelTest(history.historyTreeModel()); - tabWidget.addTab(historyTreeModelView, "HistoryTreeModel"); - - QTreeView *historyMenuModelView = new QTreeView(&tabWidget); - historyMenuModelView->header()->setStretchLastSection(true); - HistoryMenuModel *menuModel = new HistoryMenuModel((HistoryTreeModel*)history.historyTreeModel(), &tabWidget); - new ModelTest(menuModel); - historyMenuModelView->setModel(menuModel); - tabWidget.addTab(historyMenuModelView, "HistoryMenuModel"); - - QTableView *historyCompletionModelView = new QTableView(&tabWidget); - historyCompletionModelView->horizontalHeader()->setStretchLastSection(true); - HistoryCompletionModel *completionModel = new HistoryCompletionModel(&tabWidget); - completionModel->setSourceModel(history.historyFilterModel()); - historyCompletionModelView->setModel(completionModel); - tabWidget.addTab(historyCompletionModelView, "HistoryCompletionModel"); - - HistoryDialog dialog(0, &history); - tabWidget.addTab(dialog.tree, "DialogModel"); - - tabWidget.setCurrentIndex(3); - tabWidget.show(); - - return application.exec(); -} - diff --git a/manualtests/locationbar/.gitignore b/manualtests/locationbar/.gitignore deleted file mode 100644 index 3c98d718..00000000 --- a/manualtests/locationbar/.gitignore +++ /dev/null @@ -1 +0,0 @@ -locationbar diff --git a/manualtests/locationbar/locationbar.pro b/manualtests/locationbar/locationbar.pro deleted file mode 100644 index 41b93df9..00000000 --- a/manualtests/locationbar/locationbar.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) - -# Input -SOURCES += main_locationbar.cpp -HEADERS += - diff --git a/manualtests/locationbar/main_locationbar.cpp b/manualtests/locationbar/main_locationbar.cpp deleted file mode 100644 index c3b5a07e..00000000 --- a/manualtests/locationbar/main_locationbar.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include -#include -#include -#include - -#include "browserapplication.h" -#include "locationbar.h" -#include "webview.h" - -int main(int argc, char **argv) -{ - BrowserApplication application(argc, argv); - QCoreApplication::setApplicationName(QLatin1String("urllineeditexample")); - QMainWindow w; - - QWidget *window = new QWidget; - QComboBox *comboBox = new QComboBox(window); - comboBox->setEditable(true); - QLineEdit *lineEdit = new QLineEdit(window); - LocationBar *s1 = new LocationBar(window); - LocationBar *s2 = new LocationBar(window); - WebView *view = new WebView(window); - view->setUrl(QUrl("http://www.google.com")); - s2->setWebView(view); - - QVBoxLayout *layout = new QVBoxLayout; - layout->addWidget(comboBox); - layout->addWidget(lineEdit); - layout->addWidget(s1); - layout->addWidget(s2); - layout->addWidget(view); - window->setLayout(layout); - w.show(); - w.setCentralWidget(window); - - QToolBar *bar = w.addToolBar("foo"); - QSplitter *splitter = new QSplitter(window); - splitter->addWidget(new LocationBar); - splitter->addWidget(new QLineEdit); - bar->addWidget(splitter); - return application.exec(); -} - diff --git a/manualtests/manualtests.pri b/manualtests/manualtests.pri deleted file mode 100644 index eab9f33c..00000000 --- a/manualtests/manualtests.pri +++ /dev/null @@ -1,4 +0,0 @@ -win32: CONFIG += console -mac:CONFIG -= app_bundle - -include($$PWD/../src/src.pri) diff --git a/manualtests/manualtests.pro b/manualtests/manualtests.pro deleted file mode 100644 index 52817cad..00000000 --- a/manualtests/manualtests.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - adblock \ - bookmarks \ - downloadmanager \ - history \ - locationbar \ - modelmenu \ - searchlineedit \ - utils \ - webviewsearch - -CONFIG += ordered diff --git a/manualtests/modelmenu/.gitignore b/manualtests/modelmenu/.gitignore deleted file mode 100644 index 2f8ac853..00000000 --- a/manualtests/modelmenu/.gitignore +++ /dev/null @@ -1 +0,0 @@ -modelmenu diff --git a/manualtests/modelmenu/main_modelmenu.cpp b/manualtests/modelmenu/main_modelmenu.cpp deleted file mode 100644 index 279c342c..00000000 --- a/manualtests/modelmenu/main_modelmenu.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include -#include -#include - -#include - -#include - -class Menu : public ModelMenu -{ - Q_OBJECT - -public: - Menu(QWidget *parent); - -protected: - bool prePopulated(); - void postPopulated(); - ModelMenu *createBaseMenu(); - -private slots: - void activated2(const QModelIndex &index); - -}; - -Menu::Menu(QWidget *parent) - : ModelMenu(parent) -{ - connect(this, SIGNAL(activated(const QModelIndex &)), - this, SLOT(activated2(const QModelIndex &))); -} - -bool Menu::prePopulated() -{ - qDebug() << __FUNCTION__; - return ModelMenu::prePopulated(); -} - -void Menu::postPopulated() -{ - qDebug() << __FUNCTION__; - return ModelMenu::postPopulated(); -} - -ModelMenu *Menu::createBaseMenu() -{ - qDebug() << __FUNCTION__; - return new Menu(this); - return ModelMenu::createBaseMenu(); -} - -void Menu::activated2(const QModelIndex &index) -{ - qDebug() << __FUNCTION__ << index.data() << this; -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - QMainWindow mainWindow; - Menu *menu = new Menu(&mainWindow); - menu->setTitle("Test"); - QDirModel *model = new QDirModel(menu); - menu->setModel(model); - menu->setRootIndex(model->index(QDir::homePath())); - mainWindow.menuBar()->addMenu(menu); - mainWindow.show(); - return app.exec(); -} - -#include "main_modelmenu.moc" - diff --git a/manualtests/modelmenu/modelmenu.pro b/manualtests/modelmenu/modelmenu.pro deleted file mode 100644 index 78a06670..00000000 --- a/manualtests/modelmenu/modelmenu.pro +++ /dev/null @@ -1,10 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) - -# Input -SOURCES += main_modelmenu.cpp -HEADERS += diff --git a/manualtests/searchlineedit/.gitignore b/manualtests/searchlineedit/.gitignore deleted file mode 100644 index 1713e66b..00000000 --- a/manualtests/searchlineedit/.gitignore +++ /dev/null @@ -1 +0,0 @@ -searchlineedit diff --git a/manualtests/searchlineedit/main_searchlineedit.cpp b/manualtests/searchlineedit/main_searchlineedit.cpp deleted file mode 100644 index 53b7c971..00000000 --- a/manualtests/searchlineedit/main_searchlineedit.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2008-2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include -#include -#include -#include -#include - -#include "searchlineedit.h" -#include "searchbutton.h" - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - - QDialog window; - QPushButton *button1 = new QPushButton("One"); - SearchLineEdit *s1 = new SearchLineEdit(&window); - SearchLineEdit *s2 = new SearchLineEdit(&window); - QCompleter *completer = new QCompleter(&window); - s2->setCompleter(completer); - s2->searchButton()->setShowMenuTriangle(true); - QObject::connect(s2->searchButton(), SIGNAL(clicked()), - completer, SLOT(complete())); - QStringList list; - list << "a" << "b" << "c"; - s2->completer()->setModel(new QStringListModel(list)); - - QVBoxLayout *layout = new QVBoxLayout; - layout->addWidget(s1); - layout->addWidget(s2); - layout->addWidget(button1); - - window.setLayout(layout); - window.show(); - return application.exec(); -} - diff --git a/manualtests/searchlineedit/searchlineedit.pro b/manualtests/searchlineedit/searchlineedit.pro deleted file mode 100644 index 3cc1340b..00000000 --- a/manualtests/searchlineedit/searchlineedit.pro +++ /dev/null @@ -1,14 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) - -# Input -RESOURCES = -FORMS = -SOURCES = searchbutton.cpp clearbutton.cpp lineedit.cpp searchlineedit.cpp -HEADERS = searchbutton.h clearbutton.h lineedit.h lineedit_p.h searchlineedit.h - -SOURCES += main_searchlineedit.cpp diff --git a/manualtests/utils/editview/.gitignore b/manualtests/utils/editview/.gitignore deleted file mode 100644 index 53dfa8a4..00000000 --- a/manualtests/utils/editview/.gitignore +++ /dev/null @@ -1 +0,0 @@ -editview diff --git a/manualtests/utils/editview/editview.pro b/manualtests/utils/editview/editview.pro deleted file mode 100644 index 18c3fe24..00000000 --- a/manualtests/utils/editview/editview.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) - -# Input -FORMS += editview.ui -SOURCES += main_editview.cpp -HEADERS += diff --git a/manualtests/utils/editview/editview.ui b/manualtests/utils/editview/editview.ui deleted file mode 100644 index beee2a32..00000000 --- a/manualtests/utils/editview/editview.ui +++ /dev/null @@ -1,87 +0,0 @@ - - - Dialog - - - - 0 - 0 - 790 - 398 - - - - Dialog - - - - - - Qt::Horizontal - - - - - - - - - - RemoveAll - - - - - - - - - - - - - - RemoveAll - - - - - - - - - - - - - - RemoveAll - - - - - - - - - - - - EditListView - QListView -
editlistview.h
-
- - EditTreeView - QTreeView -
edittreeview.h
-
- - EditTableView - QTableView -
edittableview.h
-
-
- - -
diff --git a/manualtests/utils/editview/main_editview.cpp b/manualtests/utils/editview/main_editview.cpp deleted file mode 100644 index 578f1983..00000000 --- a/manualtests/utils/editview/main_editview.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include -#include - -#include "ui_editview.h" - -class Window : public QDialog, public Ui_Dialog -{ - Q_OBJECT - -public: - Window(); -}; - -Window::Window() - : QDialog() -{ - setupUi(this); - QStringList list; - list << "a" << "b" << "c"; - listView->setModel(new QStringListModel(list)); - tableView->setModel(new QStringListModel(list)); - connect(listViewRemoveAllButton, SIGNAL(clicked()), listView, SLOT(removeAll())); - connect(tableViewRemoveAllButton, SIGNAL(clicked()), tableView, SLOT(removeAll())); - connect(treeViewRemoveAllButton, SIGNAL(clicked()), treeView, SLOT(removeAll())); - - QStandardItemModel *model = new QStandardItemModel(this); - QStandardItem *parentItem = model->invisibleRootItem(); - for (int i = 0; i < 4; ++i) { - QStandardItem *item = new QStandardItem(QString("item %0").arg(i)); - parentItem->appendRow(item); - item = new QStandardItem(QString("item %0").arg(i * 2)); - parentItem->appendRow(item); - parentItem = item; - } - treeView->setModel(model); - treeView->expandAll(); -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - Window window; - window.show(); - return app.exec(); -} - -#include "main_editview.moc" - diff --git a/manualtests/utils/lineedit/.gitignore b/manualtests/utils/lineedit/.gitignore deleted file mode 100644 index 19f5a9a7..00000000 --- a/manualtests/utils/lineedit/.gitignore +++ /dev/null @@ -1 +0,0 @@ -lineedit diff --git a/manualtests/utils/lineedit/bookmark.png b/manualtests/utils/lineedit/bookmark.png deleted file mode 100644 index be21134b..00000000 Binary files a/manualtests/utils/lineedit/bookmark.png and /dev/null differ diff --git a/manualtests/utils/lineedit/dialog.ui b/manualtests/utils/lineedit/dialog.ui deleted file mode 100644 index e5501383..00000000 --- a/manualtests/utils/lineedit/dialog.ui +++ /dev/null @@ -1,289 +0,0 @@ - - Dialog - - - - 0 - 0 - 474 - 348 - - - - Dialog - - - - - - - - Left: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Foo Bar Baz Endorphin LineEdit Manual Test This is the end - - - - - - - Right: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Foo Bar Baz Endorphin LineEdit Manual Test This is the end - - - - - - - Foo Bar Baz Endorphin LineEdit Manual Test This is the end - - - - - - - Empty: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Horizontal - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Foo Bar Baz Endorphin LineEdit Manual Test - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Widget - - - - - - Site Icon - - - true - - - - - - - RSS - - - false - - - - - - - Bookmark - - - - - - - - - - Position - - - - - - Left - - - true - - - - - - - Right - - - - - - - - - - - 0 - 0 - - - - 3 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 28 - - - - - - - - - - Add - - - - - - - Remove - - - - - - - Swap Visibility - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Add ToolButton - - - - - - - - - - LineEdit - QLineEdit -
lineedit.h
-
-
- - -
diff --git a/manualtests/utils/lineedit/lineedit.pro b/manualtests/utils/lineedit/lineedit.pro deleted file mode 100644 index 55d0d804..00000000 --- a/manualtests/utils/lineedit/lineedit.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) - -# Input -RESOURCES = -FORMS = dialog.ui -SOURCES = main_lineedit.cpp lineedit.cpp -HEADERS = lineedit.h lineedit_p.h diff --git a/manualtests/utils/lineedit/main_lineedit.cpp b/manualtests/utils/lineedit/main_lineedit.cpp deleted file mode 100644 index 2403cff0..00000000 --- a/manualtests/utils/lineedit/main_lineedit.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include - -#include -#include "ui_dialog.h" - -class Dialog : public QDialog, public Ui_Dialog -{ - Q_OBJECT -public: - Dialog(QWidget *parent = 0); - - QLabel *rssButton; - QLabel *bookmarkButton; - QLabel *siteIconButton; - -private slots: - void setWidgetSpacing(int s); - void add(); - void remove(); - void showW(); - void addToolButton(); - - QWidget *getWidget(); -}; - -Dialog::Dialog(QWidget *parent) - : QDialog(parent) -{ - setupUi(this); - rssButton = new QLabel(this); - rssButton->setPixmap(QPixmap("rss.png")); - rssButton->hide(); - bookmarkButton = new QLabel(this); - bookmarkButton->setPixmap(QPixmap("bookmark.png")); - bookmarkButton->hide(); - siteIconButton = new QLabel(this); - siteIconButton->setPixmap(QPixmap("siteicon.png")); - siteIconButton->hide(); - - { - QToolButton *b = new QToolButton(this); - b->resize(16, 16); - leftLineEdit->addWidget(b, LineEdit::LeftSide); - } - { - QToolButton *b = new QToolButton(this); - b->resize(16, 16); - rightLineEdit->addWidget(b, LineEdit::RightSide); - } - connect(addButton, SIGNAL(clicked()), this, SLOT(add())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(remove())); - connect(showButton, SIGNAL(clicked()), this, SLOT(showW())); - connect(addToolButtonButton, SIGNAL(clicked()), this, SLOT(addToolButton())); - connect(spacing, SIGNAL(valueChanged(int)), this, SLOT(setWidgetSpacing(int))); -} - -QWidget *Dialog::getWidget() -{ - if (rssWidget->isChecked()) { - bookmarkWidget->setChecked(true); - return rssButton; - } - if (bookmarkWidget->isChecked()) { - siteIconWidget->setChecked(true); - return bookmarkButton; - } - if (siteIconWidget->isChecked()) { - rssWidget->setChecked(true); - return siteIconButton; - } - return 0; -} - -void Dialog::setWidgetSpacing(int s) -{ - lineEdit->setWidgetSpacing(s); -} - -void Dialog::add() -{ - LineEdit::WidgetPosition position = leftSide->isChecked() ? LineEdit::LeftSide : LineEdit::RightSide; - lineEdit->addWidget(getWidget(), position); -} - -void Dialog::remove() -{ - lineEdit->removeWidget(getWidget()); -} - -void Dialog::showW() -{ - QWidget *w = getWidget(); - w->setVisible(!w->isVisible()); -} - -void Dialog::addToolButton() -{ - LineEdit::WidgetPosition position = leftSide->isChecked() ? LineEdit::LeftSide : LineEdit::RightSide; - QToolButton *button = new QToolButton; - lineEdit->addWidget(button, position); -} - -int main(int argc,char ** argv) -{ - QApplication app(argc,argv); - - if (app.arguments().count() == 1) { - Dialog dialog; - dialog.show(); - return app.exec(); - } else { - LineEdit lineEdit; - QPushButton *rightButton = new QPushButton("Dialog bar"); - qDebug() << rightButton->sizeHint(); - lineEdit.addWidget(rightButton, LineEdit::RightSide); - lineEdit.show(); - return app.exec(); - } -} - -#include "main_lineedit.moc" - diff --git a/manualtests/utils/lineedit/rss.png b/manualtests/utils/lineedit/rss.png deleted file mode 100755 index b3c949d2..00000000 Binary files a/manualtests/utils/lineedit/rss.png and /dev/null differ diff --git a/manualtests/utils/lineedit/siteicon.png b/manualtests/utils/lineedit/siteicon.png deleted file mode 100644 index e0caa872..00000000 Binary files a/manualtests/utils/lineedit/siteicon.png and /dev/null differ diff --git a/manualtests/utils/singleapplication/.gitignore b/manualtests/utils/singleapplication/.gitignore deleted file mode 100644 index a24818bd..00000000 --- a/manualtests/utils/singleapplication/.gitignore +++ /dev/null @@ -1 +0,0 @@ -singleapplication diff --git a/manualtests/utils/singleapplication/main_singleapplication.cpp b/manualtests/utils/singleapplication/main_singleapplication.cpp deleted file mode 100644 index fc9a24ae..00000000 --- a/manualtests/utils/singleapplication/main_singleapplication.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2008, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 -#include -#include -#include - -#include - -class PlainTextEdit : public QPlainTextEdit { - Q_OBJECT - -public: - PlainTextEdit(QWidget *parent = 0) - : QPlainTextEdit(parent) { } - -public slots: - void messageReceived(QLocalSocket *socket) { - QString message; - QTextStream stream(socket); - stream >> message; - appendPlainText(message); - } - -}; - -int main(int argc, char **argv) -{ - SingleApplication app(argc, argv); - app.setApplicationName("testapp"); - if (app.arguments().count() > 1 - && app.sendMessage(app.arguments().last().toUtf8())) - return 0; - - PlainTextEdit plainTextEdit; - plainTextEdit.show(); - if (!app.startSingleServer()) - qWarning() << "Error starting server"; - app.connect(&app, SIGNAL(messageReceived(QLocalSocket *)), - &plainTextEdit, SLOT(messageReceived(QLocalSocket *))); - return app.exec(); -} - -#include "main_singleapplication.moc" - diff --git a/manualtests/utils/singleapplication/singleapplication.pro b/manualtests/utils/singleapplication/singleapplication.pro deleted file mode 100644 index a511dcd1..00000000 --- a/manualtests/utils/singleapplication/singleapplication.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) - -# Input -RESOURCES = -FORMS = -SOURCES = main_singleapplication.cpp singleapplication.cpp -HEADERS = singleapplication.h diff --git a/manualtests/utils/squeezelabel/.gitignore b/manualtests/utils/squeezelabel/.gitignore deleted file mode 100644 index f6332511..00000000 --- a/manualtests/utils/squeezelabel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -squeezelabel diff --git a/manualtests/utils/squeezelabel/main_squeezelabel.cpp b/manualtests/utils/squeezelabel/main_squeezelabel.cpp deleted file mode 100644 index eb9c07d5..00000000 --- a/manualtests/utils/squeezelabel/main_squeezelabel.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include - -#include "squeezelabel.h" - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - - SqueezeLabel label; - if (application.arguments().count() > 1) - label.setText(application.arguments().value(1)); - else - label.setText("This is one long sentence that I will have to ponder the meaning of"); - label.show(); - label.resize(100, label.height()); - - return application.exec(); -} - diff --git a/manualtests/utils/squeezelabel/squeezelabel.pro b/manualtests/utils/squeezelabel/squeezelabel.pro deleted file mode 100644 index 502ba275..00000000 --- a/manualtests/utils/squeezelabel/squeezelabel.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) - -# Input -RESOURCES = -FORMS = -SOURCES = main_squeezelabel.cpp squeezelabel.cpp -HEADERS = squeezelabel.h diff --git a/manualtests/utils/treesortfilterproxymodel/.gitignore b/manualtests/utils/treesortfilterproxymodel/.gitignore deleted file mode 100644 index c3df39de..00000000 --- a/manualtests/utils/treesortfilterproxymodel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -treesortfilterproxymodel diff --git a/manualtests/utils/treesortfilterproxymodel/main_treesortfilterproxymodel.cpp b/manualtests/utils/treesortfilterproxymodel/main_treesortfilterproxymodel.cpp deleted file mode 100644 index 46c3ec83..00000000 --- a/manualtests/utils/treesortfilterproxymodel/main_treesortfilterproxymodel.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "treesortfilterproxymodel.h" -#include "ui_treesortfilterproxymodeldialog.h" - -#include -#include -#include - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - - QDialog dialog; - Ui_TreeSortFilterProxyModelDialog ui; - ui.setupUi(&dialog); - - TreeSortFilterProxyModel *proxy = new TreeSortFilterProxyModel(&dialog); - dialog.connect(ui.search, SIGNAL(textChanged(const QString &)), - proxy, SLOT(setFilterRegExp(const QString &))); - QDirModel *dirModel = new QDirModel(&dialog); - proxy->setSourceModel(dirModel); - ui.treeView->setModel(proxy); - ui.treeView->setRootIndex(proxy->mapFromSource(dirModel->index(QDir::homePath()))); - dialog.show(); - - return application.exec(); -} - diff --git a/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodel.pro b/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodel.pro deleted file mode 100644 index 8cba043b..00000000 --- a/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodel.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../../manualtests.pri) - -# Input -SOURCES = main_treesortfilterproxymodel.cpp treesortfilterproxymodel.cpp -HEADERS = treesortfilterproxymodel.h - -FORMS += treesortfilterproxymodeldialog.ui diff --git a/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodeldialog.ui b/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodeldialog.ui deleted file mode 100644 index 842cc4be..00000000 --- a/manualtests/utils/treesortfilterproxymodel/treesortfilterproxymodeldialog.ui +++ /dev/null @@ -1,27 +0,0 @@ - - - TreeSortFilterProxyModelDialog - - - - 0 - 0 - 400 - 300 - - - - Dialog - - - - - - - - - - - - - diff --git a/manualtests/utils/utils.pro b/manualtests/utils/utils.pro deleted file mode 100644 index 1f38ed5d..00000000 --- a/manualtests/utils/utils.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - editview \ - lineedit \ - singleapplication \ - squeezelabel \ - treesortfilterproxymodel - -CONFIG += ordered diff --git a/manualtests/webviewsearch/.gitignore b/manualtests/webviewsearch/.gitignore deleted file mode 100644 index 00a73b0f..00000000 --- a/manualtests/webviewsearch/.gitignore +++ /dev/null @@ -1 +0,0 @@ -webviewsearch diff --git a/manualtests/webviewsearch/main_webviewsearch.cpp b/manualtests/webviewsearch/main_webviewsearch.cpp deleted file mode 100644 index 1c3dfeef..00000000 --- a/manualtests/webviewsearch/main_webviewsearch.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2008 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include -#include -#include -#include - -#include "webviewsearch.h" - -class WebViewWSearch : public QWebView -{ - Q_OBJECT - -public: - WebViewWSearch(QWidget *parent = 0) : QWebView(parent) - { - } - -protected: - -void resizeEvent(QResizeEvent *event) -{ - int offset = event->size().height() - event->oldSize().height(); - int currentValue = page()->mainFrame()->scrollBarValue(Qt::Vertical); - setUpdatesEnabled(false); - page()->mainFrame()->setScrollBarValue(Qt::Vertical, currentValue - offset); - setUpdatesEnabled(true); - QWebView::resizeEvent(event); -} - -public slots: - void findText(const QString &text) { - findText(text); - } -}; - -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - QMainWindow mainWindow; - - - QWidget *window = new QWidget; - QVBoxLayout *layout = new QVBoxLayout; - layout->setSpacing(0); - layout->setContentsMargins(0, 0, 0, 0); - WebViewWSearch *webView = new WebViewWSearch(&mainWindow); - WebViewSearch *webViewSearch = new WebViewSearch(webView); - layout->addWidget(webViewSearch); - webView->load(QUrl("http://reddit.com")); - layout->addWidget(webView); - window->setLayout(layout); - mainWindow.setCentralWidget(window); - mainWindow.show(); - - QMenuBar bar; - QMenu *editMenu = bar.addMenu(("&Edit")); - QAction *m_find = editMenu->addAction(("&Find")); - m_find->setShortcuts(QKeySequence::Find); - QObject::connect(m_find, SIGNAL(triggered()), webViewSearch, SLOT(showFind())); - new QShortcut(QKeySequence(Qt::Key_Slash), webViewSearch, SLOT(showFind())); - - return application.exec(); -} - -#include "main_webviewsearch.moc" diff --git a/manualtests/webviewsearch/webviewsearch.pro b/manualtests/webviewsearch/webviewsearch.pro deleted file mode 100644 index c687d100..00000000 --- a/manualtests/webviewsearch/webviewsearch.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -include(../manualtests.pri) - -SOURCES += main_webviewsearch.cpp -HEADERS += diff --git a/src/.qmake.conf b/src/.qmake.conf deleted file mode 100644 index 7c1d952d..00000000 --- a/src/.qmake.conf +++ /dev/null @@ -1,2 +0,0 @@ -QMAKEPATH += /usr/local/opt/qtwebkit -QMAKE_MAC_SDK = macosx10.13 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 596521ee..2692c848 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,31 +1,13 @@ # Some common settings project(Endorphin) -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/adblock ${CMAKE_CURRENT_SOURCE_DIR}/bookmarks ${CMAKE_CURRENT_SOURCE_DIR}/bookmarks/xbel ${CMAKE_CURRENT_SOURCE_DIR}/data ${CMAKE_CURRENT_SOURCE_DIR}/history ${CMAKE_CURRENT_SOURCE_DIR}/htmls ${CMAKE_CURRENT_SOURCE_DIR}/locationbar ${CMAKE_CURRENT_SOURCE_DIR}/network ${CMAKE_CURRENT_SOURCE_DIR}/network/cookiejar ${CMAKE_CURRENT_SOURCE_DIR}/network/cookiejar/networkcookiejar ${CMAKE_CURRENT_SOURCE_DIR}/opensearch ${CMAKE_CURRENT_SOURCE_DIR}/qwebplugins ${CMAKE_CURRENT_SOURCE_DIR}/qwebplugins/clicktoflash ${CMAKE_CURRENT_SOURCE_DIR}/useragent ${CMAKE_CURRENT_SOURCE_DIR}/utils) +include(GNUInstallDirs) -find_package(Qt5Widgets REQUIRED) -find_package(Qt5Core REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5WebKit REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5WebKitWidgets REQUIRED) -find_package(Qt5PrintSupport REQUIRED) -find_package(Qt5UiTools) -find_package(Qt5LinguistTools REQUIRED) -find_package(Qt5Script REQUIRED) - -if(NOT Qt5UiTools_FOUND) - add_definitions(-DQT_NO_UITOOLS) -endif() set(EXECUTABLE_OUTPUT_PATH ../) -set(CMAKE_INCLUDE_CURRENT_DIR ON) +find_package(Qt5Widgets REQUIRED) # Get git information - execute_process(COMMAND git log -n1 --pretty=format:%h OUTPUT_VARIABLE GIT_REV ERROR_QUIET) @@ -39,197 +21,63 @@ endif() add_definitions(-DGITVERSION=\"\\\"${GIT_REV}\\\"\") add_definitions(-DGITCHANGENUMBER=${GIT_CHANGENUMBER}) -# Add all files -set(Endorphin_SRCS - aboutdialog.cpp - acceptlanguagedialog.cpp - autosaver.cpp - autofilldialog.cpp - autofillmanager.cpp - browserapplication.cpp - browsermainwindow.cpp - clearprivatedata.cpp - clearbutton.cpp - downloadmanager.cpp - modelmenu.cpp - modeltoolbar.cpp - plaintexteditsearch.cpp - searchbar.cpp - searchbutton.cpp - searchlineedit.cpp - settings.cpp - sourcehighlighter.cpp - sourceviewer.cpp - tabbar.cpp - tabwidget.cpp - toolbarsearch.cpp - webactionmapper.cpp - webpage.cpp - webview.cpp - webviewsearch.cpp - main.cpp - adblock/adblockblockednetworkreply.cpp - adblock/adblockdialog.cpp - adblock/adblockmanager.cpp - adblock/adblockmodel.cpp - adblock/adblocknetwork.cpp - adblock/adblockpage.cpp - adblock/adblockrule.cpp - adblock/adblockschemeaccesshandler.cpp - adblock/adblocksubscription.cpp - bookmarks/addbookmarkdialog.cpp - bookmarks/bookmarksdialog.cpp - bookmarks/bookmarksmanager.cpp - bookmarks/bookmarksmenu.cpp - bookmarks/bookmarksmodel.cpp - bookmarks/bookmarkstoolbar.cpp - bookmarks/bookmarknode.cpp - bookmarks/xbel/xbelreader.cpp - bookmarks/xbel/xbelwriter.cpp - history/history.cpp - history/historycompleter.cpp - history/historymanager.cpp - locationbar/locationbar.cpp - locationbar/locationbarsiteicon.cpp - locationbar/privacyindicator.cpp - network/fileaccesshandler.cpp - network/networkaccessmanager.cpp - network/networkdiskcache.cpp - network/networkproxyfactory.cpp - network/schemeaccesshandler.cpp - network/cookiejar/cookiedialog.cpp - network/cookiejar/cookieexceptionsmodel.cpp - network/cookiejar/cookiemodel.cpp - network/cookiejar/cookieexceptionsdialog.cpp - network/cookiejar/cookiejar.cpp - network/cookiejar/networkcookiejar/networkcookiejar.cpp - opensearch/opensearchdialog.cpp - opensearch/opensearchengine.cpp - opensearch/opensearchenginedelegate.cpp - opensearch/opensearchengineaction.cpp - opensearch/opensearchenginemodel.cpp - opensearch/opensearchmanager.cpp - opensearch/opensearchreader.cpp - opensearch/opensearchwriter.cpp - qwebplugins/endorphinwebplugin.cpp - qwebplugins/webpluginfactory.cpp - useragent/useragentmenu.cpp - utils/editlistview.cpp - utils/edittableview.cpp - utils/edittreeview.cpp - utils/languagemanager.cpp - utils/lineedit.cpp - utils/networkaccessmanagerproxy.cpp - utils/singleapplication.cpp - utils/squeezelabel.cpp - utils/treesortfilterproxymodel.cpp - utils/webpageproxy.cpp -) -set(Endorphin_UIS - aboutdialog.ui - autofilldialog.ui - acceptlanguagedialog.ui - downloaditem.ui - downloads.ui - searchbanner.ui - settings.ui - adblock/adblockdialog.ui - bookmarks/addbookmarkdialog.ui - bookmarks/bookmarksdialog.ui - history/history.ui - network/passworddialog.ui - network/proxy.ui - network/cookiejar/cookies.ui - network/cookiejar/cookiesexceptions.ui - opensearch/opensearchdialog.ui +# Translations +qt5_create_translation(QM_FILES +${ENDORPHIN_SRCS} +${CMAKE_CURRENT_SOURCE_DIR}/locale/ast.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ca.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ast.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ca.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/cs_CZ.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/da_DK.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/de_DE.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/el_GR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/es.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/es_CR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/et_EE.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/fi_FI.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/fr_CA.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/fr_FR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/gl.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/he_IL.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/hu_HU.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/it_IT.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ja_JP.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ko_KR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ms.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/nb_NO.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/nl.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/pl_PL.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/pt_PT.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/pt_BR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/ru_RU.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/sk_SK.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/sr_RS.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/sr_RS@latin.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/tr_TR.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/uk.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/zh_CN.ts +${CMAKE_CURRENT_SOURCE_DIR}/locale/zh_TW.ts ) -QT5_WRAP_UI(UIS ${Endorphin_UIS}) -set(Endorphin_RSCS - data/data.qrc - data/graphics/graphics.qrc - data/searchengines/searchengines.qrc - htmls/htmls.qrc - useragent/useragents.qrc -) -QT5_ADD_RESOURCES(RSCS ${Endorphin_RSCS}) +# Generate executable +add_executable(endorphin main.cpp ${TRS}) +target_link_libraries(endorphin Qt5::Widgets endorphin-base) -set(Endorphin_MOCS - aboutdialog.h - acceptlanguagedialog.h - autosaver.h - autofilldialog.h - autofillmanager.h - browserapplication.h - browsermainwindow.h - clearprivatedata.h - clearbutton.h - downloadmanager.h - modelmenu.h - modeltoolbar.h - plaintexteditsearch.h - searchbar.h - searchbutton.h - searchlineedit.h - settings.h - sourcehighlighter.h - sourceviewer.h - tabbar.h - tabwidget.h - toolbarsearch.h - webactionmapper.h - webpage.h - webview.h - webviewsearch.h -) -QT5_WRAP_CPP(MOCS ${Endorphin_MOCS}) -# Translations -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ast.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ca.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/cs_CZ.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/da_DK.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/de_DE.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/el_GR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/es.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/es_CR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/et_EE.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/fi_FI.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/fr_CA.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/fr_FR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/gl.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/he_IL.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/hu_HU.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/it_IT.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ja_JP.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ko_KR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ms.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/nb_NO.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/nl.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/pl_PL.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/pt_PT.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/pt_BR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/ru_RU.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/sk_SK.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/sr_RS.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/sr_RS@latin.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/tr_TR.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/uk.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/zh_CN.ts) -qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR}/locale/zh_TW.ts) +if(NOT QT_TRANSLATIONS_DIR) +get_target_property(QT5_QMAKE_EXECUTABLE Qt5::qmake IMPORTED_LOCATION) +execute_process( COMMAND ${QT5_QMAKE_EXECUTABLE} -query QT_INSTALL_TRANSLATIONS +OUTPUT_VARIABLE qt_translations_dir OUTPUT_STRIP_TRAILING_WHITESPACE ) +file( TO_CMAKE_PATH "${qt_translations_dir}" qt_translations_dir) +set( QT_TRANSLATIONS_DIR ${qt_translations_dir} CACHE PATH +"The location of the Qt translations" FORCE) +endif() -# Generate executable -add_executable(endorphin ${Endorphin_SRCS} ${UIS} ${RSCS} ${TRS} ${MOCS} ${QM_FILES}) -qt5_use_modules(endorphin Widgets) -qt5_use_modules(endorphin Core) -qt5_use_modules(endorphin Gui) -qt5_use_modules(endorphin WebKit) -qt5_use_modules(endorphin Network) -qt5_use_modules(endorphin WebKitWidgets) -qt5_use_modules(endorphin PrintSupport) +install(FILES ${QM_FILES} +DESTINATION ${CMAKE_INSTALL_BINDIR}/endorphin_locale/) -if(Qt5UiTools_FOUND) - qt5_use_modules(endorphin UiTools) -endif() -qt5_use_modules(endorphin Script) +install(TARGETS endorphin + DESTINATION ${CMAKE_INSTALL_BINDIR} +) diff --git a/src/aboutdialog.cpp b/src/aboutdialog.cpp index 036ea72f..e498b3c9 100644 --- a/src/aboutdialog.cpp +++ b/src/aboutdialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Matvey Kozhev * * This program is free software; you can redistribute it and/or modify @@ -20,29 +20,25 @@ #include "aboutdialog.h" -#include -#include -#include -#include -#include -#include - -#include -#include +#include +#include +#include +#include +#include +#include +#include AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("About %1").arg(qApp->applicationName())); - logo->setPixmap(qApp->windowIcon().pixmap(128, 128)); name->setText(qApp->applicationName()); version->setText(qApp->applicationVersion()); - webkitVersion->setText(tr("WebKit version: %1").arg(qWebKitVersion())); - connect(authorsButton, SIGNAL(clicked()), - this, SLOT(authorsButtonClicked())); - connect(licenseButton, SIGNAL(clicked()), - this, SLOT(licenseButtonClicked())); + connect(authorsButton, &QPushButton::clicked, + this, &AboutDialog::authorsButtonClicked); + connect(licenseButton, &QPushButton::clicked, + this, &AboutDialog::licenseButtonClicked); } void AboutDialog::displayFile(const QString &fileName, const QString &title) @@ -62,10 +58,10 @@ void AboutDialog::displayFile(const QString &fileName, const QString &title) stream.setCodec("UTF-8"); QString text = stream.readAll(); // this is done to force the content of the text editor to be LTR, and monospaced. - textEdit.setHtml(QString(QLatin1String("
%1
")).arg(text)); + textEdit.setHtml(QString(QStringLiteral("
%1
")).arg(text)); textEdit.setReadOnly(true); - connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(close())); + connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::close); buttonBox.setCenterButtons(true); layout.addWidget(&textEdit); layout.addWidget(&buttonBox); @@ -74,17 +70,17 @@ void AboutDialog::displayFile(const QString &fileName, const QString &title) dialog.setLayout(&layout); dialog.setWindowTitle(title); dialog.setWindowFlags(Qt::Sheet); - dialog.resize(600, 350); + dialog.resize(650, 400); dialog.exec(); } void AboutDialog::authorsButtonClicked() { - displayFile(QLatin1String(":AUTHORS"), tr("Authors")); + displayFile(QStringLiteral(":AUTHORS"), tr("Authors")); } void AboutDialog::licenseButtonClicked() { - displayFile(QLatin1String(":LICENSE.GPL2"), tr("License")); + displayFile(QStringLiteral(":LICENSE"), tr("License")); } diff --git a/src/aboutdialog.h b/src/aboutdialog.h index d58f9341..89aca529 100644 --- a/src/aboutdialog.h +++ b/src/aboutdialog.h @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef ABOUTDIALOG_H #define ABOUTDIALOG_H -#include +#include #include "ui_aboutdialog.h" class AboutDialog : public QDialog, private Ui_AboutDialog @@ -28,9 +28,9 @@ class AboutDialog : public QDialog, private Ui_AboutDialog Q_OBJECT public: - AboutDialog(QWidget *parent = 0); + AboutDialog(QWidget *parent = nullptr); -private slots: +private Q_SLOTS: void authorsButtonClicked(); void licenseButtonClicked(); diff --git a/src/aboutdialog.ui b/src/aboutdialog.ui index 03523702..1cf5d5e2 100644 --- a/src/aboutdialog.ui +++ b/src/aboutdialog.ui @@ -6,201 +6,200 @@ 0 0 - 450 - 253 + 760 + 515 true - - - - - - 0 - 0 - - - - - - - false - - - Qt::AlignCenter - - - - - - - - 0 - 0 - - - - - 16 - 75 - true - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - 0 - 0 - - - - - 12 - 50 - false - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - 0 - 0 - - - - - 11 - 50 - false - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Lightweight WebKit-based web browser - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - 0 - 0 - - - - <html><head/><body><p><span style=" font-size:9pt;">Copyright © 2020 Aaron Dewes &lt; </span><a href="mailto:aaron.dewes@web.de"><span style=" font-size:9pt; text-decoration: underline; color:#0000ff;">aaron.dewes@web.de</span></a><span style=" font-size:9pt;">&gt; </span></p></body></html> - - - Qt::AlignCenter - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Authors - - - - - - - License - - - - - - - Close - - - true - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - + + + + 450 + 0 + 520 + 530 + + + + + 0 + 0 + + + + img { +height: 1000px +} + + + + + + :/512x512/endorphin.png + + + false + + + Qt::AlignCenter + + + + + + 10 + 10 + 441 + 501 + + + + + + + + 0 + 0 + + + + + 40 + 75 + true + + + + Name + + + Qt::AlignCenter + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + + true + + + + Qt::NoFocus + + + Close + + + false + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::NoFocus + + + License + + + + + + + + 0 + 0 + + + + + 12 + 50 + false + + + + Version + + + Qt::AlignCenter + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + Lightweight WebKit-based web browser + + + Qt::AlignCenter + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + Qt::NoFocus + + + Authors + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + diff --git a/src/acceptlanguagedialog.cpp b/src/acceptlanguagedialog.cpp index fe7c952b..dab380f9 100644 --- a/src/acceptlanguagedialog.cpp +++ b/src/acceptlanguagedialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,17 +22,18 @@ #include "browserapplication.h" #include "languagemanager.h" -#include -#include +#include +#include +#include AcceptLanguageDialog::AcceptLanguageDialog(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags) { setupUi(this); - connect(addButton, SIGNAL(clicked()), this, SLOT(addLanguage())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeLanguage())); - connect(moveUpButton, SIGNAL(clicked()), this, SLOT(moveLanguageUp())); - connect(moveDownButton, SIGNAL(clicked()), this, SLOT(moveLanguageDown())); + connect(addButton, &QPushButton::clicked, this, &AcceptLanguageDialog::addLanguage); + connect(removeButton, &QPushButton::clicked, this, &AcceptLanguageDialog::removeLanguage); + connect(moveUpButton, &QPushButton::clicked, this, &AcceptLanguageDialog::moveLanguageUp); + connect(moveDownButton, &QPushButton::clicked, this, &AcceptLanguageDialog::moveLanguageDown); listView->setModel(&m_model); connect(listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentChanged(const QModelIndex &, const QModelIndex &))); @@ -52,14 +53,14 @@ QStringList AcceptLanguageDialog::expand(const QLocale::Language language) for (int j = 0; j < countries.size(); ++j) { QString languageString; if (countries.count() == 1) { - languageString = QString(QLatin1String("%1 [%2]")) - .arg(QLocale::languageToString(language)) - .arg(QLocale(language).name().split(QLatin1Char('_')).at(0)); + languageString = QString(QStringLiteral("%1 [%2]")) + .arg(QLocale::languageToString(language), + QLocale(language).name().split(QChar('_')).at(0)); } else { - languageString = QString(QLatin1String("%1/%2 [%3]")) - .arg(QLocale::languageToString(language)) - .arg(QLocale::countryToString(countries.at(j))) - .arg(QLocale(language, countries.at(j)).name().split(QLatin1Char('_')).join(QLatin1String("-")).toLower()); + languageString = QString(QStringLiteral("%1/%2 [%3]")) + .arg(QLocale::languageToString(language), + QLocale::countryToString(countries.at(j)), + QLocale(language, countries.at(j)).name().replace('_', "-").toLower()); } if (!allLanguages.contains(languageString)) @@ -94,19 +95,19 @@ void AcceptLanguageDialog::accept() void AcceptLanguageDialog::load() { QSettings settings; - settings.beginGroup(QLatin1String("network")); - m_model.setStringList(settings.value(QLatin1String("acceptLanguages"), defaultAcceptList()).toStringList()); + settings.beginGroup(QStringLiteral("network")); + m_model.setStringList(settings.value(QStringLiteral("acceptLanguages"), defaultAcceptList()).toStringList()); } void AcceptLanguageDialog::save() { QSettings settings; - settings.beginGroup(QLatin1String("network")); + settings.beginGroup(QStringLiteral("network")); QStringList result = m_model.stringList(); if (result == defaultAcceptList() || result.isEmpty()) - settings.remove(QLatin1String("acceptLanguages")); + settings.remove(QStringLiteral("acceptLanguages")); else - settings.setValue(QLatin1String("acceptLanguages"), result); + settings.setValue(QStringLiteral("acceptLanguages"), result); } /* @@ -118,19 +119,19 @@ QByteArray AcceptLanguageDialog::httpString(const QStringList &list) { QStringList processed; qreal qvalue = 1.0; - foreach (const QString &string, list) { - int leftBracket = string.indexOf(QLatin1Char('[')); - int rightBracket = string.indexOf(QLatin1Char(']')); + Q_FOREACH (const QString &string, list) { + int leftBracket = string.indexOf(QChar('[')); + int rightBracket = string.indexOf(QChar(']')); QString tag = string.mid(leftBracket + 1, rightBracket - leftBracket - 1); if (processed.isEmpty()) { processed << tag; } else { - processed << QString(QLatin1String("%1; %2")).arg(tag).arg(QString::number(qvalue, 'f', 1)); + processed << QString(QStringLiteral("%1; %2")).arg(tag, QString::number(qvalue, 'f', 1)); } if (qvalue > .1) qvalue -= .1; } - return processed.join(QLatin1String(", ")).toLatin1(); + return processed.join(QStringLiteral(", ")).toLatin1(); } void AcceptLanguageDialog::moveLanguageUp() diff --git a/src/acceptlanguagedialog.h b/src/acceptlanguagedialog.h index 00afea26..141e0344 100644 --- a/src/acceptlanguagedialog.h +++ b/src/acceptlanguagedialog.h @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef ACCEPTLANGUAGEDIALOG_H #define ACCEPTLANGUAGEDIALOG_H -#include +#include #include "ui_acceptlanguagedialog.h" #include @@ -30,12 +30,12 @@ class AcceptLanguageDialog : public QDialog, public Ui_AcceptLanguage Q_OBJECT public: - AcceptLanguageDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0); + AcceptLanguageDialog(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); void accept(); static QByteArray httpString(const QStringList &list); static QStringList defaultAcceptList(); -private slots: +private Q_SLOTS: void load(); void save(); diff --git a/src/acceptlanguagedialog.ui b/src/acceptlanguagedialog.ui index aae65afe..b6eaab89 100644 --- a/src/acceptlanguagedialog.ui +++ b/src/acceptlanguagedialog.ui @@ -1,139 +1,142 @@ - - AcceptLanguage - - - - 0 - 0 - 397 - 251 - - - - Languages - - - - - - Languages: in order of preference: - - - true - - - - - - - false - - - Move &Up - - - - - - - false - - - Move &Down - - - - - - - false - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 38 - - - - - - - - - - - Add... - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - listView - moveUpButton - moveDownButton - removeButton - addComboBox - addButton - buttonBox - - - - - buttonBox - accepted() - AcceptLanguage - accept() - - - 227 - 228 - - - 157 - 250 - - - - - buttonBox - rejected() - AcceptLanguage - reject() - - - 295 - 234 - - - 286 - 250 - - - - - + + AcceptLanguage + + + + 0 + 0 + 397 + 251 + + + + Languages + + + + + + Languages: in order of preference: + + + true + + + + + + + false + + + Move & +Up + + + + + + + false + + + Move & +Down + + + + + + + false + + + & +Remove + + + + + + + Qt::Vertical + + + + 20 + 38 + + + + + + + + + + + Add... + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + listView + moveUpButton + moveDownButton + removeButton + addComboBox + addButton + buttonBox + + + + + buttonBox + accepted() + AcceptLanguage + accept() + + + 227 + 228 + + + 157 + 250 + + + + + buttonBox + rejected() + AcceptLanguage + reject() + + + 295 + 234 + + + 286 + 250 + + + + + diff --git a/src/adblock/adblock.pri b/src/adblock/adblock.pri deleted file mode 100644 index 9cce5388..00000000 --- a/src/adblock/adblock.pri +++ /dev/null @@ -1,29 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD - -VPATH += $$PWD - -HEADERS += \ - adblockblockednetworkreply.h \ - adblockdialog.h \ - adblockmanager.h \ - adblockmodel.h \ - adblocknetwork.h \ - adblockpage.h \ - adblockrule.h \ - adblockschemeaccesshandler.h \ - adblocksubscription.h - -SOURCES += \ - adblockblockednetworkreply.cpp \ - adblockdialog.cpp \ - adblockmanager.cpp \ - adblockmodel.cpp \ - adblocknetwork.cpp \ - adblockpage.cpp \ - adblockrule.cpp \ - adblockschemeaccesshandler.cpp \ - adblocksubscription.cpp - -FORMS += \ - adblockdialog.ui diff --git a/src/adblock/adblockblockednetworkreply.cpp b/src/adblock/adblockblockednetworkreply.cpp deleted file mode 100644 index 510525ff..00000000 --- a/src/adblock/adblockblockednetworkreply.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockblockednetworkreply.h" - -#include "adblockrule.h" - -#include -#include - -AdBlockBlockedNetworkReply::AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule *rule, QObject *parent) - : QNetworkReply(parent) -{ - setOperation(QNetworkAccessManager::GetOperation); - setRequest(request); - setUrl(request.url()); - setError(QNetworkReply::ContentAccessDenied, tr("Blocked by AdBlockRule: %1").arg(rule->filter())); - QTimer::singleShot(0, this, SLOT(delayedFinished())); -} - -qint64 AdBlockBlockedNetworkReply::readData(char *data, qint64 maxSize) -{ - Q_UNUSED(data); - Q_UNUSED(maxSize); - return -1; -} - -void AdBlockBlockedNetworkReply::delayedFinished() -{ - emit error(QNetworkReply::ContentAccessDenied); - emit finished(); -} - diff --git a/src/adblock/adblockblockednetworkreply.h b/src/adblock/adblockblockednetworkreply.h deleted file mode 100644 index b9914df7..00000000 --- a/src/adblock/adblockblockednetworkreply.h +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKBLOCKEDNETWORKREPLY_H -#define ADBLOCKBLOCKEDNETWORKREPLY_H - -#include - -class AdBlockRule; -class AdBlockBlockedNetworkReply : public QNetworkReply -{ - Q_OBJECT - -public: - AdBlockBlockedNetworkReply(const QNetworkRequest &request, const AdBlockRule *rule, QObject *parent = 0); - void abort() {}; - -protected: - qint64 readData(char *data, qint64 maxSize); - -private slots: - void delayedFinished(); - -}; - -#endif // ADBLOCKBLOCKEDNETWORKREPLY_H - diff --git a/src/adblock/adblockdialog.cpp b/src/adblock/adblockdialog.cpp deleted file mode 100644 index a9d66857..00000000 --- a/src/adblock/adblockdialog.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockdialog.h" - -#include "adblockmodel.h" -#include "adblockmanager.h" -#include "adblocksubscription.h" -#include "treesortfilterproxymodel.h" - -#include -#include -#include - -#include - -AdBlockDialog::AdBlockDialog(QWidget *parent) - : QDialog(parent) -{ - setupUi(this); - m_adBlockModel = new AdBlockModel(this); - m_proxyModel = new TreeSortFilterProxyModel(this); - m_proxyModel->setSourceModel(m_adBlockModel); - treeView->setModel(m_proxyModel); - connect(search, SIGNAL(textChanged(QString)), - m_proxyModel, SLOT(setFilterFixedString(QString))); - - AdBlockManager *manager = AdBlockManager::instance(); - adblockCheckBox->setChecked(manager->isEnabled()); - connect(adblockCheckBox, SIGNAL(toggled(bool)), - AdBlockManager::instance(), SLOT(setEnabled(bool))); - - QMenu *menu = new QMenu(this); - connect(menu, SIGNAL(aboutToShow()), - this, SLOT(aboutToShowActionMenu())); - actionToolButton->setMenu(menu); - actionToolButton->setIcon(QIcon(QLatin1String(":128x128/run.png"))); - actionToolButton->setPopupMode(QToolButton::InstantPopup); - - AdBlockSubscription *subscription = manager->customRules(); - QModelIndex subscriptionIndex = m_adBlockModel->index(subscription); - treeView->expand(m_proxyModel->mapFromSource(subscriptionIndex)); -} - -void AdBlockDialog::aboutToShowActionMenu() -{ - QMenu *menu = actionToolButton->menu(); - menu->clear(); - - QAction *addRule = menu->addAction(tr("Add Custom Rule")); - connect(addRule, SIGNAL(triggered()), this, SLOT(addCustomRule())); - - QAction *learnRule = menu->addAction(tr("Learn more about writing rules...")); - connect(learnRule, SIGNAL(triggered()), this, SLOT(learnAboutWritingFilters())); - - menu->addSeparator(); - - QModelIndex idx = m_proxyModel->mapToSource(treeView->currentIndex()); - - QAction *updateSubscription = menu->addAction(tr("Update Subscription")); - connect(updateSubscription, SIGNAL(triggered()), this, SLOT(updateSubscription())); - if (!idx.isValid()) - updateSubscription->setEnabled(false); - - QAction *addSubscription = menu->addAction(tr("Browse Subscriptions...")); - connect(addSubscription, SIGNAL(triggered()), this, SLOT(browseSubscriptions())); - - menu->addSeparator(); - - QAction *removeSubscription = menu->addAction(tr("Remove Subscription")); - connect(removeSubscription, SIGNAL(triggered()), this, SLOT(removeSubscription())); - if (!idx.isValid()) - removeSubscription->setEnabled(false); -} - -void AdBlockDialog::addCustomRule(const QString &rule) -{ - AdBlockManager *manager = AdBlockManager::instance(); - AdBlockSubscription *subscription = manager->customRules(); - Q_ASSERT(subscription); - subscription->addRule(AdBlockRule(rule)); - // reset the model - qApp->processEvents(); - - QModelIndex parent = m_adBlockModel->index(subscription); - int x = m_adBlockModel->rowCount(parent); - QModelIndex ruleIndex = m_adBlockModel->index(x - 1, 0, parent); - treeView->expand(m_proxyModel->mapFromSource(parent)); - treeView->edit(m_proxyModel->mapFromSource(ruleIndex)); -} - -void AdBlockDialog::updateSubscription() -{ - QModelIndex idx = m_proxyModel->mapToSource(treeView->currentIndex()); - if (!idx.isValid()) - return; - if (idx.parent().isValid()) - idx = idx.parent(); - AdBlockSubscription *subscription = (AdBlockSubscription*)m_adBlockModel->subscription(idx); - subscription->updateNow(); -} - -void AdBlockDialog::browseSubscriptions() -{ - QUrl url(QLatin1String("http://adblockplus.org/en/subscriptions")); - QDesktopServices::openUrl(url); -} - -void AdBlockDialog::learnAboutWritingFilters() -{ - QUrl url(QLatin1String("http://adblockplus.org/en/filters")); - QDesktopServices::openUrl(url); -} - -void AdBlockDialog::removeSubscription() -{ - QModelIndex idx = m_proxyModel->mapToSource(treeView->currentIndex()); - if (!idx.isValid()) - return; - if (idx.parent().isValid()) - idx = idx.parent(); - AdBlockSubscription *subscription = (AdBlockSubscription*)m_adBlockModel->subscription(idx); - AdBlockManager::instance()->removeSubscription(subscription); -} - diff --git a/src/adblock/adblockdialog.h b/src/adblock/adblockdialog.h deleted file mode 100644 index 9f0971f8..00000000 --- a/src/adblock/adblockdialog.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKDIALOG_H -#define ADBLOCKDIALOG_H - -#include -#include "ui_adblockdialog.h" - -class AdBlockModel; -class TreeSortFilterProxyModel; -class AdBlockDialog : public QDialog, public Ui_AdBlockDialog -{ - Q_OBJECT - -public: - AdBlockDialog(QWidget *parent = 0); - -public slots: - void addCustomRule(const QString &rule = QString()); - -private slots: - void learnAboutWritingFilters(); - void aboutToShowActionMenu(); - void updateSubscription(); - void browseSubscriptions(); - void removeSubscription(); - -private: - AdBlockModel *m_adBlockModel; - TreeSortFilterProxyModel *m_proxyModel; - -}; - -#endif // ADBLOCKDIALOG_H - diff --git a/src/adblock/adblockdialog.ui b/src/adblock/adblockdialog.ui deleted file mode 100644 index b4fd9641..00000000 --- a/src/adblock/adblockdialog.ui +++ /dev/null @@ -1,153 +0,0 @@ - - - AdBlockDialog - - - - 0 - 0 - 483 - 487 - - - - AdBlock Configuration - - - - - - Enable AdBlock - - - true - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Ok - - - - - - - true - - - - 0 - - - - - Qt::Horizontal - - - - 398 - 23 - - - - - - - - - - - - - - Action - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - SearchLineEdit - QLineEdit -
searchlineedit.h
-
- - EditTreeView - QTreeView -
edittreeview.h
-
-
- - - - buttonBox - accepted() - AdBlockDialog - accept() - - - 75 - 495 - - - 157 - 274 - - - - - buttonBox - rejected() - AdBlockDialog - reject() - - - 75 - 495 - - - 286 - 274 - - - - - adblockCheckBox - toggled(bool) - adblockWidget - setEnabled(bool) - - - 106 - 39 - - - 349 - 74 - - - - -
diff --git a/src/adblock/adblockmanager.cpp b/src/adblock/adblockmanager.cpp deleted file mode 100644 index f0a0b426..00000000 --- a/src/adblock/adblockmanager.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockmanager.h" - -#include "autosaver.h" -#include "adblockdialog.h" -#include "adblocknetwork.h" -#include "adblockpage.h" -#include "adblocksubscription.h" -#include "browserapplication.h" -#include "networkaccessmanager.h" - -#include -#include - -#include - -// #define ADBLOCKMANAGER_DEBUG - -AdBlockManager *AdBlockManager::s_adBlockManager = 0; - -AdBlockManager::AdBlockManager(QObject *parent) - : QObject(parent) - , m_loaded(false) - , m_enabled(true) - , m_saveTimer(new AutoSaver(this)) - , m_adBlockDialog(0) - , m_adBlockNetwork(0) - , m_adBlockPage(0) -{ - connect(this, SIGNAL(rulesChanged()), - m_saveTimer, SLOT(changeOccurred())); -} - -AdBlockManager::~AdBlockManager() -{ - m_saveTimer->saveIfNeccessary(); -} - -AdBlockManager *AdBlockManager::instance() -{ - if (!s_adBlockManager) { - // Set a parent that will delete us before the application exits - s_adBlockManager = new AdBlockManager(BrowserApplication::networkAccessManager()); - } - return s_adBlockManager; -} - -bool AdBlockManager::isEnabled() const -{ - if (!m_loaded) { - AdBlockManager *that = const_cast(this); - that->load(); - } - return m_enabled; -} - -void AdBlockManager::setEnabled(bool enabled) -{ - if (isEnabled() == enabled) - return; - emit rulesGoingToChange(); - m_enabled = enabled; - emit rulesChanged(); -} - -AdBlockNetwork *AdBlockManager::network() -{ - if (!m_adBlockNetwork) - m_adBlockNetwork = new AdBlockNetwork(this); - return m_adBlockNetwork; -} - -AdBlockPage *AdBlockManager::page() -{ - if (!m_adBlockPage) - m_adBlockPage = new AdBlockPage(this); - return m_adBlockPage; -} - -static QUrl customSubscriptionLocation() -{ - QString fileName = BrowserApplication::dataFilePath(QLatin1String("adblock_subscription_custom")); - return QUrl::fromLocalFile(fileName); -} - -QUrl AdBlockManager::customSubscriptionUrl() -{ - QUrl location = customSubscriptionLocation(); - QString encodedUrl = QString::fromUtf8(location.toEncoded()); - QUrl url(QString(QLatin1String("abp:subscribe?location=%1&title=%2")) - .arg(encodedUrl) - .arg(tr("Custom Rules"))); - return url; -} - -AdBlockSubscription *AdBlockManager::customRules() -{ - QUrl location = customSubscriptionLocation(); - foreach (AdBlockSubscription *subscription, m_subscriptions) { - if (subscription->location() == location) - return subscription; - } - QUrl url = customSubscriptionUrl(); - AdBlockSubscription *customAdBlockSubscription = new AdBlockSubscription(url, this); - addSubscription(customAdBlockSubscription); - return customAdBlockSubscription; -} - -QList AdBlockManager::subscriptions() const -{ - if (!m_loaded) { - AdBlockManager *that = const_cast(this); - that->load(); - } - return m_subscriptions; -} - -void AdBlockManager::removeSubscription(AdBlockSubscription *subscription) -{ - if (!subscription) - return; -#if defined(ADBLOCKMANAGER_DEBUG) - qDebug() << "AdBlockManager::" << __FUNCTION__ << subscription->location(); -#endif - m_saveTimer->saveIfNeccessary(); - emit rulesGoingToChange(); - m_subscriptions.removeOne(subscription); - if (subscription->parent() == this) - subscription->deleteLater(); - emit rulesChanged(); -} - -void AdBlockManager::addSubscription(AdBlockSubscription *subscription) -{ - if (!subscription) - return; -#if defined(ADBLOCKMANAGER_DEBUG) - qDebug() << "AdBlockManager::" << __FUNCTION__ << subscription->location(); -#endif - emit rulesGoingToChange(); - m_subscriptions.append(subscription); - connect(subscription, SIGNAL(goingToChange()), this, SIGNAL(rulesGoingToChange())); - connect(subscription, SIGNAL(rulesChanged()), this, SIGNAL(rulesChanged())); - connect(subscription, SIGNAL(changed()), this, SIGNAL(rulesChanged())); - emit rulesChanged(); -} - -void AdBlockManager::save() -{ -#if defined(ADBLOCKMANAGER_DEBUG) - qDebug() << "AdBlockManager::" << __FUNCTION__ << m_loaded; -#endif - if (!m_loaded) - return; - - QSettings settings; - settings.beginGroup(QLatin1String("AdBlock")); - settings.setValue(QLatin1String("enabled"), m_enabled); - QStringList subscriptions; - foreach (AdBlockSubscription *subscription, m_subscriptions) { - if (!subscription) - continue; - subscriptions.append(QString::fromUtf8(subscription->url().toEncoded())); - subscription->saveRules(); - } - settings.setValue(QLatin1String("subscriptions"), subscriptions); -} - -void AdBlockManager::load() -{ -#if defined(ADBLOCKMANAGER_DEBUG) - qDebug() << "AdBlockManager::" << __FUNCTION__ << m_loaded; -#endif - - if (m_loaded) - return; - m_loaded = true; - - QSettings settings; - settings.beginGroup(QLatin1String("AdBlock")); - m_enabled = settings.value(QLatin1String("enabled"), m_enabled).toBool(); - - QStringList defaultSubscriptions; - defaultSubscriptions.append(QString::fromUtf8(customSubscriptionUrl().toEncoded())); - defaultSubscriptions.append(QLatin1String("abp:subscribe?location=http://adblockplus.mozdev.org/easylist/easylist.txt&title=EasyList")); - - QStringList subscriptions = settings.value(QLatin1String("subscriptions"), defaultSubscriptions).toStringList(); - foreach (const QString &subscription, subscriptions) { - QUrl url = QUrl::fromEncoded(subscription.toUtf8()); - AdBlockSubscription *adBlockSubscription = new AdBlockSubscription(url, this); - connect(adBlockSubscription, SIGNAL(goingToChange()), this, SIGNAL(rulesGoingToChange())); - connect(adBlockSubscription, SIGNAL(rulesChanged()), this, SIGNAL(rulesChanged())); - connect(adBlockSubscription, SIGNAL(changed()), this, SIGNAL(rulesChanged())); - m_subscriptions.append(adBlockSubscription); - } -} - -AdBlockDialog *AdBlockManager::showDialog() -{ - if (!m_adBlockDialog) { - m_adBlockDialog = new AdBlockDialog(0); - m_adBlockDialog->setAttribute(Qt::WA_DeleteOnClose, true); - } - m_adBlockDialog->show(); - return m_adBlockDialog; -} - diff --git a/src/adblock/adblockmanager.h b/src/adblock/adblockmanager.h deleted file mode 100644 index 462a9a08..00000000 --- a/src/adblock/adblockmanager.h +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKMANAGER_H -#define ADBLOCKMANAGER_H - -#include - -#include - -class QUrl; -class AutoSaver; -class AdBlockDialog; -class AdBlockNetwork; -class AdBlockPage; -class AdBlockSubscription; -class AdBlockManager : public QObject -{ - Q_OBJECT - -signals: - void rulesGoingToChange(); - void rulesChanged(); - -public: - AdBlockManager(QObject *parent = 0); - ~AdBlockManager(); - - void load(); - - static AdBlockManager *instance(); - bool isEnabled() const; - - QList subscriptions() const; - void removeSubscription(AdBlockSubscription *subscription); - void addSubscription(AdBlockSubscription *subscription); - - AdBlockNetwork *network(); - AdBlockPage *page(); - AdBlockSubscription *customRules(); - -public slots: - void setEnabled(bool enabled); - AdBlockDialog *showDialog(); - -private slots: - void save(); - -private: - static QUrl customSubscriptionUrl(); - static AdBlockManager *s_adBlockManager; - - bool m_loaded; - bool m_enabled; - AutoSaver *m_saveTimer; - QPointer m_adBlockDialog; - AdBlockNetwork *m_adBlockNetwork; - AdBlockPage *m_adBlockPage; - QList m_subscriptions; - -}; - -#endif // ADBLOCKMANAGER_H - diff --git a/src/adblock/adblockmodel.cpp b/src/adblock/adblockmodel.cpp deleted file mode 100644 index 6c96ce3b..00000000 --- a/src/adblock/adblockmodel.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockmodel.h" - -#include "adblockrule.h" -#include "adblocksubscription.h" -#include "adblockmanager.h" - -AdBlockModel::AdBlockModel(QObject *parent) - : QAbstractItemModel(parent) - , m_manager(AdBlockManager::instance()) -{ - connect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - connect(m_manager, SIGNAL(rulesGoingToChange()), this, SLOT(rulesGoingToChange())); -} - -void AdBlockModel::rulesGoingToChange() -{ - beginResetModel(); -} - -void AdBlockModel::rulesChanged() -{ - endResetModel(); -} - -const AdBlockRule AdBlockModel::rule(const QModelIndex &index) const -{ - const AdBlockSubscription *parent = static_cast(index.internalPointer()); - Q_ASSERT(parent); - return parent->allRules().at(index.row()); -} - -AdBlockSubscription *AdBlockModel::subscription(const QModelIndex &index) const -{ - const AdBlockSubscription *parent = static_cast(index.internalPointer()); - if (parent) - return 0; - int row = index.row(); - if (row < 0 || row >= m_manager->subscriptions().count()) - return 0; - return m_manager->subscriptions().at(row); -} - -QModelIndex AdBlockModel::index(AdBlockSubscription *subscription) -{ - int row = m_manager->subscriptions().indexOf(subscription); - if (row < 0 || row >= m_manager->subscriptions().count()) - return QModelIndex(); - return createIndex(row, 0, (void*) 0); -} - -QVariant AdBlockModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - switch (section) { - case 0: return tr("Rule"); - } - } - return QAbstractItemModel::headerData(section, orientation, role); -} - -QVariant AdBlockModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid() - || index.model() != this - || index.column() != 0) - return QVariant(); - - switch (role) { - case Qt::EditRole: - case Qt::DisplayRole: - if (index.parent().isValid()) { - const AdBlockRule r = rule(index); - return r.filter(); - } else { - AdBlockSubscription *sub = subscription(index); - if (sub) - return sub->title(); - } - break; - case Qt::CheckStateRole: - if (index.parent().isValid()) { - const AdBlockRule r = rule(index); - return r.isEnabled() ? Qt::Checked : Qt::Unchecked; - } else { - AdBlockSubscription *sub = subscription(index); - if (sub) - return sub->isEnabled() ? Qt::Checked : Qt::Unchecked; - } - break; - default: - break; - } - - return QVariant(); -} - -int AdBlockModel::columnCount(const QModelIndex &parent) const -{ - return (parent.column() > 0) ? 0 : 1; -} - -int AdBlockModel::rowCount(const QModelIndex &parent) const -{ - if (parent.column() > 0) - return 0; - - if (!parent.isValid()) - return m_manager->subscriptions().count(); - - if (parent.internalPointer() != 0) - return 0; - - const AdBlockSubscription *parentNode = subscription(parent); - return parentNode ? parentNode->allRules().count() : 0; -} - -QModelIndex AdBlockModel::index(int row, int column, const QModelIndex &parent) const -{ - if (row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent)) - return QModelIndex(); - - if (!parent.isValid()) - return createIndex(row, column, (void*)0); - - // get the parent node - const AdBlockSubscription *parentNode = subscription(parent); - return createIndex(row, column, (void*)parentNode); -} - -QModelIndex AdBlockModel::parent(const QModelIndex &index) const -{ - if (!index.isValid()) - return QModelIndex(); - - AdBlockSubscription *parent = static_cast(index.internalPointer()); - if (!parent) - return QModelIndex(); - - int parentRow = m_manager->subscriptions().indexOf(parent); - return createIndex(parentRow, 0, (void*)0); -} - -Qt::ItemFlags AdBlockModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - return Qt::NoItemFlags; - - Qt::ItemFlags flags = Qt::ItemIsSelectable; - - if (index.parent().isValid()) { - flags |= Qt::ItemIsUserCheckable | Qt::ItemIsEditable; - const AdBlockSubscription *parentNode = subscription(index.parent()); - if (parentNode && parentNode->isEnabled()) - flags |= Qt::ItemIsEnabled; - } else { - flags |= Qt::ItemIsUserCheckable | Qt::ItemIsEditable | Qt::ItemIsEnabled; - } - - return flags; -} - -bool AdBlockModel::removeRows(int row, int count, const QModelIndex &parent) -{ - if (row < 0 || count <= 0 || row + count > rowCount(parent)) - return false; - - if (!parent.isValid()) { - disconnect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - beginRemoveRows(QModelIndex(), row, row + count - 1); - for (int i = row + count - 1; i >= row; --i) { - AdBlockManager *manager = AdBlockManager::instance(); - manager->removeSubscription(manager->subscriptions().at(i)); - } - endRemoveRows(); - connect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - return true; - } else { - AdBlockSubscription *sub = subscription(parent); - if (sub) { - disconnect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - beginRemoveRows(parent, row, row + count - 1); - QList rules = sub->allRules(); - for (int i = row + count - 1; i >= row; --i) - sub->removeRule(i); - endRemoveRows(); - connect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - return true; - } - } - - return false; -} - -bool AdBlockModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (!index.isValid() - || index.model() != this - || index.column() != 0 - || (flags(index) & Qt::ItemIsEditable) == 0) - return false; - - disconnect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - bool changed = false; - switch (role) { - case Qt::EditRole: - case Qt::DisplayRole: - if (index.parent().isValid()) { - AdBlockSubscription *sub = subscription(index.parent()); - if (sub) { - AdBlockRule r = rule(index); - r.setFilter(value.toString()); - sub->replaceRule(r, index.row()); - dataChanged(index, index); - changed = true; - } - } else { - AdBlockSubscription *sub = subscription(index); - if (sub) { - sub->setTitle(value.toString()); - dataChanged(index, index); - changed = true; - } - } - break; - case Qt::CheckStateRole: - if (index.parent().isValid()) { - AdBlockSubscription *sub = subscription(index.parent()); - if (sub) { - AdBlockRule r = rule(index); - r.setEnabled(value == Qt::Checked); - sub->replaceRule(r, index.row()); - dataChanged(index, index); - changed = true; - } - } else { - AdBlockSubscription *sub = subscription(index); - if (sub) { - sub->setEnabled(value == Qt::Checked); - dataChanged(index, index); - changed = true; - } - } - break; - default: - break; - } - connect(m_manager, SIGNAL(rulesChanged()), this, SLOT(rulesChanged())); - return changed; -} - -bool AdBlockModel::hasChildren(const QModelIndex &parent) const -{ - if (!parent.isValid()) - return true; - if (parent.internalPointer() == 0) - return true; - return false; -} - diff --git a/src/adblock/adblockmodel.h b/src/adblock/adblockmodel.h deleted file mode 100644 index 05dd36d2..00000000 --- a/src/adblock/adblockmodel.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKMODEL_H -#define ADBLOCKMODEL_H - -#include - -class AdBlockRule; -class AdBlockSubscription; -class AdBlockManager; -class AdBlockModel : public QAbstractItemModel -{ - Q_OBJECT - -public: - AdBlockModel(QObject *parent = 0); - - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index = QModelIndex()) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - bool hasChildren(const QModelIndex &parent = QModelIndex()) const; - - const AdBlockRule rule(const QModelIndex &index) const; - AdBlockSubscription *subscription(const QModelIndex &index) const; - QModelIndex index(AdBlockSubscription *subscription); - -private slots: - void rulesGoingToChange(); - void rulesChanged(); - -private: - AdBlockManager *m_manager; -}; - -#endif // ADBLOCKMODEL_H - diff --git a/src/adblock/adblocknetwork.cpp b/src/adblock/adblocknetwork.cpp deleted file mode 100644 index c0354fd4..00000000 --- a/src/adblock/adblocknetwork.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblocknetwork.h" - -#include "adblockblockednetworkreply.h" -#include "adblockmanager.h" -#include "adblocksubscription.h" - -#include - -// #define ADBLOCKNETWORK_DEBUG - -AdBlockNetwork::AdBlockNetwork(QObject *parent) - : QObject(parent) -{ -} - -QNetworkReply *AdBlockNetwork::block(const QNetworkRequest &request) -{ - QUrl url = request.url(); - - if (url.scheme() == QLatin1String("data")) - return 0; - - AdBlockManager *manager = AdBlockManager::instance(); - if (!manager->isEnabled()) - return 0; - - QString urlString = QString::fromUtf8(url.toEncoded()); - const AdBlockRule *blockedRule = 0; -#if defined(ADBLOCKNETWORK_DEBUG) - const AdBlockSubscription *blockingSubscription = 0; -#endif - - QList subscriptions = manager->subscriptions(); - foreach (AdBlockSubscription *subscription, subscriptions) { - if (subscription->allow(urlString)) - return 0; - - if (const AdBlockRule *rule = subscription->block(urlString)) { - blockedRule = rule; -#if defined(ADBLOCKNETWORK_DEBUG) - blockingSubscription = subscription; -#endif - break; - } - } - - if (blockedRule) { -#if defined(ADBLOCKNETWORK_DEBUG) - qDebug() << "AdBlockNetwork::" << __FUNCTION__ << "rule:" << blockedRule->filter() << "subscription:" << blockingSubscription->title() << url; -#endif - AdBlockBlockedNetworkReply *reply = new AdBlockBlockedNetworkReply(request, blockedRule, this); - return reply; - } - return 0; -} - diff --git a/src/adblock/adblocknetwork.h b/src/adblock/adblocknetwork.h deleted file mode 100644 index 6dbbdeab..00000000 --- a/src/adblock/adblocknetwork.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKNETWORK_H -#define ADBLOCKNETWORK_H - -#include - -class QNetworkRequest; -class QNetworkReply; -class AdBlockNetwork : public QObject -{ - Q_OBJECT - -public: - AdBlockNetwork(QObject *parent = 0); - - QNetworkReply *block(const QNetworkRequest &request); - -}; - -#endif // ADBLOCKNETWORK_H - diff --git a/src/adblock/adblockpage.cpp b/src/adblock/adblockpage.cpp deleted file mode 100644 index 4fe3131d..00000000 --- a/src/adblock/adblockpage.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockpage.h" - -#include "adblockmanager.h" -#include "adblocksubscription.h" -#include "adblockrule.h" - -#include -#include -#include - -#include - -// #define ADBLOCKPAGE_DEBUG - -AdBlockPage::AdBlockPage(QObject *parent) - : QObject(parent) -{ -} - -void AdBlockPage::checkRule(const AdBlockRule *rule, QWebPage *page, const QString &host) -{ - if (!rule->isEnabled()) - return; - - QString filter = rule->filter(); - int offset = filter.indexOf(QLatin1String("##")); - if (offset == -1) - return; - - QString selectorQuery; - if (offset > 0) { - QString domainRules = filter.mid(0, offset); - selectorQuery = filter.mid(offset + 2); - QStringList domains = domainRules.split(QLatin1Char(',')); - - bool match = false; - foreach (const QString &domain, domains) { - bool reverse = (domain[0] == QLatin1Char('~')); - if (reverse) { - QString xdomain = domain.mid(1); - if (host.endsWith(xdomain)) - return; - match = true; - } - if (host.endsWith(domain)) - match = true; - } - if (!match) - return; - } - - if (offset == 0) - selectorQuery = filter.mid(2); - - Q_UNUSED(page); - QWebElement document = page->mainFrame()->documentElement(); - QWebElementCollection elements = document.findAll(selectorQuery); -#if defined(ADBLOCKPAGE_DEBUG) - if (elements.count() != 0) - qDebug() << "AdBlockPage::" << __FUNCTION__ << "blocking" << elements.count() << "items" << selectorQuery << elements.count() << "rule:" << rule->filter(); -#endif - foreach (QWebElement element, elements) { - element.setStyleProperty(QLatin1String("visibility"), QLatin1String("hidden")); - element.removeFromDocument(); - } -} - -void AdBlockPage::applyRulesToPage(QWebPage *page) -{ - if (!page || !page->mainFrame()) - return; - AdBlockManager *manager = AdBlockManager::instance(); - if (!manager->isEnabled()) - return; - QString host = page->mainFrame()->url().host(); - QList subscriptions = manager->subscriptions(); - foreach (AdBlockSubscription *subscription, subscriptions) { - QList rules = subscription->pageRules(); - foreach (const AdBlockRule *rule, rules) { - checkRule(rule, page, host); - } - } -} - diff --git a/src/adblock/adblockpage.h b/src/adblock/adblockpage.h deleted file mode 100644 index 60244902..00000000 --- a/src/adblock/adblockpage.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKPAGE_H -#define ADBLOCKPAGE_H - -#include - -class AdBlockRule; -class QWebPage; -class AdBlockPage : public QObject -{ - Q_OBJECT - -public: - AdBlockPage(QObject *parent = 0); - - void applyRulesToPage(QWebPage *page); - -private: - void checkRule(const AdBlockRule *rule, QWebPage *page, const QString &host); -}; - -#endif // ADBLOCKPAGE_H - diff --git a/src/adblock/adblockrule.cpp b/src/adblock/adblockrule.cpp deleted file mode 100644 index b6608e86..00000000 --- a/src/adblock/adblockrule.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Copyright (c) 2009, Zsombor Gegesy - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockrule.h" - -#include "adblocksubscription.h" - -#include -#include -#include - -// #define ADBLOCKRULE_DEBUG - -AdBlockRule::AdBlockRule(const QString &filter) -{ - setFilter(filter); -} - -QString AdBlockRule::filter() const -{ - return m_filter; -} - -void AdBlockRule::setFilter(const QString &filter) -{ - m_filter = filter; - - m_cssRule = false; - m_enabled = true; - m_exception = false; - bool regExpRule = false; - - if (filter.startsWith(QLatin1String("!")) - || filter.trimmed().isEmpty()) - m_enabled = false; - - if (filter.contains(QLatin1String("##"))) - m_cssRule = true; - - QString parsedLine = filter; - if (parsedLine.startsWith(QLatin1String("@@"))) { - m_exception = true; - parsedLine = parsedLine.mid(2); - } - if (parsedLine.startsWith(QLatin1Char('/'))) { - if (parsedLine.endsWith(QLatin1Char('/'))) { - parsedLine = parsedLine.mid(1); - parsedLine = parsedLine.left(parsedLine.size() - 1); - regExpRule = true; - } - } - int options = parsedLine.indexOf(QLatin1String("$"), 0); - if (options >= 0) { - m_options = parsedLine.mid(options + 1).split(QLatin1Char(',')); - parsedLine = parsedLine.left(options); - } - - setPattern(parsedLine, regExpRule); - - if (m_options.contains(QLatin1String("match-case"))) { - m_regExp.setCaseSensitivity(Qt::CaseSensitive); - m_options.removeOne(QLatin1String("match-case")); - } -} - -bool AdBlockRule::networkMatch(const QString &encodedUrl) const -{ - if (m_cssRule) { -#if defined(ADBLOCKRULE_DEBUG) - qDebug() << "AdBlockRule::" << __FUNCTION__ << "m_cssRule" << m_cssRule; -#endif - return false; - } - - if (!m_enabled) { -#if defined(ADBLOCKRULE_DEBUG) - qDebug() << "AdBlockRule::" << __FUNCTION__ << "is not enabled"; -#endif - return false; - } - - bool matched = m_regExp.indexIn(encodedUrl) != -1; - - if (matched - && !m_options.isEmpty()) { - - // we only support domain right now - if (m_options.count() == 1) { - foreach (const QString &option, m_options) { - if (option.startsWith(QLatin1String("domain="))) { - QUrl url = QUrl::fromEncoded(encodedUrl.toUtf8()); - QString host = url.host(); - QStringList domainOptions = option.mid(7).split(QLatin1Char('|')); - foreach (QString domainOption, domainOptions) { - bool negate = domainOption.at(0) == QLatin1Char('~'); - if (negate) - domainOption = domainOption.mid(1); - bool hostMatched = domainOption == host; - if (hostMatched && !negate) - return true; - if (!hostMatched && negate) - return true; - } - } - } - } - -#if defined(ADBLOCKRULE_DEBUG) - qDebug() << "AdBlockRule::" << __FUNCTION__ << "options are currently not supported" << m_options; -#endif - return false; - } -#if defined(ADBLOCKRULE_DEBUG) - //qDebug() << "AdBlockRule::" << __FUNCTION__ << encodedUrl << "MATCHED" << matched << filter(); -#endif - - return matched; -} - -bool AdBlockRule::isException() const -{ - return m_exception; -} - -void AdBlockRule::setException(bool exception) -{ - m_exception = exception; -} - -bool AdBlockRule::isEnabled() const -{ - return m_enabled; -} - -void AdBlockRule::setEnabled(bool enabled) -{ - m_enabled = enabled; - if (!enabled) { - m_filter = QLatin1String("!") + m_filter; - } else { - m_filter = m_filter.mid(1); - } -} - -QString AdBlockRule::regExpPattern() const -{ - return m_regExp.pattern(); -} - -static QString convertPatternToRegExp(const QString &wildcardPattern) { - QString pattern = wildcardPattern; - return pattern.replace(QRegExp(QLatin1String("\\*+")), QLatin1String("*")) // remove multiple wildcards - .replace(QRegExp(QLatin1String("\\^\\|$")), QLatin1String("^")) // remove anchors following separator placeholder - .replace(QRegExp(QLatin1String("^(\\*)")), QLatin1String("")) // remove leading wildcards - .replace(QRegExp(QLatin1String("(\\*)$")), QLatin1String("")) // remove trailing wildcards - .replace(QRegExp(QLatin1String("(\\W)")), QLatin1String("\\\\1")) // escape special symbols - .replace(QRegExp(QLatin1String("^\\\\\\|\\\\\\|")), - QLatin1String("^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?")) // process extended anchor at expression start - .replace(QRegExp(QLatin1String("\\\\\\^")), - QLatin1String("(?:[^\\w\\d\\-.%]|$)")) // process separator placeholders - .replace(QRegExp(QLatin1String("^\\\\\\|")), QLatin1String("^")) // process anchor at expression start - .replace(QRegExp(QLatin1String("\\\\\\|$")), QLatin1String("$")) // process anchor at expression end - .replace(QRegExp(QLatin1String("\\\\\\*")), QLatin1String(".*")) // replace wildcards by .* - ; -} - -void AdBlockRule::setPattern(const QString &pattern, bool isRegExp) -{ - m_regExp = QRegExp(isRegExp ? pattern : convertPatternToRegExp(pattern), - Qt::CaseInsensitive, QRegExp::RegExp2); -} - diff --git a/src/adblock/adblockrule.h b/src/adblock/adblockrule.h deleted file mode 100644 index c877b79a..00000000 --- a/src/adblock/adblockrule.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKRULE_H -#define ADBLOCKRULE_H - -#include - -class QUrl; -class QRegExp; -class AdBlockRule -{ - -public: - AdBlockRule(const QString &filter = QString()); - - QString filter() const; - void setFilter(const QString &filter); - - bool isCSSRule() const { return m_cssRule; } - bool networkMatch(const QString &encodedUrl) const; - - bool isException() const; - void setException(bool exception); - - bool isEnabled() const; - void setEnabled(bool enabled); - - QString regExpPattern() const; - void setPattern(const QString &pattern, bool isRegExp); - -private: - QString m_filter; - - bool m_cssRule; - bool m_exception; - bool m_enabled; - QRegExp m_regExp; - QStringList m_options; -}; - -#endif // ADBLOCKRULE_H - diff --git a/src/adblock/adblockschemeaccesshandler.cpp b/src/adblock/adblockschemeaccesshandler.cpp deleted file mode 100644 index fe5166ed..00000000 --- a/src/adblock/adblockschemeaccesshandler.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblockschemeaccesshandler.h" - -#include "adblockmanager.h" -#include "adblocksubscription.h" -#include "adblockdialog.h" - -#include -#include - -AdBlockSchemeAccessHandler::AdBlockSchemeAccessHandler(QObject *parent) - : SchemeAccessHandler(parent) -{ -} - -QNetworkReply *AdBlockSchemeAccessHandler::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) -{ - Q_UNUSED(outgoingData); - if (op != QNetworkAccessManager::GetOperation) - return 0; - - if (request.url().path() != QLatin1String("subscribe")) - return 0; - - AdBlockSubscription *subscription = new AdBlockSubscription(request.url(), AdBlockManager::instance()); - - QMessageBox::StandardButton result = QMessageBox::question(0 - , tr("Subscribe?") - , tr("Subscribe to this AdBlock subscription?\n%1").arg(subscription->title()) - , QMessageBox::Yes | QMessageBox::No); - if (result == QMessageBox::No) { - delete subscription; - } else { - AdBlockManager::instance()->addSubscription(subscription); - AdBlockDialog *dialog = AdBlockManager::instance()->showDialog(); - QAbstractItemModel *model = dialog->treeView->model(); - dialog->treeView->setCurrentIndex(model->index(model->rowCount() -1, 0)); - dialog->setFocus(); - } - return 0; -} - diff --git a/src/adblock/adblockschemeaccesshandler.h b/src/adblock/adblockschemeaccesshandler.h deleted file mode 100644 index fccee5aa..00000000 --- a/src/adblock/adblockschemeaccesshandler.h +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKSCHEMEACCESSHANDLER_H -#define ADBLOCKSCHEMEACCESSHANDLER_H - -#include "schemeaccesshandler.h" - -class AdBlockSchemeAccessHandler : public SchemeAccessHandler -{ -public: - AdBlockSchemeAccessHandler(QObject *parent = 0); - - virtual QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0); -}; - -#endif // ADBLOCKSCHEMEACCESSHANDLER_H diff --git a/src/adblock/adblocksubscription.cpp b/src/adblock/adblocksubscription.cpp deleted file mode 100644 index 2fb0a80e..00000000 --- a/src/adblock/adblocksubscription.cpp +++ /dev/null @@ -1,374 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "adblocksubscription.h" - -#include "browserapplication.h" -#include "networkaccessmanager.h" - -#include -#include -#include -#include -#include -#include - -// #define ADBLOCKSUBSCRIPTION_DEBUG - -AdBlockSubscription::AdBlockSubscription(const QUrl &url, QObject *parent) - : QObject(parent) - , m_url(url.toEncoded()) - , m_enabled(false) - , m_downloading(0) -{ - parseUrl(url); -} - -void AdBlockSubscription::parseUrl(const QUrl &url) -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << url; -#endif - if (url.scheme() != QLatin1String("abp")) - return; - if (url.path() != QLatin1String("subscribe")) - return; - QUrlQuery query(url.query()); - m_title = query.queryItemValue("title"); - m_enabled = query.queryItemValue("enabled") != QLatin1String("false"); - m_location = query.queryItemValue("location").toUtf8(); - QString lastUpdateString = query.queryItemValue("lastUpdate"); - m_lastUpdate = QDateTime::fromString(lastUpdateString, Qt::ISODate); - loadRules(); -} - -QUrl AdBlockSubscription::url() const -{ - QUrl url; - url.setScheme(QLatin1String("abp")); - url.setPath(QLatin1String("subscribe")); - - QUrlQuery queryItems; - - queryItems.addQueryItem(QLatin1String("location"), QString::fromUtf8(m_location)); - queryItems.addQueryItem(QLatin1String("title"), m_title); - if (!m_enabled) - queryItems.addQueryItem(QLatin1String("enabled"), QLatin1String("false")); - if (m_lastUpdate.isValid()) - queryItems.addQueryItem(QLatin1String("lastUpdate"), m_lastUpdate.toString(Qt::ISODate)); - url.setQuery(queryItems); - return url; -} - -bool AdBlockSubscription::isEnabled() const -{ - return m_enabled; -} - -void AdBlockSubscription::setEnabled(bool enabled) -{ - if (m_enabled == enabled) - return; - m_enabled = enabled; - populateCache(); - emit changed(); -} - -QString AdBlockSubscription::title() const -{ - return m_title; -} - -void AdBlockSubscription::setTitle(const QString &title) -{ - if (m_title == title) - return; - m_title = title; - emit changed(); -} - -QUrl AdBlockSubscription::location() const -{ - return QUrl::fromEncoded(m_location); -} - -void AdBlockSubscription::setLocation(const QUrl &url) -{ - if (url == location()) - return; - m_location = url.toEncoded(); - m_lastUpdate = QDateTime(); - emit changed(); -} - -QDateTime AdBlockSubscription::lastUpdate() const -{ - return m_lastUpdate; -} - -QString AdBlockSubscription::rulesFileName() const -{ - if (location().scheme() == QLatin1String("file")) - return location().toLocalFile(); - - if (m_location.isEmpty()) - return QString(); - - QByteArray sha1 = QCryptographicHash::hash(m_location, QCryptographicHash::Sha1).toHex(); - QString fileName = BrowserApplication::dataFilePath(QString(QLatin1String("adblock_subscription_%1")).arg(QLatin1String(sha1))); - return fileName; -} - -void AdBlockSubscription::loadRules() -{ - QString fileName = rulesFileName(); -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << fileName; -#endif - QFile file(fileName); - if (file.exists()) { - if (!file.open(QFile::ReadOnly)) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "Unable to open adblock file for reading" << fileName; - } else { - QTextStream textStream(&file); - QString header = textStream.readLine(1024); - if (!header.startsWith(QLatin1String("[Adblock"))) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "adblock file does not start with [Adblock" << fileName << "Header:" << header; - file.close(); - file.remove(); - m_lastUpdate = QDateTime(); - } else { - m_rules.clear(); - while (!textStream.atEnd()) { - QString line = textStream.readLine(); - m_rules.append(AdBlockRule(line)); - } - populateCache(); - emit rulesChanged(); - } - } - } - - if (!m_lastUpdate.isValid() - || m_lastUpdate.addDays(7) < QDateTime::currentDateTime()) { - updateNow(); - } -} - -void AdBlockSubscription::updateNow() -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << location(); -#endif - if (m_downloading) { -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << "already downloading, stopping"; -#endif - return; - } - - if (!location().isValid()) { -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << location() << "isn't valid"; -#endif - return; - } - - if (location().scheme() == QLatin1String("file")) { -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << "local file, not downloading"; -#endif - m_lastUpdate = QDateTime::currentDateTime(); - loadRules(); - emit changed(); - return; - } - - QNetworkRequest request(location()); - QNetworkReply *reply = BrowserApplication::networkAccessManager()->get(request); - m_downloading = reply; - connect(reply, SIGNAL(finished()), this, SLOT(rulesDownloaded())); -} - -void AdBlockSubscription::rulesDownloaded() -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << rulesFileName(); -#endif - QNetworkReply *reply = qobject_cast(sender()); - if (!reply) { -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << "no reply?"; -#endif - return; - } - - QByteArray response = reply->readAll(); - QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - reply->close(); - reply->deleteLater(); - - if (reply->error() != QNetworkReply::NoError) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "error" << reply->errorString(); - return; - } - - if (redirect.isValid()) { -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << "redirect to:" << redirect; -#endif - QNetworkRequest request(redirect); - m_downloading = BrowserApplication::networkAccessManager()->get(request); - connect(m_downloading, SIGNAL(finished()), this, SLOT(rulesDownloaded())); - return; - } - - if (response.isEmpty()) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "empty response"; - return; - } - - QString fileName = rulesFileName(); - QFile file(fileName); - if (!file.open(QFile::ReadWrite)) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "Unable to open adblock file for writing:" << fileName; - return; - } - file.write(response); - m_lastUpdate = QDateTime::currentDateTime(); - loadRules(); - emit changed(); - m_downloading = 0; -} - -void AdBlockSubscription::saveRules() -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << rulesFileName() << m_rules.count(); -#endif - QString fileName = rulesFileName(); - if (fileName.isEmpty()) - return; - - QFile file(fileName); - if (!file.open(QFile::ReadWrite | QIODevice::Truncate)) { - qWarning() << "AdBlockSubscription::" << __FUNCTION__ << "Unable to open adblock file for writing:" << fileName; - return; - } - - QTextStream textStream(&file); - textStream << "[Adblock Plus 0.7.1]" << endl; - foreach (const AdBlockRule &rule, m_rules) - textStream << rule.filter() << endl; -} - -QList AdBlockSubscription::pageRules() const -{ - return m_pageRules; -} - -const AdBlockRule *AdBlockSubscription::allow(const QString &urlString) const -{ - foreach (const AdBlockRule *rule, m_networkExceptionRules) { - if (rule->networkMatch(urlString)) - return rule; - } - return 0; -} - -const AdBlockRule *AdBlockSubscription::block(const QString &urlString) const -{ - foreach (const AdBlockRule *rule, m_networkBlockRules) { - if (rule->networkMatch(urlString)) - return rule; - } - return 0; -} - -QList AdBlockSubscription::allRules() const -{ - return m_rules; -} - -void AdBlockSubscription::addRule(const AdBlockRule &rule) -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << rule.filter(); -#endif - m_rules.append(rule); - populateCache(); - emit rulesChanged(); -} - -void AdBlockSubscription::removeRule(int offset) -{ -#if defined(ADBLOCKSUBSCRIPTION_DEBUG) - qDebug() << "AdBlockSubscription::" << __FUNCTION__ << offset << m_rules.count(); -#endif - if (offset < 0 || offset >= m_rules.count()) - return; - m_rules.removeAt(offset); - populateCache(); - emit rulesChanged(); -} - -void AdBlockSubscription::replaceRule(const AdBlockRule &rule, int offset) -{ - if (offset < 0 || offset >= m_rules.count()) - return; - m_rules[offset] = rule; - populateCache(); - emit rulesChanged(); -} - -void AdBlockSubscription::populateCache() -{ - m_networkExceptionRules.clear(); - m_networkBlockRules.clear(); - m_pageRules.clear(); - if (!isEnabled()) - return; - - for (int i = 0; i < m_rules.count(); ++i) { - const AdBlockRule *rule = &m_rules.at(i); - if (!rule->isEnabled()) - continue; - - if (rule->isCSSRule()) { - m_pageRules.append(rule); - continue; - } - - if (rule->isException()) { - m_networkExceptionRules.append(rule); - } else { - m_networkBlockRules.append(rule); - } - } -} - diff --git a/src/adblock/adblocksubscription.h b/src/adblock/adblocksubscription.h deleted file mode 100644 index 5f600486..00000000 --- a/src/adblock/adblocksubscription.h +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ADBLOCKSUBSCRIPTION_H -#define ADBLOCKSUBSCRIPTION_H - -#include - -#include "adblockrule.h" - -#include -#include - -class QNetworkReply; -class QUrl; -class AdBlockSubscription : public QObject -{ - Q_OBJECT - -signals: - void goingToChange(); - void changed(); - void rulesChanged(); - -public: - AdBlockSubscription(const QUrl &url, QObject *parent = 0); - QUrl url() const; - - bool isEnabled() const; - void setEnabled(bool enabled); - - QString title() const; - void setTitle(const QString &title); - - QUrl location() const; - void setLocation(const QUrl &url); - - void updateNow(); - QDateTime lastUpdate() const; - - void saveRules(); - - const AdBlockRule *allow(const QString &urlString) const; - const AdBlockRule *block(const QString &urlString) const; - QList pageRules() const; - - QList allRules() const; - void addRule(const AdBlockRule &rule); - void removeRule(int offset); - void replaceRule(const AdBlockRule &rule, int offset); - -private slots: - void rulesDownloaded(); - -private: - void populateCache(); - QString rulesFileName() const; - void parseUrl(const QUrl &url); - void loadRules(); - - QByteArray m_url; - - QString m_title; - QByteArray m_location; - QDateTime m_lastUpdate; - bool m_enabled; - - QNetworkReply *m_downloading; - QList m_rules; - - // sorted list - QList m_networkExceptionRules; - QList m_networkBlockRules; - QList m_pageRules; -}; - -#endif // ADBLOCKSUBSCRIPTION_H - diff --git a/src/autofilldialog.cpp b/src/autofilldialog.cpp deleted file mode 100644 index 7c8d3427..00000000 --- a/src/autofilldialog.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "autofilldialog.h" - -#include "autofillmanager.h" -#include "browserapplication.h" - -#include - -AutoFillModel::AutoFillModel(QObject *parent) - : QAbstractTableModel(parent) -{ - AutoFillManager *manager = BrowserApplication::instance()->autoFillManager(); - Q_ASSERT(manager); - connect(manager, SIGNAL(autoFillChanged()), this, SLOT(autoFillChanged())); - autoFillChanged(); -} - -void AutoFillModel::autoFillChanged() -{ - beginResetModel(); - AutoFillManager *manager = BrowserApplication::instance()->autoFillManager(); - m_forms = manager->forms(); - endResetModel(); -} - -QVariant AutoFillModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Horizontal - && role == Qt::DisplayRole) { - switch (section) { - case 0: return tr("WebSite"); - case 1: return tr("User Name"); - } - } - return QAbstractTableModel::headerData(section, orientation, role); -} - -QVariant AutoFillModel::data(const QModelIndex &index, int role) const -{ - if (index.row() < 0 || index.row() >= m_forms.size()) - return QVariant(); - - switch (role) { - case Qt::UserRole: - return m_forms[index.row()].hasAPassword; - case Qt::DisplayRole: - case Qt::EditRole: { - switch (index.column()) { - case 0: - return m_forms[index.row()].url.host(); - case 1: { - QStringList help; - QStringList choices; - foreach (const AutoFillManager::Element &element, m_forms[index.row()].elements) { - QString key = element.first.toLower(); - if (key.contains(QLatin1String("pass"))) - continue; - if (key.contains(QLatin1String("user")) - || key.contains(QLatin1String("email")) - || key.contains(QLatin1String("login")) - || key == QLatin1String("u")) - return element.second; - choices.append(element.second); - help.append(element.first); - } - if (choices.count() == 1) - return choices.first(); - qWarning() << "AutoFillModel: Unknown user id, choices:" << help << "url" << m_forms[index.row()].url.toString(); - return help.join(QLatin1String(",")); - } - } - } - default: - break; - } - return QVariant(); -} - -int AutoFillModel::columnCount(const QModelIndex &parent) const -{ - return (parent.isValid()) ? 0 : 2; -} - -int AutoFillModel::rowCount(const QModelIndex &parent) const -{ - return (parent.isValid()) ? 0 : m_forms.count(); -} - -bool AutoFillModel::removeRows(int row, int count, const QModelIndex &parent) -{ - if (parent.isValid()) - return false; - int lastRow = row + count - 1; - beginRemoveRows(parent, row, lastRow); - for (int i = lastRow; i >= row; --i) - m_forms.removeAt(i); - AutoFillManager *manager = BrowserApplication::instance()->autoFillManager(); - disconnect(manager, SIGNAL(autoFillChanged()), this, SLOT(autoFillChanged())); - manager->setForms(m_forms); - connect(manager, SIGNAL(autoFillChanged()), this, SLOT(autoFillChanged())); - endRemoveRows(); - return true; -} - -AutoFillDialog::AutoFillDialog(QWidget *parent, Qt::WindowFlags flags) - : QDialog(parent, flags) -{ - setupUi(this); - setWindowFlags(Qt::Sheet); - connect(removeButton, SIGNAL(clicked()), tableView, SLOT(removeSelected())); - connect(removeAllButton, SIGNAL(clicked()), tableView, SLOT(removeAll())); - tableView->verticalHeader()->hide(); - tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - tableView->setAlternatingRowColors(true); - tableView->setTextElideMode(Qt::ElideMiddle); - tableView->setShowGrid(false); - tableView->setSortingEnabled(true); - - AutoFillModel *model = new AutoFillModel(); - QSortFilterProxyModel *m_proxyModel = new QSortFilterProxyModel(this); - connect(search, SIGNAL(textChanged(QString)), - m_proxyModel, SLOT(setFilterFixedString(QString))); - m_proxyModel->setSourceModel(model); - tableView->setModel(m_proxyModel); - - QFont f = font(); - f.setPointSize(10); - QFontMetrics fm(f); - int height = fm.height() + fm.height() / 3; - tableView->verticalHeader()->setDefaultSectionSize(height); - tableView->verticalHeader()->setMinimumSectionSize(-1); - for (int i = 0; i < model->columnCount(); ++i) { - int header = tableView->horizontalHeader()->sectionSizeHint(i); - switch (i) { - case 0: - header = fm.horizontalAdvance(QLatin1String("averagehost.domain.com")); - break; - case 1: - header = fm.horizontalAdvance(QLatin1String("_session_id")); - break; - } - int buffer = fm.horizontalAdvance(QLatin1String("xx")); - header += buffer; - tableView->horizontalHeader()->resizeSection(i, header); - } - tableView->horizontalHeader()->setStretchLastSection(true); -} - diff --git a/src/autofilldialog.h b/src/autofilldialog.h deleted file mode 100644 index 6e8f70c4..00000000 --- a/src/autofilldialog.h +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef AUTOFILLDIALOG_H -#define AUTOFILLDIALOG_H - -#include -#include "ui_autofilldialog.h" - -#include "autofillmanager.h" - -#include - -class AutoFillModel : public QAbstractTableModel -{ - Q_OBJECT - -public: - AutoFillModel(QObject *parent = 0); - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - -private slots: - void autoFillChanged(); - -private: - QList m_forms; -}; - - -class AutoFillDialog : public QDialog, public Ui_AutoFillDialog -{ - Q_OBJECT - -public: - AutoFillDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0); - -}; - -#endif // AUTOFILLDIALOG_H - diff --git a/src/autofilldialog.ui b/src/autofilldialog.ui deleted file mode 100644 index 93fbcbaa..00000000 --- a/src/autofilldialog.ui +++ /dev/null @@ -1,126 +0,0 @@ - - - AutoFillDialog - - - - 0 - 0 - 529 - 421 - - - - Form Passwords - - - - - - Qt::Horizontal - - - - 252 - 20 - - - - - - - - - - - false - - - - - - - Remove - - - - - - - Remove All - - - - - - - Qt::Horizontal - - - - 36 - 20 - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Ok - - - - - - - - EditTableView - QTableView -
edittableview.h
-
- - SearchLineEdit - QLineEdit -
searchlineedit.h
-
-
- - - - buttonBox - accepted() - AutoFillDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - AutoFillDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - -
diff --git a/src/autofillmanager.cpp b/src/autofillmanager.cpp deleted file mode 100644 index 851ee20d..00000000 --- a/src/autofillmanager.cpp +++ /dev/null @@ -1,413 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "autofillmanager.h" - -#include "autosaver.h" -#include "browserapplication.h" -#include "browsermainwindow.h" -#include "networkaccessmanagerproxy.h" -#include "webpageproxy.h" -#include "webview.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -// #define AUTOFILL_DEBUG - -AutoFillManager::AutoFillManager(QObject *parent) - : QObject(parent) - , m_savePasswordForms(true) - , m_allowAutoCompleteOff(true) - , m_saveTimer(new AutoSaver(this)) -{ - connect(this, SIGNAL(autoFillChanged()), - m_saveTimer, SLOT(changeOccurred())); - loadSettings(); - loadFormData(); -} - -AutoFillManager::~AutoFillManager() -{ - m_saveTimer->saveIfNeccessary(); -} - -void AutoFillManager::save() const -{ - saveFormData(); -} - -void AutoFillManager::setForms(const QList
&forms) -{ - m_forms = forms; - emit autoFillChanged(); -} - -QList AutoFillManager::forms() const -{ - return m_forms; -} - -void AutoFillManager::loadSettings() -{ - QSettings settings; - settings.beginGroup(QLatin1String("autofill")); - m_savePasswordForms = settings.value(QLatin1String("passwordForms"), m_savePasswordForms).toBool(); - m_allowAutoCompleteOff = settings.value(QLatin1String("ignoreAutoCompleteOff"), m_allowAutoCompleteOff).toBool(); -} - -QString AutoFillManager::autoFillDataFile() -{ - QString fileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/data/Endorphin"; - fileName += QLatin1String("/autofill.dat"); - return fileName; -} - -void AutoFillManager::saveFormData() const -{ - QString fileName = autoFillDataFile(); - QFile file(fileName); - if (!file.open(QFile::WriteOnly)) { - qWarning() << "Unable to open" << fileName << "to store autofill data"; - return; - } - - QDataStream stream(&file); - stream << m_forms; -} - -void AutoFillManager::loadFormData() -{ - QString fileName = autoFillDataFile(); - QFile file(fileName); - if (!file.open(QFile::ReadOnly)) - return; - - QDataStream stream(&file); - stream >> m_forms; -} - -void AutoFillManager::post(const QNetworkRequest &request, const QByteArray &outgoingData) -{ -#ifdef AUTOFILL_DEBUG - qDebug() << "AutoFillManager::" << __FUNCTION__ << outgoingData << request.url(); -#endif - - // Don't even give the options to save this site user name & password. - if (QWebSettings::globalSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) { - return; - } - - // Determine the url - QByteArray refererHeader = request.rawHeader("Referer"); - if (refererHeader.isEmpty()) { - // XXX We could store the frame url in the request if this is a common problem - qWarning() << "AutoFillManager:" << "Unable to determine the request Referer"; - return; - } - QUrl url = QUrl::fromEncoded(refererHeader); - url = stripUrl(url); - - // Check that the url isn't in m_never - if (m_never.contains(url)) - return; - - // Check the request type - QVariant typeVariant = request.attribute((QNetworkRequest::Attribute)(WebPageProxy::pageAttributeId() + 1)); - QWebPage::NavigationType type = (QWebPage::NavigationType)typeVariant.toInt(); - if (typeVariant.isValid() && type != QWebPage::NavigationTypeFormSubmitted) { - // XXX Does this occur normally? - qWarning() << "AutoFillManager:" << "Type is not FormSubmitted" << type - << "expected:" << QWebPage::NavigationTypeFormSubmitted; - return; - } - - // Determine the QWebView - QVariant v = request.attribute((QNetworkRequest::Attribute)(WebPageProxy::pageAttributeId())); - QWebPage *webPage = (QWebPage*)(v.value()); - if (!webPage) { - qWarning() << "AutoFillManager:" << "QWebPage is not set in QNetworkRequest."; - return; - } -#if 0 - // TODO CHECK reply ownership - if (!NetworkAccessManagerProxy::exists(webPage)) { - qWarning() << "AutoFillManager:" << "QWebPage no longer exists."; - return; - } -#endif - - // Find the matching form on the webpage - Form form = findForm(webPage, outgoingData); - if (!form.isValid()) { -#if 0 - qWarning() << "AutoFillManager:" << "Unable to find matching form on the webpage."; -#endif - return; - } - form.url = url; - - // Check if we allow storing this form if it has a password - if (!allowedToAutoFill(form.hasAPassword)) - return; - - // Prompt if we have never seen this password - int alreadyAccepted = -1; - for (int i = 0; i < m_forms.count(); ++i) { - const Form &form = m_forms.at(i); - if (form.url == url) { - alreadyAccepted = i; - break; - } - } - if (form.hasAPassword && alreadyAccepted == -1) { - QMessageBox messageBox; - messageBox.setText(tr("Would you like to save this password?
\ - To review passwords you have saved and remove them, open the AutoFill panel of preferences.")); - messageBox.addButton(tr("Never for this site"), QMessageBox::DestructiveRole); - messageBox.addButton(tr("Not now"), QMessageBox::RejectRole); - messageBox.addButton(QMessageBox::Yes); - messageBox.setDefaultButton(QMessageBox::Yes); - messageBox.exec(); - switch (messageBox.buttonRole(messageBox.clickedButton())) { - case QMessageBox::DestructiveRole: - m_never.append(url); - return; - case QMessageBox::RejectRole: - return; - default: - break; - } - } - -#ifdef AUTOFILL_DEBUG - qDebug() << "AutoFillManager:" << "Saving" << form.url; -#endif - // TODO When we can hook into element events we can save multiple passwords for different users - if (alreadyAccepted != -1) - m_forms.removeAt(alreadyAccepted); - m_forms.append(form); - emit autoFillChanged(); -} - -AutoFillManager::Form AutoFillManager::findForm(QWebPage *webPage, const QByteArray &outgoingData) const -{ - Form form; - QUrlQuery argsUrl(outgoingData); - QList > encodedArgs = argsUrl.queryItems(); - QSet > args; - // XXX Is there a Qt function to do this? (unencode '+' to ' ') - for (int i = 0; i < encodedArgs.count(); ++i) { - QString key = encodedArgs[i].first; - QString value = encodedArgs[i].second.replace(QLatin1String("+"), QLatin1String(" ")); - QPair p(key, value); - args.insert(p); - } - - QFile file(QLatin1String(":parseForms.js")); - if (!file.open(QFile::ReadOnly)) { - qWarning() << "AutoFillManager:" << "Unable to open js form parsing file"; - return form; - } - QString script = QLatin1String(file.readAll()); - - // XXX Do I need to do this on subframes? - QVariant r = webPage->mainFrame()->evaluateJavaScript(script); - QVariantList list = r.toList(); - foreach (const QVariant &formVariant, list) { - QVariantMap map = formVariant.toMap(); - bool formHasPasswords = false; - QString formName = map[QLatin1String("name")].toString(); - QVariantList elements = map[QLatin1String("elements")].toList(); - QSet > formElements; - QSet > deadElements; - foreach (const QVariant &element, elements) { - QVariantMap elementMap = element.toMap(); - QString name = elementMap[QLatin1String("name")].toString(); - QString value = elementMap[QLatin1String("value")].toString(); - QString type = elementMap[QLatin1String("type")].toString(); - if (type == QLatin1String("password")) - formHasPasswords = true; - QPair p(name, value); - if ((elementMap[QLatin1String("autocomplete")].toString()) == QLatin1String("off")) - deadElements.insert(p); - if (!name.isEmpty()) - formElements.insert(p); - } - if (formElements.intersect(args) == args) { - form.hasAPassword = formHasPasswords; - form.name = formName; - if (m_allowAutoCompleteOff) - args = args.subtract(deadElements); - form.elements = args.values(); - break; - } -#ifdef AUTOFILL_DEBUG - qDebug() << formName; - qDebug() << formElements; - qDebug() << args; - qDebug() << formElements.count() << args.count() << formElements.subtract(args); -#endif - } - return form; -} - -QUrl AutoFillManager::stripUrl(const QUrl &url) -{ - QUrl cleanUrl = url; - cleanUrl.setQuery(QUrlQuery()); - cleanUrl.setFragment(QString()); - cleanUrl.setUserInfo(QString()); - return cleanUrl; -} - -bool AutoFillManager::allowedToAutoFill(bool password) const -{ - if (password && m_savePasswordForms) - return true; - return false; -} - -QList AutoFillManager::fetchForms(const QUrl &url) const -{ - QList forms; - foreach (const Form &form, m_forms) - if (form.url == url) - forms.append(form); -#ifdef AUTOFILL_DEBUG - qDebug() << "AutoFillManager::" << __FUNCTION__ << url << m_forms.count() << "found:" << forms.count(); -#endif - return forms; -} - -void AutoFillManager::fill(QWebPage *page) const -{ -#ifdef AUTOFILL_DEBUG - qDebug() << "AutoFillManager::" << __FUNCTION__ << page; -#endif - if (!page || !page->mainFrame()) - return; - - QUrl url = page->mainFrame()->url(); - url = stripUrl(url); - - const QList forms = fetchForms(url); - if (forms.isEmpty()) - return; - - foreach (const Form &form, forms) { - QString formName = QString(QLatin1String("\"%1\"")).arg(form.name); - if (form.name.isEmpty()) - formName = QLatin1String("0"); - foreach (const AutoFillManager::Element &element, form.elements) { - const QString key = element.first; - const QString value = element.second; - - // When we drop 4.5 migrate this to the 4.6 dom API - bool disabled = page->mainFrame()->evaluateJavaScript(QString(QLatin1String("document.forms[%1].elements[\"%2\"].disabled")).arg(formName).arg(key)).toBool(); - if (disabled) { -#ifdef AUTOFILL_DEBUG - qDebug() << formName << "is disabled"; -#endif - continue; - } - bool readOnly = page->mainFrame()->evaluateJavaScript(QString(QLatin1String("document.forms[%1].elements[\"%2\"].readonly")).arg(formName).arg(key)).toBool(); - if (readOnly) { -#ifdef AUTOFILL_DEBUG - qDebug() << formName << "is readOnly"; -#endif - continue; - } - - QString type = page->mainFrame()->evaluateJavaScript(QString(QLatin1String("document.forms[%1].elements[\"%2\"].type")).arg(formName).arg(key)).toString(); - if (type.isEmpty() - || type == QLatin1String("hidden") - || type == QLatin1String("reset") - || type == QLatin1String("submit")) { -#ifdef AUTOFILL_DEBUG - qDebug() << formName << key << "is hidden, reset or submit"; -#endif - continue; - } -#ifdef AUTOFILL_DEBUG - qDebug() << "type:" << type << "readonly" << readOnly << "disabled" << disabled << key << value; -#endif - QString setType = (type == QLatin1String("checkbox")) - ? QLatin1String("checked") - : QLatin1String("value"); - - // XXX is there a cleaner way to do this? - QString jsValue = value; - jsValue.replace(QLatin1Char('\\'), QLatin1String("\\\\")); - jsValue.replace(QLatin1Char('\"'), QLatin1String("\\\"")); - QString javascript = QString(QLatin1String("document.forms[%1].elements[\"%2\"].%3=\"%4\";")) - .arg(formName) - .arg(key) - .arg(setType) - .arg(jsValue); - page->mainFrame()->evaluateJavaScript(javascript); - } - } -} - -QDataStream &operator>>(QDataStream &in, AutoFillManager::Form &form) -{ - AutoFillManager::Form::load(in, form); - return in; -} - -QDataStream &operator<<(QDataStream &out, const AutoFillManager::Form &form) -{ - AutoFillManager::Form::save(out, form); - return out; -} - -void AutoFillManager::Form::load(QDataStream &in, AutoFillManager::Form &form) -{ - in >> form.elements; - in >> form.url; - in >> form.name; - in >> form.hasAPassword; -} - -void AutoFillManager::Form::save(QDataStream &out, const AutoFillManager::Form &form) -{ - out << form.elements; - out << form.url; - out << form.name; - out << form.hasAPassword; -} diff --git a/src/autofillmanager.h b/src/autofillmanager.h deleted file mode 100644 index 2cecd61a..00000000 --- a/src/autofillmanager.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef AUTOFILLMANAGER_H -#define AUTOFILLMANAGER_H - -#include - -#include - -class QWebPage; -class AutoSaver; -class AutoFillManager : public QObject -{ - Q_OBJECT - -signals: - void autoFillChanged(); - -public: - typedef QPair Element; - class Form { - public: - bool isValid() { return !elements.isEmpty(); } - static void load(QDataStream &in, Form &subscription); - static void save(QDataStream &out, const Form &subscription); - - QList elements; - QUrl url; - QString name; - bool hasAPassword; - }; - - AutoFillManager(QObject *parent = 0); - ~AutoFillManager(); - - void loadSettings(); - - void post(const QNetworkRequest &request, const QByteArray &outgoingData); - void fill(QWebPage *page) const; - - void setForms(const QList &forms); - QList forms() const; - -private slots: - void save() const; - -private: - Form findForm(QWebPage *page, const QByteArray &outgoingData) const; - static QUrl stripUrl(const QUrl &url); - static QString autoFillDataFile(); - bool allowedToAutoFill(bool password) const; - QList fetchForms(const QUrl &url) const; - - void saveFormData() const; - void loadFormData(); - - bool m_savePasswordForms; - bool m_allowAutoCompleteOff; - - QList m_forms; - QList m_never; - AutoSaver *m_saveTimer; -}; - -QDataStream &operator<<(QDataStream &, const AutoFillManager::Form &form); -QDataStream &operator>>(QDataStream &, AutoFillManager::Form &form); - -#endif // AUTOFILLMANAGER_H - diff --git a/src/autosaver.cpp b/src/autosaver.cpp index de7794ac..85a5deff 100644 --- a/src/autosaver.cpp +++ b/src/autosaver.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -62,11 +62,11 @@ #include "autosaver.h" -#include -#include -#include +#include +#include +#include -#include +#include #define AUTOSAVE_IN 1000 * 3 // seconds #define MAXWAIT 1000 * 15 // seconds diff --git a/src/autosaver.h b/src/autosaver.h index f39b64cc..e83df97b 100644 --- a/src/autosaver.h +++ b/src/autosaver.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,8 +63,8 @@ #ifndef AUTOSAVER_H #define AUTOSAVER_H -#include -#include +#include +#include #include /* @@ -82,7 +82,7 @@ class AutoSaver : public QObject ~AutoSaver(); void saveIfNeccessary(); -public slots: +public Q_SLOTS: void changeOccurred(); protected: diff --git a/src/bookmarks/addbookmarkdialog.cpp b/src/bookmarks/addbookmarkdialog.cpp index bd0f0ac2..d03a17a8 100644 --- a/src/bookmarks/addbookmarkdialog.cpp +++ b/src/bookmarks/addbookmarkdialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -66,9 +66,15 @@ #include "bookmarknode.h" #include "bookmarksmanager.h" #include "bookmarksmodel.h" +#ifndef NO_BROWSERAPPLICATION #include "browserapplication.h" +#else +#ifdef FOR_AUTOTEST +#include "tst_addbookmarkdialog.h" +#endif +#endif -#include +#include #include AddBookmarkProxyModel::AddBookmarkProxyModel(QObject *parent) @@ -90,15 +96,23 @@ bool AddBookmarkProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &s AddBookmarkDialog::AddBookmarkDialog(QWidget *parent, BookmarksManager *bookmarksManager) : QDialog(parent) , m_bookmarksManager(bookmarksManager) - , m_addedNode(0) - , m_proxyModel(0) + , m_addedNode(nullptr) + , m_proxyModel(nullptr) , m_addFolder(false) { setWindowFlags(Qt::Sheet); setupUi(this); if (!m_bookmarksManager) +#ifndef NO_BROWSERAPPLICATION m_bookmarksManager = BrowserApplication::bookmarksManager(); +#else +#ifdef FOR_AUTOTEST + m_bookmarksManager = tst_AddBookmarkDialog::bookmarksManager(); +#else +#error "No bookmarksmanager provided! Build this either with BrowserApplication included or for autotests" +#endif +#endif m_proxyModel = new AddBookmarkProxyModel(this); BookmarksModel *model = m_bookmarksManager->bookmarksModel(); diff --git a/src/bookmarks/addbookmarkdialog.h b/src/bookmarks/addbookmarkdialog.h index d50381c6..33e92f3b 100644 --- a/src/bookmarks/addbookmarkdialog.h +++ b/src/bookmarks/addbookmarkdialog.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -66,14 +66,14 @@ #include "ui_addbookmarkdialog.h" -#include +#include class AddBookmarkProxyModel : public QSortFilterProxyModel { Q_OBJECT public: - AddBookmarkProxyModel(QObject *parent = 0); + AddBookmarkProxyModel(QObject *parent = nullptr); int columnCount(const QModelIndex &parent = QModelIndex()) const; protected: @@ -88,7 +88,7 @@ class AddBookmarkDialog : public QDialog, public Ui_AddBookmarkDialog Q_OBJECT public: - AddBookmarkDialog(QWidget *parent = 0, BookmarksManager *bookmarksManager = 0); + AddBookmarkDialog(QWidget *parent = nullptr, BookmarksManager *bookmarksManager = nullptr); void setUrl(const QString &url); QString url() const; @@ -104,7 +104,7 @@ class AddBookmarkDialog : public QDialog, public Ui_AddBookmarkDialog BookmarkNode *addedNode() const; -private slots: +private Q_SLOTS: void accept(); private: diff --git a/src/bookmarks/bookmarknode.cpp b/src/bookmarks/bookmarknode.cpp index 1d927dfb..4f6fa523 100644 --- a/src/bookmarks/bookmarknode.cpp +++ b/src/bookmarks/bookmarknode.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,9 +63,9 @@ #include "bookmarknode.h" BookmarkNode::BookmarkNode(BookmarkNode::Type type, BookmarkNode *parent) : - expanded(false) - , m_parent(parent) - , m_type(type) + expanded(false) + , m_parent(parent) + , m_type(type) { if (parent) parent->add(this); @@ -77,18 +77,18 @@ BookmarkNode::~BookmarkNode() m_parent->remove(this); for (int i = m_children.count() -1; i >= 0; --i) delete m_children[i]; - m_parent = 0; + m_parent = nullptr; m_type = BookmarkNode::Root; } bool BookmarkNode::operator==(const BookmarkNode &other) const { if (url != other.url - || title != other.title - || desc != other.desc - || expanded != other.expanded - || m_type != other.m_type - || m_children.count() != other.m_children.count()) + || title != other.title + || desc != other.desc + || expanded != other.expanded + || m_type != other.m_type + || m_children.count() != other.m_children.count()) return false; for (int i = 0; i < m_children.count(); ++i) @@ -136,7 +136,7 @@ void BookmarkNode::remove(BookmarkNode *child) { if (!child) return; - child->m_parent = 0; + child->m_parent = nullptr; m_children.removeAll(child); } diff --git a/src/bookmarks/bookmarknode.h b/src/bookmarks/bookmarknode.h index ef766546..63fe0b8d 100644 --- a/src/bookmarks/bookmarknode.h +++ b/src/bookmarks/bookmarknode.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,8 +63,8 @@ #ifndef BOOKMARKNODE_H #define BOOKMARKNODE_H -#include -#include +#include +#include class BookmarkNode { @@ -76,7 +76,7 @@ class BookmarkNode Separator }; - BookmarkNode(Type type = Root, BookmarkNode *parent = 0); + BookmarkNode(Type type = Root, BookmarkNode *parent = nullptr); ~BookmarkNode(); bool operator==(const BookmarkNode &other) const; diff --git a/src/bookmarks/bookmarks.pri b/src/bookmarks/bookmarks.pri deleted file mode 100644 index 34f899e6..00000000 --- a/src/bookmarks/bookmarks.pri +++ /dev/null @@ -1,27 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - addbookmarkdialog.h \ - bookmarksdialog.h \ - bookmarksmanager.h \ - bookmarksmenu.h \ - bookmarksmodel.h \ - bookmarkstoolbar.h \ - bookmarknode.h - -SOURCES += \ - addbookmarkdialog.cpp \ - bookmarksdialog.cpp \ - bookmarksmanager.cpp \ - bookmarksmenu.cpp \ - bookmarksmodel.cpp \ - bookmarkstoolbar.cpp \ - bookmarknode.cpp - -FORMS += \ - addbookmarkdialog.ui \ - bookmarksdialog.ui - -include(xbel/xbel.pri) diff --git a/src/bookmarks/bookmarksdialog.cpp b/src/bookmarks/bookmarksdialog.cpp index 4c81b121..6c007ece 100644 --- a/src/bookmarks/bookmarksdialog.cpp +++ b/src/bookmarks/bookmarksdialog.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -68,14 +68,14 @@ #include "browserapplication.h" #include "treesortfilterproxymodel.h" -#include -#include +#include +#include BookmarksDialog::BookmarksDialog(QWidget *parent, BookmarksManager *manager) : QDialog(parent) - , m_bookmarksManager(0) - , m_bookmarksModel(0) - , m_proxyModel(0) + , m_bookmarksManager(nullptr) + , m_bookmarksModel(nullptr) + , m_proxyModel(nullptr) { m_bookmarksManager = manager; if (!m_bookmarksManager) @@ -98,7 +98,7 @@ BookmarksDialog::BookmarksDialog(QWidget *parent, BookmarksManager *manager) tree->setExpanded(m_proxyModel->index(0, 0), true); tree->setAlternatingRowColors(true); QFontMetrics fm(font()); - int header = fm.horizontalAdvance(QLatin1Char('m')) * 40; + int header = fm.horizontalAdvance(QChar('m')) * 40; tree->header()->resizeSection(0, header); tree->header()->setStretchLastSection(true); connect(tree, SIGNAL(activated(const QModelIndex&)), @@ -180,10 +180,10 @@ void BookmarksDialog::openBookmark(TabWidget::OpenUrlIn tab) const BookmarkNode *node = m_bookmarksModel->node(sourceIndex); if (!index.parent().isValid() || !node || node->type() == BookmarkNode::Folder) return; - emit openUrl( - index.sibling(index.row(), 1).data(BookmarksModel::UrlRole).toUrl(), - tab, - index.sibling(index.row(), 0).data(Qt::DisplayRole).toString()); + Q_EMIT openUrl( + index.sibling(index.row(), 1).data(BookmarksModel::UrlRole).toUrl(), + tab, + index.sibling(index.row(), 0).data(Qt::DisplayRole).toString()); } void BookmarksDialog::openBookmark() diff --git a/src/bookmarks/bookmarksdialog.h b/src/bookmarks/bookmarksdialog.h index 513e6e4f..edb3f67d 100644 --- a/src/bookmarks/bookmarksdialog.h +++ b/src/bookmarks/bookmarksdialog.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,13 +63,13 @@ #ifndef BOOKMARKSDIALOG_H #define BOOKMARKSDIALOG_H -#include +#include #include "ui_bookmarksdialog.h" #include "tabwidget.h" -#include -#include +#include +#include class TreeSortFilterProxyModel; class BookmarksManager; @@ -79,14 +79,14 @@ class BookmarksDialog : public QDialog, public Ui_BookmarksDialog { Q_OBJECT -signals: +Q_SIGNALS: void openUrl(const QUrl &url, TabWidget::OpenUrlIn tab, const QString &title); public: - BookmarksDialog(QWidget *parent = 0, BookmarksManager *manager = 0); + BookmarksDialog(QWidget *parent = nullptr, BookmarksManager *manager = nullptr); ~BookmarksDialog(); -private slots: +private Q_SLOTS: void customContextMenuRequested(const QPoint &pos); void openBookmark(TabWidget::OpenUrlIn tab); void openBookmark(); diff --git a/src/bookmarks/bookmarksmanager.cpp b/src/bookmarks/bookmarksmanager.cpp index b270980f..a865a513 100644 --- a/src/bookmarks/bookmarksmanager.cpp +++ b/src/bookmarks/bookmarksmanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,26 +65,25 @@ #include "autosaver.h" #include "bookmarknode.h" #include "bookmarksmodel.h" -#include "browserapplication.h" #include "history.h" #include "xbelreader.h" #include "xbelwriter.h" #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include -#include -#include -#include -#include +#include +#include +#include +#include -#include +#include -#include +#include #define BOOKMARKBAR QT_TRANSLATE_NOOP("BookmarksManager", "Bookmarks Bar") #define BOOKMARKMENU QT_TRANSLATE_NOOP("BookmarksManager", "Bookmarks Menu") @@ -93,10 +92,10 @@ BookmarksManager::BookmarksManager(QObject *parent) : QObject(parent) , m_loaded(false) , m_saveTimer(new AutoSaver(this)) - , m_bookmarkRootNode(0) - , m_toolbar(0) - , m_menu(0) - , m_bookmarkModel(0) + , m_bookmarkRootNode(nullptr) + , m_toolbar(nullptr) + , m_menu(nullptr) + , m_bookmarkModel(nullptr) { connect(this, SIGNAL(entryAdded(BookmarkNode *)), m_saveTimer, SLOT(changeOccurred())); @@ -124,16 +123,16 @@ void BookmarksManager::load() m_loaded = true; QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/data/Endorphin"; - QString bookmarkFile = dir + QLatin1String("/bookmarks.xbel"); + QString bookmarkFile = dir + QStringLiteral("/bookmarks.xbel"); if (!QFile::exists(bookmarkFile)) - bookmarkFile = QLatin1String(":defaultbookmarks.xbel"); + bookmarkFile = QStringLiteral(":defaultbookmarks.xbel"); XbelReader reader; m_bookmarkRootNode = reader.read(bookmarkFile); if (reader.error() != QXmlStreamReader::NoError) { - QMessageBox::warning(0, QLatin1String("Loading Bookmark"), - tr("Error when loading bookmarks on line %1, column %2:\n" - "%3").arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.errorString())); + QMessageBox::warning(nullptr, QStringLiteral("Loading Bookmark"), + tr("Error when loading bookmarks on line %1, column %2:\n" + "%3").arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.errorString())); } QList others; @@ -142,7 +141,7 @@ void BookmarksManager::load() if (node->type() == BookmarkNode::Folder) { // Automatically convert if ((node->title == tr("Toolbar Bookmarks") - || node->title == QLatin1String(BOOKMARKBAR)) && !m_toolbar) { + || node->title == QString(BOOKMARKBAR)) && !m_toolbar) { node->title = tr(BOOKMARKBAR); m_toolbar = node; @@ -150,7 +149,7 @@ void BookmarksManager::load() // Automatically convert if ((node->title == tr("Menu") - || node->title == QLatin1String(BOOKMARKMENU)) && !m_menu) { + || node->title == QString(BOOKMARKMENU)) && !m_menu) { node->title = tr(BOOKMARKMENU); m_menu = node; } @@ -185,10 +184,10 @@ void BookmarksManager::save() const XbelWriter writer; QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/data/Endorphin"; - QString bookmarkFile = dir + QLatin1String("/bookmarks.xbel"); + QString bookmarkFile = dir + QStringLiteral("/bookmarks.xbel"); // Save root folder titles in English (i.e. not localized) - m_menu->title = QLatin1String(BOOKMARKMENU); - m_toolbar->title = QLatin1String(BOOKMARKBAR); + m_menu->title = QString(BOOKMARKMENU); + m_toolbar->title = QString(BOOKMARKBAR); if (!writer.write(bookmarkFile, m_bookmarkRootNode)) qWarning() << "BookmarkManager: error saving to" << bookmarkFile; // Restore localized titles @@ -279,18 +278,18 @@ BookmarksModel *BookmarksManager::bookmarksModel() void BookmarksManager::importBookmarks() { QStringList supportedFormats; - supportedFormats << tr("XBEL bookmarks").append(QLatin1String("(*.xbel *.xml)")); - supportedFormats << tr("HTML Netscape bookmarks").append(QLatin1String("(*.html)")); + supportedFormats << tr("XBEL bookmarks").append(QStringLiteral("(*.xbel *.xml)")); + supportedFormats << tr("HTML Netscape bookmarks").append(QStringLiteral("(*.html)")); - QString fileName = QFileDialog::getOpenFileName(0, tr("Open File"), - QString(), supportedFormats.join(QLatin1String(";;"))); + QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Open File"), + QString(), supportedFormats.join(QStringLiteral(";;"))); if (fileName.isEmpty()) return; XbelReader reader; - BookmarkNode *importRootNode = 0; - if (fileName.endsWith(QLatin1String(".html"))) { - QString program = QLatin1String("htmlToXBel"); + BookmarkNode *importRootNode = nullptr; + if (fileName.endsWith(QStringLiteral(".html"))) { + QString program = QStringLiteral("htmlToXBel"); QStringList arguments; arguments << fileName; QProcess process; @@ -298,12 +297,12 @@ void BookmarksManager::importBookmarks() process.waitForFinished(-1); if (process.error() != QProcess::UnknownError) { if (process.error() == QProcess::FailedToStart) { - QMessageBox::warning(0, tr("htmlToXBel tool required"), - tr("htmlToXBel tool, which is shipped with Endorphin and is needed to import HTML bookmarks, " - "is not installed or not available in the search paths.")); + QMessageBox::warning(nullptr, tr("htmlToXBel tool required"), + tr("htmlToXBel tool, which is shipped with Endorphin and is needed to import HTML bookmarks, " + "is not installed or not available in the search paths.")); } else { - QMessageBox::warning(0, tr("Loading Bookmark"), - tr("Error when loading HTML bookmarks: %1\n").arg(process.errorString())); + QMessageBox::warning(nullptr, tr("Loading Bookmark"), + tr("Error when loading HTML bookmarks: %1\n").arg(process.errorString())); } return; } @@ -312,9 +311,9 @@ void BookmarksManager::importBookmarks() importRootNode = reader.read(fileName); } if (reader.error() != QXmlStreamReader::NoError) { - QMessageBox::warning(0, QLatin1String("Loading Bookmark"), - tr("Error when loading bookmarks on line %1, column %2:\n" - "%3").arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.errorString())); + QMessageBox::warning(nullptr, QStringLiteral("Loading Bookmark"), + tr("Error when loading bookmarks on line %1, column %2:\n" + "%3").arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.errorString())); delete importRootNode; return; } @@ -326,15 +325,15 @@ void BookmarksManager::importBookmarks() void BookmarksManager::exportBookmarks() { - QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"), - tr("%1 Bookmarks.xbel").arg(QCoreApplication::applicationName()), - tr("XBEL bookmarks").append(QLatin1String("(*.xbel *.xml)"))); + QString fileName = QFileDialog::getSaveFileName(nullptr, tr("Save File"), + tr("%1 Bookmarks.xbel").arg(QCoreApplication::applicationName()), + tr("XBEL bookmarks").append(QStringLiteral("(*.xbel *.xml)"))); if (fileName.isEmpty()) return; XbelWriter writer; if (!writer.write(fileName, m_bookmarkRootNode)) - QMessageBox::critical(0, tr("Export error"), tr("error saving bookmarks")); + QMessageBox::critical(nullptr, tr("Export error"), tr("error saving bookmarks")); } RemoveBookmarksCommand::RemoveBookmarksCommand(BookmarksManager *m_bookmarkManagaer, BookmarkNode *parent, int row) @@ -357,19 +356,19 @@ RemoveBookmarksCommand::~RemoveBookmarksCommand() void RemoveBookmarksCommand::undo() { m_parent->add(m_node, m_row); - emit m_bookmarkManagaer->entryAdded(m_node); + Q_EMIT m_bookmarkManagaer->entryAdded(m_node); m_done = false; } void RemoveBookmarksCommand::redo() { m_parent->remove(m_node); - emit m_bookmarkManagaer->entryRemoved(m_parent, m_row, m_node); + Q_EMIT m_bookmarkManagaer->entryRemoved(m_parent, m_row, m_node); m_done = true; } InsertBookmarksCommand::InsertBookmarksCommand(BookmarksManager *m_bookmarkManagaer, - BookmarkNode *parent, BookmarkNode *node, int row) + BookmarkNode *parent, BookmarkNode *node, int row) : RemoveBookmarksCommand(m_bookmarkManagaer, parent, row) { setText(BookmarksManager::tr("Insert Bookmark")); @@ -377,7 +376,7 @@ InsertBookmarksCommand::InsertBookmarksCommand(BookmarksManager *m_bookmarkManag } ChangeBookmarkCommand::ChangeBookmarkCommand(BookmarksManager *m_bookmarkManagaer, BookmarkNode *node, - const QString &newValue, bool title) + const QString &newValue, bool title) : QUndoCommand() , m_bookmarkManagaer(m_bookmarkManagaer) , m_title(title) @@ -399,7 +398,7 @@ void ChangeBookmarkCommand::undo() m_node->title = m_oldValue; else m_node->url = m_oldValue; - emit m_bookmarkManagaer->entryChanged(m_node); + Q_EMIT m_bookmarkManagaer->entryChanged(m_node); } void ChangeBookmarkCommand::redo() @@ -408,6 +407,6 @@ void ChangeBookmarkCommand::redo() m_node->title = m_newValue; else m_node->url = m_newValue; - emit m_bookmarkManagaer->entryChanged(m_node); + Q_EMIT m_bookmarkManagaer->entryChanged(m_node); } diff --git a/src/bookmarks/bookmarksmanager.h b/src/bookmarks/bookmarksmanager.h index 63d90021..2ecf8c51 100644 --- a/src/bookmarks/bookmarksmanager.h +++ b/src/bookmarks/bookmarksmanager.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef BOOKMARKSMANAGER_H #define BOOKMARKSMANAGER_H -#include +#include #include @@ -33,13 +33,13 @@ class BookmarksManager : public QObject { Q_OBJECT -signals: +Q_SIGNALS: void entryAdded(BookmarkNode *item); void entryRemoved(BookmarkNode *parent, int row, BookmarkNode *item); void entryChanged(BookmarkNode *item); public: - BookmarksManager(QObject *parent = 0); + BookmarksManager(QObject *parent = nullptr); ~BookmarksManager(); void addBookmark(BookmarkNode *parent, BookmarkNode *node, int row = -1); @@ -58,11 +58,11 @@ class BookmarksManager : public QObject return &m_commands; } -public slots: +public Q_SLOTS: void importBookmarks(); void exportBookmarks(); -private slots: +private Q_SLOTS: void save() const; private: diff --git a/src/bookmarks/bookmarksmenu.cpp b/src/bookmarks/bookmarksmenu.cpp index af09382d..0d8bb530 100644 --- a/src/bookmarks/bookmarksmenu.cpp +++ b/src/bookmarks/bookmarksmenu.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,7 +65,13 @@ #include "bookmarknode.h" #include "bookmarksmanager.h" #include "bookmarksmodel.h" +#ifndef NO_BROWSERAPPLICATION #include "browserapplication.h" +#else +#ifdef FOR_AUTOTEST +#include "tst_addbookmarkdialog.h" +#endif +#endif BookmarksMenu::BookmarksMenu(QWidget *parent) : ModelMenu(parent) @@ -86,7 +92,7 @@ ModelMenu *BookmarksMenu::createBaseMenu() void BookmarksMenu::activated(const QModelIndex &index) { - emit openUrl(index.data(BookmarksModel::UrlRole).toUrl(), + Q_EMIT openUrl(index.data(BookmarksModel::UrlRole).toUrl(), index.data(Qt::DisplayRole).toString()); } @@ -133,7 +139,7 @@ void BookmarksMenu::openAll() TabWidget::OpenUrlIn tab; tab = (i == 0) ? TabWidget::CurrentTab : TabWidget::NewTab; - emit openUrl(child.data(BookmarksModel::UrlRole).toUrl(), + Q_EMIT openUrl(child.data(BookmarksModel::UrlRole).toUrl(), tab, child.data(Qt::DisplayRole).toString()); } @@ -141,13 +147,21 @@ void BookmarksMenu::openAll() BookmarksMenuBarMenu::BookmarksMenuBarMenu(QWidget *parent) : BookmarksMenu(parent) - , m_bookmarksManager(0) + , m_bookmarksManager(nullptr) { } bool BookmarksMenuBarMenu::prePopulated() { +#ifndef NO_BROWSERAPPLICATION m_bookmarksManager = BrowserApplication::bookmarksManager(); +#else +#ifdef FOR_AUTOTEST + m_bookmarksManager = tst_AddBookmarkDialog::bookmarksManager(); +#else +#error "Nothing provides a bookmarksmanager" +#endif +#endif setModel(m_bookmarksManager->bookmarksModel()); setRootIndex(m_bookmarksManager->bookmarksModel()->index(m_bookmarksManager->menu())); // initial actions diff --git a/src/bookmarks/bookmarksmenu.h b/src/bookmarks/bookmarksmenu.h index 9513e923..7074bf30 100644 --- a/src/bookmarks/bookmarksmenu.h +++ b/src/bookmarks/bookmarksmenu.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -67,8 +67,8 @@ #include "tabwidget.h" -#include -#include +#include +#include class BookmarksManager; @@ -77,18 +77,18 @@ class BookmarksMenu : public ModelMenu { Q_OBJECT -signals: +Q_SIGNALS: void openUrl(const QUrl &url, const QString &title); void openUrl(const QUrl &url, TabWidget::OpenUrlIn tab, const QString &title); public: - BookmarksMenu(QWidget *parent = 0); + BookmarksMenu(QWidget *parent = nullptr); protected: void postPopulated(); ModelMenu *createBaseMenu(); -private slots: +private Q_SLOTS: void openAll(); void activated(const QModelIndex &index); @@ -100,7 +100,7 @@ class BookmarksMenuBarMenu : public BookmarksMenu Q_OBJECT public: - BookmarksMenuBarMenu(QWidget *parent = 0); + BookmarksMenuBarMenu(QWidget *parent = nullptr); void setInitialActions(QList actions); protected: diff --git a/src/bookmarks/bookmarksmodel.cpp b/src/bookmarks/bookmarksmodel.cpp index df5c9f8e..3150d414 100644 --- a/src/bookmarks/bookmarksmodel.cpp +++ b/src/bookmarks/bookmarksmodel.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,12 +65,14 @@ #include "addbookmarkdialog.h" #include "bookmarknode.h" #include "bookmarksmanager.h" +#ifndef NO_BROWSERAPPLICATION #include "browserapplication.h" +#endif #include "xbelreader.h" #include "xbelwriter.h" #include -#include +#include #include @@ -119,7 +121,7 @@ void BookmarksModel::entryRemoved(BookmarkNode *parent, int row, BookmarkNode *i void BookmarksModel::entryChanged(BookmarkNode *item) { QModelIndex idx = index(item); - emit dataChanged(idx, idx); + Q_EMIT dataChanged(idx, idx); } bool BookmarksModel::removeRows(int row, int count, const QModelIndex &parent) @@ -131,7 +133,7 @@ bool BookmarksModel::removeRows(int row, int count, const QModelIndex &parent) for (int i = row + count - 1; i >= row; --i) { BookmarkNode *node = bookmarkNode->children().at(i); if (node == m_bookmarksManager->menu() - || node == m_bookmarksManager->toolbar()) + || node == m_bookmarksManager->toolbar()) continue; m_bookmarksManager->removeBookmark(node); @@ -147,8 +149,10 @@ QVariant BookmarksModel::headerData(int section, Qt::Orientation orientation, in { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { - case 0: return tr("Title"); - case 1: return tr("Address"); + case 0: + return tr("Title"); + case 1: + return tr("Address"); } } return QAbstractItemModel::headerData(section, orientation, role); @@ -165,14 +169,18 @@ QVariant BookmarksModel::data(const QModelIndex &index, int role) const case Qt::DisplayRole: if (bookmarkNode->type() == BookmarkNode::Separator) { switch (index.column()) { - case 0: return QString(50, 0xB7); - case 1: return QString(); + case 0: + return QString(50, 0xB7); + case 1: + return QString(); } } switch (index.column()) { - case 0: return bookmarkNode->title; - case 1: return bookmarkNode->url; + case 0: + return bookmarkNode->title; + case 1: + return bookmarkNode->url; } break; case BookmarksModel::UrlRole: @@ -191,7 +199,9 @@ QVariant BookmarksModel::data(const QModelIndex &index, int role) const if (index.column() == 0) { if (bookmarkNode->type() == BookmarkNode::Folder) return QApplication::style()->standardIcon(QStyle::SP_DirIcon); +#ifndef NO_BROWSERAPPLICATION return BrowserApplication::instance()->icon(bookmarkNode->url); +#endif } } @@ -231,7 +241,7 @@ QModelIndex BookmarksModel::parent(const QModelIndex &index) const return QModelIndex(); BookmarkNode *itemNode = node(index); - BookmarkNode *parentNode = (itemNode ? itemNode->parent() : 0); + BookmarkNode *parentNode = (itemNode ? itemNode->parent() : nullptr); if (!parentNode || parentNode == m_bookmarksManager->bookmarks()) return QModelIndex(); @@ -263,13 +273,13 @@ Qt::ItemFlags BookmarksModel::flags(const QModelIndex &index) const flags |= Qt::ItemIsDropEnabled; if (node == m_bookmarksManager->menu() - || node == m_bookmarksManager->toolbar()) + || node == m_bookmarksManager->toolbar()) return flags; flags |= Qt::ItemIsDragEnabled; if ((index.column() == 0 && type != BookmarkNode::Separator) - || (index.column() == 1 && type == BookmarkNode::Bookmark)) + || (index.column() == 1 && type == BookmarkNode::Bookmark)) flags |= Qt::ItemIsEditable; return flags; @@ -280,13 +290,13 @@ Qt::DropActions BookmarksModel::supportedDropActions() const return Qt::CopyAction | Qt::MoveAction; } -#define MIMETYPE QLatin1String("application/bookmarks.xbel") +#define MIMETYPE QStringLiteral("application/bookmarks.xbel") QStringList BookmarksModel::mimeTypes() const { QStringList types; types << MIMETYPE; - types << QLatin1String("text/uri-list"); + types << QStringLiteral("text/uri-list"); return types; } @@ -296,7 +306,7 @@ QMimeData *BookmarksModel::mimeData(const QModelIndexList &indexes) const QByteArray data; QDataStream stream(&data, QIODevice::WriteOnly); QList urls; - foreach (const QModelIndex &index, indexes) { + Q_FOREACH (const QModelIndex &index, indexes) { if (index.column() != 0 || !index.isValid()) continue; QByteArray encodedData; @@ -314,7 +324,7 @@ QMimeData *BookmarksModel::mimeData(const QModelIndexList &indexes) const } bool BookmarksModel::dropMimeData(const QMimeData *data, - Qt::DropAction action, int row, int column, const QModelIndex &parent) + Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (action == Qt::IgnoreAction) return true; @@ -346,7 +356,7 @@ bool BookmarksModel::dropMimeData(const QMimeData *data, return false; QUndoStack *undoStack = m_bookmarksManager->undoRedoStack(); - undoStack->beginMacro(QLatin1String("Move Bookmarks")); + undoStack->beginMacro(QStringLiteral("Move Bookmarks")); while (!stream.atEnd()) { QByteArray encodedData; diff --git a/src/bookmarks/bookmarksmodel.h b/src/bookmarks/bookmarksmodel.h index 3960524d..3c56ab5f 100644 --- a/src/bookmarks/bookmarksmodel.h +++ b/src/bookmarks/bookmarksmodel.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,7 +63,7 @@ #ifndef BOOKMARKSMODEL_H #define BOOKMARKSMODEL_H -#include +#include #include @@ -73,7 +73,7 @@ class BookmarksModel : public QAbstractItemModel { Q_OBJECT -public slots: +public Q_SLOTS: void entryAdded(BookmarkNode *item); void entryRemoved(BookmarkNode *parent, int row, BookmarkNode *item); void entryChanged(BookmarkNode *item); @@ -86,7 +86,7 @@ public slots: SeparatorRole = Qt::UserRole + 4 }; - BookmarksModel(BookmarksManager *bookmarkManager, QObject *parent = 0); + BookmarksModel(BookmarksManager *bookmarkManager, QObject *parent = nullptr); inline BookmarksManager *bookmarksManager() const { return m_bookmarksManager; } diff --git a/src/bookmarks/bookmarkstoolbar.cpp b/src/bookmarks/bookmarkstoolbar.cpp index ea7d6964..791fd6a0 100644 --- a/src/bookmarks/bookmarkstoolbar.cpp +++ b/src/bookmarks/bookmarkstoolbar.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -25,17 +25,32 @@ #include "bookmarksmanager.h" #include "bookmarksmenu.h" #include "bookmarksmodel.h" +#ifndef NO_BROWSERAPPLICATION #include "browserapplication.h" +#else +#ifdef FOR_AUTOTEST +#include "tst_addbookmarkdialog.h" +#endif +#endif #include "modelmenu.h" -#include +#include BookmarksToolBar::BookmarksToolBar(BookmarksModel *model, QWidget *parent) : ModelToolBar(parent) , m_bookmarksModel(model) { setModel(model); + +#ifndef NO_BROWSERAPPLICATION setRootIndex(model->index(BrowserApplication::bookmarksManager()->toolbar())); +#else +#ifdef FOR_AUTOTEST + setRootIndex(model->index(tst_AddBookmarkDialog::bookmarksManager()->toolbar())); +#else +#error "Nothing provides a bookmarksmanager" +#endif +#endif setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), @@ -57,7 +72,7 @@ void BookmarksToolBar::contextMenuRequested(const QPoint &position) QVariant variant = action->data(); Q_ASSERT(variant.canConvert()); - QAction *menuAction = 0; + QAction *menuAction = nullptr; if (!action->menu()) { menuAction = menu.addAction(tr("Open"), this, SLOT(openBookmarkInCurrentTab())); @@ -85,7 +100,7 @@ void BookmarksToolBar::bookmarkActivated(const QModelIndex &index) { Q_ASSERT(index.isValid()); - emit openUrl( + Q_EMIT openUrl( index.data(BookmarksModel::UrlRole).toUrl(), index.data(Qt::DisplayRole).toString()); } @@ -94,7 +109,7 @@ void BookmarksToolBar::openBookmark() { QModelIndex index = ModelToolBar::index(qobject_cast(sender())); - emit openUrl( + Q_EMIT openUrl( index.data(BookmarksModel::UrlRole).toUrl(), index.data(Qt::DisplayRole).toString()); } @@ -103,7 +118,7 @@ void BookmarksToolBar::openBookmarkInCurrentTab() { QModelIndex index = ModelToolBar::index(qobject_cast(sender())); - emit openUrl( + Q_EMIT openUrl( index.data(BookmarksModel::UrlRole).toUrl(), TabWidget::CurrentTab, index.data(Qt::DisplayRole).toString()); @@ -113,7 +128,7 @@ void BookmarksToolBar::openBookmarkInNewTab() { QModelIndex index = ModelToolBar::index(qobject_cast(sender())); - emit openUrl( + Q_EMIT openUrl( index.data(BookmarksModel::UrlRole).toUrl(), TabWidget::NewTab, index.data(Qt::DisplayRole).toString()); diff --git a/src/bookmarks/bookmarkstoolbar.h b/src/bookmarks/bookmarkstoolbar.h index b18570ff..3b13667f 100644 --- a/src/bookmarks/bookmarkstoolbar.h +++ b/src/bookmarks/bookmarkstoolbar.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -25,29 +25,29 @@ #include "tabwidget.h" -#include +#include #include -#include +#include class BookmarksModel; class BookmarksToolBar : public ModelToolBar { Q_OBJECT -signals: +Q_SIGNALS: void openUrl(const QUrl &url, const QString &title); void openUrl(const QUrl &url, TabWidget::OpenUrlIn tab, const QString &title); public: - BookmarksToolBar(BookmarksModel *model, QWidget *parent = 0); + BookmarksToolBar(BookmarksModel *model, QWidget *parent = nullptr); protected: virtual ModelMenu *createMenu(); -private slots: +private Q_SLOTS: void contextMenuRequested(const QPoint &position); -protected slots: +protected Q_SLOTS: void openBookmark(); void openBookmarkInCurrentTab(); void openBookmarkInNewTab(); diff --git a/src/bookmarks/xbel/libxbel.cmake b/src/bookmarks/xbel/libxbel.cmake new file mode 100644 index 00000000..4d498d21 --- /dev/null +++ b/src/bookmarks/xbel/libxbel.cmake @@ -0,0 +1,8 @@ +set(XBEL_SRCS + src/bookmarks/xbel/xbelreader.cpp + src/bookmarks/xbel/xbelwriter.cpp + src/bookmarks/bookmarknode.cpp +) + +add_library(xbel STATIC ${XBEL_SRCS}) +target_link_libraries(xbel Qt5::Core) diff --git a/src/bookmarks/xbel/xbel.pri b/src/bookmarks/xbel/xbel.pri deleted file mode 100644 index 7615d5d3..00000000 --- a/src/bookmarks/xbel/xbel.pri +++ /dev/null @@ -1,11 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - xbelreader.h \ - xbelwriter.h - -SOURCES += \ - xbelreader.cpp \ - xbelwriter.cpp diff --git a/src/bookmarks/xbel/xbelreader.cpp b/src/bookmarks/xbel/xbelreader.cpp index 5c9818f0..cada9fc9 100644 --- a/src/bookmarks/xbel/xbelreader.cpp +++ b/src/bookmarks/xbel/xbelreader.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -62,20 +62,20 @@ #include "xbelreader.h" -#include +#include #include "bookmarknode.h" QString XmlEntityResolver::resolveUndeclaredEntity(const QString &entity) { - if (entity == QLatin1String("nbsp")) - return QLatin1String(" "); + if (entity == QStringLiteral("nbsp")) + return QStringLiteral(" "); return QString(); } XbelReader::XbelReader() - : m_entityResolver(0) + : m_entityResolver(nullptr) { m_entityResolver = new XmlEntityResolver(); setEntityResolver(m_entityResolver); @@ -103,9 +103,9 @@ BookmarkNode *XbelReader::read(QIODevice *device) while (!atEnd()) { readNext(); if (isStartElement()) { - QString version = attributes().value(QLatin1String("version")).toString(); - if (name() == QLatin1String("xbel") - && (version.isEmpty() || version == QLatin1String("1.0"))) { + QString version = attributes().value(QStringLiteral("version")).toString(); + if (name().toString() == QStringLiteral("xbel") + && (version.isEmpty() || version == QStringLiteral("1.0"))) { readXBEL(root); } else { raiseError(QObject::tr("The file is not an XBEL version 1.0 file.")); @@ -117,7 +117,7 @@ BookmarkNode *XbelReader::read(QIODevice *device) void XbelReader::readXBEL(BookmarkNode *parent) { - Q_ASSERT(isStartElement() && name() == QLatin1String("xbel")); + Q_ASSERT(isStartElement() && name() == QStringLiteral("xbel")); while (!atEnd()) { readNext(); @@ -125,11 +125,11 @@ void XbelReader::readXBEL(BookmarkNode *parent) break; if (isStartElement()) { - if (name() == QLatin1String("folder")) + if (name().toString() == QStringLiteral("folder")) readFolder(parent); - else if (name() == QLatin1String("bookmark")) + else if (name().toString() == QStringLiteral("bookmark")) readBookmarkNode(parent); - else if (name() == QLatin1String("separator")) + else if (name().toString() == QStringLiteral("separator")) readSeparator(parent); else skipUnknownElement(); @@ -139,10 +139,10 @@ void XbelReader::readXBEL(BookmarkNode *parent) void XbelReader::readFolder(BookmarkNode *parent) { - Q_ASSERT(isStartElement() && name() == QLatin1String("folder")); + Q_ASSERT(isStartElement() && name().toString() == QStringLiteral("folder")); BookmarkNode *folder = new BookmarkNode(BookmarkNode::Folder, parent); - folder->expanded = (attributes().value(QLatin1String("folded")) == QLatin1String("no")); + folder->expanded = (attributes().value(QStringLiteral("folded")) == QStringLiteral("no")); while (!atEnd()) { readNext(); @@ -151,15 +151,15 @@ void XbelReader::readFolder(BookmarkNode *parent) break; if (isStartElement()) { - if (name() == QLatin1String("title")) + if (name().toString() == QStringLiteral("title")) readTitle(folder); - else if (name() == QLatin1String("desc")) + else if (name().toString() == QStringLiteral("desc")) readDescription(folder); - else if (name() == QLatin1String("folder")) + else if (name().toString() == QStringLiteral("folder")) readFolder(folder); - else if (name() == QLatin1String("bookmark")) + else if (name().toString() == QStringLiteral("bookmark")) readBookmarkNode(folder); - else if (name() == QLatin1String("separator")) + else if (name().toString() == QStringLiteral("separator")) readSeparator(folder); else skipUnknownElement(); @@ -169,13 +169,13 @@ void XbelReader::readFolder(BookmarkNode *parent) void XbelReader::readTitle(BookmarkNode *parent) { - Q_ASSERT(isStartElement() && name() == QLatin1String("title")); + Q_ASSERT(isStartElement() && name().toString() == QStringLiteral("title")); parent->title = readElementText(); } void XbelReader::readDescription(BookmarkNode *parent) { - Q_ASSERT(isStartElement() && name() == QLatin1String("desc")); + Q_ASSERT(isStartElement() && name().toString() == QStringLiteral("desc")); parent->desc = readElementText(); } @@ -188,18 +188,18 @@ void XbelReader::readSeparator(BookmarkNode *parent) void XbelReader::readBookmarkNode(BookmarkNode *parent) { - Q_ASSERT(isStartElement() && name() == QLatin1String("bookmark")); + Q_ASSERT(isStartElement() && name().toString() == QStringLiteral("bookmark")); BookmarkNode *bookmark = new BookmarkNode(BookmarkNode::Bookmark, parent); - bookmark->url = attributes().value(QLatin1String("href")).toString(); + bookmark->url = attributes().value(QStringLiteral("href")).toString(); while (!atEnd()) { readNext(); if (isEndElement()) break; if (isStartElement()) { - if (name() == QLatin1String("title")) + if (name().toString() == QStringLiteral("title")) readTitle(bookmark); - else if (name() == QLatin1String("desc")) + else if (name().toString() == QStringLiteral("desc")) readDescription(bookmark); else skipUnknownElement(); diff --git a/src/bookmarks/xbel/xbelreader.h b/src/bookmarks/xbel/xbelreader.h index 43fb31a7..c54b53ca 100644 --- a/src/bookmarks/xbel/xbelreader.h +++ b/src/bookmarks/xbel/xbelreader.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,8 +63,9 @@ #ifndef XBELREADER_H #define XBELREADER_H -#include -#include +#include +#include +#include class BookmarkNode; class XmlEntityResolver : public QXmlStreamEntityResolver diff --git a/src/bookmarks/xbel/xbelwriter.cpp b/src/bookmarks/xbel/xbelwriter.cpp index c81cee6f..cb2c0dd8 100644 --- a/src/bookmarks/xbel/xbelwriter.cpp +++ b/src/bookmarks/xbel/xbelwriter.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -62,7 +62,7 @@ #include "xbelwriter.h" -#include +#include #include "bookmarknode.h" @@ -84,9 +84,9 @@ bool XbelWriter::write(QIODevice *device, const BookmarkNode *root) setDevice(device); writeStartDocument(); - writeDTD(QLatin1String("")); - writeStartElement(QLatin1String("xbel")); - writeAttribute(QLatin1String("version"), QLatin1String("1.0")); + writeDTD(QStringLiteral("")); + writeStartElement(QStringLiteral("xbel")); + writeAttribute(QStringLiteral("version"), QStringLiteral("1.0")); if (root->type() == BookmarkNode::Root) { for (int i = 0; i < root->children().count(); ++i) writeItem(root->children().at(i)); @@ -102,24 +102,24 @@ void XbelWriter::writeItem(const BookmarkNode *parent) { switch (parent->type()) { case BookmarkNode::Folder: - writeStartElement(QLatin1String("folder")); - writeAttribute(QLatin1String("folded"), parent->expanded ? QLatin1String("no") : QLatin1String("yes")); - writeTextElement(QLatin1String("title"), parent->title); + writeStartElement(QStringLiteral("folder")); + writeAttribute(QStringLiteral("folded"), parent->expanded ? QStringLiteral("no") : QStringLiteral("yes")); + writeTextElement(QStringLiteral("title"), parent->title); for (int i = 0; i < parent->children().count(); ++i) writeItem(parent->children().at(i)); writeEndElement(); break; case BookmarkNode::Bookmark: - writeStartElement(QLatin1String("bookmark")); + writeStartElement(QStringLiteral("bookmark")); if (!parent->url.isEmpty()) - writeAttribute(QLatin1String("href"), parent->url); - writeTextElement(QLatin1String("title"), parent->title); + writeAttribute(QStringLiteral("href"), parent->url); + writeTextElement(QStringLiteral("title"), parent->title); if (!parent->desc.isEmpty()) - writeAttribute(QLatin1String("desc"), parent->desc); + writeAttribute(QStringLiteral("desc"), parent->desc); writeEndElement(); break; case BookmarkNode::Separator: - writeEmptyElement(QLatin1String("separator")); + writeEmptyElement(QStringLiteral("separator")); break; default: break; diff --git a/src/bookmarks/xbel/xbelwriter.h b/src/bookmarks/xbel/xbelwriter.h index 0d62ac8a..c43af16c 100644 --- a/src/bookmarks/xbel/xbelwriter.h +++ b/src/bookmarks/xbel/xbelwriter.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,8 +63,8 @@ #ifndef XBELWRITER_H #define XBELWRITER_H -#include -#include +#include +#include class BookmarkNode; class XbelWriter : public QXmlStreamWriter diff --git a/src/browserapplication.cpp b/src/browserapplication.cpp index 6f0771f7..15946a51 100644 --- a/src/browserapplication.cpp +++ b/src/browserapplication.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -59,32 +59,79 @@ ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ #include "browserapplication.h" #include "autosaver.h" -#include "autofillmanager.h" #include "bookmarksmanager.h" #include "browsermainwindow.h" -#include "cookiejar.h" #include "downloadmanager.h" #include "historymanager.h" #include "languagemanager.h" -#include "networkaccessmanager.h" #include "tabwidget.h" #include "webview.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include +#include #ifdef Q_OS_WIN #include @@ -92,24 +139,60 @@ // #define BROWSERAPPLICATION_DEBUG -DownloadManager *BrowserApplication::s_downloadManager = 0; -HistoryManager *BrowserApplication::s_historyManager = 0; -NetworkAccessManager *BrowserApplication::s_networkAccessManager = 0; -BookmarksManager *BrowserApplication::s_bookmarksManager = 0; -LanguageManager *BrowserApplication::s_languageManager = 0; -AutoFillManager *BrowserApplication::s_autoFillManager = 0; +DownloadManager *BrowserApplication::s_downloadManager = nullptr; +HistoryManager *BrowserApplication::s_historyManager = nullptr; +BookmarksManager *BrowserApplication::s_bookmarksManager = nullptr; +LanguageManager *BrowserApplication::s_languageManager = nullptr; + + +static void setUserStyleSheet(QWebEngineProfile *profile, const QString &styleSheet, BrowserMainWindow *mainWindow = nullptr) +{ + Q_ASSERT(profile); + QString scriptName(QStringLiteral("userStyleSheet")); + QWebEngineScript script; + QList styleSheets = profile->scripts()->findScripts(scriptName); + if (!styleSheets.isEmpty()) + script = styleSheets.first(); + Q_FOREACH (const QWebEngineScript &s, styleSheets) + profile->scripts()->remove(s); + + if (script.isNull()) { + script.setName(scriptName); + script.setInjectionPoint(QWebEngineScript::DocumentReady); + script.setRunsOnSubFrames(true); + script.setWorldId(QWebEngineScript::ApplicationWorld); + } + QString source = QString::fromLatin1("(function() {"\ + "var css = document.getElementById(\"_qt_testBrowser_userStyleSheet\");"\ + "if (css == undefined) {"\ + " css = document.createElement(\"style\");"\ + " css.type = \"text/css\";"\ + " css.id = \"_qt_testBrowser_userStyleSheet\";"\ + " document.head.appendChild(css);"\ + "}"\ + "css.innerText = \"%1\";"\ + "})()").arg(styleSheet); + script.setSourceCode(source); + profile->scripts()->insert(script); + // run the script on the already loaded views + // this has to be deferred as it could mess with the storage initialization on startup + if (mainWindow) + QMetaObject::invokeMethod(mainWindow, "runScriptOnOpenViews", Qt::QueuedConnection, Q_ARG(QString, source)); +} BrowserApplication::BrowserApplication(int &argc, char **argv) : SingleApplication(argc, argv) , quitting(false) + , m_privateProfile(0) + , m_privateBrowsing(false) { - QCoreApplication::setOrganizationDomain(QLatin1String("aarondewes.github.io/endorphin/")); - QCoreApplication::setApplicationName(QLatin1String("Endorphin")); - QCoreApplication::setApplicationVersion(QLatin1String("0.12.1" + QCoreApplication::setOrganizationDomain(QStringLiteral("EndorphinBrowser.gitlab.io/")); + QCoreApplication::setApplicationName(QStringLiteral("Endorphin")); + QCoreApplication::setApplicationVersion(QStringLiteral("0.12.1" #ifdef GITVERSION - " (Git: " GITCHANGENUMBER " " GITVERSION ")" + " (Git: " GITCHANGENUMBER " " GITVERSION ")" #endif - )); + )); #ifndef AUTOTESTS connect(this, SIGNAL(messageReceived(QLocalSocket *)), @@ -121,7 +204,7 @@ BrowserApplication::BrowserApplication(int &argc, char **argv) sendMessage(message.toUtf8()); } // If we could connect to another Endorphin then exit - QString message = QString(QLatin1String("endorphin://getwinid")); + QString message = QString(QStringLiteral("endorphin://getwinid")); if (sendMessage(message.toUtf8(), 500)) return; @@ -140,25 +223,25 @@ BrowserApplication::BrowserApplication(int &argc, char **argv) QApplication::setQuitOnLastWindowClosed(true); #endif - QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl"); + QDesktopServices::setUrlHandler(QStringLiteral("http"), this, "openUrl"); - // Until QtWebkit defaults to 16 - QWebSettings::globalSettings()->setFontSize(QWebSettings::DefaultFontSize, 16); - QWebSettings::globalSettings()->setFontSize(QWebSettings::DefaultFixedFontSize, 16); + // Until QtWebEngine defaults to 16 + QWebEngineSettings::globalSettings()->setFontSize(QWebEngineSettings::DefaultFontSize, 16); + QWebEngineSettings::globalSettings()->setFontSize(QWebEngineSettings::DefaultFixedFontSize, 16); QSettings settings; - settings.beginGroup(QLatin1String("sessions")); - m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray(); + settings.beginGroup(QStringLiteral("sessions")); + m_lastSession = settings.value(QStringLiteral("lastSession")).toByteArray(); settings.endGroup(); #if defined(Q_WS_MAC) - connect(this, SIGNAL(lastWindowClosed()), - this, SLOT(lastWindowClosed())); + connect(this, &BrowserApplication::lastWindowClosed, + this, &BrowserApplication::lastWindowClosed); #endif // setting this in the postLaunch actually takes a lot more time // because the event has to be propagated to everyone. - setWindowIcon(QIcon(QLatin1String(":128x128/endorphin.png"))); + setWindowIcon(QIcon(QStringLiteral(":128x128/endorphin.png"))); #ifndef AUTOTESTS QTimer::singleShot(0, this, SLOT(postLaunch())); @@ -171,18 +254,16 @@ BrowserApplication::~BrowserApplication() quitting = true; delete s_downloadManager; qDeleteAll(m_mainWindows); - delete s_networkAccessManager; delete s_bookmarksManager; delete s_languageManager; delete s_historyManager; - delete s_autoFillManager; } #if defined(Q_WS_MAC) void BrowserApplication::lastWindowClosed() { clean(); - BrowserMainWindow *mw = new BrowserMainWindow; + BrowserMainWindow *mw = new BrowserMainWindow(nullptr, nullptr, QWebEngineProfile::defaultProfile()); mw->goHome(); m_mainWindows.prepend(mw); } @@ -196,7 +277,6 @@ BrowserApplication *BrowserApplication::instance() void BrowserApplication::retranslate() { bookmarksManager()->retranslate(); - networkAccessManager()->loadSettings(); } // The only special property of an argument url is that the file's @@ -222,10 +302,10 @@ void BrowserApplication::messageReceived(QLocalSocket *socket) return; // Got a normal url - if (!message.startsWith(QLatin1String("endorphin://"))) { + if (!message.startsWith(QStringLiteral("endorphin://"))) { QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - TabWidget::OpenUrlIn tab = TabWidget::OpenUrlIn(settings.value(QLatin1String("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); + settings.beginGroup(QStringLiteral("tabs")); + TabWidget::OpenUrlIn tab = TabWidget::OpenUrlIn(settings.value(QStringLiteral("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); settings.endGroup(); if (QUrl(message) == m_lastAskedUrl && m_lastAskedUrlDateTime.addSecs(10) > QDateTime::currentDateTime()) { @@ -235,40 +315,40 @@ void BrowserApplication::messageReceived(QLocalSocket *socket) mainWindow()->tabWidget()->loadString(message, tab); return; } else { - if (message.startsWith(QLatin1String("endorphin://getwinid"))) { - #ifdef Q_OS_WIN - QString winid = QString(QLatin1String("%1")).arg((qlonglong)mainWindow()->winId()); - #else + if (message.startsWith(QStringLiteral("endorphin://getwinid"))) { +#ifdef Q_OS_WIN + QString winid = QString(QStringLiteral("%1")).arg((qlonglong)mainWindow()->winId()); +#else mainWindow()->show(); mainWindow()->setFocus(); mainWindow()->raise(); mainWindow()->activateWindow(); alert(mainWindow()); QString winid; - #endif - #ifdef BROWSERAPPLICATION_DEBUG +#endif +#ifdef BROWSERAPPLICATION_DEBUG qDebug() << "BrowserApplication::" << __FUNCTION__ << "sending win id" << winid << mainWindow()->winId(); - #endif - QString message = QLatin1String("endorphin://winid/") + winid; +#endif + QString message = QStringLiteral("endorphin://winid/") + winid; socket->write(message.toUtf8()); socket->waitForBytesWritten(); return; - } + } - if (message.startsWith(QLatin1String("endorphin://winid"))) { + if (message.startsWith(QStringLiteral("endorphin://winid"))) { QString winid = message.mid(21); - #ifdef BROWSERAPPLICATION_DEBUG +#ifdef BROWSERAPPLICATION_DEBUG qDebug() << "BrowserApplication::" << __FUNCTION__ << "got win id:" << winid; - #endif - #ifdef Q_OS_WIN +#endif +#ifdef Q_OS_WIN WId wid = (WId)winid.toLongLong(); SetForegroundWindow(wid); - #endif +#endif return; } QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - TabWidget::OpenUrlIn tab = TabWidget::OpenUrlIn(settings.value(QLatin1String("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); + settings.beginGroup(QStringLiteral("tabs")); + TabWidget::OpenUrlIn tab = TabWidget::OpenUrlIn(settings.value(QStringLiteral("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); settings.endGroup(); if (QUrl(message) == m_lastAskedUrl && m_lastAskedUrlDateTime.addSecs(10) > QDateTime::currentDateTime()) { @@ -285,7 +365,7 @@ void BrowserApplication::quitBrowser() if (s_downloadManager && !downloadManager()->allowQuit()) return; - if (QSettings().value(QLatin1String("tabs/confirmClosingMultipleTabs"), true).toBool()) { + if (QSettings().value(QStringLiteral("tabs/confirmClosingMultipleTabs"), true).toBool()) { clean(); int tabCount = 0; for (int i = 0; i < m_mainWindows.count(); ++i) { @@ -296,10 +376,10 @@ void BrowserApplication::quitBrowser() QWidget *widget = mainWindow(); QApplication::alert(widget); int ret = QMessageBox::warning(widget, QString(), - tr("There are %1 windows and %2 tabs open\n" - "Do you want to quit anyway?").arg(m_mainWindows.count()).arg(tabCount), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + tr("There are %1 windows and %2 tabs open\n" + "Do you want to quit anyway?").arg(m_mainWindows.count()).arg(tabCount), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No); if (ret == QMessageBox::No) return; } @@ -316,16 +396,16 @@ void BrowserApplication::postLaunch() { QString directory = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); if (directory.isEmpty()) - directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName(); - QWebSettings::setIconDatabasePath(directory); + directory = QDir::homePath() + QStringLiteral("/.") + QCoreApplication::applicationName(); + // QWebEngineSettings::setIconDatabasePath(directory); loadSettings(); // newMainWindow() needs to be called in main() for this to happen if (m_mainWindows.count() > 0) { QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - int startup = settings.value(QLatin1String("startupBehavior")).toInt(); + settings.beginGroup(QStringLiteral("MainWindow")); + int startup = settings.value(QStringLiteral("startupBehavior")).toInt(); QStringList args = QCoreApplication::arguments(); if (args.count() > 1) { @@ -359,39 +439,38 @@ void BrowserApplication::postLaunch() void BrowserApplication::loadSettings() { QSettings settings; - settings.beginGroup(QLatin1String("websettings")); + settings.beginGroup(QStringLiteral("websettings")); - QWebSettings *defaultSettings = QWebSettings::globalSettings(); - QString standardFontFamily = defaultSettings->fontFamily(QWebSettings::StandardFont); - int standardFontSize = defaultSettings->fontSize(QWebSettings::DefaultFontSize); + QWebEngineSettings *defaultSettings = QWebEngineSettings::globalSettings(); + QWebEngineProfile *defaultProfile = QWebEngineProfile::defaultProfile(); + QString standardFontFamily = defaultSettings->fontFamily(QWebEngineSettings::StandardFont); + int standardFontSize = defaultSettings->fontSize(QWebEngineSettings::DefaultFontSize); QFont standardFont = QFont(standardFontFamily, standardFontSize); - standardFont = settings.value(QLatin1String("standardFont"), standardFont).value(); - defaultSettings->setFontFamily(QWebSettings::StandardFont, standardFont.family()); - defaultSettings->setFontSize(QWebSettings::DefaultFontSize, standardFont.pointSize()); - int minimumFontSize = settings.value(QLatin1String("minimumFontSize"), - defaultSettings->fontSize(QWebSettings::MinimumFontSize)).toInt(); - defaultSettings->setFontSize(QWebSettings::MinimumFontSize, minimumFontSize); - - QString fixedFontFamily = defaultSettings->fontFamily(QWebSettings::FixedFont); - int fixedFontSize = defaultSettings->fontSize(QWebSettings::DefaultFixedFontSize); + standardFont = settings.value(QStringLiteral("standardFont"), standardFont).value(); + defaultSettings->setFontFamily(QWebEngineSettings::StandardFont, standardFont.family()); + defaultSettings->setFontSize(QWebEngineSettings::DefaultFontSize, standardFont.pointSize()); + int minimumFontSize = settings.value(QStringLiteral("minimumFontSize"), + defaultSettings->fontSize(QWebEngineSettings::MinimumFontSize)).toInt(); + defaultSettings->setFontSize(QWebEngineSettings::MinimumFontSize, minimumFontSize); + + QString fixedFontFamily = defaultSettings->fontFamily(QWebEngineSettings::FixedFont); + int fixedFontSize = defaultSettings->fontSize(QWebEngineSettings::DefaultFixedFontSize); QFont fixedFont = QFont(fixedFontFamily, fixedFontSize); - fixedFont = settings.value(QLatin1String("fixedFont"), fixedFont).value(); - defaultSettings->setFontFamily(QWebSettings::FixedFont, fixedFont.family()); - defaultSettings->setFontSize(QWebSettings::DefaultFixedFontSize, fixedFont.pointSize()); + fixedFont = settings.value(QStringLiteral("fixedFont"), fixedFont).value(); + defaultSettings->setFontFamily(QWebEngineSettings::FixedFont, fixedFont.family()); + defaultSettings->setFontSize(QWebEngineSettings::DefaultFixedFontSize, fixedFont.pointSize()); - defaultSettings->setAttribute(QWebSettings::JavascriptCanOpenWindows, !(settings.value(QLatin1String("blockPopupWindows"), true).toBool())); - defaultSettings->setAttribute(QWebSettings::JavascriptEnabled, settings.value(QLatin1String("enableJavascript"), true).toBool()); - defaultSettings->setAttribute(QWebSettings::PluginsEnabled, settings.value(QLatin1String("enablePlugins"), true).toBool()); - defaultSettings->setAttribute(QWebSettings::AutoLoadImages, settings.value(QLatin1String("enableImages"), true).toBool()); - defaultSettings->setAttribute(QWebSettings::LocalStorageEnabled, settings.value(QLatin1String("enableLocalStorage"), true).toBool()); - defaultSettings->setAttribute(QWebSettings::DeveloperExtrasEnabled, settings.value(QLatin1String("enableInspector"), false).toBool()); - defaultSettings->setAttribute(QWebSettings::DnsPrefetchEnabled, true); + defaultSettings->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, !(settings.value(QStringLiteral("blockPopupWindows"), true).toBool())); + defaultSettings->setAttribute(QWebEngineSettings::JavascriptEnabled, settings.value(QStringLiteral("enableJavascript"), true).toBool()); + defaultSettings->setAttribute(QWebEngineSettings::AutoLoadImages, settings.value(QStringLiteral("enableImages"), true).toBool()); + defaultSettings->setAttribute(QWebEngineSettings::LocalStorageEnabled, settings.value(QStringLiteral("enableLocalStorage"), true).toBool()); + defaultSettings->setAttribute(QWebEngineSettings::DnsPrefetchEnabled, true); - QUrl url = settings.value(QLatin1String("userStyleSheet")).toUrl(); - defaultSettings->setUserStyleSheetUrl(url); + QString css = settings.value(QStringLiteral("userStyleSheet")).toString(); + setUserStyleSheet(defaultProfile, css, mainWindow()); - int maximumPagesInCache = settings.value(QLatin1String("maximumPagesInCache"), 3).toInt(); - QWebSettings::globalSettings()->setMaximumPagesInCache(maximumPagesInCache); +// int maximumPagesInCache = settings.value(QStringLiteral("maximumPagesInCache"), 3).toInt(); +// QWebEngineSettings::globalSettings()->setMaximumPagesInCache(maximumPagesInCache); settings.endGroup(); } @@ -432,17 +511,16 @@ void BrowserApplication::saveSession() if (quitting) return; QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - settings.setValue(QLatin1String("restoring"), false); + settings.beginGroup(QStringLiteral("MainWindow")); + settings.setValue(QStringLiteral("restoring"), false); settings.endGroup(); - QWebSettings *globalSettings = QWebSettings::globalSettings(); - if (globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled)) + if (m_privateBrowsing) return; clean(); - settings.beginGroup(QLatin1String("sessions")); + settings.beginGroup(QStringLiteral("sessions")); int version = 2; @@ -457,7 +535,7 @@ void BrowserApplication::saveSession() stream << qint32(m_mainWindows.count()); for (int i = 0; i < m_mainWindows.count(); ++i) stream << m_mainWindows.at(i)->saveState(); - settings.setValue(QLatin1String("lastSession"), data); + settings.setValue(QStringLiteral("lastSession"), data); settings.endGroup(); } @@ -470,16 +548,16 @@ bool BrowserApplication::restoreLastSession() { { QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - if (settings.value(QLatin1String("restoring"), false).toBool()) { - QMessageBox::StandardButton result = QMessageBox::question(0, tr("Restore failed"), - tr("Endorphin crashed while trying to restore this session. Should I try again?"), QMessageBox::Yes | QMessageBox::No); + settings.beginGroup(QStringLiteral("MainWindow")); + if (settings.value(QStringLiteral("restoring"), false).toBool()) { + QMessageBox::StandardButton result = QMessageBox::question(nullptr, tr("Restore failed"), + tr("Endorphin crashed while trying to restore this session. Should I try again?"), QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::No) return false; } // saveSession will be called by an AutoSaver timer from the set tabs // and in saveSession we will reset this flag back to false - settings.setValue(QLatin1String("restoring"), true); + settings.setValue(QStringLiteral("restoring"), true); } int version = 2; QList windows; @@ -502,7 +580,7 @@ bool BrowserApplication::restoreLastSession() windows.append(windowState); } for (int i = 0; i < windows.count(); ++i) { - BrowserMainWindow *newWindow = 0; + BrowserMainWindow *newWindow = nullptr; if (i == 0 && m_mainWindows.count() >= 1) { newWindow = mainWindow(); } else { @@ -558,10 +636,10 @@ BrowserMainWindow *BrowserApplication::newMainWindow() { if (!m_mainWindows.isEmpty()) mainWindow()->m_autoSaver->saveIfNeccessary(); - BrowserMainWindow *browser = new BrowserMainWindow(); + BrowserMainWindow *browser = new BrowserMainWindow(nullptr, nullptr, QWebEngineProfile::defaultProfile()); m_mainWindows.prepend(browser); - connect(this, SIGNAL(privacyChanged(bool)), - browser, SLOT(privacyChanged(bool))); + connect(this, &BrowserApplication::privacyChanged, + this, &BrowserApplication::privacyChanged); browser->show(); return browser; } @@ -570,7 +648,7 @@ BrowserMainWindow *BrowserApplication::mainWindow() { clean(); - BrowserMainWindow *activeWindow = 0; + BrowserMainWindow *activeWindow = nullptr; if (m_mainWindows.isEmpty()) { activeWindow = newMainWindow(); @@ -583,11 +661,6 @@ BrowserMainWindow *BrowserApplication::mainWindow() return activeWindow; } -CookieJar *BrowserApplication::cookieJar() -{ - return (CookieJar*)networkAccessManager()->cookieJar(); -} - DownloadManager *BrowserApplication::downloadManager() { if (!s_downloadManager) @@ -595,13 +668,6 @@ DownloadManager *BrowserApplication::downloadManager() return s_downloadManager; } -NetworkAccessManager *BrowserApplication::networkAccessManager() -{ - if (!s_networkAccessManager) - s_networkAccessManager = new NetworkAccessManager(); - return s_networkAccessManager; -} - HistoryManager *BrowserApplication::historyManager() { if (!s_historyManager) @@ -620,26 +686,19 @@ LanguageManager *BrowserApplication::languageManager() { if (!s_languageManager) { s_languageManager = new LanguageManager(); - s_languageManager->addLocaleDirectory(dataFilePath(QLatin1String("locale"))); - s_languageManager->addLocaleDirectory(qApp->applicationDirPath() + QLatin1String("/src/.qm/locale")); - s_languageManager->addLocaleDirectory(installedDataDirectory() + QLatin1String("/locale")); + s_languageManager->addLocaleDirectory(dataFilePath(QStringLiteral("locale"))); + s_languageManager->addLocaleDirectory(qApp->applicationDirPath() + QStringLiteral("/src/.qm/locale")); + s_languageManager->addLocaleDirectory(installedDataDirectory() + QStringLiteral("/locale")); + s_languageManager->addLocaleDirectory(installedDataDirectory() + QStringLiteral("/endorphin_locale")); s_languageManager->loadLanguageFromSettings(); - connect(s_languageManager, SIGNAL(languageChanged(const QString &)), - qApp, SLOT(retranslate())); + connect(s_languageManager, &LanguageManager::languageChanged, + BrowserApplication::instance(), &BrowserApplication::retranslate); } return s_languageManager; } - -AutoFillManager *BrowserApplication::autoFillManager() -{ - if (!s_autoFillManager) { - s_autoFillManager = new AutoFillManager; - } - return s_autoFillManager; -} - QIcon BrowserApplication::icon(const QUrl &url) { + /* QIcon icon = QWebSettings::iconForUrl(url); if (!icon.isNull()) return icon.pixmap(16, 16); @@ -652,12 +711,14 @@ QIcon BrowserApplication::icon(const QUrl &url) return pixmap; } return icon; + */ + return QPixmap(":graphics/defaulticon.png"); } QString BrowserApplication::installedDataDirectory() { #if defined(Q_WS_X11) - return QLatin1String(PKGDATADIR); + return QString(PKGDATADIR); #else return qApp->applicationDirPath(); #endif @@ -667,34 +728,56 @@ QString BrowserApplication::dataFilePath(const QString &fileName) { QString directory = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/data/Endorphin"; if (directory.isEmpty()) - directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName(); + directory = QDir::homePath() + QStringLiteral("/.") + QCoreApplication::applicationName(); if (!QFile::exists(directory)) { QDir dir; dir.mkpath(directory); } - return directory + QLatin1String("/") + fileName; + return directory + QStringLiteral("/") + fileName; } bool BrowserApplication::zoomTextOnly() { - return QWebSettings::globalSettings()->testAttribute(QWebSettings::ZoomTextOnly); + QSettings settings; + settings.beginGroup(QStringLiteral("WebEngine")); + bool textOnly = settings.value(QStringLiteral("zoomTextOnly")).toBool(); + settings.endGroup(); + return textOnly; } void BrowserApplication::setZoomTextOnly(bool textOnly) { - QWebSettings::globalSettings()->setAttribute(QWebSettings::ZoomTextOnly, textOnly); - emit instance()->zoomTextOnlyChanged(textOnly); + QSettings settings; + settings.beginGroup(QStringLiteral("WebEngine")); + settings.setValue(QStringLiteral("zoomTextOnly"), textOnly); + settings.endGroup(); + Q_EMIT instance()->zoomTextOnlyChanged(textOnly); } bool BrowserApplication::isPrivate() { - return QWebSettings::globalSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled); + return m_privateBrowsing; } -void BrowserApplication::setPrivate(bool isPrivate) + +void BrowserApplication::setPrivate(bool privateBrowsing) { - QWebSettings::globalSettings()->setAttribute(QWebSettings::PrivateBrowsingEnabled, isPrivate); - emit instance()->privacyChanged(isPrivate); + if (m_privateBrowsing == privateBrowsing) + return; + m_privateBrowsing = privateBrowsing; + if (privateBrowsing) { + if (!m_privateProfile) + m_privateProfile = new QWebEngineProfile(this); + Q_FOREACH (BrowserMainWindow* window, mainWindows()) { + window->tabWidget()->setProfile(m_privateProfile); + } + } else { + Q_FOREACH (BrowserMainWindow* window, mainWindows()) { + window->tabWidget()->setProfile(QWebEngineProfile::defaultProfile()); + window->tabWidget()->clear(); + } + } + Q_EMIT privacyChanged(privateBrowsing); } Qt::MouseButtons BrowserApplication::eventMouseButtons() const @@ -716,4 +799,3 @@ void BrowserApplication::setEventKeyboardModifiers(Qt::KeyboardModifiers modifie { m_eventKeyboardModifiers = modifiers; } - diff --git a/src/browserapplication.h b/src/browserapplication.h index 3d1b4827..a060c8d1 100644 --- a/src/browserapplication.h +++ b/src/browserapplication.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,19 +65,17 @@ #include "singleapplication.h" -#include -#include -#include +#include +#include +#include -class AutoFillManager; class BookmarksManager; class BrowserMainWindow; -class CookieJar; class DownloadManager; class HistoryManager; -class NetworkAccessManager; class LanguageManager; class QLocalSocket; +class QWebEngineProfile; class BrowserApplication : public SingleApplication { Q_OBJECT @@ -98,12 +96,9 @@ class BrowserApplication : public SingleApplication bool canRestoreSession() const; static HistoryManager *historyManager(); - static CookieJar *cookieJar(); static DownloadManager *downloadManager(); - static NetworkAccessManager *networkAccessManager(); static BookmarksManager *bookmarksManager(); static LanguageManager *languageManager(); - static AutoFillManager *autoFillManager(); static QString installedDataDirectory(); static QString dataFilePath(const QString &fileName); @@ -115,14 +110,11 @@ class BrowserApplication : public SingleApplication static bool zoomTextOnly(); - static bool isPrivate(); - static void setPrivate(bool isPrivate); - #if defined(Q_WS_MAC) bool event(QEvent *event); #endif -public slots: +public Q_SLOTS: BrowserMainWindow *newMainWindow(); bool restoreLastSession(); #if defined(Q_WS_MAC) @@ -134,13 +126,16 @@ public slots: void askDesktopToOpenUrl(const QUrl &url); -private slots: + bool isPrivate(); + void setPrivate(bool isPrivate); + +private Q_SLOTS: void retranslate(); void messageReceived(QLocalSocket *socket); void postLaunch(); void openUrl(const QUrl &url); -signals: +Q_SIGNALS: void zoomTextOnlyChanged(bool textOnly); void privacyChanged(bool isPrivate); @@ -150,14 +145,14 @@ private slots: static HistoryManager *s_historyManager; static DownloadManager *s_downloadManager; - static NetworkAccessManager *s_networkAccessManager; static BookmarksManager *s_bookmarksManager; static LanguageManager *s_languageManager; - static AutoFillManager *s_autoFillManager; QList > m_mainWindows; QByteArray m_lastSession; bool quitting; + QWebEngineProfile *m_privateProfile; + bool m_privateBrowsing; Qt::MouseButtons m_eventMouseButtons; Qt::KeyboardModifiers m_eventKeyboardModifiers; diff --git a/src/browsermainwindow.cpp b/src/browsermainwindow.cpp index 84dd2afc..ac51437a 100644 --- a/src/browsermainwindow.cpp +++ b/src/browsermainwindow.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Jason A. Donenfeld * Copyright 2008 Ariya Hidayat * @@ -65,7 +65,6 @@ #include "browsermainwindow.h" #include "aboutdialog.h" -#include "adblockmanager.h" #include "addbookmarkdialog.h" #include "autosaver.h" #include "bookmarksdialog.h" @@ -75,13 +74,12 @@ #include "bookmarkstoolbar.h" #include "browserapplication.h" #include "clearprivatedata.h" +#include "devtoolswindow.h" #include "downloadmanager.h" #include "history.h" #include "languagemanager.h" -#include "networkaccessmanager.h" #include "opensearchdialog.h" #include "settings.h" -#include "sourceviewer.h" #include "tabbar.h" #include "tabwidget.h" #include "toolbarsearch.h" @@ -89,38 +87,40 @@ #include "webview.h" #include "webviewsearch.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags, QWebEngineProfile *profile) : QMainWindow(parent, flags) - , m_navigationBar(0) - , m_navigationSplitter(0) - , m_toolbarSearch(0) + , m_navigationBar(nullptr) + , m_navigationSplitter(nullptr) + , m_toolbarSearch(nullptr) #if defined(Q_WS_MAC) , m_bookmarksToolbarFrame(0) #endif - , m_bookmarksToolbar(0) - , m_tabWidget(new TabWidget(this)) + , m_bookmarksToolbar(nullptr) + , m_tabWidget(new TabWidget(this, profile)) , m_autoSaver(new AutoSaver(this)) + , m_profile(profile) { setAttribute(Qt::WA_DeleteOnClose, true); statusBar()->setSizeGripEnabled(true); @@ -130,12 +130,12 @@ BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags) setupMenu(); setupToolBar(); - m_filePrivateBrowsingAction->setChecked(BrowserApplication::isPrivate()); + m_filePrivateBrowsingAction->setChecked(BrowserApplication::instance()->isPrivate()); QWidget *centralWidget = new QWidget(this); BookmarksModel *boomarksModel = BrowserApplication::bookmarksManager()->bookmarksModel(); m_bookmarksToolbar = new BookmarksToolBar(boomarksModel, this); - m_bookmarksToolbar->setObjectName(QLatin1String("BookmarksToolbar")); + m_bookmarksToolbar->setObjectName(QStringLiteral("BookmarksToolbar")); connect(m_bookmarksToolbar, SIGNAL(openUrl(const QUrl&, const QString&)), m_tabWidget, SLOT(loadUrlFromUser(const QUrl&, const QString&))); connect(m_bookmarksToolbar, SIGNAL(openUrl(const QUrl&, TabWidget::OpenUrlIn, const QString&)), @@ -192,18 +192,11 @@ BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags) m_autoSaver, SLOT(changeOccurred())); connect(m_tabWidget, SIGNAL(geometryChangeRequested(const QRect &)), this, SLOT(geometryChangeRequested(const QRect &))); - connect(m_tabWidget, SIGNAL(printRequested(QWebFrame *)), - this, SLOT(printRequested(QWebFrame *))); - connect(m_tabWidget, SIGNAL(menuBarVisibilityChangeRequested(bool)), - menuBar(), SLOT(setVisible(bool))); - connect(m_tabWidget, SIGNAL(statusBarVisibilityChangeRequested(bool)), - statusBar(), SLOT(setVisible(bool))); - connect(m_tabWidget, SIGNAL(toolBarVisibilityChangeRequested(bool)), - m_navigationBar, SLOT(setVisible(bool))); - connect(m_tabWidget, SIGNAL(toolBarVisibilityChangeRequested(bool)), - m_bookmarksToolbar, SLOT(setVisible(bool))); + connect(m_tabWidget, SIGNAL(printRequested()), + this, SLOT(printRequested())); connect(m_tabWidget, SIGNAL(lastTabClosed()), this, SLOT(lastTabClosed())); + connect(m_tabWidget, &TabWidget::devToolsRequested, this, &BrowserMainWindow::handleDevToolsRequested); updateWindowTitle(); loadDefaultState(); @@ -216,7 +209,7 @@ BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags) // Add each item in the menu bar to the main window so // if the menu bar is hidden the shortcuts still work. QList actions = menuBar()->actions(); - foreach (QAction *action, actions) { + Q_FOREACH (QAction *action, actions) { if (action->menu()) actions += action->menu()->actions(); addAction(action); @@ -225,7 +218,7 @@ BrowserMainWindow::BrowserMainWindow(QWidget *parent, Qt::WindowFlags flags) setWindowIcon(QIcon()); #endif #if defined(Q_WS_X11) - setWindowRole(QLatin1String("browser")); + setWindowRole(QStringLiteral("browser")); #endif retranslate(); } @@ -238,6 +231,7 @@ BrowserMainWindow::~BrowserMainWindow() void BrowserMainWindow::keyPressEvent(QKeyEvent *event) { + QSettings settings; switch (event->key()) { case Qt::Key_HomePage: m_historyHomeAction->trigger(); @@ -248,8 +242,12 @@ void BrowserMainWindow::keyPressEvent(QKeyEvent *event) event->accept(); break; case Qt::Key_Search: - m_toolsWebSearchAction->trigger(); - event->accept(); + settings.beginGroup(QStringLiteral("appearance")); + if(settings.value(QStringLiteral("urlBarType"), 0).toInt() == 0) { + m_toolsWebSearchAction->trigger(); + event->accept(); + } + settings.endGroup(); break; case Qt::Key_OpenUrl: m_fileOpenLocationAction->trigger(); @@ -277,8 +275,8 @@ BrowserMainWindow *BrowserMainWindow::parentWindow(QWidget *widget) void BrowserMainWindow::loadDefaultState() { QSettings settings; - settings.beginGroup(QLatin1String("BrowserMainWindow")); - QByteArray data = settings.value(QLatin1String("defaultState")).toByteArray(); + settings.beginGroup(QStringLiteral("BrowserMainWindow")); + QByteArray data = settings.value(QStringLiteral("defaultState")).toByteArray(); restoreState(data); settings.endGroup(); } @@ -296,9 +294,9 @@ void BrowserMainWindow::save() BrowserApplication::instance()->saveSession(); QSettings settings; - settings.beginGroup(QLatin1String("BrowserMainWindow")); + settings.beginGroup(QStringLiteral("BrowserMainWindow")); QByteArray data = saveState(false); - settings.setValue(QLatin1String("defaultState"), data); + settings.setValue(QStringLiteral("defaultState"), data); settings.endGroup(); } @@ -306,7 +304,7 @@ static const qint32 BrowserMainWindowMagic = 0xba; QByteArray BrowserMainWindow::saveState(bool withTabs) const { - int version = 3; + int version = 4; QByteArray data; QDataStream stream(&data, QIODevice::WriteOnly); @@ -322,7 +320,6 @@ QByteArray BrowserMainWindow::saveState(bool withTabs) const stream << tabWidget()->saveState(); else stream << QByteArray(); - stream << m_navigationSplitter->saveState(); stream << m_tabWidget->tabBar()->showTabBarWhenOneTab(); stream << qint32(toolBarArea(m_navigationBar)); @@ -373,7 +370,6 @@ bool BrowserMainWindow::restoreState(const QByteArray &state) stream >> showBookmarksBarDEAD; stream >> showStatusbar; stream >> tabState; - stream >> splitterState; stream >> showTabBarWhenOneTab; stream >> navigationBarLocation; stream >> bookmarkBarLocation; @@ -407,8 +403,6 @@ bool BrowserMainWindow::restoreState(const QByteArray &state) statusBar()->setVisible(showStatusbar); - m_navigationSplitter->restoreState(splitterState); - tabWidget()->restoreState(tabState); m_tabWidget->tabBar()->setShowTabBarWhenOneTab(showTabBarWhenOneTab); @@ -436,8 +430,8 @@ bool BrowserMainWindow::restoreState(const QByteArray &state) void BrowserMainWindow::lastTabClosed() { QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - bool quit = settings.value(QLatin1String("quitAsLastTabClosed"), true).toBool(); + settings.beginGroup(QStringLiteral("tabs")); + bool quit = settings.value(QStringLiteral("quitAsLastTabClosed"), true).toBool(); if (quit) close(); @@ -540,13 +534,13 @@ void BrowserMainWindow::setupMenu() m_fileMenu->addAction(m_fileQuit); #if defined(Q_WS_X11) - m_fileNewWindowAction->setIcon(QIcon::fromTheme(QLatin1String("window-new"))); - m_fileOpenFileAction->setIcon(QIcon::fromTheme(QLatin1String("document-open"))); - m_filePrintPreviewAction->setIcon(QIcon::fromTheme(QLatin1String("document-print-preview"))); - m_filePrintAction->setIcon(QIcon::fromTheme(QLatin1String("document-print"))); - m_fileSaveAsAction->setIcon(QIcon::fromTheme(QLatin1String("document-save-as"))); - m_fileCloseWindow->setIcon(QIcon::fromTheme(QLatin1String("window-close"))); - m_fileQuit->setIcon(QIcon::fromTheme(QLatin1String("application-exit"))); + m_fileNewWindowAction->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); + m_fileOpenFileAction->setIcon(QIcon::fromTheme(QStringLiteral("document-open"))); + m_filePrintPreviewAction->setIcon(QIcon::fromTheme(QStringLiteral("document-print-preview"))); + m_filePrintAction->setIcon(QIcon::fromTheme(QStringLiteral("document-print"))); + m_fileSaveAsAction->setIcon(QIcon::fromTheme(QStringLiteral("document-save-as"))); + m_fileCloseWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); + m_fileQuit->setIcon(QIcon::fromTheme(QStringLiteral("application-exit"))); #endif // Edit @@ -554,28 +548,28 @@ void BrowserMainWindow::setupMenu() menuBar()->addMenu(m_editMenu); m_editUndoAction = new QAction(m_editMenu); m_editUndoAction->setShortcuts(QKeySequence::Undo); - m_tabWidget->addWebAction(m_editUndoAction, QWebPage::Undo); + m_tabWidget->addWebAction(m_editUndoAction, QWebEnginePage::Undo); m_editMenu->addAction(m_editUndoAction); m_editRedoAction = new QAction(m_editMenu); m_editRedoAction->setShortcuts(QKeySequence::Redo); - m_tabWidget->addWebAction(m_editRedoAction, QWebPage::Redo); + m_tabWidget->addWebAction(m_editRedoAction, QWebEnginePage::Redo); m_editMenu->addAction(m_editRedoAction); m_editMenu->addSeparator(); m_editCutAction = new QAction(m_editMenu); m_editCutAction->setShortcuts(QKeySequence::Cut); - m_tabWidget->addWebAction(m_editCutAction, QWebPage::Cut); + m_tabWidget->addWebAction(m_editCutAction, QWebEnginePage::Cut); m_editMenu->addAction(m_editCutAction); m_editCopyAction = new QAction(m_editMenu); m_editCopyAction->setShortcuts(QKeySequence::Copy); - m_tabWidget->addWebAction(m_editCopyAction, QWebPage::Copy); + m_tabWidget->addWebAction(m_editCopyAction, QWebEnginePage::Copy); m_editMenu->addAction(m_editCopyAction); m_editPasteAction = new QAction(m_editMenu); m_editPasteAction->setShortcuts(QKeySequence::Paste); - m_tabWidget->addWebAction(m_editPasteAction, QWebPage::Paste); + m_tabWidget->addWebAction(m_editPasteAction, QWebEnginePage::Paste); m_editMenu->addAction(m_editPasteAction); m_editSelectAllAction = new QAction(m_editMenu); m_editSelectAllAction->setShortcuts(QKeySequence::SelectAll); - m_tabWidget->addWebAction(m_editSelectAllAction, QWebPage::SelectAll); + m_tabWidget->addWebAction(m_editSelectAllAction, QWebEnginePage::SelectAll); m_editMenu->addAction(m_editSelectAllAction); m_editMenu->addSeparator(); @@ -596,13 +590,13 @@ void BrowserMainWindow::setupMenu() m_editMenu->addAction(m_editFindPreviousAction); #if defined(Q_WS_X11) - m_editUndoAction->setIcon(QIcon::fromTheme(QLatin1String("edit-undo"))); - m_editRedoAction->setIcon(QIcon::fromTheme(QLatin1String("edit-redo"))); - m_editCutAction->setIcon(QIcon::fromTheme(QLatin1String("edit-cut"))); - m_editCopyAction->setIcon(QIcon::fromTheme(QLatin1String("edit-copy"))); - m_editPasteAction->setIcon(QIcon::fromTheme(QLatin1String("edit-paste"))); - m_editSelectAllAction->setIcon(QIcon::fromTheme(QLatin1String("edit-select-all"))); - m_editFindAction->setIcon(QIcon::fromTheme(QLatin1String("edit-find"))); + m_editUndoAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-undo"))); + m_editRedoAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-redo"))); + m_editCutAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-cut"))); + m_editCopyAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy"))); + m_editPasteAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-paste"))); + m_editSelectAllAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-all"))); + m_editFindAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-find"))); #endif // View @@ -640,7 +634,7 @@ void BrowserMainWindow::setupMenu() shortcuts.append(QKeySequence(Qt::CTRL | Qt::Key_Period)); shortcuts.append(Qt::Key_Escape); m_viewStopAction->setShortcuts(shortcuts); - m_tabWidget->addWebAction(m_viewStopAction, QWebPage::Stop); + m_tabWidget->addWebAction(m_viewStopAction, QWebEnginePage::Stop); m_viewMenu->addAction(m_viewStopAction); m_viewReloadAction = new QAction(m_viewMenu); @@ -648,7 +642,7 @@ void BrowserMainWindow::setupMenu() shortcuts.append(QKeySequence(Qt::CTRL | Qt::Key_R)); shortcuts.append(QKeySequence(Qt::Key_F5)); m_viewReloadAction->setShortcuts(shortcuts); - m_tabWidget->addWebAction(m_viewReloadAction, QWebPage::Reload); + m_tabWidget->addWebAction(m_viewReloadAction, QWebEnginePage::Reload); m_viewMenu->addAction(m_viewReloadAction); m_viewZoomInAction = new QAction(m_viewMenu); @@ -714,10 +708,10 @@ void BrowserMainWindow::setupMenu() #if defined(Q_WS_X11) m_viewStopAction->setIcon(m_stopIcon); m_viewReloadAction->setIcon(m_reloadIcon); - m_viewZoomInAction->setIcon(QIcon::fromTheme(QLatin1String("zoom-in"))); - m_viewZoomNormalAction->setIcon(QIcon::fromTheme(QLatin1String("zoom-original"))); - m_viewZoomOutAction->setIcon(QIcon::fromTheme(QLatin1String("zoom-out"))); - m_viewFullScreenAction->setIcon(QIcon::fromTheme(QLatin1String("view-fullscreen"))); + m_viewZoomInAction->setIcon(QIcon::fromTheme(QStringLiteral("zoom-in"))); + m_viewZoomNormalAction->setIcon(QIcon::fromTheme(QStringLiteral("zoom-original"))); + m_viewZoomOutAction->setIcon(QIcon::fromTheme(QStringLiteral("zoom-out"))); + m_viewFullScreenAction->setIcon(QIcon::fromTheme(QStringLiteral("view-fullscreen"))); #endif // History @@ -728,14 +722,14 @@ void BrowserMainWindow::setupMenu() QList historyActions; m_historyBackAction = new QAction(this); - m_tabWidget->addWebAction(m_historyBackAction, QWebPage::Back); + m_tabWidget->addWebAction(m_historyBackAction, QWebEnginePage::Back); m_historyBackAction->setShortcuts(QKeySequence::Back); #if !defined(Q_WS_X11) m_historyBackAction->setIconVisibleInMenu(false); #endif m_historyForwardAction = new QAction(this); - m_tabWidget->addWebAction(m_historyForwardAction, QWebPage::Forward); + m_tabWidget->addWebAction(m_historyForwardAction, QWebEnginePage::Forward); m_historyForwardAction->setShortcuts(QKeySequence::Forward); #if !defined(Q_WS_X11) m_historyForwardAction->setIconVisibleInMenu(false); @@ -757,8 +751,8 @@ void BrowserMainWindow::setupMenu() historyActions.append(m_historyRestoreLastSessionAction); m_historyMenu->setInitialActions(historyActions); #if defined(Q_WS_X11) - m_historyRestoreLastSessionAction->setIcon(QIcon::fromTheme(QLatin1String("document-revert"))); - m_historyHomeAction->setIcon(QIcon::fromTheme(QLatin1String("go-home"))); + m_historyRestoreLastSessionAction->setIcon(QIcon::fromTheme(QStringLiteral("document-revert"))); + m_historyHomeAction->setIcon(QIcon::fromTheme(QStringLiteral("go-home"))); #endif // Bookmarks @@ -775,7 +769,7 @@ void BrowserMainWindow::setupMenu() this, SLOT(showBookmarksDialog())); m_bookmarksAddAction = new QAction(this); - m_bookmarksAddAction->setIcon(QIcon(QLatin1String(":addbookmark.png"))); + m_bookmarksAddAction->setIcon(QIcon(QStringLiteral(":addbookmark.png"))); #if !defined(Q_WS_X11) m_bookmarksAddAction->setIconVisibleInMenu(false); #endif @@ -794,8 +788,8 @@ void BrowserMainWindow::setupMenu() bookmarksActions.append(m_bookmarksAddFolderAction); m_bookmarksMenu->setInitialActions(bookmarksActions); - m_bookmarksAddFolderAction->setIcon(QIcon::fromTheme(QLatin1String("folder-new"))); - m_bookmarksShowAllAction->setIcon(QIcon::fromTheme(QLatin1String("user-bookmarks"))); + m_bookmarksAddFolderAction->setIcon(QIcon::fromTheme(QStringLiteral("folder-new"))); + m_bookmarksShowAllAction->setIcon(QIcon::fromTheme(QStringLiteral("user-bookmarks"))); // Window m_windowMenu = new QMenu(menuBar()); @@ -808,25 +802,21 @@ void BrowserMainWindow::setupMenu() m_toolsMenu = new QMenu(menuBar()); menuBar()->addMenu(m_toolsMenu); - m_toolsWebSearchAction = new QAction(m_toolsMenu); - connect(m_toolsWebSearchAction, SIGNAL(triggered()), - this, SLOT(webSearch())); - m_toolsMenu->addAction(m_toolsWebSearchAction); + QSettings settings; + settings.beginGroup(QStringLiteral("appearance")); + if(settings.value(QStringLiteral("urlBarType"), 0).toInt() == 0) { + m_toolsWebSearchAction = new QAction(m_toolsMenu); + connect(m_toolsWebSearchAction, SIGNAL(triggered()), + this, SLOT(webSearch())); + m_toolsMenu->addAction(m_toolsWebSearchAction); + } + settings.endGroup(); m_toolsClearPrivateDataAction = new QAction(m_toolsMenu); connect(m_toolsClearPrivateDataAction, SIGNAL(triggered()), this, SLOT(clearPrivateData())); m_toolsMenu->addAction(m_toolsClearPrivateDataAction); - m_toolsEnableInspectorAction = new QAction(m_toolsMenu); - connect(m_toolsEnableInspectorAction, SIGNAL(triggered(bool)), - this, SLOT(toggleInspector(bool))); - m_toolsEnableInspectorAction->setCheckable(true); - QSettings settings; - settings.beginGroup(QLatin1String("websettings")); - m_toolsEnableInspectorAction->setChecked(settings.value(QLatin1String("enableInspector"), false).toBool()); - m_toolsMenu->addAction(m_toolsEnableInspectorAction); - m_toolsSearchManagerAction = new QAction(m_toolsMenu); m_toolsSearchManagerAction->setMenuRole(QAction::NoRole); connect(m_toolsSearchManagerAction, SIGNAL(triggered()), @@ -836,11 +826,6 @@ void BrowserMainWindow::setupMenu() m_toolsUserAgentMenu = new UserAgentMenu(m_toolsMenu); m_toolsMenu->addMenu(m_toolsUserAgentMenu); - m_adBlockDialogAction = new QAction(m_toolsMenu); - connect(m_adBlockDialogAction, SIGNAL(triggered()), - AdBlockManager::instance(), SLOT(showDialog())); - m_toolsMenu->addAction(m_adBlockDialogAction); - m_toolsMenu->addSeparator(); m_toolsPreferencesAction = new QAction(m_toolsMenu); m_toolsPreferencesAction->setMenuRole(QAction::PreferencesRole); @@ -869,8 +854,8 @@ void BrowserMainWindow::setupMenu() m_helpMenu->addAction(m_helpAboutApplicationAction); #if defined(Q_WS_X11) - m_helpChangeLanguageAction->setIcon(QIcon::fromTheme(QLatin1String("preferences-desktop-locale"))); - m_helpAboutQtAction->setIcon(QPixmap(QLatin1String(":/trolltech/qmessagebox/images/qtlogo-64.png"))); + m_helpChangeLanguageAction->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-locale"))); + m_helpAboutQtAction->setIcon(QPixmap(QStringLiteral(":/trolltech/qmessagebox/images/qtlogo-64.png"))); m_helpAboutApplicationAction->setIcon(windowIcon()); #endif } @@ -889,13 +874,13 @@ void BrowserMainWindow::aboutToShowTextEncodingMenu() int currentCodec = -1; QStringList codecs; QList mibs = QTextCodec::availableMibs(); - foreach (const int &mib, mibs) { - QString codec = QLatin1String(QTextCodec::codecForMib(mib)->name()); + Q_FOREACH (const int &mib, mibs) { + QString codec = QString(QTextCodec::codecForMib(mib)->name()); codecs.append(codec); } codecs.sort(); - QString defaultTextEncoding = QWebSettings::globalSettings()->defaultTextEncoding(); + QString defaultTextEncoding = QWebEngineSettings::globalSettings()->defaultTextEncoding(); currentCodec = codecs.indexOf(defaultTextEncoding); QAction *defaultEncoding = m_viewTextEncodingMenu->addAction(tr("Default")); @@ -921,9 +906,9 @@ void BrowserMainWindow::viewTextEncoding(QAction *action) Q_ASSERT(action); QString codec = action->data().toString(); if (codec.isEmpty()) - QWebSettings::globalSettings()->setDefaultTextEncoding(QString()); + QWebEngineSettings::globalSettings()->setDefaultTextEncoding(QString()); else - QWebSettings::globalSettings()->setDefaultTextEncoding(codec); + QWebEngineSettings::globalSettings()->setDefaultTextEncoding(codec); } void BrowserMainWindow::retranslate() @@ -982,16 +967,19 @@ void BrowserMainWindow::retranslate() m_windowMenu->setTitle(tr("&Window")); m_toolsMenu->setTitle(tr("&Tools")); - m_toolsWebSearchAction->setText(tr("Web &Search")); - m_toolsWebSearchAction->setShortcut(QKeySequence(tr("Ctrl+K", "Web Search"))); + QSettings settings; + settings.beginGroup(QStringLiteral("appearance")); + if(settings.value(QStringLiteral("urlBarType"), 0).toInt() == 0) { + m_toolsWebSearchAction->setText(tr("Web &Search")); + m_toolsWebSearchAction->setShortcut(QKeySequence(tr("Ctrl+K", "Web Search"))); + } + settings.endGroup(); m_toolsClearPrivateDataAction->setText(tr("&Clear Private Data")); m_toolsClearPrivateDataAction->setShortcut(QKeySequence(tr("Ctrl+Shift+Delete", "Clear Private Data"))); - m_toolsEnableInspectorAction->setText(tr("Enable Web &Inspector")); m_toolsPreferencesAction->setText(tr("Options...")); m_toolsPreferencesAction->setShortcut(tr("Ctrl+,")); m_toolsSearchManagerAction->setText(tr("Configure Search Engines...")); m_toolsUserAgentMenu->setTitle(tr("User Agent")); - m_adBlockDialogAction->setText(tr("&Ad Block...")); m_helpMenu->setTitle(tr("&Help")); m_helpChangeLanguageAction->setText(tr("Switch application language ")); @@ -1010,10 +998,10 @@ void BrowserMainWindow::setupToolBar() { setUnifiedTitleAndToolBarOnMac(true); m_navigationBar = new QToolBar(this); - m_navigationBar->setObjectName(QLatin1String("NavigationToolBar")); + m_navigationBar->setObjectName(QStringLiteral("NavigationToolBar")); addToolBar(m_navigationBar); - m_historyBackAction->setIcon(style()->standardIcon(QStyle::SP_ArrowBack, 0, this)); + m_historyBackAction->setIcon(style()->standardIcon(QStyle::SP_ArrowBack, nullptr, this)); m_historyBackMenu = new QMenu(this); m_historyBackAction->setMenu(m_historyBackMenu); connect(m_historyBackMenu, SIGNAL(aboutToShow()), @@ -1022,7 +1010,7 @@ void BrowserMainWindow::setupToolBar() this, SLOT(openActionUrl(QAction *))); m_navigationBar->addAction(m_historyBackAction); - m_historyForwardAction->setIcon(style()->standardIcon(QStyle::SP_ArrowForward, 0, this)); + m_historyForwardAction->setIcon(style()->standardIcon(QStyle::SP_ArrowForward, nullptr, this)); m_historyForwardMenu = new QMenu(this); connect(m_historyForwardMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowForwardMenu())); @@ -1035,21 +1023,27 @@ void BrowserMainWindow::setupToolBar() m_stopReloadAction->setIcon(m_reloadIcon); m_navigationBar->addAction(m_stopReloadAction); - m_navigationSplitter = new QSplitter(m_navigationBar); - m_navigationSplitter->addWidget(m_tabWidget->locationBarStack()); - - m_toolbarSearch = new ToolbarSearch(m_navigationBar); - m_navigationSplitter->addWidget(m_toolbarSearch); - connect(m_toolbarSearch, SIGNAL(search(const QUrl&, TabWidget::OpenUrlIn)), - m_tabWidget, SLOT(loadUrl(const QUrl&, TabWidget::OpenUrlIn))); - m_navigationSplitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); + QSettings settings; + settings.beginGroup(QStringLiteral("appearance")); + if(settings.value(QStringLiteral("urlBarType"), 0).toInt() == 0) { + m_navigationSplitter = new QSplitter(m_navigationBar); + m_navigationSplitter->addWidget(m_tabWidget->locationBarStack()); + m_toolbarSearch = new ToolbarSearch(m_navigationBar); + m_navigationSplitter->addWidget(m_toolbarSearch); + connect(m_toolbarSearch, SIGNAL(search(const QUrl&, TabWidget::OpenUrlIn)), + m_tabWidget, SLOT(loadUrl(const QUrl&, TabWidget::OpenUrlIn))); + m_navigationSplitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); + m_navigationSplitter->setCollapsible(0, false); + m_navigationBar->addWidget(m_navigationSplitter); + int splitterWidth = m_navigationSplitter->width(); + QList sizes; + sizes << (int)((double)splitterWidth * .80) << (int)((double)splitterWidth * .20); + m_navigationSplitter->setSizes(sizes); + } else { + m_navigationBar->addWidget(m_tabWidget->locationBarStack()); + } + settings.endGroup(); m_tabWidget->locationBarStack()->setMinimumWidth(120); - m_navigationSplitter->setCollapsible(0, false); - m_navigationBar->addWidget(m_navigationSplitter); - int splitterWidth = m_navigationSplitter->width(); - QList sizes; - sizes << (int)((double)splitterWidth * .80) << (int)((double)splitterWidth * .20); - m_navigationSplitter->setSizes(sizes); } void BrowserMainWindow::showBookmarksDialog() @@ -1064,7 +1058,7 @@ void BrowserMainWindow::showBookmarksDialog() void BrowserMainWindow::addBookmark() { WebView *webView = currentTab(); - QString url = QLatin1String(webView->url().toEncoded()); + QString url = QString(webView->url().toEncoded()); QString title = webView->title(); AddBookmarkDialog dialog; @@ -1150,7 +1144,7 @@ void BrowserMainWindow::selectLineEdit() void BrowserMainWindow::fileSaveAs() { - BrowserApplication::downloadManager()->download(currentTab()->url(), true); + currentTab()->page()->download(currentTab()->url(), ""); } void BrowserMainWindow::preferences() @@ -1189,8 +1183,8 @@ void BrowserMainWindow::fileNew() BrowserMainWindow *window = BrowserApplication::instance()->newMainWindow(); QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - int startup = settings.value(QLatin1String("startupBehavior")).toInt(); + settings.beginGroup(QStringLiteral("MainWindow")); + int startup = settings.value(QStringLiteral("startupBehavior")).toInt(); if (startup == 0) window->goHome(); @@ -1211,9 +1205,11 @@ void BrowserMainWindow::filePrintPreview() { if (!currentTab()) return; - QPrintPreviewDialog dialog(this); - connect(&dialog, SIGNAL(paintRequested(QPrinter *)), - currentTab(), SLOT(print(QPrinter *))); + + QPrinter printer; + QPrintPreviewDialog dialog(&printer, currentTab()->page()->view()); + connect(&dialog, &QPrintPreviewDialog::paintRequested, + this, &BrowserMainWindow::printDocument); dialog.exec(); } @@ -1221,29 +1217,52 @@ void BrowserMainWindow::filePrint() { if (!currentTab()) return; - printRequested(currentTab()->page()->mainFrame()); + printRequested(); } -void BrowserMainWindow::printRequested(QWebFrame *frame) +void BrowserMainWindow::printRequested() { - QPrinter printer; - QPrintDialog dialog(&printer, this); - dialog.setWindowTitle(tr("Print Document")); + if (!currentTab()) + return; + QPrinter printer(QPrinter::HighResolution); + QPrintDialog dialog(&printer, currentTab()->page()->view()); if (dialog.exec() != QDialog::Accepted) return; - frame->print(&printer); + printDocument(&printer); +} + +void BrowserMainWindow::printDocument(QPrinter *printer) +{ + if (!currentTab()) + return; + QEventLoop loop; + bool result; + auto printPreview = [&](bool success) { result = success; loop.quit(); }; + currentTab()->page()->print(printer, std::move(printPreview)); + loop.exec(); + if (!result) { + QPainter painter; + if (painter.begin(printer)) { + QFont font = painter.font(); + font.setPixelSize(20); + painter.setFont(font); + painter.drawText(QPointF(10,25), + QStringLiteral("Could not generate print preview.")); + + painter.end(); + } + } } void BrowserMainWindow::privateBrowsing() { - if (!BrowserApplication::isPrivate()) { + if (!BrowserApplication::instance()->isPrivate()) { QString title = tr("Are you sure you want to turn on private browsing?"); QString text1 = tr("When private browsing is turned on, some actions concerning your privacy will be disabled:"); QStringList actions; actions.append(tr("Webpages are not added to the history.")); actions.append(tr("Items are automatically removed from the Downloads window.")); - actions.append(tr("New cookies are not stored, current cookies can't be accessed.")); actions.append(tr("Site icons won't be stored.")); actions.append(tr("Session won't be saved.")); actions.append(tr("Searches are not added to the pop-up menu in the search box.")); @@ -1252,18 +1271,18 @@ void BrowserMainWindow::privateBrowsing() QString text2 = tr("Until you close the window, you can still click the Back and Forward " "buttons to return to the webpages you have opened."); - QString message = QString(QLatin1String("%1

%2

  • %3

%4

")) - .arg(title, text1, actions.join(QLatin1String("
  • ")), text2); + QString message = QString(QStringLiteral("%1

    %2

    • %3

    %4

    ")) + .arg(title, text1, actions.join(QStringLiteral("
  • ")), text2); QMessageBox::StandardButton button = QMessageBox::question(this, tr("Private Browsing"), message, - QMessageBox::Ok | QMessageBox::Cancel, - QMessageBox::Ok); + QMessageBox::Ok | QMessageBox::Cancel, + QMessageBox::Ok); if (button == QMessageBox::Ok) - BrowserApplication::setPrivate(true); + BrowserApplication::instance()->setPrivate(true); else m_filePrivateBrowsingAction->setChecked(false); } else { - BrowserApplication::setPrivate(false); + BrowserApplication::instance()->setPrivate(false); } } @@ -1290,8 +1309,8 @@ void BrowserMainWindow::closeEvent(QCloseEvent *event) if (m_tabWidget->count() > 1) { QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - bool confirm = settings.value(QLatin1String("confirmClosingMultipleTabs"), true).toBool(); + settings.beginGroup(QStringLiteral("tabs")); + bool confirm = settings.value(QStringLiteral("confirmClosingMultipleTabs"), true).toBool(); if (confirm) { QApplication::alert(this); int ret = QMessageBox::warning(this, QString(), @@ -1390,18 +1409,31 @@ void BrowserMainWindow::viewPageSource() return; QString title = currentTab()->title(); - QString markup = currentTab()->page()->mainFrame()->toHtml(); + QEventLoop loop; + connect(this, SIGNAL(notifyGotHTML()), &loop, SLOT(quit())); + currentTab()->page()->toHtml([this](const QVariant &v) + { + QString tmp = v.toString(); + this->gotHTML(tmp); + }); + loop.exec(); QUrl url = currentTab()->url(); - SourceViewer *viewer = new SourceViewer(markup, title, url); - viewer->setAttribute(Qt::WA_DeleteOnClose); - viewer->show(); + if(!url.toString().startsWith("view-source:")) { + tabWidget()->loadUrl(QUrl("view-source:" + url.toString()), TabWidget::NewSelectedTab); + } +} + +void BrowserMainWindow::gotHTML(QString &value) +{ + markup = value; + Q_EMIT notifyGotHTML(); } void BrowserMainWindow::goHome() { QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - QString home = settings.value(QLatin1String("home"), QLatin1String("about:home")).toString(); + settings.beginGroup(QStringLiteral("MainWindow")); + QString home = settings.value(QStringLiteral("home"), QStringLiteral("about:home")).toString(); tabWidget()->loadString(home); } @@ -1417,23 +1449,6 @@ void BrowserMainWindow::clearPrivateData() dialog.exec(); } -void BrowserMainWindow::toggleInspector(bool enable) -{ - QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, enable); - if (enable) { - int result = QMessageBox::question(this, tr("Web Inspector"), - tr("The web inspector will only work correctly for pages that were loaded after enabling.\n" - "Do you want to reload all pages?"), - QMessageBox::Yes | QMessageBox::No); - if (result == QMessageBox::Yes) { - m_tabWidget->reloadAllTabs(); - } - } - QSettings settings; - settings.beginGroup(QLatin1String("websettings")); - settings.setValue(QLatin1String("enableInspector"), enable); -} - void BrowserMainWindow::swapFocus() { if (currentTab()->hasFocus()) { @@ -1496,10 +1511,10 @@ void BrowserMainWindow::aboutToShowBackMenu() m_historyBackMenu->clear(); if (!currentTab()) return; - QWebHistory *history = currentTab()->history(); + QWebEngineHistory *history = currentTab()->history(); int historyCount = history->count(); for (int i = history->backItems(historyCount).count() - 1; i >= 0; --i) { - QWebHistoryItem item = history->backItems(history->count()).at(i); + QWebEngineHistoryItem item = history->backItems(history->count()).at(i); QAction *action = new QAction(this); action->setData(-1*(historyCount - i - 1)); QIcon icon = BrowserApplication::instance()->icon(item.url()); @@ -1514,10 +1529,10 @@ void BrowserMainWindow::aboutToShowForwardMenu() m_historyForwardMenu->clear(); if (!currentTab()) return; - QWebHistory *history = currentTab()->history(); + QWebEngineHistory *history = currentTab()->history(); int historyCount = history->count(); for (int i = 0; i < history->forwardItems(history->count()).count(); ++i) { - QWebHistoryItem item = history->forwardItems(historyCount).at(i); + QWebEngineHistoryItem item = history->forwardItems(historyCount).at(i); QAction *action = new QAction(this); action->setData(historyCount - i); QIcon icon = BrowserApplication::instance()->icon(item.url()); @@ -1535,7 +1550,7 @@ void BrowserMainWindow::aboutToShowWindowMenu() m_windowMenu->addSeparator(); QAction *downloadManagerAction = m_windowMenu->addAction(tr("Downloads"), this, SLOT(downloadManager()), QKeySequence(tr("Ctrl+Y", "Download Manager"))); - downloadManagerAction->setIcon(QIcon::fromTheme(QLatin1String("emblem-downloads"))); + downloadManagerAction->setIcon(QIcon::fromTheme(QStringLiteral("emblem-downloads"))); m_windowMenu->addSeparator(); QList windows = BrowserApplication::instance()->mainWindows(); @@ -1566,7 +1581,7 @@ void BrowserMainWindow::showWindow() void BrowserMainWindow::openActionUrl(QAction *action) { int offset = action->data().toInt(); - QWebHistory *history = currentTab()->history(); + QWebEngineHistory *history = currentTab()->history(); if (offset < 0) history->goToItem(history->backItems(-1*offset).first()); // back else if (offset > 0) @@ -1578,3 +1593,23 @@ void BrowserMainWindow::geometryChangeRequested(const QRect &geometry) setGeometry(geometry); } + + +DevToolsWindow *BrowserMainWindow::createDevToolsWindow() +{ + auto devWindow = new DevToolsWindow(this); + devWindow->show(); + return devWindow; +} + +void BrowserMainWindow::handleDevToolsRequested(QWebEnginePage *source) +{ + source->setDevToolsPage(createDevToolsWindow()->page()); + source->triggerAction(QWebEnginePage::InspectElement); +} + +void BrowserMainWindow::runScriptOnOpenViews(QString source) +{ + for (int i =0; i < tabWidget()->count(); ++i) + tabWidget()->webView(i)->page()->runJavaScript(source); +} diff --git a/src/browsermainwindow.h b/src/browsermainwindow.h index ff924875..5e1b5b69 100644 --- a/src/browsermainwindow.h +++ b/src/browsermainwindow.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,11 +63,12 @@ #ifndef BROWSERMAINWINDOW_H #define BROWSERMAINWINDOW_H -#include +#include +#include class AutoSaver; class BookmarksToolBar; -class QWebFrame; +class QWebEnginePage; class TabWidget; class ToolbarSearch; class WebView; @@ -76,6 +77,9 @@ class QFrame; class HistoryMenu; class BookmarksMenuBarMenu; class UserAgentMenu; +class DevToolsWindow; +class QPrinter; +class QCloseEvent; /*! The MainWindow of the Browser Application. @@ -87,7 +91,7 @@ class BrowserMainWindow : public QMainWindow Q_OBJECT public: - BrowserMainWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0); + BrowserMainWindow(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags(), QWebEngineProfile *profile = QWebEngineProfile::defaultProfile()); ~BrowserMainWindow(); QSize sizeHint() const; @@ -100,12 +104,17 @@ class BrowserMainWindow : public QMainWindow QByteArray saveState(bool withTabs = true) const; bool restoreState(const QByteArray &state); QAction *showMenuBarAction() const; - QAction *searchManagerAction() const { return m_toolsSearchManagerAction; } + QAction *searchManagerAction() const { + return m_toolsSearchManagerAction; + } + void handleDevToolsRequested(QWebEnginePage *source); -public slots: +public Q_SLOTS: void goHome(); void privacyChanged(bool isPrivate); void zoomTextOnlyChanged(bool textOnly); + void runScriptOnOpenViews(QString source); + void printDocument(QPrinter *printer); protected: void closeEvent(QCloseEvent *event); @@ -113,7 +122,7 @@ public slots: void mousePressEvent(QMouseEvent *event); void changeEvent(QEvent *event); -private slots: +private Q_SLOTS: void save(); void lastTabClosed(); @@ -149,7 +158,6 @@ private slots: void webSearch(); void clearPrivateData(); - void toggleInspector(bool enable); void aboutApplication(); void downloadManager(); void selectLineEdit(); @@ -164,15 +172,18 @@ private slots: void showWindow(); void swapFocus(); - void printRequested(QWebFrame *frame); + void printRequested(); void geometryChangeRequested(const QRect &geometry); + void gotHTML(QString &value); + private: void retranslate(); void loadDefaultState(); void setupMenu(); void setupToolBar(); void updateStopReloadActionText(bool loading); + DevToolsWindow *createDevToolsWindow(); private: QMenu *m_fileMenu; @@ -231,11 +242,9 @@ private slots: QMenu *m_toolsMenu; QAction *m_toolsWebSearchAction; QAction *m_toolsClearPrivateDataAction; - QAction *m_toolsEnableInspectorAction; QAction *m_toolsPreferencesAction; QAction *m_toolsSearchManagerAction; UserAgentMenu *m_toolsUserAgentMenu; - QAction *m_adBlockDialogAction; QMenu *m_helpMenu; QAction *m_helpChangeLanguageAction; @@ -265,7 +274,14 @@ private slots: bool m_menuBarVisible; bool m_statusBarVisible; + QString markup; + + QWebEngineProfile *m_profile; + friend class BrowserApplication; + +Q_SIGNALS: + void notifyGotHTML(); }; #endif // BROWSERMAINWINDOW_H diff --git a/src/clearbutton.cpp b/src/clearbutton.cpp index b4d1c050..9c0f36d2 100644 --- a/src/clearbutton.cpp +++ b/src/clearbutton.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -28,7 +28,7 @@ #include "clearbutton.h" -#include +#include ClearButton::ClearButton(QWidget *parent) : QAbstractButton(parent) @@ -41,9 +41,9 @@ ClearButton::ClearButton(QWidget *parent) // First check for a style icon, current KDE provides one if (m_styleImage.isNull()) { - QLatin1String iconName = (layoutDirection() == Qt::RightToLeft) - ? QLatin1String("edit-clear-locationbar-ltr") - : QLatin1String("edit-clear-locationbar-rtl"); + QString iconName = (layoutDirection() == Qt::RightToLeft) + ? QStringLiteral("edit-clear-locationbar-ltr") + : QStringLiteral("edit-clear-locationbar-rtl"); QIcon icon = QIcon::fromTheme(iconName); if (!icon.isNull()) m_styleImage = icon.pixmap(16, 16).toImage(); diff --git a/src/clearbutton.h b/src/clearbutton.h index 5df47f52..b3a4ea68 100644 --- a/src/clearbutton.h +++ b/src/clearbutton.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,16 +29,16 @@ #ifndef CLEARBUTTON_H #define CLEARBUTTON_H -#include +#include class ClearButton : public QAbstractButton { Q_OBJECT public: - ClearButton(QWidget *parent = 0); + ClearButton(QWidget *parent = nullptr); -public slots: +public Q_SLOTS: void textChanged(const QString &text); protected: diff --git a/src/clearprivatedata.cpp b/src/clearprivatedata.cpp index 5afeef02..13019238 100644 --- a/src/clearprivatedata.cpp +++ b/src/clearprivatedata.cpp @@ -21,21 +21,18 @@ #include "browserapplication.h" #include "browsermainwindow.h" -#include "cookiejar.h" #include "downloadmanager.h" #include "historymanager.h" -#include "networkaccessmanager.h" #include "toolbarsearch.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include ClearPrivateData::ClearPrivateData(QWidget *parent) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint) @@ -46,36 +43,20 @@ ClearPrivateData::ClearPrivateData(QWidget *parent) layout->addWidget(new QLabel(tr("Clear the following items:"))); QSettings settings; - settings.beginGroup(QLatin1String("clearprivatedata")); + settings.beginGroup(QStringLiteral("clearprivatedata")); m_browsingHistory = new QCheckBox(tr("&Browsing History")); - m_browsingHistory->setChecked(settings.value(QLatin1String("browsingHistory"), true).toBool()); + m_browsingHistory->setChecked(settings.value(QStringLiteral("browsingHistory"), true).toBool()); layout->addWidget(m_browsingHistory); m_downloadHistory = new QCheckBox(tr("&Download History")); - m_downloadHistory->setChecked(settings.value(QLatin1String("downloadHistory"), true).toBool()); + m_downloadHistory->setChecked(settings.value(QStringLiteral("downloadHistory"), true).toBool()); layout->addWidget(m_downloadHistory); m_searchHistory = new QCheckBox(tr("&Search History")); - m_searchHistory->setChecked(settings.value(QLatin1String("searchHistory"), true).toBool()); + m_searchHistory->setChecked(settings.value(QStringLiteral("searchHistory"), true).toBool()); layout->addWidget(m_searchHistory); - m_cookies = new QCheckBox(tr("&Cookies")); - m_cookies->setChecked(settings.value(QLatin1String("cookies"), true).toBool()); - layout->addWidget(m_cookies); - - m_cache = new QCheckBox(tr("C&ached Web Pages")); - if (BrowserApplication::networkAccessManager()->cache()) { - m_cache->setChecked(settings.value(QLatin1String("cache"), true).toBool()); - } else { - m_cache->setEnabled(false); - } - layout->addWidget(m_cache); - - m_favIcons = new QCheckBox(tr("Website &Icons")); - m_favIcons->setChecked(settings.value(QLatin1String("favIcons"), true).toBool()); - layout->addWidget(m_favIcons); - settings.endGroup(); QPushButton *acceptButton = new QPushButton(tr("Clear &Private Data")); @@ -95,14 +76,12 @@ ClearPrivateData::ClearPrivateData(QWidget *parent) void ClearPrivateData::accept() { QSettings settings; - settings.beginGroup(QLatin1String("clearprivatedata")); + settings.beginGroup(QStringLiteral("clearprivatedata")); - settings.setValue(QLatin1String("browsingHistory"), m_browsingHistory->isChecked()); - settings.setValue(QLatin1String("downloadHistory"), m_downloadHistory->isChecked()); - settings.setValue(QLatin1String("searchHistory"), m_searchHistory->isChecked()); - settings.setValue(QLatin1String("cookies"), m_cookies->isChecked()); - settings.setValue(QLatin1String("cache"), m_cache->isChecked()); - settings.setValue(QLatin1String("favIcons"), m_favIcons->isChecked()); + settings.setValue(QStringLiteral("browsingHistory"), m_browsingHistory->isChecked()); + settings.setValue(QStringLiteral("downloadHistory"), m_downloadHistory->isChecked()); + settings.setValue(QStringLiteral("searchHistory"), m_searchHistory->isChecked()); + settings.setValue(QStringLiteral("cache"), m_cache->isChecked()); settings.endGroup(); @@ -121,17 +100,5 @@ void ClearPrivateData::accept() mainWindows.at(i)->toolbarSearch()->setText(QString()); } } - - if (m_cookies->isChecked()) { - BrowserApplication::cookieJar()->clear(); - } - - if (m_cache->isChecked() && BrowserApplication::networkAccessManager()->cache()) { - BrowserApplication::networkAccessManager()->cache()->clear(); - } - - if (m_favIcons->isChecked()) { - QWebSettings::clearIconDatabase(); - } QDialog::accept(); } diff --git a/src/clearprivatedata.h b/src/clearprivatedata.h index db5d823e..f365f89d 100644 --- a/src/clearprivatedata.h +++ b/src/clearprivatedata.h @@ -20,7 +20,7 @@ #ifndef CLEARPRIVATEDATA_H #define CLEARPRIVATEDATA_H -#include +#include class QCheckBox; @@ -29,9 +29,9 @@ class ClearPrivateData : public QDialog Q_OBJECT public: - ClearPrivateData(QWidget *parent = 0); + ClearPrivateData(QWidget *parent = nullptr); -public slots: +public Q_SLOTS: void accept(); private: diff --git a/src/data/data.qrc b/src/data/data.qrc index 85eff66e..6f7da0dc 100644 --- a/src/data/data.qrc +++ b/src/data/data.qrc @@ -2,11 +2,13 @@ 128x128/endorphin.png 128x128/run.png + 512x512/endorphin.png endorphin.svg defaultbookmarks.xbel + qwebchannel.js fetchLinks.js parseForms.js ../../AUTHORS - ../../LICENSE.GPL2 + ../../LICENSE diff --git a/src/data/defaultbookmarks.xbel b/src/data/defaultbookmarks.xbel index 56e92d6d..0c8179f5 100644 --- a/src/data/defaultbookmarks.xbel +++ b/src/data/defaultbookmarks.xbel @@ -3,7 +3,7 @@ Bookmarks Bar - + Endorphin diff --git a/src/data/endorphin.svg b/src/data/endorphin.svg index 23af42cd..d981b474 100644 --- a/src/data/endorphin.svg +++ b/src/data/endorphin.svg @@ -1,5 +1,4 @@ - + inkscape:export-filename="/home/jbache/icon/endorphin-16.png" + inkscape:output_extension="org.inkscape.output.svg.inkscape" + sodipodi:docname="endorphin.svg" + inkscape:version="1.0 (4035a4fb49, 2020-05-01)" + sodipodi:version="0.32" + id="svg2383" + height="64px" + width="64px"> + style="stop-color:#c7cde6;stop-opacity:1;" /> + style="stop-color:#adbeff;stop-opacity:0;" /> + style="stop-color:#5e86c1;stop-opacity:1;" /> + style="stop-color:#103070;stop-opacity:1;" /> + style="stop-color:#dbdbdb;stop-opacity:1;" /> + style="stop-color:#cbcbcb;stop-opacity:0;" /> + id="stop3267" /> + id="stop3269" /> + style="stop-color:#ffffff;stop-opacity:1;" /> + style="stop-color:#c7d0d2;stop-opacity:1;" /> + style="stop-color:#eaffff;stop-opacity:1;" /> + style="stop-color:#016792;stop-opacity:1;" /> + inkscape:vp_z="64 : 32 : 1" + inkscape:vp_y="0 : 1000 : 0" + inkscape:vp_x="0 : 32 : 1" + sodipodi:type="inkscape:persp3d" /> + fy="30.985296" + fx="20.594498" + cy="30.985296" + cx="20.594498" + id="radialGradient3215" + xlink:href="#linearGradient3207" + inkscape:collect="always" /> + r="7.9169221" + fy="30.030596" + fx="23.45262" + cy="30.030596" + cx="23.45262" + id="radialGradient3542" + xlink:href="#linearGradient3536" + inkscape:collect="always" /> + width="1.421433" + x="-0.21071652" + id="filter4316" + inkscape:collect="always"> + inkscape:collect="always" /> + width="1.3576974" + x="-0.17884872" + id="filter4384" + inkscape:collect="always"> + inkscape:collect="always" /> + id="filter4654" + inkscape:collect="always"> + inkscape:collect="always" /> + id="filter4788" + inkscape:collect="always"> - - - + inkscape:collect="always" /> - + id="radialGradient3350" + xlink:href="#linearGradient3207" + inkscape:collect="always" /> + - + - + id="linearGradient3380" + xlink:href="#linearGradient3536" + inkscape:collect="always" /> + id="radialGradient3384" + xlink:href="#linearGradient3265" + inkscape:collect="always" /> + - + - + + fx="17.947458" + cy="27.263075" + cx="17.947458" + gradientTransform="matrix(1.5119908,0,0,1.9265069,-16.649017,-31.851372)" + gradientUnits="userSpaceOnUse" + id="radialGradient4003" + xlink:href="#linearGradient3265" + inkscape:collect="always" /> + width="1.30616" + x="-0.15308" + id="filter4028" + inkscape:collect="always"> + inkscape:collect="always" /> + inkscape:document-units="px" + showgrid="true" + inkscape:current-layer="layer1" + inkscape:cy="32" + inkscape:cx="26.669396" + inkscape:zoom="11.313708" + inkscape:pageshadow="2" + inkscape:pageopacity="0" + borderopacity="1.0" + bordercolor="#666666" + pagecolor="#ffffff" + id="base" /> @@ -321,234 +311,234 @@ + id="layer1"> + id="g4582"> + id="path4584" + sodipodi:nodetypes="cccc" /> + id="path4586" + sodipodi:cx="31.884089" + sodipodi:cy="35.908577" + sodipodi:rx="18.834753" + sodipodi:ry="18.834753" + d="M 50.718842,35.908577 A 18.834753,18.834753 0 1 1 13.049335,35.908577 A 18.834753,18.834753 0 1 1 50.718842,35.908577 z" + transform="matrix(0.7572962,0,0,0.7572962,4.7171145,9.0365597)" /> + id="path4588" /> + id="path4590" + sodipodi:nodetypes="cccccccccccccccccccccccc" /> + id="path4592" + sodipodi:nodetypes="cccccccccccccccccc" /> + id="path4594" + sodipodi:cx="14.624254" + sodipodi:cy="35.78001" + sodipodi:rx="11.34585" + sodipodi:ry="7.1996326" + d="M 25.970104,35.78001 A 11.34585,7.1996326 0 1 1 3.2784042,35.78001 A 11.34585,7.1996326 0 1 1 25.970104,35.78001 z" + transform="matrix(1.1599619,-0.6165902,0.6730581,1.0626441,-12.182788,5.040139)" /> + id="path4596" + sodipodi:nodetypes="cccccccccccccccccc" /> + id="path4598" + sodipodi:nodetypes="cc" /> + id="path4600" /> + id="path4602" + sodipodi:nodetypes="cc" /> + id="path4604" + sodipodi:nodetypes="cc" /> + id="path4606" + sodipodi:nodetypes="cccc" /> + id="path4608" + transform="matrix(1.3532078,0,0,1.5930591,-11.463268,-11.435411)" + sodipodi:nodetypes="ccsc" /> + id="path4610" + transform="matrix(0.741485,0,0,1.5982971,5.0201391,-7.4791344)" + sodipodi:nodetypes="ccc" /> + id="path4612" + sodipodi:nodetypes="cc" /> + id="path4614" + sodipodi:nodetypes="cssscccssssc" /> + id="path4616" + sodipodi:nodetypes="csssssc" /> + id="path4618" + sodipodi:nodetypes="cccc" /> + d="M 9.5090016,22.973713 C 10.055548,22.636975 9.4256925,21.737991 9.7278156,20.95667 C 10.14478,19.611154 10.929561,19.126639 11.596916,18.368536 C 12.810535,19.295346 12.341395,20.874223 12.136569,22.914126" + style="fill:url(#radialGradient4003);fill-opacity:1;fill-rule:evenodd;stroke:#99a2b5;stroke-width:1.4074353;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + sodipodi:ry="18.834753" + sodipodi:rx="18.834753" + sodipodi:cy="35.908577" + sodipodi:cx="31.884089" + id="path2395" + style="fill:url(#radialGradient3350);fill-opacity:1;fill-rule:nonzero;stroke:#1d386c;stroke-width:1.23112547;stroke-linecap:square;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + sodipodi:type="arc" /> + style="fill:url(#linearGradient3999);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + sodipodi:ry="18.834753" + sodipodi:rx="18.834753" + sodipodi:cy="35.908577" + sodipodi:cx="31.884089" + id="path4706" + style="fill:none;fill-opacity:1;fill-rule:nonzero;stroke:#bbbdeb;stroke-width:0.86756015;stroke-linecap:square;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.36040608" + sodipodi:type="arc" /> + d="M 42.781052,32.752204 C 41.249236,34.07167 39.600081,35.694975 37.482839,35.623153 C 36.737277,37.146605 38.181394,38.414696 39.056233,39.430168 C 40.230532,41.080357 42.029602,42.658582 41.869227,44.934154 C 40.974195,46.337406 41.600003,48.349035 40.297679,49.554063 C 39.19752,50.29351 39.034475,53.188512 40.665815,51.56651 C 42.097709,50.463275 43.69408,49.611993 45.319439,48.900818 C 46.971663,47.56789 48.14913,45.702429 49.790122,44.354272 C 51.182276,42.831963 52.495564,41.226563 53.859434,39.679871 C 55.084628,37.840031 51.961805,37.433212 50.923092,37.022321 C 49.627534,34.474864 48.39208,36.954351 48.337387,34.732772 C 48.10893,33.094716 48.311403,32.470804 48.975692,31.216755 C 49.789434,30.133524 49.330425,28.769757 48.720013,27.730347 C 48.118355,26.219232 48.0168,24.560108 47.560138,23.003761 C 46.239001,22.347865 45.704063,24.831234 45.09834,25.736416 C 44.89478,27.076385 43.401025,27.80548 42.792718,26.313782 C 41.50471,24.852701 39.489999,24.570109 38.05769,23.30244 C 36.499642,22.100503 34.90866,20.936016 33.266347,19.878353 C 32.399028,19.116492 30.984489,16.73833 30.00574,18.121019 C 29.671168,20.04738 30.205812,22.179865 29.139259,23.925626 C 28.295773,26.029985 30.647833,26.968219 30.986678,29.173704 C 31.05546,31.198272 30.86667,33.269977 32.442632,32.687628 C 34.049136,32.398265 35.686229,32.368472 37.273519,31.93357 C 39.073612,31.598984 41.369533,31.216758 42.781052,32.752204 z" + style="fill:url(#radialGradient3995);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + d="M 49.93235,30.388552 C 47.82072,34.401319 46.727054,33.189132 48.495752,35.249835 C 50.735744,37.652922 53.495233,35.797464 56.033898,34.013806 C 55.983985,29.547881 54.870916,28.033047 53.928426,25.649299 C 52.454137,19.757964 53.853262,19.641135 53.645489,17.715364 C 53.165661,11.760338 52.179439,10.014491 46.731858,5.3869589 C 43.032791,3.9700351 36.892935,3.1349984 34.254145,3.2932536 C 30.858002,3.1370986 25.780525,10.550881 23.525133,13.763425 C 19.329393,18.146857 18.528921,18.387788 14.418995,22.941492 C 12.225576,26.138193 12.469147,25.933394 11.797219,30.412199 C 8.6838122,41.186314 8.5780129,38.979792 12.722053,40.426658 C 15.33566,38.786494 18.657883,33.882319 21.537997,32.735065 C 22.092799,28.099171 26.642405,28.042198 30.288151,25.343983 C 31.719919,25.141047 32.97845,25.359878 34.408125,28.293641 C 36.600412,35.711386 35.973593,45.014448 43.017092,36.371383 C 43.272437,33.096004 44.666975,37.899578 44.307987,34.541118 C 43.972712,31.087367 46.120083,27.966594 44.837503,24.771217 C 43.83804,22.683987 41.415554,22.464112 39.342216,18.69481" + style="fill:#001b52;fill-opacity:0.26943006;fill-rule:evenodd;stroke:none;stroke-width:0.89999998;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + sodipodi:ry="7.1996326" + sodipodi:rx="11.34585" + sodipodi:cy="35.78001" + sodipodi:cx="14.624254" + id="path4093" + style="opacity:0.21645023;fill:#d6d6d6;fill-opacity:0.5076142;fill-rule:nonzero;stroke:none;stroke-width:0.69999999;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + sodipodi:type="arc" /> + d="M 50.99577,29.364545 C 48.61105,33.377311 47.631034,32.601011 49.628473,34.661714 C 52.158156,37.064801 54.675605,33.574158 57.542584,31.7905 C 57.48622,27.324577 56.2292,25.809742 55.164821,23.425993 C 53.499867,17.534657 55.079935,17.417831 54.845291,15.492059 C 54.303409,9.5370327 53.189645,7.7911846 47.037543,3.1636536 C 42.860089,1.7467298 35.926187,0.9116931 32.946132,1.0699483 C 29.110778,0.91379344 23.376645,8.3275768 20.829572,11.54012 C 16.09121,15.923552 15.187217,16.164484 10.545767,20.718187 C 8.0686783,23.914888 8.3437519,23.71009 7.5849245,28.188895 C 4.0688721,38.963009 3.9493895,36.756486 8.6293676,38.203353 C 11.580981,36.563188 15.332857,31.659014 18.585447,30.51176 C 19.212,25.875866 24.349991,25.818892 28.467229,23.120678 C 30.084162,22.917742 32.656436,22.473661 34.271006,25.407424 C 37.745007,30.08513 35.187407,44.824075 43.141818,36.181009 C 43.430187,32.905631 42.958778,36.118214 42.553366,32.759754 C 42.17473,29.306003 44.699633,25.566511 43.251183,22.371135 C 42.122461,20.283904 41.033702,20.240807 38.692224,16.471505" + style="fill:url(#radialGradient3990);fill-opacity:1;fill-rule:evenodd;stroke:#737f98;stroke-width:1.45179427;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + d="M 8.0197082,28.956274 L 9.5750039,28.901155 L 9.5309088,28.269629 L 8.2261446,28.022015 L 8.0197082,28.956274 z" + style="fill:#727ba6;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:0.80435652;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + d="M 41.486308,12.416104 C 42.419555,14.697378 43.041722,15.73432 43.456499,17.186042 C 43.871277,18.637762 43.663887,21.541202 43.663887,21.541202 L 40.881129,18.485051 L 41.486308,12.416104 z" + style="fill:#879bc8;fill-opacity:0.34010153;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + d="M 43.980632,22.070999 C 46.365466,25.295505 49.810827,28.027927 51.015685,29.338751" + style="fill:none;fill-rule:evenodd;stroke:#737f98;stroke-width:1.1291734;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + d="M 10.93913,28.812444 C 10.82321,28.984802 10.707289,29.157158 10.59137,29.329515 C 11.109648,29.782834 11.981478,30.059378 12.455561,30.33592 C 13.860344,30.123634 13.689393,29.701892 14.065171,29.375273 C 13.359709,29.026173 13.124253,29.355199 12.344713,29.283581 C 12.03823,29.259118 11.245613,28.836908 10.93913,28.812444 z" + style="fill:#7c84ac;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:0.80435652;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + id="path4302" + d="M 39.321598,26.574697 C 41.52815,27.623432 36.702359,24.120051 36.685925,24.054314 C 36.596421,23.64407 36.467914,23.154928 36.364883,22.668486 C 36.269137,22.216441 36.195392,21.766728 36.195392,21.384828" + style="opacity:0.18297873;fill:none;fill-rule:evenodd;stroke:#fefefe;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;filter:url(#filter4384)" /> + d="M 14.73884,23.8338 C 15.399556,23.495837 16.563629,22.562694 16.709032,21.759917" + style="fill:none;fill-rule:evenodd;stroke:#b0cada;stroke-width:1.61310494px;stroke-linecap:round;stroke-linejoin:miter;stroke-opacity:1" /> + d="M 34.256206,1.8984169 C 34.256206,1.8984169 44.198481,1.9071018 46.976443,4.1582488 C 47.881561,4.8917197 55.197633,7.8369716 54.055969,15.741188 C 53.272579,21.164926 53.771252,20.749337 54.027656,22.359429 C 54.290608,24.010643 56.42395,28.085268 56.42395,28.085268 L 56.838729,31.403486 L 52.51188,34.514316 C 52.51188,34.514316 51.060161,33.728114 51.965095,32.647818 C 52.6209,31.864928 54.869666,30.573744 54.661146,29.3296 C 54.452985,28.087588 50.485968,22.492111 50.513373,20.826666 C 50.728838,7.7321671 40.8118,-1.1871094 25.069279,7.5409861 C 25.069279,7.5409861 30.657169,0.46934798 34.256206,1.8984169 z" + style="fill:#a9b4ca;fill-opacity:0.41624367;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + d="M 34.337062,14.293925 C 34.337062,14.293925 41.699358,20.204501 42.736301,23.107941 C 43.773246,26.011382 42.42522,27.87788 41.906748,29.744377 C 41.388277,31.610875 42.321525,33.995845 42.42522,34.825398 C 42.528913,35.654953 41.803054,36.899283 40.869805,37.314062 C 40.179963,37.620658 40.517443,26.041296 40.76611,24.352273 C 40.950474,23.100021 34.648145,16.471505 34.337062,14.293925 z" + style="fill:#7891cb;fill-opacity:0.2538071;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> + d="M 13.756746,23.36157 C 14.33984,23.1502 14.663525,22.585908 14.985851,22.095476 C 15.4307,21.250896 16.267965,20.946766 16.979949,20.470907 C 18.274728,21.052663 17.774212,22.043724 17.55569,23.324168" + style="fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#9fa7b9;stroke-width:1.15175676;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + id="path4764" + d="M 32.854577,16.883491 C 32.854577,16.883491 33.994965,21.606525 37.520854,25.285904 C 38.684401,26.500103 37.741825,33.373437 38.316349,34.920234 C 38.890873,36.46703 39.200232,36.99736 39.200232,36.99736 L 38.581514,37.483496 C 38.581514,37.483496 37.874407,38.190602 37.255689,33.461826 C 36.63697,28.733049 36.088334,25.46268 33.171519,23.606525 L 32.854577,16.883491 z" + style="fill:#ffffff;fill-opacity:0.44041448999999999;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;filter:url(#filter4028)" /> + d="M 42.603184,14.502525 C 44.105786,16.358681 45.343222,17.949671 45.343222,20.336156 C 45.343222,22.722642 48.70198,28.114331 49.939417,28.998214 C 51.176853,29.882098 50.911688,29.882098 50.911688,29.882098 L 48.436815,33.240855 L 50.027805,29.174991 C 50.027805,29.174991 43.663844,24.40202 43.575455,22.634253 C 43.487067,20.866486 43.487067,18.038059 43.045125,16.181904 C 42.603184,14.325749 42.426407,14.23736 42.603184,14.502525 z" + style="fill:#ffffff;fill-opacity:0.44041449;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;filter:url(#filter4788)" /> + d="M 43.806178,15.151521 C 45.319416,17.535271 43.397278,19.476624 44.069109,22.320326" + style="fill:none;fill-rule:evenodd;stroke:#737f98;stroke-width:1.29048383;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + d="M 6.0987963,34.478291 C 6.9237541,34.684531 6.9974108,34.669799 8.3968931,35.097009 C 8.4263568,35.921967 8.1022652,36.393372 7.9107572,36.864777 C 10.408268,35.943223 11.028966,33.449466 11.474603,33.488412 C 12.201734,34.157192 12.22176,34.693392 8.5736698,37.571884 C 7.6161295,37.32145 6.6585888,37.071017 5.7010485,36.820583 C 5.8041683,36.15767 5.7747055,36.15767 6.0987963,34.478291 z" + style="fill:#5e616f;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> diff --git a/src/data/qwebchannel.js b/src/data/qwebchannel.js new file mode 100644 index 00000000..1fb83624 --- /dev/null +++ b/src/data/qwebchannel.js @@ -0,0 +1,475 @@ +/* + * Copyright 2021 Aaron Dewes + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA + */ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtWebChannel module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +var QWebChannelMessageTypes = { + signal: 1, + propertyUpdate: 2, + init: 3, + idle: 4, + debug: 5, + invokeMethod: 6, + connectToSignal: 7, + disconnectFromSignal: 8, + setProperty: 9, + response: 10, +}; + +var QWebChannel = function(transport, initCallback) +{ + if (typeof transport !== "object" || typeof transport.send !== "function") { + console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." + + " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send)); + return; + } + + var channel = this; + this.transport = transport; + + this.send = function(data) + { + if (typeof(data) !== "string") { + data = JSON.stringify(data); + } + channel.transport.send(data); + } + + this.transport.onmessage = function(message) + { + var data = message.data; + if (typeof data === "string") { + data = JSON.parse(data); + } + switch (data.type) { + case QWebChannelMessageTypes.signal: + channel.handleSignal(data); + break; + case QWebChannelMessageTypes.response: + channel.handleResponse(data); + break; + case QWebChannelMessageTypes.propertyUpdate: + channel.handlePropertyUpdate(data); + break; + default: + console.error("invalid message received:", message.data); + break; + } + } + + this.execCallbacks = {}; + this.execId = 0; + this.exec = function(data, callback) + { + if (!callback) { + // if no callback is given, send directly + channel.send(data); + return; + } + if (channel.execId === Number.MAX_VALUE) { + // wrap + channel.execId = Number.MIN_VALUE; + } + if (data.hasOwnProperty("id")) { + console.error("Cannot exec message with property id: " + JSON.stringify(data)); + return; + } + data.id = channel.execId++; + channel.execCallbacks[data.id] = callback; + channel.send(data); + }; + + this.objects = {}; + + this.handleSignal = function(message) + { + var object = channel.objects[message.object]; + if (object) { + object.signalEmitted(message.signal, message.args); + } else { + console.warn("Unhandled signal: " + message.object + "::" + message.signal); + } + } + + this.handleResponse = function(message) + { + if (!message.hasOwnProperty("id")) { + console.error("Invalid response message received: ", JSON.stringify(message)); + return; + } + channel.execCallbacks[message.id](message.data); + delete channel.execCallbacks[message.id]; + } + + this.handlePropertyUpdate = function(message) + { + message.data.forEach(data => { + var object = channel.objects[data.object]; + if (object) { + object.propertyUpdate(data.signals, data.properties); + } else { + console.warn("Unhandled property update: " + data.object + "::" + data.signal); + } + }); + channel.exec({type: QWebChannelMessageTypes.idle}); + } + + this.debug = function(message) + { + channel.send({type: QWebChannelMessageTypes.debug, data: message}); + }; + + channel.exec({type: QWebChannelMessageTypes.init}, function(data) { + for (const objectName of Object.keys(data)) { + new QObject(objectName, data[objectName], channel); + } + + // now unwrap properties, which might reference other registered objects + for (const objectName of Object.keys(channel.objects)) { + channel.objects[objectName].unwrapProperties(); + } + + if (initCallback) { + initCallback(channel); + } + channel.exec({type: QWebChannelMessageTypes.idle}); + }); +}; + +function QObject(name, data, webChannel) +{ + this.__id__ = name; + webChannel.objects[name] = this; + + // List of callbacks that get invoked upon signal emission + this.__objectSignals__ = {}; + + // Cache of all properties, updated when a notify signal is emitted + this.__propertyCache__ = {}; + + var object = this; + + // ---------------------------------------------------------------------- + + this.unwrapQObject = function(response) + { + if (response instanceof Array) { + // support list of objects + return response.map(qobj => object.unwrapQObject(qobj)) + } + if (!(response instanceof Object)) + return response; + + if (!response["__QObject*__"] || response.id === undefined) { + var jObj = {}; + for (const propName of Object.keys(response)) { + jObj[propName] = object.unwrapQObject(response[propName]); + } + return jObj; + } + + var objectId = response.id; + if (webChannel.objects[objectId]) + return webChannel.objects[objectId]; + + if (!response.data) { + console.error("Cannot unwrap unknown QObject " + objectId + " without data."); + return; + } + + var qObject = new QObject( objectId, response.data, webChannel ); + qObject.destroyed.connect(function() { + if (webChannel.objects[objectId] === qObject) { + delete webChannel.objects[objectId]; + // reset the now deleted QObject to an empty {} object + // just assigning {} though would not have the desired effect, but the + // below also ensures all external references will see the empty map + // NOTE: this detour is necessary to workaround QTBUG-40021 + Object.keys(qObject).forEach(name => delete qObject[name]); + } + }); + // here we are already initialized, and thus must directly unwrap the properties + qObject.unwrapProperties(); + return qObject; + } + + this.unwrapProperties = function() + { + for (const propertyIdx of Object.keys(object.__propertyCache__)) { + object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]); + } + } + + function addSignal(signalData, isPropertyNotifySignal) + { + var signalName = signalData[0]; + var signalIndex = signalData[1]; + object[signalName] = { + connect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to connect to signal " + signalName); + return; + } + + object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || []; + object.__objectSignals__[signalIndex].push(callback); + + // only required for "pure" signals, handled separately for properties in propertyUpdate + if (isPropertyNotifySignal) + return; + + // also note that we always get notified about the destroyed signal + if (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)") + return; + + // and otherwise we only need to be connected only once + if (object.__objectSignals__[signalIndex].length == 1) { + webChannel.exec({ + type: QWebChannelMessageTypes.connectToSignal, + object: object.__id__, + signal: signalIndex + }); + } + }, + disconnect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to disconnect from signal " + signalName); + return; + } + object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || []; + var idx = object.__objectSignals__[signalIndex].indexOf(callback); + if (idx === -1) { + console.error("Cannot find connection of signal " + signalName + " to " + callback.name); + return; + } + object.__objectSignals__[signalIndex].splice(idx, 1); + if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) { + // only required for "pure" signals, handled separately for properties in propertyUpdate + webChannel.exec({ + type: QWebChannelMessageTypes.disconnectFromSignal, + object: object.__id__, + signal: signalIndex + }); + } + } + }; + } + + /** + * Invokes all callbacks for the given signalname. Also works for property notify callbacks. + */ + function invokeSignalCallbacks(signalName, signalArgs) + { + var connections = object.__objectSignals__[signalName]; + if (connections) { + connections.forEach(function(callback) { + callback.apply(callback, signalArgs); + }); + } + } + + this.propertyUpdate = function(signals, propertyMap) + { + // update property cache + for (const propertyIndex of Object.keys(propertyMap)) { + var propertyValue = propertyMap[propertyIndex]; + object.__propertyCache__[propertyIndex] = this.unwrapQObject(propertyValue); + } + + for (const signalName of Object.keys(signals)) { + // Invoke all callbacks, as signalEmitted() does not. This ensures the + // property cache is updated before the callbacks are invoked. + invokeSignalCallbacks(signalName, signals[signalName]); + } + } + + this.signalEmitted = function(signalName, signalArgs) + { + invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs)); + } + + function addMethod(methodData) + { + var methodName = methodData[0]; + var methodIdx = methodData[1]; + + // Fully specified methods are invoked by id, others by name for host-side overload resolution + var invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodName + + object[methodName] = function() { + var args = []; + var callback; + var errCallback; + for (var i = 0; i < arguments.length; ++i) { + var argument = arguments[i]; + if (typeof argument === "function") + callback = argument; + else if (argument instanceof QObject && webChannel.objects[argument.__id__] !== undefined) + args.push({ + "id": argument.__id__ + }); + else + args.push(argument); + } + + var result; + // during test, webChannel.exec synchronously calls the callback + // therefore, the promise must be constucted before calling + // webChannel.exec to ensure the callback is set up + if (!callback && (typeof(Promise) === 'function')) { + result = new Promise(function(resolve, reject) { + callback = resolve; + errCallback = reject; + }); + } + + webChannel.exec({ + "type": QWebChannelMessageTypes.invokeMethod, + "object": object.__id__, + "method": invokedMethod, + "args": args + }, function(response) { + if (response !== undefined) { + var result = object.unwrapQObject(response); + if (callback) { + (callback)(result); + } + } else if (errCallback) { + (errCallback)(); + } + }); + + return result; + }; + } + + function bindGetterSetter(propertyInfo) + { + var propertyIndex = propertyInfo[0]; + var propertyName = propertyInfo[1]; + var notifySignalData = propertyInfo[2]; + // initialize property cache with current value + // NOTE: if this is an object, it is not directly unwrapped as it might + // reference other QObject that we do not know yet + object.__propertyCache__[propertyIndex] = propertyInfo[3]; + + if (notifySignalData) { + if (notifySignalData[0] === 1) { + // signal name is optimized away, reconstruct the actual name + notifySignalData[0] = propertyName + "Changed"; + } + addSignal(notifySignalData, true); + } + + Object.defineProperty(object, propertyName, { + configurable: true, + get: function () { + var propertyValue = object.__propertyCache__[propertyIndex]; + if (propertyValue === undefined) { + // This shouldn't happen + console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__); + } + + return propertyValue; + }, + set: function(value) { + if (value === undefined) { + console.warn("Property setter for " + propertyName + " called with undefined value!"); + return; + } + object.__propertyCache__[propertyIndex] = value; + var valueToSend = value; + if (valueToSend instanceof QObject && webChannel.objects[valueToSend.__id__] !== undefined) + valueToSend = { "id": valueToSend.__id__ }; + webChannel.exec({ + "type": QWebChannelMessageTypes.setProperty, + "object": object.__id__, + "property": propertyIndex, + "value": valueToSend + }); + } + }); + + } + + // ---------------------------------------------------------------------- + + data.methods.forEach(addMethod); + + data.properties.forEach(bindGetterSetter); + + data.signals.forEach(function(signal) { addSignal(signal, false); }); + + Object.assign(object, data.enums); +} + +//required for use with nodejs +if (typeof module === 'object') { + module.exports = { + QWebChannel: QWebChannel + }; +} + +new QWebChannel(qt.webChannelTransport, function (channel) { + window.endorphin = channel.objects.endorphin; + const links = document.getElementsByTagName("link"); + for(link of links) { + if(link.rel == "search") { + window.endorphin.addSearchProvider(link.href); + } + } +}); + diff --git a/src/devtoolswindow.cpp b/src/devtoolswindow.cpp new file mode 100644 index 00000000..441907b1 --- /dev/null +++ b/src/devtoolswindow.cpp @@ -0,0 +1,54 @@ +/* + * Copyright 2020 Aaron Dewes + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA + */ + +#include "devtoolswindow.h" +#include +#include +#include +#include +#include +#include + +DevToolsWindow::DevToolsWindow(QWidget *parent, Qt::WindowFlags flags) + : QMainWindow(parent, flags) + , m_webView(new QWebEngineView()) +{ + setCentralWidget(m_webView); +} + +DevToolsWindow::~DevToolsWindow() +{ +} + +void DevToolsWindow::geometryChangeRequested(const QRect &geometry) +{ + setGeometry(geometry); +} + +QWebEnginePage *DevToolsWindow::page() +{ + return m_webView->page(); +} + +QSize DevToolsWindow::sizeHint() const +{ + QRect desktopRect = qApp->primaryScreen()->geometry(); + QSize size = desktopRect.size() * 0.4; + return size; +} diff --git a/tools/htmlToXBel/mainapp.h b/src/devtoolswindow.h similarity index 57% rename from tools/htmlToXBel/mainapp.h rename to src/devtoolswindow.h index 64aa4be7..bdc8e780 100644 --- a/tools/htmlToXBel/mainapp.h +++ b/src/devtoolswindow.h @@ -17,26 +17,34 @@ * Boston, MA 02110-1301 USA */ -#ifndef MAINAPP_H -#define MAINAPP_H +#ifndef DEVTOOLSWINDOW_H +#define DEVTOOLSWINDOW_H -#include -#include +#include +#include -class QWebEngineView; -class QPushButton; +class QWebEnginePage; +/*! + The MainWindow of the Browser Application. -class MainApp : public QObject + Handles the tab widget and all the actions + */ +class DevToolsWindow : public QMainWindow { -Q_OBJECT + Q_OBJECT + public: - MainApp(QObject *parent = nullptr); - QString get(QString &input); - void ranJavaScript(QString &value); + DevToolsWindow(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); + ~DevToolsWindow(); + QWebEnginePage *page(); + QSize sizeHint() const; -Q_SIGNALS: - void notifyRanJavaScript(); +private Q_SLOTS: + void geometryChangeRequested(const QRect &geometry); +private: + QWebEngineView *m_webView; }; -#endif // MAINAPP_H \ No newline at end of file +#endif // DEVTOOLSWINDOW_H + diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 2bf07cff..a3cec345 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Jason A. Donenfeld * * This program is free software; you can redistribute it and/or modify @@ -17,7 +17,55 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ - +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ /**************************************************************************** ** ** Copyright (C) 2008-2008 Trolltech ASA. All rights reserved. @@ -64,24 +112,28 @@ #include "downloadmanager.h" #include "autosaver.h" +#ifndef NO_BROWSERAPPLICATION #include "browserapplication.h" -#include "networkaccessmanager.h" +#endif #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include +#include -#include +#include //#define DOWNLOADMANAGER_DEBUG @@ -90,30 +142,23 @@ It moves the data from the QNetworkReply into the QFile as well as update the information/progressbar and report errors. */ -DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget *parent) +DownloadItem::DownloadItem(QWebEngineDownloadItem *download, QWidget *parent) : QWidget(parent) - , m_reply(reply) - , m_requestFileName(requestFileName) - , m_bytesReceived(0) - , m_startedSaving(false) - , m_finishedDownloading(false) - , m_gettingFileName(false) - , m_canceledFileSelect(false) + , m_download(download) { setupUi(this); QPalette p = downloadInfoLabel->palette(); p.setColor(QPalette::Text, Qt::darkGray); downloadInfoLabel->setPalette(p); progressBar->setMaximum(0); - tryAgainButton->hide(); - connect(stopButton, SIGNAL(clicked()), this, SLOT(stop())); + tryAgainButton->hide(); connect(openButton, SIGNAL(clicked()), this, SLOT(open())); connect(tryAgainButton, SIGNAL(clicked()), this, SLOT(tryAgain())); - if (!requestFileName) { - QSettings settings; - settings.beginGroup(QLatin1String("downloadmanager")); - m_requestFileName = settings.value(QLatin1String("alwaysPromptForFileName"), false).toBool(); + if (download) { + QString file = QDir::cleanPath(download->downloadDirectory() + QDir::separator() + download->downloadFileName()); + m_file.setFile(file); + m_url = download->url(); } init(); @@ -121,26 +166,12 @@ DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget * void DownloadItem::init() { - if (!m_reply) - return; - - m_startedSaving = false; - m_finishedDownloading = false; - - openButton->setEnabled(false); - - // attach to the m_reply - m_url = m_reply->url(); - m_reply->setParent(this); - connect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead())); - connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), - this, SLOT(error(QNetworkReply::NetworkError))); - connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), - this, SLOT(downloadProgress(qint64, qint64))); - connect(m_reply, SIGNAL(metaDataChanged()), - this, SLOT(metaDataChanged())); - connect(m_reply, SIGNAL(finished()), - this, SLOT(finished())); + if (m_download) { + connect(m_download.data(), SIGNAL(downloadProgress(qint64,qint64)), + this, SLOT(downloadProgress())); + connect(m_download.data(), SIGNAL(finished()), + this, SLOT(finished())); + } // reset info downloadInfoLabel->clear(); @@ -149,96 +180,43 @@ void DownloadItem::init() // start timer for the download estimation m_downloadTime.start(); - - if (m_reply->error() != QNetworkReply::NoError) { - error(m_reply->error()); - finished(); - } } -void DownloadItem::getFileName() +bool DownloadItem::getFileName(bool promptForFileName) { - if (m_gettingFileName) - return; - - QString downloadDirectory = BrowserApplication::downloadManager()->downloadDirectory(); + QSettings settings; + settings.beginGroup(QStringLiteral("downloadmanager")); +#ifndef NO_BROWSERAPPLICATION + QString defaultLocation = BrowserApplication::downloadManager()->downloadDirectory(); +#else + QString defaultLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + '/'; +#endif + if (m_file.absoluteDir().exists()) + defaultLocation = m_file.absolutePath(); + QString downloadDirectory = settings.value(QStringLiteral("downloadDirectory"), defaultLocation).toString(); + if (!downloadDirectory.isEmpty()) + downloadDirectory += QChar('/'); - QString defaultFileName = saveFileName(downloadDirectory); + QString defaultFileName = QFileInfo(downloadDirectory, m_file.fileName()).absoluteFilePath(); QString fileName = defaultFileName; - if (m_requestFileName) { - m_gettingFileName = true; + if (promptForFileName) { fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName); - m_gettingFileName = false; if (fileName.isEmpty()) { - progressBar->setVisible(false); - stop(); + if (m_download) + m_download->cancel(); fileNameLabel->setText(tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName())); - m_canceledFileSelect = true; - return; - } - QFileInfo fileInfo = QFileInfo(fileName); - BrowserApplication::downloadManager()->setDownloadDirectory(fileInfo.absoluteDir().absolutePath()); - fileNameLabel->setText(fileInfo.fileName()); - } - m_output.setFileName(fileName); - - // Check file path for saving. - QDir saveDirPath = QFileInfo(m_output.fileName()).dir(); - if (!saveDirPath.exists()) { - if (!saveDirPath.mkpath(saveDirPath.absolutePath())) { - progressBar->setVisible(false); - stop(); - downloadInfoLabel->setText(tr("Download directory (%1) couldn't be created.").arg(saveDirPath.absolutePath())); - return; - } - } - - fileNameLabel->setText(QFileInfo(m_output.fileName()).fileName()); - if (m_requestFileName) - downloadReadyRead(); -} - -QString DownloadItem::saveFileName(const QString &directory) const -{ - // Move this function into QNetworkReply to also get file name sent from the server - QString path; - if (m_reply->hasRawHeader("Content-Disposition")) { - QString value = QLatin1String(m_reply->rawHeader("Content-Disposition")); - int pos = value.indexOf(QLatin1String("filename=")); - if (pos != -1) { - QString name = value.mid(pos + 9); - if (name.startsWith(QLatin1Char('"')) && name.endsWith(QLatin1Char('"'))) - name = name.mid(1, name.size() - 2); - path = name; + return false; } } - if (path.isEmpty()) - path = m_url.path(); + m_file.setFile(fileName); - QFileInfo info(path); - QString baseName = info.completeBaseName(); - QString endName = info.suffix(); - - if (baseName.isEmpty()) { - baseName = QLatin1String("unnamed_download"); - -#ifdef DOWNLOADMANAGER_DEBUG - qDebug() << "DownloadItem::" << __FUNCTION__ << "downloading unknown file:" << m_url; -#endif + if (m_download && m_download->state() == QWebEngineDownloadItem::DownloadRequested) { + m_download->setDownloadFileName(m_file.fileName()); + m_download->setDownloadDirectory(m_file.absolutePath()); } - if (!endName.isEmpty()) - endName = QLatin1Char('.') + endName; - - QString name = directory + baseName + endName; - if (!m_requestFileName && QFile::exists(name)) { - // already exists, don't overwrite - int i = 1; - do { - name = directory + baseName + QLatin1Char('-') + QString::number(i++) + endName; - } while (QFile::exists(name)); - } - return name; + fileNameLabel->setText(m_file.fileName()); + return true; } void DownloadItem::stop() @@ -246,17 +224,17 @@ void DownloadItem::stop() setUpdatesEnabled(false); stopButton->setEnabled(false); stopButton->hide(); - tryAgainButton->setEnabled(true); - tryAgainButton->show(); setUpdatesEnabled(true); - m_reply->abort(); - emit downloadFinished(); + if (m_download) + m_download->cancel(); + + Q_EMIT statusChanged(); + Q_EMIT downloadFinished(); } void DownloadItem::open() { - QFileInfo info(m_output); - QUrl url = QUrl::fromLocalFile(info.absoluteFilePath()); + QUrl url = QUrl::fromLocalFile(m_file.absoluteFilePath()); QDesktopServices::openUrl(url); } @@ -271,73 +249,12 @@ void DownloadItem::tryAgain() stopButton->setVisible(true); progressBar->setVisible(true); - QNetworkReply *r = BrowserApplication::networkAccessManager()->get(QNetworkRequest(m_url)); - if (m_reply) - m_reply->deleteLater(); - if (m_output.exists()) - m_output.remove(); - m_reply = r; + m_download.data()->resume(); init(); - emit statusChanged(); -} - -void DownloadItem::downloadReadyRead() -{ - if (m_requestFileName && m_output.fileName().isEmpty()) - return; - if (!m_output.isOpen()) { - // in case someone else has already put a file there - if (!m_requestFileName) - getFileName(); - if (!m_output.open(QIODevice::WriteOnly)) { - downloadInfoLabel->setText(tr("Error opening output file: %1") - .arg(m_output.errorString())); - stop(); - emit statusChanged(); - return; - } - emit statusChanged(); - } - if (-1 == m_output.write(m_reply->readAll())) { - downloadInfoLabel->setText(tr("Error saving: %1") - .arg(m_output.errorString())); - stopButton->click(); - } else { - m_startedSaving = true; - if (m_finishedDownloading) - finished(); - } -} - -void DownloadItem::error(QNetworkReply::NetworkError) -{ -#ifdef DOWNLOADMANAGER_DEBUG - qDebug() << "DownloadItem::" << __FUNCTION__ << m_reply->errorString() << m_url; -#endif - - downloadInfoLabel->setText(tr("Network Error: %1").arg(m_reply->errorString())); - tryAgainButton->setEnabled(true); - tryAgainButton->setVisible(true); - emit downloadFinished(); + Q_EMIT statusChanged(); } -void DownloadItem::metaDataChanged() -{ - QVariant locationHeader = m_reply->header(QNetworkRequest::LocationHeader); - if (locationHeader.isValid()) { - m_url = locationHeader.toUrl(); - m_reply->deleteLater(); - m_reply = BrowserApplication::networkAccessManager()->get(QNetworkRequest(m_url)); - init(); - return; - } - -#ifdef DOWNLOADMANAGER_DEBUG - qDebug() << "DownloadItem::" << __FUNCTION__ << "not handled."; -#endif -} - -void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) +void DownloadItem::downloadProgress() { QTime now = QTime::currentTime(); if (m_lastProgressTime.msecsTo(now) < 200) @@ -345,84 +262,56 @@ void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) m_lastProgressTime = now; - m_bytesReceived = bytesReceived; - qint64 currentValue = 0; - qint64 totalValue = 0; - if (bytesTotal > 0) { - currentValue = bytesReceived * 100 / bytesTotal; - totalValue = 100; + if (m_download.data()->totalBytes() == -1) { + progressBar->setValue(0); + progressBar->setMaximum(0); + } else { + progressBar->setValue(m_download.data()->receivedBytes()); + progressBar->setMaximum(m_download.data()->totalBytes()); } - progressBar->setValue(currentValue); - progressBar->setMaximum(totalValue); - - emit progress(currentValue, totalValue); updateInfoLabel(); } -qint64 DownloadItem::bytesTotal() const -{ - return m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); +QString DownloadItem::dataString(qint64 size) { + return DownloadManager::dataString(size); } -qint64 DownloadItem::bytesReceived() const -{ - return m_bytesReceived; -} - -double DownloadItem::remainingTime() const +void DownloadItem::updateInfoLabel() { - if (!downloading()) - return -1.0; - double timeRemaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed(); + // update info label + double speed = m_download.data()->receivedBytes() * 1000.0 / m_downloadTime.elapsed(); + double timeRemaining = ((double)(m_download.data()->totalBytes() - m_download.data()->receivedBytes())) / speed; + QString timeRemainingString = tr("seconds"); + if (timeRemaining > 60) { + timeRemaining = timeRemaining / 60; + timeRemainingString = tr("minutes"); + } + timeRemaining = floor(timeRemaining); // When downloading the eta should never be 0 if (timeRemaining == 0) timeRemaining = 1; - return timeRemaining; -} - -double DownloadItem::currentSpeed() const -{ - if (!downloading()) - return -1.0; - - return m_bytesReceived * 1000.0 / m_downloadTime.elapsed(); -} - -void DownloadItem::updateInfoLabel() -{ - if (m_reply->error() != QNetworkReply::NoError) - return; - - qint64 bytesTotal = m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); - bool running = !downloadedSuccessfully(); - - // update info label - double speed = currentSpeed(); - double timeRemaining = remainingTime(); - QString info; - if (running) { + if (!downloadedSuccessfully()) { QString remaining; - - if (bytesTotal != 0) { - remaining = DownloadManager::timeString(timeRemaining); - } - - info = QString(tr("%1 of %2 (%3/sec) - %4")) - .arg(DownloadManager::dataString(m_bytesReceived)) - .arg(bytesTotal == 0 ? tr("?") : DownloadManager::dataString(bytesTotal)) - .arg(DownloadManager::dataString((int)speed)) + if (m_download.data()->totalBytes() != 0) + remaining = tr("- %4 %5 remaining") + .arg(timeRemaining) + .arg(timeRemainingString); + info = tr("%1 of %2 (%3/sec) %4") + .arg(dataString(m_download.data()->receivedBytes())) + .arg(m_download.data()->totalBytes() == 0 ? tr("?") : dataString(m_download.data()->totalBytes())) + .arg(dataString((int)speed)) .arg(remaining); } else { - if (m_bytesReceived == bytesTotal) - info = DownloadManager::dataString(m_output.size()); - else - info = tr("%1 of %2 - Download Complete") - .arg(DownloadManager::dataString(m_bytesReceived)) - .arg(DownloadManager::dataString(bytesTotal)); + if (m_download.data()->receivedBytes() != m_download.data()->totalBytes()) { + info = tr("%1 of %2 - Stopped") + .arg(dataString(m_download.data()->receivedBytes())) + .arg(dataString(m_download.data()->totalBytes())); + } else + info = dataString(m_download.data()->receivedBytes()); } downloadInfoLabel->setText(info); } @@ -434,23 +323,48 @@ bool DownloadItem::downloading() const bool DownloadItem::downloadedSuccessfully() const { - return (stopButton->isHidden() && tryAgainButton->isHidden()); + bool completed = m_download + && m_download->isFinished() + && m_download->state() == QWebEngineDownloadItem::DownloadCompleted; + return completed || !stopButton->isVisible(); } void DownloadItem::finished() { - m_finishedDownloading = true; - if (!m_startedSaving) { - return; + if (m_download) { + QWebEngineDownloadItem::DownloadState state = m_download->state(); + QString message; + bool interrupted = false; + + switch (state) { + case QWebEngineDownloadItem::DownloadRequested: // Fall-through. + case QWebEngineDownloadItem::DownloadInProgress: + Q_UNREACHABLE(); + break; + case QWebEngineDownloadItem::DownloadCompleted: + break; + case QWebEngineDownloadItem::DownloadCancelled: + message = QStringLiteral("Download cancelled"); + interrupted = true; + break; + case QWebEngineDownloadItem::DownloadInterrupted: + message = QStringLiteral("Download interrupted"); + interrupted = true; + break; + } + + if (interrupted) { + downloadInfoLabel->setText(message); + return; + } } + progressBar->hide(); stopButton->setEnabled(false); stopButton->hide(); - openButton->setEnabled(true); - m_output.close(); updateInfoLabel(); - emit statusChanged(); - emit downloadFinished(); + Q_EMIT statusChanged(); + Q_EMIT downloadFinished(); } /*! @@ -463,16 +377,15 @@ DownloadManager::DownloadManager(QWidget *parent) : QDialog(parent) , m_autoSaver(new AutoSaver(this)) , m_model(new DownloadModel(this)) - , m_manager(BrowserApplication::networkAccessManager()) - , m_iconProvider(0) + , m_iconProvider(nullptr) , m_removePolicy(Never) { setupUi(this); QSettings settings; - settings.beginGroup(QLatin1String("downloadmanager")); + settings.beginGroup(QStringLiteral("downloadmanager")); QString defaultLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); - setDownloadDirectory(settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString()); + setDownloadDirectory(settings.value(QStringLiteral("downloadDirectory"), defaultLocation).toString()); downloadsView->setShowGrid(false); downloadsView->verticalHeader()->hide(); @@ -481,7 +394,6 @@ DownloadManager::DownloadManager(QWidget *parent) downloadsView->horizontalHeader()->setStretchLastSection(true); downloadsView->setModel(m_model); connect(cleanupButton, SIGNAL(clicked()), this, SLOT(cleanup())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(close())); load(); } @@ -507,10 +419,10 @@ bool DownloadManager::allowQuit() { if (activeDownloads() >= 1) { int choice = QMessageBox::warning(this, QString(), - tr("There are %1 downloads in progress\n" - "Do you want to quit anyway?").arg(activeDownloads()), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + tr("There are %1 downloads in progress\n" + "Do you want to quit anyway?").arg(activeDownloads()), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No); if (choice == QMessageBox::No) { show(); return false; @@ -522,16 +434,16 @@ bool DownloadManager::allowQuit() bool DownloadManager::externalDownload(const QUrl &url) { QSettings settings; - settings.beginGroup(QLatin1String("downloadmanager")); - if (!settings.value(QLatin1String("external"), false).toBool()) + settings.beginGroup(QStringLiteral("downloadmanager")); + if (!settings.value(QStringLiteral("external"), false).toBool()) return false; - QString program = settings.value(QLatin1String("externalPath")).toString(); + QString program = settings.value(QStringLiteral("externalPath")).toString(); if (program.isEmpty()) return false; // Split program at every space not inside double quotes - QRegExp regex(QLatin1String("\"([^\"]+)\"|([^ ]+)")); + QRegExp regex(QStringLiteral("\"([^\"]+)\"|([^ ]+)")); QStringList args; for (int pos = 0; (pos = regex.indexIn(program, pos)) != -1; pos += regex.matchedLength()) args << regex.cap(1) + regex.cap(2); @@ -541,38 +453,13 @@ bool DownloadManager::externalDownload(const QUrl &url) return QProcess::startDetached(args.takeFirst(), args << QString::fromUtf8(url.toEncoded())); } -void DownloadManager::download(const QNetworkRequest &request, bool requestFileName) -{ - if (request.url().isEmpty()) - return; - if (externalDownload(request.url())) - return; - handleUnsupportedContent(m_manager->get(request), requestFileName); -} - -void DownloadManager::handleUnsupportedContent(QNetworkReply *reply, bool requestFileName) +void DownloadManager::download(QWebEngineDownloadItem *download) { - if (!reply || reply->url().isEmpty()) - return; - if (externalDownload(reply->url())) + if (externalDownload(download->url())) return; - - QVariant header = reply->header(QNetworkRequest::ContentLengthHeader); - bool ok; - int size = header.toInt(&ok); - if (ok && size == 0) - return; - -#ifdef DOWNLOADMANAGER_DEBUG - qDebug() << "DownloadManager::" << __FUNCTION__ << reply->url() << "requestFileName" << requestFileName; -#endif - - DownloadItem *item = new DownloadItem(reply, requestFileName, this); + DownloadItem *item = new DownloadItem(download, this); addItem(item); - if (item->m_canceledFileSelect) - return; - if (!isVisible()) show(); @@ -589,6 +476,8 @@ void DownloadManager::addItem(DownloadItem *item) m_downloads.append(item); m_model->endInsertRows(); updateItemCount(); + if (row == 0) + show(); downloadsView->setIndexWidget(m_model->index(row, 0), item); QIcon icon = style()->standardIcon(QStyle::SP_FileIcon); item->fileIcon->setPixmap(icon.pixmap(48, 48)); @@ -629,22 +518,20 @@ void DownloadManager::updateRow(DownloadItem *item) return; if (!m_iconProvider) m_iconProvider = new QFileIconProvider(); - QIcon icon = m_iconProvider->icon(item->m_output.fileName()); + QIcon icon = m_iconProvider->icon(item->m_file); if (icon.isNull()) icon = style()->standardIcon(QStyle::SP_FileIcon); item->fileIcon->setPixmap(icon.pixmap(48, 48)); - - int oldHeight = downloadsView->rowHeight(row); - downloadsView->setRowHeight(row, qMax(oldHeight, item->minimumSizeHint().height())); + downloadsView->setRowHeight(row, item->minimumSizeHint().height()); bool remove = false; - QWebSettings *globalSettings = QWebSettings::globalSettings(); if (!item->downloading() - && globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled)) - remove = true; + && BrowserApplication::instance()->isPrivate()) + remove = true; + if (item->downloadedSuccessfully() - && removePolicy() == DownloadManager::SuccessFullDownload) { + && removePolicy() == DownloadManager::SuccessFullDownload) { remove = true; } if (remove) @@ -669,61 +556,59 @@ void DownloadManager::setRemovePolicy(RemovePolicy policy) void DownloadManager::save() const { QSettings settings; - settings.beginGroup(QLatin1String("downloadmanager")); + settings.beginGroup(QStringLiteral("downloadmanager")); QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy")); - settings.setValue(QLatin1String("removeDownloadsPolicy"), QLatin1String(removePolicyEnum.valueToKey(m_removePolicy))); - settings.setValue(QLatin1String("size"), size()); + settings.setValue(QStringLiteral("removeDownloadsPolicy"), QString(removePolicyEnum.valueToKey(m_removePolicy))); + settings.setValue(QStringLiteral("size"), size()); if (m_removePolicy == Exit) return; for (int i = 0; i < m_downloads.count(); ++i) { - QString key = QString(QLatin1String("download_%1_")).arg(i); - settings.setValue(key + QLatin1String("url"), m_downloads[i]->m_url); - settings.setValue(key + QLatin1String("location"), QFileInfo(m_downloads[i]->m_output).filePath()); - settings.setValue(key + QLatin1String("done"), m_downloads[i]->downloadedSuccessfully()); + QString key = QString(QStringLiteral("download_%1_")).arg(i); + settings.setValue(key + QStringLiteral("url"), m_downloads[i]->m_url); + settings.setValue(key + QStringLiteral("location"), m_downloads[i]->m_file.filePath()); + settings.setValue(key + QStringLiteral("done"), m_downloads[i]->downloadedSuccessfully()); } int i = m_downloads.count(); - QString key = QString(QLatin1String("download_%1_")).arg(i); - while (settings.contains(key + QLatin1String("url"))) { - settings.remove(key + QLatin1String("url")); - settings.remove(key + QLatin1String("location")); - settings.remove(key + QLatin1String("done")); - key = QString(QLatin1String("download_%1_")).arg(++i); + QString key = QString(QStringLiteral("download_%1_")).arg(i); + while (settings.contains(key + QStringLiteral("url"))) { + settings.remove(key + QStringLiteral("url")); + settings.remove(key + QStringLiteral("location")); + settings.remove(key + QStringLiteral("done")); + key = QString(QStringLiteral("download_%1_")).arg(++i); } } void DownloadManager::load() { QSettings settings; - settings.beginGroup(QLatin1String("downloadmanager")); - QSize size = settings.value(QLatin1String("size")).toSize(); + settings.beginGroup(QStringLiteral("downloadmanager")); + QSize size = settings.value(QStringLiteral("size")).toSize(); if (size.isValid()) resize(size); - QByteArray value = settings.value(QLatin1String("removeDownloadsPolicy"), QLatin1String("Never")).toByteArray(); + QByteArray value = settings.value(QStringLiteral("removeDownloadsPolicy"), QStringLiteral("Never")).toByteArray(); QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy")); m_removePolicy = removePolicyEnum.keyToValue(value) == -1 ? - Never : - static_cast(removePolicyEnum.keyToValue(value)); + Never : + static_cast(removePolicyEnum.keyToValue(value)); int i = 0; - QString key = QString(QLatin1String("download_%1_")).arg(i); - while (settings.contains(key + QLatin1String("url"))) { - QUrl url = settings.value(key + QLatin1String("url")).toUrl(); - QString fileName = settings.value(key + QLatin1String("location")).toString(); - bool done = settings.value(key + QLatin1String("done"), true).toBool(); - if (!url.isEmpty() && !fileName.isEmpty()) { + QString key = QString(QStringLiteral("download_%1_")).arg(i); + while (settings.contains(key + QStringLiteral("url"))) { + QUrl url = settings.value(key + QStringLiteral("url")).toUrl(); + QString fileName = settings.value(key + QStringLiteral("location")).toString(); + bool done = settings.value(key + QStringLiteral("done"), true).toBool(); + if (done && !url.isEmpty() && !fileName.isEmpty()) { DownloadItem *item = new DownloadItem(0, this); - item->m_output.setFileName(fileName); - item->fileNameLabel->setText(QFileInfo(item->m_output.fileName()).fileName()); + item->m_file.setFile(fileName); + item->fileNameLabel->setText(item->m_file.fileName()); item->m_url = url; item->stopButton->setVisible(false); item->stopButton->setEnabled(false); - item->tryAgainButton->setVisible(!done); - item->tryAgainButton->setEnabled(!done); - item->progressBar->setVisible(false); + item->progressBar->hide(); addItem(item); } - key = QString(QLatin1String("download_%1_")).arg(++i); + key = QString(QStringLiteral("download_%1_")).arg(++i); } cleanupButton->setEnabled(m_downloads.count() - activeDownloads() > 0); updateActiveItemCount(); @@ -738,7 +623,7 @@ void DownloadManager::cleanup() updateActiveItemCount(); if (m_downloads.isEmpty() && m_iconProvider) { delete m_iconProvider; - m_iconProvider = 0; + m_iconProvider = nullptr; } m_autoSaver->changeOccurred(); } @@ -753,7 +638,7 @@ void DownloadManager::setDownloadDirectory(const QString &directory) { m_downloadDirectory = directory; if (!m_downloadDirectory.isEmpty()) - m_downloadDirectory += QLatin1Char('/'); + m_downloadDirectory += QChar('/'); } QString DownloadManager::downloadDirectory() @@ -797,7 +682,7 @@ QString DownloadManager::dataString(qint64 size) unit = tr("GB"); } - return QString(QLatin1String("%1 %2")).arg(newSize, 0, 'f', 1).arg(unit); + return QString(QStringLiteral("%1 %2")).arg(newSize, 0, 'f', 1).arg(unit); } DownloadModel::DownloadModel(DownloadManager *downloadManager, QObject *parent) @@ -829,7 +714,7 @@ bool DownloadModel::removeRows(int row, int count, const QModelIndex &parent) int lastRow = row + count - 1; for (int i = lastRow; i >= row; --i) { if (m_downloadManager->m_downloads.at(i)->downloadedSuccessfully() - || m_downloadManager->m_downloads.at(i)->tryAgainButton->isEnabled()) { + || m_downloadManager->m_downloads.at(i)->tryAgainButton->isEnabled()) { beginRemoveRows(parent, i, i); m_downloadManager->m_downloads.takeAt(i)->deleteLater(); endRemoveRows(); @@ -843,7 +728,7 @@ bool DownloadModel::removeRows(int row, int count, const QModelIndex &parent) Qt::ItemFlags DownloadModel::flags(const QModelIndex &index) const { if (index.row() < 0 || index.row() >= rowCount(index.parent())) - return 0; + return Qt::ItemFlags(); Qt::ItemFlags defaultFlags = QAbstractItemModel::flags(index); @@ -858,11 +743,11 @@ QMimeData *DownloadModel::mimeData(const QModelIndexList &indexes) const { QMimeData *mimeData = new QMimeData(); QList urls; - foreach (const QModelIndex &index, indexes) { + Q_FOREACH (const QModelIndex &index, indexes) { if (!index.isValid()) continue; DownloadItem *item = m_downloadManager->m_downloads.at(index.row()); - urls.append(QUrl::fromLocalFile(QFileInfo(item->m_output).absoluteFilePath())); + urls.append(QUrl::fromLocalFile(item->m_file.absoluteFilePath())); } mimeData->setUrls(urls); return mimeData; diff --git a/src/downloadmanager.h b/src/downloadmanager.h index aecba983..55961245 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Jason A. Donenfeld * * This program is free software; you can redistribute it and/or modify @@ -67,64 +67,54 @@ #include "ui_downloads.h" #include "ui_downloaditem.h" -#include +#include -#include -#include +#include +#include +#include #include +#include class DownloadItem : public QWidget, public Ui_DownloadItem { Q_OBJECT -signals: +Q_SIGNALS: void statusChanged(); - void progress(qint64 bytesReceived = 0, qint64 bytesTotal = 0); void downloadFinished(); public: - DownloadItem(QNetworkReply *reply = 0, bool requestFileName = false, QWidget *parent = 0); + DownloadItem(QWebEngineDownloadItem *download, QWidget *parent = 0); bool downloading() const; bool downloadedSuccessfully() const; - qint64 bytesTotal() const; - qint64 bytesReceived() const; - double remainingTime() const; - double currentSpeed() const; - - QUrl m_url; + void init(); + bool getFileName(bool promptForFileName = false); - QFile m_output; - QNetworkReply *m_reply; + QFileInfo m_file; -private slots: +private Q_SLOTS: void stop(); void tryAgain(); void open(); - void downloadReadyRead(); - void error(QNetworkReply::NetworkError code); - void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); - void metaDataChanged(); + void downloadProgress(); void finished(); private: - void getFileName(); - void init(); + friend class DownloadManager; void updateInfoLabel(); - QString saveFileName(const QString &directory) const; - - bool m_requestFileName; + QUrl m_url; qint64 m_bytesReceived; QElapsedTimer m_downloadTime; - bool m_startedSaving; - bool m_finishedDownloading; - bool m_gettingFileName; - bool m_canceledFileSelect; + bool m_stopped; QTime m_lastProgressTime; + QScopedPointer m_download; friend class DownloadManager; + + static QString dataString(qint64 size); }; class AutoSaver; @@ -137,8 +127,7 @@ QT_END_NAMESPACE class DownloadManager : public QDialog, public Ui_DownloadDialog { Q_OBJECT - Q_PROPERTY(RemovePolicy removePolicy READ removePolicy WRITE setRemovePolicy) - Q_ENUMS(RemovePolicy) + Q_PROPERTY(RemovePolicy removePolicy READ removePolicy WRITE setRemovePolicy NOTIFY removePolicyChanged) public: enum RemovePolicy { @@ -146,14 +135,16 @@ class DownloadManager : public QDialog, public Ui_DownloadDialog Exit, SuccessFullDownload }; + Q_ENUM(RemovePolicy) - DownloadManager(QWidget *parent = 0); + DownloadManager(QWidget *parent = nullptr); ~DownloadManager(); int activeDownloads() const; bool allowQuit(); RemovePolicy removePolicy() const; void setRemovePolicy(RemovePolicy policy); + void removePolicyChanged(){}; static QString timeString(double timeRemaining); static QString dataString(qint64 size); @@ -161,14 +152,11 @@ class DownloadManager : public QDialog, public Ui_DownloadDialog void setDownloadDirectory(const QString &directory); QString downloadDirectory(); -public slots: - void download(const QNetworkRequest &request, bool requestFileName = false); - inline void download(const QUrl &url, bool requestFileName = false) - { download(QNetworkRequest(url), requestFileName); } - void handleUnsupportedContent(QNetworkReply *reply, bool requestFileName = false); +public Q_SLOTS: + void download(QWebEngineDownloadItem *download); void cleanup(); -private slots: +private Q_SLOTS: void save() const; void updateRow(DownloadItem *item); void updateRow(); @@ -183,7 +171,6 @@ private slots: AutoSaver *m_autoSaver; DownloadModel *m_model; - QNetworkAccessManager *m_manager; QFileIconProvider *m_iconProvider; QList m_downloads; RemovePolicy m_removePolicy; @@ -198,7 +185,7 @@ class DownloadModel : public QAbstractListModel Q_OBJECT public: - DownloadModel(DownloadManager *downloadManager, QObject *parent = 0); + DownloadModel(DownloadManager *downloadManager, QObject *parent = nullptr); QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; int rowCount(const QModelIndex &parent = QModelIndex()) const; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); diff --git a/src/downloads.ui b/src/downloads.ui index 134148b2..8cd9c2b4 100644 --- a/src/downloads.ui +++ b/src/downloads.ui @@ -6,15 +6,24 @@ 0 0 - 340 - 233 + 552 + 366 Downloads - + + 0 + + + 0 + + + 0 + + 0 @@ -82,13 +91,6 @@ - - - - QDialogButtonBox::Close - - - diff --git a/src/history/history.cpp b/src/history/history.cpp index 5045c899..eb0e1ab3 100644 --- a/src/history/history.cpp +++ b/src/history/history.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -69,24 +69,23 @@ #include "historymanager.h" #include "treesortfilterproxymodel.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include -#include +#include -#include +#include HistoryModel::HistoryModel(HistoryManager *history, QObject *parent) : QAbstractTableModel(parent) @@ -124,16 +123,18 @@ void HistoryModel::entryAdded() void HistoryModel::entryUpdated(int offset) { QModelIndex idx = index(offset, 0); - emit dataChanged(idx, idx); + Q_EMIT dataChanged(idx, idx); } QVariant HistoryModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal - && role == Qt::DisplayRole) { + && role == Qt::DisplayRole) { switch (section) { - case 0: return tr("Title"); - case 1: return tr("Address"); + case 0: + return tr("Title"); + case 1: + return tr("Address"); } } return QAbstractTableModel::headerData(section, orientation, role); @@ -236,12 +237,12 @@ int HistoryMenuModel::rowCount(const QModelIndex &parent) const int folders = sourceModel()->rowCount(); int bumpedItems = bumpedRows(); if (bumpedItems <= MOVEDROWS - && bumpedItems == sourceModel()->rowCount(sourceModel()->index(0, 0))) + && bumpedItems == sourceModel()->rowCount(sourceModel()->index(0, 0))) --folders; return bumpedItems + folders; } - if (parent.internalId() == -1) { + if (parent.internalId() == (quintptr)-1) { if (parent.row() < bumpedRows()) return 0; } @@ -271,7 +272,7 @@ QModelIndex HistoryMenuModel::mapToSource(const QModelIndex &proxyIndex) const if (!proxyIndex.isValid()) return QModelIndex(); - if (proxyIndex.internalId() == -1) { + if (proxyIndex.internalId() == (quintptr)-1) { int bumpedItems = bumpedRows(); if (proxyIndex.row() < bumpedItems) return m_treeModel->index(proxyIndex.row(), proxyIndex.column(), m_treeModel->index(0, 0)); @@ -288,8 +289,8 @@ QModelIndex HistoryMenuModel::mapToSource(const QModelIndex &proxyIndex) const QModelIndex HistoryMenuModel::index(int row, int column, const QModelIndex &parent) const { if (row < 0 - || column < 0 || column >= columnCount(parent) - || parent.column() > 0) + || column < 0 || column >= columnCount(parent) + || parent.column() > 0) return QModelIndex(); if (!parent.isValid()) return createIndex(row, column, -1); @@ -328,7 +329,7 @@ QMimeData *HistoryMenuModel::mimeData(const QModelIndexList &indexes) const { QMimeData *mimeData = new QMimeData; QList urls; - foreach (const QModelIndex &idx, indexes) { + Q_FOREACH (const QModelIndex &idx, indexes) { QUrl url = idx.data(HistoryModel::UrlRole).toUrl(); urls.append(url); } @@ -339,8 +340,8 @@ QMimeData *HistoryMenuModel::mimeData(const QModelIndexList &indexes) const #ifndef NO_BROWSERAPPLICATION HistoryMenu::HistoryMenu(QWidget *parent) : ModelMenu(parent) - , m_history(0) - , m_historyMenuModel(0) + , m_history(nullptr) + , m_historyMenuModel(nullptr) { setMaxRows(7); connect(this, SIGNAL(activated(const QModelIndex &)), @@ -350,7 +351,7 @@ HistoryMenu::HistoryMenu(QWidget *parent) void HistoryMenu::activated(const QModelIndex &index) { - emit openUrl(index.data(HistoryModel::UrlRole).toUrl(), + Q_EMIT openUrl(index.data(HistoryModel::UrlRole).toUrl(), index.data(HistoryModel::TitleRole).toString()); } @@ -399,8 +400,8 @@ void HistoryMenu::showHistoryDialog() void HistoryMenu::clearHistoryDialog() { - if (m_history && QMessageBox::question(0, tr("Clear History"), tr("Do you want to clear the history?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { + if (m_history && QMessageBox::question(nullptr, tr("Clear History"), tr("Do you want to clear the history?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { m_history->clear(); } } @@ -412,11 +413,16 @@ void HistoryMenu::setInitialActions(QList actions) addAction(m_initialActions.at(i)); } +#endif + +#ifndef NO_HISTORYDIALOG HistoryDialog::HistoryDialog(QWidget *parent, HistoryManager *setHistory) : QDialog(parent) { HistoryManager *history = setHistory; +#ifndef NO_BROWSERAPPLICATION if (!history) history = BrowserApplication::historyManager(); +#endif setupUi(this); tree->setUniformRowHeights(true); tree->setSelectionBehavior(QAbstractItemView::SelectRows); @@ -435,7 +441,7 @@ HistoryDialog::HistoryDialog(QWidget *parent, HistoryManager *setHistory) : QDia tree->setExpanded(proxyModel->index(0, 0), true); tree->setAlternatingRowColors(true); QFontMetrics fm(font()); - int header = fm.horizontalAdvance(QLatin1Char('m')) * 40; + int header = fm.horizontalAdvance(QChar('m')) * 40; tree->header()->resizeSection(0, header); tree->header()->setStretchLastSection(true); connect(tree, SIGNAL(activated(const QModelIndex&)), @@ -464,9 +470,11 @@ void HistoryDialog::open() QModelIndex index = tree->currentIndex(); if (!index.parent().isValid()) return; +#ifndef NO_BROWSERAPPLICATION BrowserApplication::instance()->setEventMouseButtons(qApp->mouseButtons()); BrowserApplication::instance()->setEventKeyboardModifiers(qApp->keyboardModifiers()); - emit openUrl(index.data(HistoryModel::UrlRole).toUrl(), +#endif + Q_EMIT openUrl(index.data(HistoryModel::UrlRole).toUrl(), index.data(HistoryModel::TitleRole).toString()); } @@ -552,7 +560,7 @@ void HistoryFilterModel::setSourceModel(QAbstractItemModel *newSourceModel) void HistoryFilterModel::sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { - emit dataChanged(mapFromSource(topLeft), mapFromSource(bottomRight)); + Q_EMIT dataChanged(mapFromSource(topLeft), mapFromSource(bottomRight)); } QVariant HistoryFilterModel::headerData(int section, Qt::Orientation orientation, int role) const @@ -602,7 +610,7 @@ QModelIndex HistoryFilterModel::mapFromSource(const QModelIndex &sourceIndex) co int sourceOffset = sourceModel()->rowCount() - sourceIndex.row(); QList::iterator pos = std::lower_bound(m_filteredRows.begin(), - m_filteredRows.end(), HistoryData(sourceOffset, -1)); + m_filteredRows.end(), HistoryData(sourceOffset, -1)); if (pos == m_filteredRows.end()) return QModelIndex(); @@ -614,7 +622,7 @@ QModelIndex HistoryFilterModel::index(int row, int column, const QModelIndex &pa { load(); if (row < 0 || row >= rowCount(parent) - || column < 0 || column >= columnCount(parent)) + || column < 0 || column >= columnCount(parent)) return QModelIndex(); return createIndex(row, column, m_filteredRows[row].tailOffset); @@ -643,7 +651,7 @@ void HistoryFilterModel::load() const } else { // we already know about this url: just increment its frecency score QList::iterator pos = std::lower_bound(m_filteredRows.begin(), - m_filteredRows.end(), HistoryData(m_historyHash[url], -1)); + m_filteredRows.end(), HistoryData(m_historyHash[url], -1)); Q_ASSERT(pos != m_filteredRows.end()); pos->frecency += frecencyScore(idx); } @@ -662,7 +670,7 @@ void HistoryFilterModel::sourceRowsInserted(const QModelIndex &parent, int start int currentFrecency = 0; if (m_historyHash.contains(url)) { QList::iterator pos = std::lower_bound(m_filteredRows.begin(), - m_filteredRows.end(), HistoryData(m_historyHash[url], -1)); + m_filteredRows.end(), HistoryData(m_historyHash[url], -1)); Q_ASSERT(pos != m_filteredRows.end()); int realRow = pos - m_filteredRows.begin(); currentFrecency = pos->frecency; @@ -753,7 +761,7 @@ QVariant HistoryTreeModel::data(const QModelIndex &index, int role) const QDate date = idx.data(HistoryModel::DateRole).toDate(); if (date == QDate::currentDate()) return tr("Earlier Today"); - return date.toString(QLatin1String("dddd, MMMM d, yyyy")); + return date.toString(QStringLiteral("dddd, MMMM d, yyyy")); } if (index.column() == 1) { return tr("%n item(s)", "", rowCount(index.sibling(index.row(), 0))); @@ -784,8 +792,8 @@ int HistoryTreeModel::columnCount(const QModelIndex &parent) const int HistoryTreeModel::rowCount(const QModelIndex &parent) const { if (parent.internalId() != 0 - || parent.column() > 0 - || !sourceModel()) + || parent.column() > 0 + || !sourceModel()) return 0; // row count OF dates @@ -843,12 +851,12 @@ QModelIndex HistoryTreeModel::mapToSource(const QModelIndex &proxyIndex) const QModelIndex HistoryTreeModel::index(int row, int column, const QModelIndex &parent) const { if (row < 0 - || column < 0 || column >= columnCount(parent) - || parent.column() > 0) + || column < 0 || column >= columnCount(parent) + || parent.column() > 0) return QModelIndex(); if (!parent.isValid()) - return createIndex(row, column, (void*) 0); + return createIndex(row, column, (void*) nullptr); return createIndex(row, column, parent.row() + 1); } @@ -857,7 +865,7 @@ QModelIndex HistoryTreeModel::parent(const QModelIndex &index) const int offset = index.internalId(); if (offset == 0 || !index.isValid()) return QModelIndex(); - return createIndex(offset - 1, 0, (void*) 0); + return createIndex(offset - 1, 0, (void*) nullptr); } bool HistoryTreeModel::hasChildren(const QModelIndex &parent) const @@ -986,26 +994,26 @@ void HistoryTreeModel::sourceRowsRemoved(const QModelIndex &parent, int start, i Q_UNUSED(parent); // Avoid warnings when compiling release Q_ASSERT(!parent.isValid()); if (!m_sourceRowCache.isEmpty()) - for (int i = end; i >= start;) { - QList::iterator it; - it = std::lower_bound(m_sourceRowCache.begin(), m_sourceRowCache.end(), i); - if (*it != i) - --it; - int row = qMax(0, it - m_sourceRowCache.begin()); - int offset = m_sourceRowCache[row]; - QModelIndex dateParent = index(row, 0); - // If we can remove all the rows in the date do that and skip over them - int rc = rowCount(dateParent); - if (i - rc + 1 == offset && start <= i - rc + 1) { - m_sourceRowCache.removeAt(row); - i -= rc + 1; - } else { - ++row; - --i; + for (int i = end; i >= start;) { + QList::iterator it; + it = std::lower_bound(m_sourceRowCache.begin(), m_sourceRowCache.end(), i); + if (*it != i) + --it; + int row = qMax(0, it - m_sourceRowCache.begin()); + int offset = m_sourceRowCache[row]; + QModelIndex dateParent = index(row, 0); + // If we can remove all the rows in the date do that and skip over them + int rc = rowCount(dateParent); + if (i - rc + 1 == offset && start <= i - rc + 1) { + m_sourceRowCache.removeAt(row); + i -= rc + 1; + } else { + ++row; + --i; + } + for (int j = row; j < m_sourceRowCache.count(); ++j) + --m_sourceRowCache[j]; } - for (int j = row; j < m_sourceRowCache.count(); ++j) - --m_sourceRowCache[j]; - } if (removingDown) { endRemoveRows(); removingDown = false; diff --git a/src/history/history.h b/src/history/history.h index de064256..c8ddb08d 100644 --- a/src/history/history.h +++ b/src/history/history.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,21 +65,19 @@ #include "modelmenu.h" -#include +#include #include -#include -#include -#include -#include - -#include +#include +#include +#include +#include class HistoryManager; class HistoryModel : public QAbstractTableModel { Q_OBJECT -public slots: +public Q_SLOTS: void historyReset(); void historyGoingToChange(); void entryAdded(); @@ -95,7 +93,7 @@ public slots: MaxRole = TitleRole }; - HistoryModel(HistoryManager *history, QObject *parent = 0); + HistoryModel(HistoryManager *history, QObject *parent = nullptr); QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; @@ -116,10 +114,13 @@ class HistoryFilterModel : public QAbstractProxyModel Q_OBJECT public: - HistoryFilterModel(QAbstractItemModel *sourceModel, QObject *parent = 0); + HistoryFilterModel(QAbstractItemModel *sourceModel, QObject *parent = nullptr); inline bool historyContains(const QString &url) const - { load(); return m_historyHash.contains(url); } + { + load(); + return m_historyHash.contains(url); + } int historyLocation(const QString &url) const; enum Roles { @@ -140,7 +141,7 @@ class HistoryFilterModel : public QAbstractProxyModel void recalculateFrecencies(); -private slots: +private Q_SLOTS: void sourceReset(); void sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); void sourceRowsInserted(const QModelIndex &parent, int start, int end); @@ -162,7 +163,7 @@ private slots: bool operator==(const HistoryData &other) const { return (tailOffset == other.tailOffset) - && (frecency == -1 || other.frecency == -1 || frecency == other.frecency); + && (frecency == -1 || other.frecency == -1 || frecency == other.frecency); } bool operator!=(const HistoryData &other) const { return !(*this == other); @@ -194,7 +195,7 @@ class HistoryMenuModel : public QAbstractProxyModel Q_OBJECT public: - HistoryMenuModel(HistoryTreeModel *sourceModel, QObject *parent = 0); + HistoryMenuModel(HistoryTreeModel *sourceModel, QObject *parent = nullptr); int columnCount(const QModelIndex &parent) const; int rowCount(const QModelIndex &parent = QModelIndex()) const; QModelIndex mapFromSource(const QModelIndex & sourceIndex) const; @@ -217,18 +218,18 @@ class HistoryMenu : public ModelMenu { Q_OBJECT -signals: +Q_SIGNALS: void openUrl(const QUrl &url, const QString &title); public: - HistoryMenu(QWidget *parent = 0); + HistoryMenu(QWidget *parent = nullptr); void setInitialActions(QList actions); protected: bool prePopulated(); void postPopulated(); -private slots: +private Q_SLOTS: void activated(const QModelIndex &index); void showHistoryDialog(); void clearHistoryDialog(); @@ -248,7 +249,7 @@ class HistoryTreeModel : public QAbstractProxyModel Q_OBJECT public: - HistoryTreeModel(QAbstractItemModel *sourceModel, QObject *parent = 0); + HistoryTreeModel(QAbstractItemModel *sourceModel, QObject *parent = nullptr); QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; int columnCount(const QModelIndex &parent) const; int rowCount(const QModelIndex &parent = QModelIndex()) const; @@ -263,7 +264,7 @@ class HistoryTreeModel : public QAbstractProxyModel void setSourceModel(QAbstractItemModel *sourceModel); -private slots: +private Q_SLOTS: void sourceReset(); void sourceRowsInserted(const QModelIndex &parent, int start, int end); void sourceRowsRemoved(const QModelIndex &parent, int start, int end); @@ -275,20 +276,24 @@ private slots: }; -#ifndef NO_BROWSERAPPLICATION +#ifndef NO_HISTORYDIALOG #include "ui_history.h" class HistoryDialog : public QDialog, public Ui_HistoryDialog { Q_OBJECT -signals: +Q_SIGNALS: void openUrl(const QUrl &url, const QString &title); public: - HistoryDialog(QWidget *parent = 0, HistoryManager *history = 0); +#ifndef NO_BROWSERAPPLICATION + HistoryDialog(QWidget *parent = nullptr, HistoryManager *history = nullptr); +#else + HistoryDialog(QWidget *parent, HistoryManager *history); +#endif -private slots: +private Q_SLOTS: void customContextMenuRequested(const QPoint &pos); void open(); void copy(); diff --git a/src/history/history.pri b/src/history/history.pri deleted file mode 100644 index 96ff3e59..00000000 --- a/src/history/history.pri +++ /dev/null @@ -1,16 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - history.h \ - historycompleter.h \ - historymanager.h - -SOURCES += \ - history.cpp \ - historycompleter.cpp \ - historymanager.cpp - -FORMS += \ - history.ui diff --git a/src/history/historymanager.cpp b/src/history/historymanager.cpp index 937d5865..29689c12 100644 --- a/src/history/historymanager.cpp +++ b/src/history/historymanager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -64,17 +64,19 @@ #include "autosaver.h" #include "history.h" +#ifndef NO_BROWSERAPPLICATION +#include "browserapplication.h" +#endif -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include -#include +#include // Fix so we don't have to include browserapplication. Reduces the size. @@ -85,7 +87,7 @@ QString HistoryManager::dataFilePath(const QString &fileName) QDir dir; dir.mkpath(directory); } - return directory + QLatin1String("/") + fileName; + return directory + QStringLiteral("/") + fileName; } QString HistoryEntry::userTitle() const @@ -103,12 +105,12 @@ QString HistoryEntry::userTitle() const static const unsigned int HISTORY_VERSION = 23; HistoryManager::HistoryManager(QObject *parent) - : QWebHistoryInterface(parent) + : QObject(parent) , m_saveTimer(new AutoSaver(this)) , m_daysToExpire(30) - , m_historyModel(0) - , m_historyFilterModel(0) - , m_historyTreeModel(0) + , m_historyModel(nullptr) + , m_historyFilterModel(nullptr) + , m_historyTreeModel(nullptr) { m_expiredTimer.setSingleShot(true); connect(&m_expiredTimer, SIGNAL(timeout()), @@ -122,9 +124,6 @@ HistoryManager::HistoryManager(QObject *parent) m_historyModel = new HistoryModel(this, this); m_historyFilterModel = new HistoryFilterModel(m_historyModel, this); m_historyTreeModel = new HistoryTreeModel(m_historyFilterModel, this); - - // QWebHistoryInterface will delete the history manager - QWebHistoryInterface::setDefaultInterface(this); } HistoryManager::~HistoryManager() @@ -147,16 +146,23 @@ bool HistoryManager::historyContains(const QString &url) const void HistoryManager::addHistoryEntry(const QString &url) { +#ifndef NO_BROWSERAPPLICATION + if (BrowserApplication::instance()->isPrivate()) + return; +#endif + QUrl cleanUrl(url); cleanUrl.setPassword(QString()); cleanUrl.setHost(cleanUrl.host().toLower()); - HistoryEntry item(atomicString(cleanUrl.toString()), QDateTime::currentDateTime()); - prependHistoryEntry(item); + if(!cleanUrl.toString().toLower().contains("endorphinbrowser.gitlab.io/newTab/")) { + HistoryEntry item(atomicString(cleanUrl.toString()), QDateTime::currentDateTime()); + prependHistoryEntry(item); + } } void HistoryManager::setHistory(const QList &history, bool loadedAndSorted) { - emit historyGoingToChange(); + Q_EMIT historyGoingToChange(); m_history = history; // verify that it is sorted by date @@ -171,7 +177,7 @@ void HistoryManager::setHistory(const QList &history, bool loadedA m_lastSavedUrl.clear(); m_saveTimer->changeOccurred(); } - emit historyReset(); + Q_EMIT historyReset(); } HistoryModel *HistoryManager::historyModel() const @@ -211,7 +217,7 @@ void HistoryManager::checkForExpired() HistoryEntry item = m_history.takeLast(); // remove from saved file also m_lastSavedUrl.clear(); - emit entryRemoved(item); + Q_EMIT entryRemoved(item); } if (nextTimeout > 0) @@ -220,12 +226,14 @@ void HistoryManager::checkForExpired() void HistoryManager::prependHistoryEntry(const HistoryEntry &item) { - QWebSettings *globalSettings = QWebSettings::globalSettings(); - if (globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled)) + /* + QWebEngineSettings *globalSettings = QWebEngineSettings::globalSettings(); + if (globalSettings->testAttribute(QWebEngineSettings::PrivateBrowsingEnabled)) return; + */ m_history.prepend(item); - emit entryAdded(item); + Q_EMIT entryAdded(item); if (m_history.count() == 1) checkForExpired(); } @@ -238,7 +246,7 @@ void HistoryManager::updateHistoryEntry(const QUrl &url, const QString &title) m_saveTimer->changeOccurred(); if (m_lastSavedUrl.isEmpty()) m_lastSavedUrl = m_history.at(i).url; - emit entryUpdated(i); + Q_EMIT entryUpdated(i); break; } } @@ -248,14 +256,14 @@ void HistoryManager::removeHistoryEntry(const HistoryEntry &item) { m_lastSavedUrl.clear(); m_history.removeOne(item); - emit entryRemoved(item); + Q_EMIT entryRemoved(item); } void HistoryManager::removeHistoryEntry(const QUrl &url, const QString &title) { for (int i = 0; i < m_history.count(); ++i) { if (url == m_history.at(i).url - && (title.isEmpty() || title == m_history.at(i).title)) { + && (title.isEmpty() || title == m_history.at(i).title)) { removeHistoryEntry(m_history.at(i)); break; } @@ -278,29 +286,29 @@ void HistoryManager::setDaysToExpire(int limit) void HistoryManager::clear() { - emit historyGoingToChange(); + Q_EMIT historyGoingToChange(); m_history.clear(); m_atomicStringHash.clear(); m_lastSavedUrl.clear(); m_saveTimer->changeOccurred(); m_saveTimer->saveIfNeccessary(); - emit historyReset(); - emit historyCleared(); + Q_EMIT historyReset(); + Q_EMIT historyCleared(); } void HistoryManager::loadSettings() { // load settings QSettings settings; - settings.beginGroup(QLatin1String("history")); - m_daysToExpire = settings.value(QLatin1String("historyLimit"), 30).toInt(); + settings.beginGroup(QStringLiteral("history")); + m_daysToExpire = settings.value(QStringLiteral("historyLimit"), 30).toInt(); } void HistoryManager::load() { loadSettings(); - QFile historyFile(HistoryManager::dataFilePath(QLatin1String("history"))); + QFile historyFile(HistoryManager::dataFilePath(QStringLiteral("history"))); if (!historyFile.exists()) return; @@ -374,8 +382,8 @@ QString HistoryManager::atomicString(const QString &string) { void HistoryManager::save() { QSettings settings; - settings.beginGroup(QLatin1String("history")); - settings.setValue(QLatin1String("historyLimit"), m_daysToExpire); + settings.beginGroup(QStringLiteral("history")); + settings.setValue(QStringLiteral("historyLimit"), m_daysToExpire); bool saveAll = m_lastSavedUrl.isEmpty(); int first = m_history.count() - 1; @@ -391,7 +399,7 @@ void HistoryManager::save() if (first == m_history.count() - 1) saveAll = true; - QFile historyFile(HistoryManager::dataFilePath(QLatin1String("history"))); + QFile historyFile(HistoryManager::dataFilePath(QStringLiteral("history"))); // When saving everything use a temporary file to prevent possible data loss. QTemporaryFile tempFile; diff --git a/src/history/historymanager.h b/src/history/historymanager.h index 548ab6ab..b5fbb4ed 100644 --- a/src/history/historymanager.h +++ b/src/history/historymanager.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,19 +63,18 @@ #ifndef HISTORYMANAGER_H #define HISTORYMANAGER_H -#include +#include #include -#include -#include -#include +#include +#include class HistoryEntry { public: HistoryEntry() {} HistoryEntry(const QString &u, - const QDateTime &d = QDateTime(), const QString &t = QString()) - : url(u), title(t), dateTime(d) {} + const QDateTime &d = QDateTime(), const QString &t = QString()) + : url(u), title(t), dateTime(d) {} inline bool operator==(const HistoryEntry &other) const { return other.title == title @@ -84,7 +83,9 @@ class HistoryEntry // history is sorted in reverse inline bool operator <(const HistoryEntry &other) const - { return dateTime > other.dateTime; } + { + return dateTime > other.dateTime; + } QString userTitle() const; @@ -97,12 +98,12 @@ class AutoSaver; class HistoryModel; class HistoryFilterModel; class HistoryTreeModel; -class HistoryManager : public QWebHistoryInterface +class HistoryManager : public QObject { Q_OBJECT - Q_PROPERTY(int daysToExpire READ daysToExpire WRITE setDaysToExpire) + Q_PROPERTY(int daysToExpire READ daysToExpire WRITE setDaysToExpire NOTIFY daysToExpireChanged) -signals: +Q_SIGNALS: void historyCleared(); void historyGoingToChange(); void historyReset(); @@ -111,7 +112,7 @@ class HistoryManager : public QWebHistoryInterface void entryUpdated(int offset); public: - HistoryManager(QObject *parent = 0); + HistoryManager(QObject *parent = nullptr); ~HistoryManager(); bool historyContains(const QString &url) const; @@ -121,6 +122,7 @@ class HistoryManager : public QWebHistoryInterface int daysToExpire() const; void setDaysToExpire(int limit); + void daysToExpireChanged(); QList history() const; void setHistory(const QList &history, bool loadedAndSorted = false); @@ -129,14 +131,14 @@ class HistoryManager : public QWebHistoryInterface HistoryModel *historyModel() const; HistoryFilterModel *historyFilterModel() const; HistoryTreeModel *historyTreeModel() const; - + QString dataFilePath(const QString &fileName); -public slots: +public Q_SLOTS: void clear(); void loadSettings(); -private slots: +private Q_SLOTS: void save(); void checkForExpired(); diff --git a/src/htmls/dirlist.html b/src/htmls/dirlist.html index eef1c10f..543f759f 100644 --- a/src/htmls/dirlist.html +++ b/src/htmls/dirlist.html @@ -4,71 +4,90 @@ %1 -
    -

    %2

    -
    - %5 -
    - -%4 -
    -
    - - +
    +

    %2

    +
    + %5 +
    + + %4 +
    +
    + + diff --git a/src/htmls/htmls.qrc b/src/htmls/htmls.qrc index da555367..0b986866 100644 --- a/src/htmls/htmls.qrc +++ b/src/htmls/htmls.qrc @@ -2,6 +2,7 @@ dirlist.html notfound.html + settings.html startpage.html startpage.css diff --git a/src/htmls/notfound.html b/src/htmls/notfound.html index 485cc73f..ec49785c 100644 --- a/src/htmls/notfound.html +++ b/src/htmls/notfound.html @@ -4,56 +4,64 @@ %1 -
    - -

    %2

    -

    %3

    -
      -
    • %4
    • -
    • %5
    • -
    • %6
    • -
    -
    - - +
    + +

    %2

    +

    %3

    +
      +
    • %4
    • +
    • %5
    • +
    • %6
    • +
    +
    + + diff --git a/src/htmls/settings.html b/src/htmls/settings.html new file mode 100644 index 00000000..0236f6b7 --- /dev/null +++ b/src/htmls/settings.html @@ -0,0 +1,18 @@ + + + Settings + + + + + +
    + + + + \ No newline at end of file diff --git a/src/htmls/startpage.html b/src/htmls/startpage.html index 127509e3..9e4047e1 100644 --- a/src/htmls/startpage.html +++ b/src/htmls/startpage.html @@ -1,32 +1,20 @@ - - + New Tab +
  • ")); - int ret = QMessageBox::warning(mainWindow, - QCoreApplication::applicationName() + tr(" - SSL Errors"), - tr("SSL Errors:" - "

    for: %1" - "
    • %2
    \n\n" - "Do you want to ignore these errors?
    ").arg(reply->url().toString()).arg(errors), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); - - if (ret == QMessageBox::Yes) { - if (ca_new.count() > 0) { - QStringList certinfos; - for (int i = 0; i < ca_new.count(); ++i) - certinfos += certToFormattedString(ca_new.at(i)); - ret = QMessageBox::question(mainWindow, QCoreApplication::applicationName(), - tr("Certificates:
    " - "%1
    " - "Do you want to accept all these certificates?
    ") - .arg(certinfos.join(QString())), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (ret == QMessageBox::Yes) { - ca_merge += ca_new; - - QSslConfiguration sslCfg = QSslConfiguration::defaultConfiguration(); - QList ca_list = sslCfg.caCertificates(); - ca_list += ca_new; - sslCfg.setCaCertificates(ca_list); - sslCfg.setProtocol(QSsl::AnyProtocol); - QSslConfiguration::setDefaultConfiguration(sslCfg); - reply->setSslConfiguration(sslCfg); - - QByteArray pems; - for (int i = 0; i < ca_merge.count(); ++i) - pems += ca_merge.at(i).toPem() + '\n'; - settings.setValue(QLatin1String("CaCertificates"), pems); - } - } - reply->ignoreSslErrors(); - } -} -#endif - -QNetworkReply *NetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) -{ - if (op == PostOperation && outgoingData) { - QByteArray outgoingDataByteArray = outgoingData->peek(1024 * 1024); - BrowserApplication::autoFillManager()->post(request, outgoingDataByteArray); - } - - QNetworkReply *reply = 0; - // Check if there is a valid handler registered for the requested URL scheme - if (m_schemeHandlers.contains(request.url().scheme())) - reply = m_schemeHandlers[request.url().scheme()]->createRequest(op, request, outgoingData); - if (reply) - return reply; - - QNetworkRequest req = request; - req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); - if (!m_acceptLanguage.isEmpty()) - req.setRawHeader("Accept-Language", m_acceptLanguage); - - // Adblock - if (op == QNetworkAccessManager::GetOperation) { - if (!m_adblockNetwork) - m_adblockNetwork = AdBlockManager::instance()->network(); - reply = m_adblockNetwork->block(req); - if (reply) - return reply; - } - - reply = QNetworkAccessManager::createRequest(op, req, outgoingData); - emit requestCreated(op, req, reply); - return reply; -} - diff --git a/src/network/networkaccessmanager.h b/src/network/networkaccessmanager.h deleted file mode 100644 index 1044e353..00000000 --- a/src/network/networkaccessmanager.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2008-2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -/**************************************************************************** -** -** Copyright (C) 2007-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** This file may be used under the terms of the GNU General Public -** License versions 2.0 or 3.0 as published by the Free Software -** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Alternatively you may (at -** your option) use any later version of the GNU General Public -** License if such license has been publicly approved by Trolltech ASA -** (or its successors, if any) and the KDE Free Qt Foundation. In -** addition, as a special exception, Trolltech gives you certain -** additional rights. These rights are described in the Trolltech GPL -** Exception version 1.2, which can be found at -** http://www.trolltech.com/products/qt/gplexception/ and in the file -** GPL_EXCEPTION.txt in this package. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. If -** you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** In addition, as a special exception, Trolltech, as the sole -** copyright holder for Qt Designer, grants users of the Qt/Eclipse -** Integration plug-in the right for the Qt/Eclipse Integration to -** link to functionality provided by Qt Designer and its related -** libraries. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly -** granted herein. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -****************************************************************************/ - -#ifndef NETWORKACCESSMANAGER_H -#define NETWORKACCESSMANAGER_H - -#include -#include -#include -#include "networkaccessmanagerproxy.h" - -class SchemeAccessHandler; - -class AdBlockNetwork; -class NetworkAccessManager : public NetworkAccessManagerProxy -{ - Q_OBJECT - -signals: - void requestCreated(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QNetworkReply *reply); - -public: - NetworkAccessManager(QObject *parent = 0); - void setSchemeHandler(const QString &scheme, SchemeAccessHandler *handler); - - inline QNetworkReply *createRequestProxy(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) - { - return createRequest(op, request, outgoingData); - } - -protected: - QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0); - -public slots: - void loadSettings(); - -private slots: - void authenticationRequired(QNetworkReply *reply, QAuthenticator *auth); - void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *auth); -#ifndef QT_NO_OPENSSL - void sslErrors(QNetworkReply *reply, const QList &error); -#endif - void privacyChanged(bool isPrivate); - -private: -#ifndef QT_NO_OPENSSL - static QString certToFormattedString(QSslCertificate cert); -#endif - - QByteArray m_acceptLanguage; - QHash m_schemeHandlers; - - QNetworkCookieJar *m_privateCookieJar; - AdBlockNetwork *m_adblockNetwork; -}; - -#endif // NETWORKACCESSMANAGER_H diff --git a/src/network/networkdiskcache.cpp b/src/network/networkdiskcache.cpp deleted file mode 100644 index 9b139764..00000000 --- a/src/network/networkdiskcache.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "networkdiskcache.h" - -#include "browserapplication.h" - -#include -#include - -NetworkDiskCache::NetworkDiskCache(QObject *parent) - : QNetworkDiskCache(parent) - , m_private(false) -{ - QString diskCacheDirectory = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) - + QLatin1String("/browser"); - setCacheDirectory(diskCacheDirectory); - connect(BrowserApplication::instance(), SIGNAL(privacyChanged(bool)), - this, SLOT(privacyChanged(bool))); -} - -void NetworkDiskCache::loadSettings() -{ - QSettings settings; - settings.beginGroup(QLatin1String("network")); - qint64 maximumCacheSize = settings.value(QLatin1String("maximumCacheSize"), 50).toInt(); - maximumCacheSize = maximumCacheSize * 1024 * 1024; - setMaximumCacheSize(maximumCacheSize); -} - -void NetworkDiskCache::privacyChanged(bool isPrivate) -{ - m_private = isPrivate; -} - -QIODevice *NetworkDiskCache::prepare(const QNetworkCacheMetaData &metaData) -{ - if (m_private) - return 0; - return QNetworkDiskCache::prepare(metaData); -} - diff --git a/src/network/networkdiskcache.h b/src/network/networkdiskcache.h deleted file mode 100644 index ce4227de..00000000 --- a/src/network/networkdiskcache.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef NETWORKDISKCACHE_H -#define NETWORKDISKCACHE_H - -#include - -class NetworkDiskCache : public QNetworkDiskCache -{ - Q_OBJECT - -public: - NetworkDiskCache(QObject *parent = 0); - - void loadSettings(); - - QIODevice *prepare(const QNetworkCacheMetaData &metaData); - -private slots: - void privacyChanged(bool isPrivate); - -private: - bool m_private; -}; - -#endif // NETWORKDISKCACHE_H - diff --git a/src/network/networkproxyfactory.cpp b/src/network/networkproxyfactory.cpp deleted file mode 100644 index 9cda8092..00000000 --- a/src/network/networkproxyfactory.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2009 Benjamin K. Stuhl - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "networkproxyfactory.h" - -NetworkProxyFactory::NetworkProxyFactory() - : QNetworkProxyFactory() -{ -} - -void NetworkProxyFactory::setHttpProxy(const QNetworkProxy &proxy) -{ - m_httpProxy = proxy; -} - -void NetworkProxyFactory::setGlobalProxy(const QNetworkProxy &proxy) -{ - m_globalProxy = proxy; -} - -QList NetworkProxyFactory::queryProxy(const QNetworkProxyQuery &query) -{ - QList ret; - - if (query.protocolTag() == QLatin1String("http") && m_httpProxy.type() != QNetworkProxy::DefaultProxy) - ret << m_httpProxy; - ret << m_globalProxy; - - return ret; -} - diff --git a/src/network/networkproxyfactory.h b/src/network/networkproxyfactory.h deleted file mode 100644 index 9f692aa7..00000000 --- a/src/network/networkproxyfactory.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2009 Benjamin K. Stuhl - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#ifndef NETWORKPROXYFACTORY_H -#define NETWORKPROXYFACTORY_H - -#include - -class NetworkProxyFactory : public QNetworkProxyFactory -{ -public: - NetworkProxyFactory(); - - void setHttpProxy(const QNetworkProxy &proxy); - void setGlobalProxy(const QNetworkProxy &proxy); - - virtual QList queryProxy(const QNetworkProxyQuery &query = QNetworkProxyQuery()); - -private: - QNetworkProxy m_httpProxy; - QNetworkProxy m_globalProxy; -}; - -#endif // NETWORKPROXYFACTORY_H diff --git a/src/network/passworddialog.ui b/src/network/passworddialog.ui deleted file mode 100644 index 7c166586..00000000 --- a/src/network/passworddialog.ui +++ /dev/null @@ -1,111 +0,0 @@ - - PasswordDialog - - - - 0 - 0 - 399 - 148 - - - - Authentication Required - - - - - - - - DUMMY ICON - - - - - - - - 0 - 0 - - - - INTRO TEXT DUMMY - - - - - - - - - Username: - - - - - - - - - - Password: - - - - - - - QLineEdit::Password - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - PasswordDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - PasswordDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/src/network/proxy.ui b/src/network/proxy.ui deleted file mode 100644 index 33fa25f7..00000000 --- a/src/network/proxy.ui +++ /dev/null @@ -1,105 +0,0 @@ - - - ProxyDialog - - - - 0 - 0 - 369 - 144 - - - - Proxy Authentication - - - - - - ICON - - - - - - - Connect to proxy - - - true - - - - - - - Username: - - - - - - - - - - Password: - - - - - - - QLineEdit::Password - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - ProxyDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - ProxyDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/src/network/schemeaccesshandler.cpp b/src/network/schemeaccesshandler.cpp deleted file mode 100644 index 1e4a8294..00000000 --- a/src/network/schemeaccesshandler.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2009 Jonas Gehring - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "schemeaccesshandler.h" - -SchemeAccessHandler::SchemeAccessHandler(QObject *parent) - : QObject(parent) -{ -} - diff --git a/src/network/schemeaccesshandler.h b/src/network/schemeaccesshandler.h deleted file mode 100644 index c2310b05..00000000 --- a/src/network/schemeaccesshandler.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2009 Jonas Gehring - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#ifndef SCHEMEACCESSHANDLER_H -#define SCHEMEACCESSHANDLER_H - -#include - -#include - -class QNetworkReply; -class SchemeAccessHandler : public QObject -{ -public: - SchemeAccessHandler(QObject *parent = 0); - - virtual QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0) = 0; -}; - -#endif // SCHEMEACCESSHANDLER_H diff --git a/src/opensearch/opensearch.pri b/src/opensearch/opensearch.pri deleted file mode 100644 index e46dda23..00000000 --- a/src/opensearch/opensearch.pri +++ /dev/null @@ -1,27 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - opensearchdialog.h \ - opensearchengine.h \ - opensearchenginedelegate.h \ - opensearchengineaction.h \ - opensearchenginemodel.h \ - opensearchmanager.h \ - opensearchreader.h \ - opensearchwriter.h - -SOURCES += \ - opensearchdialog.cpp \ - opensearchengine.cpp \ - opensearchenginedelegate.cpp \ - opensearchengineaction.cpp \ - opensearchenginemodel.cpp \ - opensearchmanager.cpp \ - opensearchreader.cpp \ - opensearchwriter.cpp - -FORMS += opensearchdialog.ui - -QT += script diff --git a/src/opensearch/opensearchdialog.cpp b/src/opensearch/opensearchdialog.cpp index 94fdf8d8..54f960b9 100644 --- a/src/opensearch/opensearchdialog.cpp +++ b/src/opensearch/opensearchdialog.cpp @@ -20,17 +20,16 @@ #include "opensearchdialog.h" -#include "browserapplication.h" #include "opensearchenginemodel.h" #include "opensearchmanager.h" #include "toolbarsearch.h" -#include -#include +#include +#include OpenSearchDialog::OpenSearchDialog(QWidget *parent) : QDialog(parent) - , m_model(0) + , m_model(nullptr) { setModal(true); setupUi(this); @@ -58,14 +57,14 @@ OpenSearchDialog::OpenSearchDialog(QWidget *parent) void OpenSearchDialog::addButtonClicked() { QStringList fileNames = QFileDialog::getOpenFileNames(this, - tr("Open File"), - QString(), - tr("OpenSearch") + QLatin1String(" (*.xml)")); + tr("Open File"), + QString(), + tr("OpenSearch") + QStringLiteral(" (*.xml)")); - foreach (const QString &fileName, fileNames) { + Q_FOREACH (const QString &fileName, fileNames) { if (!ToolbarSearch::openSearchManager()->addEngine(fileName)) { QMessageBox::critical(this, tr("Error"), - tr("%1 is not a valid OpenSearch 1.1 description or is already on your list.").arg(fileName)); + tr("%1 is not a valid OpenSearch 1.1 description or is already on your list.").arg(fileName)); } } } @@ -74,7 +73,7 @@ void OpenSearchDialog::deleteButtonClicked() { if (m_tableView->model()->rowCount() == 1) { QMessageBox::critical(this, tr("Error"), - tr("You must have at least one search engine in here.")); + tr("You must have at least one search engine in here.")); return; } diff --git a/src/opensearch/opensearchdialog.h b/src/opensearch/opensearchdialog.h index 5f50e974..b29d6398 100644 --- a/src/opensearch/opensearchdialog.h +++ b/src/opensearch/opensearchdialog.h @@ -21,7 +21,7 @@ #ifndef OPENSEARCHDIALOG_H #define OPENSEARCHDIALOG_H -#include +#include #include "ui_opensearchdialog.h" @@ -32,9 +32,9 @@ class OpenSearchDialog : public QDialog, public Ui_OpenSearchDialog Q_OBJECT public: - OpenSearchDialog(QWidget *parent = 0); + OpenSearchDialog(QWidget *parent = nullptr); -protected slots: +protected Q_SLOTS: void addButtonClicked(); void deleteButtonClicked(); void restoreButtonClicked(); diff --git a/src/opensearch/opensearchengine.cpp b/src/opensearch/opensearchengine.cpp index b979917a..c797e358 100644 --- a/src/opensearch/opensearchengine.cpp +++ b/src/opensearch/opensearchengine.cpp @@ -22,13 +22,13 @@ #include "opensearchenginedelegate.h" #include -#include +#include #include -#include -#include -#include +#include +#include +#include #include -#include +#include #include /*! @@ -83,15 +83,15 @@ */ OpenSearchEngine::OpenSearchEngine(QObject *parent) : QObject(parent) - , m_searchMethod(QLatin1String("get")) - , m_suggestionsMethod(QLatin1String("get")) - , m_networkAccessManager(0) - , m_suggestionsReply(0) - , m_scriptEngine(0) - , m_delegate(0) + , m_searchMethod(QStringLiteral("get")) + , m_suggestionsMethod(QStringLiteral("get")) + , m_networkAccessManager(nullptr) + , m_suggestionsReply(nullptr) + , m_scriptEngine(nullptr) + , m_delegate(nullptr) { - m_requestMethods.insert(QLatin1String("get"), QNetworkAccessManager::GetOperation); - m_requestMethods.insert(QLatin1String("post"), QNetworkAccessManager::PostOperation); + m_requestMethods.insert(QStringLiteral("get"), QNetworkAccessManager::GetOperation); + m_requestMethods.insert(QStringLiteral("post"), QNetworkAccessManager::PostOperation); } /*! @@ -107,17 +107,17 @@ QString OpenSearchEngine::parseTemplate(const QString &searchTerm, const QString { QString language = QLocale().name(); // Simple conversion to RFC 3066. - language = language.replace(QLatin1Char('_'), QLatin1Char('-')); + language = language.replace(QChar('_'), QChar('-')); QString result = searchTemplate; - result.replace(QLatin1String("{count}"), QLatin1String("20")); - result.replace(QLatin1String("{startIndex}"), QLatin1String("0")); - result.replace(QLatin1String("{startPage}"), QLatin1String("0")); - result.replace(QLatin1String("{language}"), language); - result.replace(QLatin1String("{inputEncoding}"), QLatin1String("UTF-8")); - result.replace(QLatin1String("{outputEncoding}"), QLatin1String("UTF-8")); - result.replace(QRegExp(QLatin1String("\\{([^\\}]*:|)source\\??\\}")), QCoreApplication::applicationName()); - result.replace(QLatin1String("{searchTerms}"), QLatin1String(QUrl::toPercentEncoding(searchTerm))); + result.replace(QStringLiteral("{count}"), QStringLiteral("20")); + result.replace(QStringLiteral("{startIndex}"), QStringLiteral("0")); + result.replace(QStringLiteral("{startPage}"), QStringLiteral("0")); + result.replace(QStringLiteral("{language}"), language); + result.replace(QStringLiteral("{inputEncoding}"), QStringLiteral("UTF-8")); + result.replace(QStringLiteral("{outputEncoding}"), QStringLiteral("UTF-8")); + result.replace(QRegExp(QStringLiteral("\\{([^\\}]*:|)source\\??\\}")), QCoreApplication::applicationName()); + result.replace(QStringLiteral("{searchTerms}"), QString(QUrl::toPercentEncoding(searchTerm))); return result; } @@ -208,7 +208,7 @@ QUrl OpenSearchEngine::searchUrl(const QString &searchTerm) const QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_searchUrlTemplate).toUtf8()); QUrlQuery query(retVal.query()); - if (m_searchMethod != QLatin1String("post")) { + if (m_searchMethod != QStringLiteral("post")) { Parameters::const_iterator end = m_searchParameters.constEnd(); Parameters::const_iterator i = m_searchParameters.constBegin(); for (; i != end; ++i) @@ -262,7 +262,7 @@ QUrl OpenSearchEngine::suggestionsUrl(const QString &searchTerm) const QUrl retVal = QUrl::fromEncoded(parseTemplate(searchTerm, m_suggestionsUrlTemplate).toUtf8()); QUrlQuery query(retVal.query()); - if (m_suggestionsMethod != QLatin1String("post")) { + if (m_suggestionsMethod != QStringLiteral("post")) { Parameters::const_iterator end = m_suggestionsParameters.constEnd(); Parameters::const_iterator i = m_suggestionsParameters.constBegin(); for (; i != end; ++i) @@ -390,7 +390,7 @@ void OpenSearchEngine::imageObtained() return; m_image.loadFromData(response); - emit imageChanged(); + Q_EMIT imageChanged(); } /*! @@ -415,13 +415,13 @@ void OpenSearchEngine::setImage(const QImage &image) QBuffer imageBuffer; imageBuffer.open(QBuffer::ReadWrite); if (image.save(&imageBuffer, "PNG")) { - m_imageUrl = QString(QLatin1String("data:image/png;base64,%1")) - .arg(QLatin1String(imageBuffer.buffer().toBase64())); + m_imageUrl = QString(QStringLiteral("data:image/png;base64,%1")) + .arg(QString(imageBuffer.buffer().toBase64())); } } m_image = image; - emit imageChanged(); + Q_EMIT imageChanged(); } /*! @@ -452,7 +452,7 @@ bool OpenSearchEngine::operator<(const OpenSearchEngine &other) const /*! Requests contextual suggestions on the search engine, for a given \a searchTerm. - If succeeded, suggestions() signal will be emitted once the suggestions are received. + If succeeded, suggestions() signal will be Q_EMITted once the suggestions are received. \note To be able to request suggestions, you need to provide a network access manager, which will be used for network operations. @@ -473,20 +473,20 @@ void OpenSearchEngine::requestSuggestions(const QString &searchTerm) m_suggestionsReply->disconnect(this); m_suggestionsReply->abort(); m_suggestionsReply->deleteLater(); - m_suggestionsReply = 0; + m_suggestionsReply = nullptr; } Q_ASSERT(m_requestMethods.contains(m_suggestionsMethod)); - if (m_suggestionsMethod == QLatin1String("get")) { + if (m_suggestionsMethod == QStringLiteral("get")) { m_suggestionsReply = m_networkAccessManager->get(QNetworkRequest(suggestionsUrl(searchTerm))); } else { QStringList parameters; Parameters::const_iterator end = m_suggestionsParameters.constEnd(); Parameters::const_iterator i = m_suggestionsParameters.constBegin(); for (; i != end; ++i) - parameters.append(i->first + QLatin1String("=") + i->second); + parameters.append(i->first + QStringLiteral("=") + i->second); - QByteArray data = parameters.join(QLatin1String("&")).toUtf8(); + QByteArray data = parameters.join(QStringLiteral("&")).toUtf8(); m_suggestionsReply = m_networkAccessManager->post(QNetworkRequest(suggestionsUrl(searchTerm)), data); } @@ -519,9 +519,9 @@ void OpenSearchEngine::requestSearchResults(const QString &searchTerm) Parameters::const_iterator end = m_searchParameters.constEnd(); Parameters::const_iterator i = m_searchParameters.constBegin(); for (; i != end; ++i) - parameters.append(i->first + QLatin1String("=") + i->second); + parameters.append(i->first + QStringLiteral("=") + i->second); - data = parameters.join(QLatin1String("&")).toUtf8(); + data = parameters.join(QStringLiteral("&")).toUtf8(); } m_delegate->performSearchRequest(request, operation, data); @@ -534,30 +534,31 @@ void OpenSearchEngine::suggestionsObtained() m_suggestionsReply->close(); m_suggestionsReply->deleteLater(); - m_suggestionsReply = 0; + m_suggestionsReply = nullptr; if (response.isEmpty()) return; - if (!response.startsWith(QLatin1Char('[')) || !response.endsWith(QLatin1Char(']'))) + if (!response.startsWith(QChar('[')) || !response.endsWith(QChar(']'))) return; if (!m_scriptEngine) - m_scriptEngine = new QScriptEngine(); + m_scriptEngine = new QJSEngine(); // Evaluate the JSON response using QtScript. - if (!m_scriptEngine->canEvaluate(response)) + if (m_scriptEngine->evaluate(response).isError()) return; - QScriptValue responseParts = m_scriptEngine->evaluate(response); + QJSValue responseParts = m_scriptEngine->evaluate(response); if (!responseParts.property(1).isArray()) return; QStringList suggestionsList; - qScriptValueToSequence(responseParts.property(1), suggestionsList); - emit suggestions(suggestionsList); + suggestionsList = responseParts.property(1).toVariant().toStringList(); + + Q_EMIT suggestions(suggestionsList); } /*! @@ -597,7 +598,7 @@ void OpenSearchEngine::setDelegate(OpenSearchEngineDelegate *delegate) /*! \fn void OpenSearchEngine::imageChanged() - This signal is emitted whenever the image of the engine changes. + This signal is Q_EMITted whenever the image of the engine changes. \sa image(), imageUrl() */ @@ -605,7 +606,7 @@ void OpenSearchEngine::setDelegate(OpenSearchEngineDelegate *delegate) /*! \fn void OpenSearchEngine::suggestions(const QStringList &suggestions) - This signal is emitted whenever new contextual suggestions have been provided + This signal is Q_EMITted whenever new contextual suggestions have been provided by the search engine. To request suggestions, use requestSuggestions(). The suggestion set is specified by \a suggestions. diff --git a/src/opensearch/opensearchengine.h b/src/opensearch/opensearchengine.h index 3ec63d22..df7473a4 100644 --- a/src/opensearch/opensearchengine.h +++ b/src/opensearch/opensearchengine.h @@ -25,38 +25,52 @@ #include #include #include -#include +#include class QNetworkReply; -class QScriptEngine; +class QJSEngine; class OpenSearchEngineDelegate; class OpenSearchEngine : public QObject { Q_OBJECT -signals: +Q_SIGNALS: void imageChanged(); + void nameChanged(); void suggestions(const QStringList &suggestions); + void descriptionChanged(); + void searchUrlTemplateChanged(); + void searchUrlChanged(); + void providesSuggestionsChanged(); + void suggestionsUrlTemplateChanged(); + void suggestionsUrlChanged(); + void searchParametersChanged(); + void suggestionsParametersChanged(); + void searchMethodChanged(); + void suggestionsMethodChanged(); + void imageUrlChanged(); + void validChanged(); + void networkAccessManagerChanged(); public: typedef QPair Parameter; typedef QList Parameters; - Q_PROPERTY(QString name READ name WRITE setName) - Q_PROPERTY(QString description READ description WRITE setDescription) - Q_PROPERTY(QString searchUrlTemplate READ searchUrlTemplate WRITE setSearchUrlTemplate) - Q_PROPERTY(Parameters searchParameters READ searchParameters WRITE setSearchParameters) - Q_PROPERTY(QString searchMethod READ searchMethod WRITE setSearchMethod) - Q_PROPERTY(QString suggestionsUrlTemplate READ suggestionsUrlTemplate WRITE setSuggestionsUrlTemplate) - Q_PROPERTY(Parameters suggestionsParameters READ suggestionsParameters WRITE setSuggestionsParameters) - Q_PROPERTY(QString suggestionsMethod READ suggestionsMethod WRITE setSuggestionsMethod) - Q_PROPERTY(bool providesSuggestions READ providesSuggestions) - Q_PROPERTY(QString imageUrl READ imageUrl WRITE setImageUrl) - Q_PROPERTY(bool valid READ isValid) - Q_PROPERTY(QNetworkAccessManager *networkAccessManager READ networkAccessManager WRITE setNetworkAccessManager) - - OpenSearchEngine(QObject *parent = 0); + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) + Q_PROPERTY(QString description READ description WRITE setDescription NOTIFY descriptionChanged) + Q_PROPERTY(QString searchUrlTemplate READ searchUrlTemplate WRITE setSearchUrlTemplate NOTIFY searchUrlTemplateChanged) + Q_PROPERTY(Parameters searchParameters READ searchParameters WRITE setSearchParameters NOTIFY searchParametersChanged) + Q_PROPERTY(QString searchMethod READ searchMethod WRITE setSearchMethod NOTIFY searchMethodChanged) + Q_PROPERTY(QString suggestionsUrlTemplate READ suggestionsUrlTemplate WRITE setSuggestionsUrlTemplate NOTIFY suggestionsUrlTemplateChanged) + Q_PROPERTY(Parameters suggestionsParameters READ suggestionsParameters WRITE setSuggestionsParameters NOTIFY suggestionsParametersChanged) + Q_PROPERTY(QString suggestionsMethod READ suggestionsMethod WRITE setSuggestionsMethod NOTIFY suggestionsMethodChanged) + Q_PROPERTY(bool providesSuggestions READ providesSuggestions NOTIFY providesSuggestionsChanged) + Q_PROPERTY(QString imageUrl READ imageUrl WRITE setImageUrl NOTIFY imageUrlChanged) + Q_PROPERTY(bool valid READ isValid NOTIFY validChanged) + Q_PROPERTY(QNetworkAccessManager *networkAccessManager READ networkAccessManager WRITE setNetworkAccessManager NOTIFY networkAccessManagerChanged) + + OpenSearchEngine(QObject *parent = nullptr); ~OpenSearchEngine(); QString name() const; @@ -104,7 +118,7 @@ class OpenSearchEngine : public QObject bool operator==(const OpenSearchEngine &other) const; bool operator<(const OpenSearchEngine &other) const; -public slots: +public Q_SLOTS: void requestSuggestions(const QString &searchTerm); void requestSearchResults(const QString &searchTerm); @@ -112,7 +126,7 @@ public slots: static QString parseTemplate(const QString &searchTerm, const QString &searchTemplate); void loadImage() const; -private slots: +private Q_SLOTS: void imageObtained(); void suggestionsObtained(); @@ -135,7 +149,7 @@ private slots: QNetworkAccessManager *m_networkAccessManager; QNetworkReply *m_suggestionsReply; - QScriptEngine *m_scriptEngine; + QJSEngine *m_scriptEngine; OpenSearchEngineDelegate *m_delegate; }; diff --git a/src/opensearch/opensearchengineaction.cpp b/src/opensearch/opensearchengineaction.cpp index 8c4282c0..758c07ee 100644 --- a/src/opensearch/opensearchengineaction.cpp +++ b/src/opensearch/opensearchengineaction.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #include "opensearchengineaction.h" #include "browserapplication.h" -#include "networkaccessmanager.h" +#include #include "opensearchengine.h" OpenSearchEngineAction::OpenSearchEngineAction(OpenSearchEngine *engine, QObject *parent) @@ -28,7 +28,7 @@ OpenSearchEngineAction::OpenSearchEngineAction(OpenSearchEngine *engine, QObject , m_engine(engine) { if (!engine->networkAccessManager()) - engine->setNetworkAccessManager(BrowserApplication::networkAccessManager()); + engine->setNetworkAccessManager(new QNetworkAccessManager()); setText(engine->name()); imageChanged(); diff --git a/src/opensearch/opensearchengineaction.h b/src/opensearch/opensearchengineaction.h index 553f79a8..7154b28c 100644 --- a/src/opensearch/opensearchengineaction.h +++ b/src/opensearch/opensearchengineaction.h @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef OPENSEARCHENGINEACTION_H #define OPENSEARCHENGINEACTION_H -#include +#include class OpenSearchEngine; class OpenSearchEngineAction : public QAction @@ -28,9 +28,9 @@ class OpenSearchEngineAction : public QAction Q_OBJECT public: - OpenSearchEngineAction(OpenSearchEngine *engine, QObject *parent = 0); + OpenSearchEngineAction(OpenSearchEngine *engine, QObject *parent = nullptr); -private slots: +private Q_SLOTS: void imageChanged(); private: diff --git a/src/opensearch/opensearchenginedelegate.h b/src/opensearch/opensearchenginedelegate.h index 5de3c598..e9a23c0d 100644 --- a/src/opensearch/opensearchenginedelegate.h +++ b/src/opensearch/opensearchenginedelegate.h @@ -21,7 +21,7 @@ #define OPENSEARCHENGINEDELEGATE_H #include -#include +#include class OpenSearchEngineDelegate { diff --git a/src/opensearch/opensearchenginemodel.cpp b/src/opensearch/opensearchenginemodel.cpp index 85559b15..b0930994 100644 --- a/src/opensearch/opensearchenginemodel.cpp +++ b/src/opensearch/opensearchenginemodel.cpp @@ -55,7 +55,7 @@ bool OpenSearchEngineModel::removeRows(int row, int count, const QModelIndex &pa for (int i = row; i <= lastRow; ++i) m_manager->removeEngine(nameList.at(i)); - // removeEngine emits changed + // removeEngine Q_EMITs changed //endRemoveRows(); return true; @@ -97,24 +97,24 @@ QVariant OpenSearchEngineModel::data(const QModelIndex &index, int role) const switch (role) { case Qt::DisplayRole: return engine->name(); - break; + break; case Qt::DecorationRole: { QImage image = engine->image(); if (image.isNull()) return BrowserApplication::icon(engine->imageUrl()); return image; - break; + break; } case Qt::ToolTipRole: QString description = tr("Description: %1").arg(engine->description()); if (engine->providesSuggestions()) { - description += QLatin1String("
    "); + description += QStringLiteral("
    "); description += tr("Provides contextual suggestions"); } return description; - break; + break; } break; @@ -122,7 +122,7 @@ QVariant OpenSearchEngineModel::data(const QModelIndex &index, int role) const switch (role) { case Qt::EditRole: case Qt::DisplayRole: - return QStringList(m_manager->keywordsForEngine(engine)).join(QLatin1String(",")); + return QStringList(m_manager->keywordsForEngine(engine)).join(QStringLiteral(",")); case Qt::ToolTipRole: return tr("Comma-separated list of keywords that may be entered in the location bar" "followed by search terms to search with this engine"); @@ -145,7 +145,7 @@ bool OpenSearchEngineModel::setData(const QModelIndex &index, const QVariant &va return false; QString engineName = m_manager->allEnginesNames().at(index.row()); - QStringList keywords = value.toString().split(QRegExp(QLatin1String("[ ,]+")), QString::SkipEmptyParts); + QStringList keywords = value.toString().split(QRegExp(QStringLiteral("[ ,]+")), Qt::SkipEmptyParts); m_manager->setKeywordsForEngine(m_manager->engine(engineName), keywords); diff --git a/src/opensearch/opensearchenginemodel.h b/src/opensearch/opensearchenginemodel.h index 23001cfd..322c0ff2 100644 --- a/src/opensearch/opensearchenginemodel.h +++ b/src/opensearch/opensearchenginemodel.h @@ -22,7 +22,7 @@ #ifndef OPENSEARCHENGINEMODEL_H #define OPENSEARCHENGINEMODEL_H -#include +#include class OpenSearchEngine; class OpenSearchManager; @@ -32,7 +32,7 @@ class OpenSearchEngineModel : public QAbstractTableModel Q_OBJECT public: - OpenSearchEngineModel(OpenSearchManager *manager, QObject *parent = 0); + OpenSearchEngineModel(OpenSearchManager *manager, QObject *parent = nullptr); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; @@ -41,7 +41,7 @@ class OpenSearchEngineModel : public QAbstractTableModel bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; -protected slots: +protected Q_SLOTS: void enginesChanged(); private: diff --git a/src/opensearch/opensearchmanager.cpp b/src/opensearch/opensearchmanager.cpp index b4bc7895..a9ea2c2b 100644 --- a/src/opensearch/opensearchmanager.cpp +++ b/src/opensearch/opensearchmanager.cpp @@ -23,20 +23,20 @@ #include "autosaver.h" #include "browserapplication.h" -#include "networkaccessmanager.h" +#include #include "opensearchengine.h" #include "opensearchreader.h" #include "opensearchwriter.h" -#include -#include +#include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include OpenSearchManager::OpenSearchManager(QObject *parent) @@ -67,14 +67,14 @@ void OpenSearchManager::setCurrentEngineName(const QString &name) return; m_current = name; - emit currentEngineChanged(); - emit changed(); + Q_EMIT currentEngineChanged(); + Q_EMIT changed(); } OpenSearchEngine *OpenSearchManager::currentEngine() const { if (m_current.isEmpty() || !m_engines.contains(m_current)) - return 0; + return nullptr; return m_engines[m_current]; } @@ -90,7 +90,7 @@ void OpenSearchManager::setCurrentEngine(OpenSearchEngine *engine) OpenSearchEngine *OpenSearchManager::engine(const QString &name) { if (!m_engines.contains(name)) - return 0; + return nullptr; return m_engines[name]; } @@ -115,7 +115,8 @@ void OpenSearchManager::addEngine(const QUrl &url) if (!url.isValid()) return; - QNetworkReply *reply = BrowserApplication::networkAccessManager()->get(QNetworkRequest(url)); + QNetworkAccessManager *manager = new QNetworkAccessManager(); + QNetworkReply *reply = manager->get(QNetworkRequest(url)); connect(reply, SIGNAL(finished()), this, SLOT(engineFromUrlAvailable())); reply->setParent(this); } @@ -150,7 +151,7 @@ bool OpenSearchManager::addEngine(OpenSearchEngine *engine) m_engines[engine->name()] = engine; - emit changed(); + Q_EMIT changed(); return true; } @@ -164,7 +165,7 @@ void OpenSearchManager::removeEngine(const QString &name) return; OpenSearchEngine *engine = m_engines[name]; - foreach (const QString &keyword, m_keywords.keys(engine)) + Q_FOREACH (const QString &keyword, m_keywords.keys(engine)) m_keywords.remove(keyword); engine->deleteLater(); @@ -177,7 +178,7 @@ void OpenSearchManager::removeEngine(const QString &name) if (name == m_current) setCurrentEngineName(m_engines.keys().at(0)); - emit changed(); + Q_EMIT changed(); } QString OpenSearchManager::generateEngineFileName(const QString &engineName) const @@ -187,7 +188,7 @@ QString OpenSearchManager::generateEngineFileName(const QString &engineName) con // Strip special characters from the name. for (int i = 0; i < engineName.count(); ++i) { if (engineName.at(i).isSpace()) { - fileName.append(QLatin1Char('_')); + fileName.append(QChar('_')); continue; } @@ -195,7 +196,7 @@ QString OpenSearchManager::generateEngineFileName(const QString &engineName) con fileName.append(engineName.at(i)); } - fileName.append(QLatin1String(".xml")); + fileName.append(QStringLiteral(".xml")); return fileName; } @@ -209,7 +210,7 @@ void OpenSearchManager::saveDirectory(const QString &dirName) OpenSearchWriter writer; - foreach (OpenSearchEngine *engine, m_engines.values()) { + Q_FOREACH (OpenSearchEngine *engine, m_engines.values()) { QString name = generateEngineFileName(engine->name()); QString fileName = dir.filePath(name); @@ -226,17 +227,17 @@ void OpenSearchManager::save() saveDirectory(enginesDirectory()); QSettings settings; - settings.beginGroup(QLatin1String("openSearch")); - settings.setValue(QLatin1String("engine"), m_current); + settings.beginGroup(QStringLiteral("openSearch")); + settings.setValue(QStringLiteral("engine"), m_current); - settings.beginWriteArray(QLatin1String("keywords"), m_keywords.count()); + settings.beginWriteArray(QStringLiteral("keywords"), m_keywords.count()); QHash::const_iterator i = m_keywords.constBegin(); QHash::const_iterator end = m_keywords.constEnd(); int j = 0; for (; i != end; ++i) { settings.setArrayIndex(j++); - settings.setValue(QLatin1String("keyword"), i.key()); - settings.setValue(QLatin1String("engine"), i.value()->name()); + settings.setValue(QStringLiteral("keyword"), i.key()); + settings.setValue(QStringLiteral("engine"), i.value()->name()); } settings.endArray(); @@ -248,7 +249,7 @@ bool OpenSearchManager::loadDirectory(const QString &dirName) if (!QFile::exists(dirName)) return false; - QDirIterator iterator(dirName, QStringList() << QLatin1String("*.xml")); + QDirIterator iterator(dirName, QStringList() << QStringLiteral("*.xml")); if (!iterator.hasNext()) return false; @@ -266,18 +267,18 @@ bool OpenSearchManager::loadDirectory(const QString &dirName) void OpenSearchManager::load() { if (!loadDirectory(enginesDirectory())) - loadDirectory(QLatin1String(":/searchengines")); + loadDirectory(QStringLiteral(":/searchengines")); // get current engine QSettings settings; - settings.beginGroup(QLatin1String("openSearch")); - m_current = settings.value(QLatin1String("engine"), QLatin1String("Google")).toString(); + settings.beginGroup(QStringLiteral("openSearch")); + m_current = settings.value(QStringLiteral("engine"), QStringLiteral("Google")).toString(); - int size = settings.beginReadArray(QLatin1String("keywords")); + int size = settings.beginReadArray(QStringLiteral("keywords")); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); - QString keyword = settings.value(QLatin1String("keyword")).toString(); - QString engineName = settings.value(QLatin1String("engine")).toString(); + QString keyword = settings.value(QStringLiteral("keyword")).toString(); + QString engineName = settings.value(QStringLiteral("engine")).toString(); m_keywords.insert(keyword, engine(engineName)); } settings.endArray(); @@ -287,18 +288,18 @@ void OpenSearchManager::load() if (!m_engines.contains(m_current) && m_engines.count() > 0) m_current = m_engines.keys().at(0); - emit currentEngineChanged(); + Q_EMIT currentEngineChanged(); } void OpenSearchManager::restoreDefaults() { - loadDirectory(QLatin1String(":/searchengines")); + loadDirectory(QStringLiteral(":/searchengines")); } QString OpenSearchManager::enginesDirectory() const { QDir directory(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/data/Endorphin"); - return directory.filePath(QLatin1String("searchengines")); + return directory.filePath(QStringLiteral("searchengines")); } bool OpenSearchManager::confirmAddition(OpenSearchEngine *engine) @@ -308,10 +309,10 @@ bool OpenSearchManager::confirmAddition(OpenSearchEngine *engine) QString host = QUrl(engine->searchUrlTemplate()).host(); - QMessageBox::StandardButton button = QMessageBox::question(0, QString(), - tr("Do you want to add the following engine to your list of search engines?

    " - "Name: %1
    Searches on: %2").arg(engine->name(), host), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + QMessageBox::StandardButton button = QMessageBox::question(nullptr, QString(), + tr("Do you want to add the following engine to your list of search engines?

    " + "Name: %1
    Searches on: %2").arg(engine->name(), host), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); return (button == QMessageBox::Yes); } @@ -357,7 +358,7 @@ void OpenSearchManager::engineFromUrlAvailable() QUrl OpenSearchManager::convertKeywordSearchToUrl(const QString &string) { - int i = string.indexOf(QLatin1Char(' ')); + int i = string.indexOf(QChar(' ')); if (i <= 0) return QUrl(); @@ -375,9 +376,9 @@ QUrl OpenSearchManager::convertKeywordSearchToUrl(const QString &string) OpenSearchEngine *OpenSearchManager::engineForKeyword(const QString &keyword) const { if (keyword.isEmpty()) - return 0; + return nullptr; if (!m_keywords.contains(keyword)) - return 0; + return nullptr; return m_keywords.value(keyword); } @@ -391,7 +392,7 @@ void OpenSearchManager::setEngineForKeyword(const QString &keyword, OpenSearchEn else m_keywords.insert(keyword, engine); - emit changed(); + Q_EMIT changed(); } QStringList OpenSearchManager::keywordsForEngine(OpenSearchEngine *engine) const @@ -404,15 +405,15 @@ void OpenSearchManager::setKeywordsForEngine(OpenSearchEngine *engine, const QSt if (!engine) return; - foreach (const QString &keyword, keywordsForEngine(engine)) + Q_FOREACH (const QString &keyword, keywordsForEngine(engine)) m_keywords.remove(keyword); - foreach (const QString &keyword, keywords) { + Q_FOREACH (const QString &keyword, keywords) { if (keyword.isEmpty()) continue; m_keywords.insert(keyword, engine); } - emit changed(); + Q_EMIT changed(); } diff --git a/src/opensearch/opensearchmanager.h b/src/opensearch/opensearchmanager.h index 1d3f33c9..da8d0528 100644 --- a/src/opensearch/opensearchmanager.h +++ b/src/opensearch/opensearchmanager.h @@ -22,11 +22,11 @@ #ifndef OPENSEARCHMANAGER_H #define OPENSEARCHMANAGER_H -#include +#include #include #include -#include +#include class QNetworkReply; class QNetworkRequest; @@ -39,12 +39,12 @@ class OpenSearchManager : public QObject { Q_OBJECT -signals: +Q_SIGNALS: void changed(); void currentEngineChanged(); public: - OpenSearchManager(QObject *parent = 0); + OpenSearchManager(QObject *parent = nullptr); ~OpenSearchManager(); QStringList allEnginesNames() const; @@ -73,7 +73,7 @@ class OpenSearchManager : public QObject void removeEngine(const QString &name); void restoreDefaults(); -public slots: +public Q_SLOTS: void save(); protected: @@ -86,7 +86,7 @@ public slots: private: bool confirmAddition(OpenSearchEngine *engine); -protected slots: +protected Q_SLOTS: void engineFromUrlAvailable(); private: diff --git a/src/opensearch/opensearchreader.cpp b/src/opensearch/opensearchreader.cpp index 7b88578a..93aac549 100644 --- a/src/opensearch/opensearchreader.cpp +++ b/src/opensearch/opensearchreader.cpp @@ -84,8 +84,8 @@ OpenSearchEngine *OpenSearchReader::read() while (!isStartElement() && !atEnd()) readNext(); - if (name() != QLatin1String("OpenSearchDescription") - || namespaceUri() != QLatin1String("http://a9.com/-/spec/opensearch/1.1/")) { + if (name() != QStringLiteral("OpenSearchDescription") + || namespaceUri() != QStringLiteral("http://a9.com/-/spec/opensearch/1.1/")) { raiseError(QObject::tr("The file is not an OpenSearch 1.1 file.")); return engine; } @@ -96,24 +96,24 @@ OpenSearchEngine *OpenSearchReader::read() if (!isStartElement()) continue; - if (name() == QLatin1String("ShortName")) { + if (name() == QStringLiteral("ShortName")) { engine->setName(readElementText()); - } else if (name() == QLatin1String("Description")) { + } else if (name() == QStringLiteral("Description")) { engine->setDescription(readElementText()); - } else if (name() == QLatin1String("Url")) { + } else if (name() == QStringLiteral("Url")) { - QString type = attributes().value(QLatin1String("type")).toString(); - QString url = attributes().value(QLatin1String("template")).toString(); - QString method = attributes().value(QLatin1String("method")).toString(); + QString type = attributes().value(QStringLiteral("type")).toString(); + QString url = attributes().value(QStringLiteral("template")).toString(); + QString method = attributes().value(QStringLiteral("method")).toString(); - if (type == QLatin1String("application/x-suggestions+json") - && !engine->suggestionsUrlTemplate().isEmpty()) + if (type == QStringLiteral("application/x-suggestions+json") + && !engine->suggestionsUrlTemplate().isEmpty()) continue; if ((type.isEmpty() - || type == QLatin1String("text/html") - || type == QLatin1String("application/xhtml+xml")) - && !engine->searchUrlTemplate().isEmpty()) + || type == QStringLiteral("text/html") + || type == QStringLiteral("application/xhtml+xml")) + && !engine->searchUrlTemplate().isEmpty()) continue; if (url.isEmpty()) @@ -123,14 +123,14 @@ OpenSearchEngine *OpenSearchReader::read() readNext(); - while (!(isEndElement() && name() == QLatin1String("Url"))) { - if (!isStartElement() || (name() != QLatin1String("Param") && name() != QLatin1String("Parameter"))) { + while (!(isEndElement() && name() == QStringLiteral("Url"))) { + if (!isStartElement() || (name() != QStringLiteral("Param") && name() != QStringLiteral("Parameter"))) { readNext(); continue; } - QString key = attributes().value(QLatin1String("name")).toString(); - QString value = attributes().value(QLatin1String("value")).toString(); + QString key = attributes().value(QStringLiteral("name")).toString(); + QString value = attributes().value(QStringLiteral("value")).toString(); if (!key.isEmpty() && !value.isEmpty()) parameters.append(OpenSearchEngine::Parameter(key, value)); @@ -139,25 +139,25 @@ OpenSearchEngine *OpenSearchReader::read() readNext(); } - if (type == QLatin1String("application/x-suggestions+json")) { + if (type == QStringLiteral("application/x-suggestions+json")) { engine->setSuggestionsUrlTemplate(url); engine->setSuggestionsParameters(parameters); engine->setSuggestionsMethod(method); - } else if (type.isEmpty() || type == QLatin1String("text/html") || type == QLatin1String("application/xhtml+xml")) { + } else if (type.isEmpty() || type == QStringLiteral("text/html") || type == QStringLiteral("application/xhtml+xml")) { engine->setSearchUrlTemplate(url); engine->setSearchParameters(parameters); engine->setSearchMethod(method); } - } else if (name() == QLatin1String("Image")) { - engine->setImageUrl(readElementText()); + } else if (name() == QStringLiteral("Image")) { + engine->setImageUrl(readElementText()); } if (!engine->name().isEmpty() - && !engine->description().isEmpty() - && !engine->suggestionsUrlTemplate().isEmpty() - && !engine->searchUrlTemplate().isEmpty() - && !engine->imageUrl().isEmpty()) + && !engine->description().isEmpty() + && !engine->suggestionsUrlTemplate().isEmpty() + && !engine->searchUrlTemplate().isEmpty() + && !engine->imageUrl().isEmpty()) break; } diff --git a/src/opensearch/opensearchwriter.cpp b/src/opensearch/opensearchwriter.cpp index 10b7c548..a9a6b647 100644 --- a/src/opensearch/opensearchwriter.cpp +++ b/src/opensearch/opensearchwriter.cpp @@ -21,7 +21,7 @@ #include "opensearchengine.h" -#include +#include #include /*! @@ -74,30 +74,30 @@ bool OpenSearchWriter::write(QIODevice *device, OpenSearchEngine *engine) void OpenSearchWriter::write(OpenSearchEngine *engine) { writeStartDocument(); - writeStartElement(QLatin1String("OpenSearchDescription")); - writeDefaultNamespace(QLatin1String("http://a9.com/-/spec/opensearch/1.1/")); + writeStartElement(QStringLiteral("OpenSearchDescription")); + writeDefaultNamespace(QStringLiteral("http://a9.com/-/spec/opensearch/1.1/")); if (!engine->name().isEmpty()) - writeTextElement(QLatin1String("ShortName"), engine->name()); + writeTextElement(QStringLiteral("ShortName"), engine->name()); if (!engine->description().isEmpty()) - writeTextElement(QLatin1String("Description"), engine->description()); + writeTextElement(QStringLiteral("Description"), engine->description()); if (!engine->searchUrlTemplate().isEmpty()) { - writeStartElement(QLatin1String("Url")); - writeAttribute(QLatin1String("method"), engine->searchMethod()); - writeAttribute(QLatin1String("type"), QLatin1String("text/html")); - writeAttribute(QLatin1String("template"), engine->searchUrlTemplate()); + writeStartElement(QStringLiteral("Url")); + writeAttribute(QStringLiteral("method"), engine->searchMethod()); + writeAttribute(QStringLiteral("type"), QStringLiteral("text/html")); + writeAttribute(QStringLiteral("template"), engine->searchUrlTemplate()); if (!engine->searchParameters().empty()) { - writeNamespace(QLatin1String("http://a9.com/-/spec/opensearch/extensions/parameters/1.0/"), QLatin1String("p")); + writeNamespace(QStringLiteral("http://a9.com/-/spec/opensearch/extensions/parameters/1.0/"), QStringLiteral("p")); QList::const_iterator end = engine->searchParameters().constEnd(); QList::const_iterator i = engine->searchParameters().constBegin(); for (; i != end; ++i) { - writeStartElement(QLatin1String("p:Parameter")); - writeAttribute(QLatin1String("name"), i->first); - writeAttribute(QLatin1String("value"), i->second); + writeStartElement(QStringLiteral("p:Parameter")); + writeAttribute(QStringLiteral("name"), i->first); + writeAttribute(QStringLiteral("value"), i->second); writeEndElement(); } } @@ -106,20 +106,20 @@ void OpenSearchWriter::write(OpenSearchEngine *engine) } if (!engine->suggestionsUrlTemplate().isEmpty()) { - writeStartElement(QLatin1String("Url")); - writeAttribute(QLatin1String("method"), engine->suggestionsMethod()); - writeAttribute(QLatin1String("type"), QLatin1String("application/x-suggestions+json")); - writeAttribute(QLatin1String("template"), engine->suggestionsUrlTemplate()); + writeStartElement(QStringLiteral("Url")); + writeAttribute(QStringLiteral("method"), engine->suggestionsMethod()); + writeAttribute(QStringLiteral("type"), QStringLiteral("application/x-suggestions+json")); + writeAttribute(QStringLiteral("template"), engine->suggestionsUrlTemplate()); if (!engine->suggestionsParameters().empty()) { - writeNamespace(QLatin1String("http://a9.com/-/spec/opensearch/extensions/parameters/1.0/"), QLatin1String("p")); + writeNamespace(QStringLiteral("http://a9.com/-/spec/opensearch/extensions/parameters/1.0/"), QStringLiteral("p")); QList::const_iterator end = engine->suggestionsParameters().constEnd(); QList::const_iterator i = engine->suggestionsParameters().constBegin(); for (; i != end; ++i) { - writeStartElement(QLatin1String("p:Parameter")); - writeAttribute(QLatin1String("name"), i->first); - writeAttribute(QLatin1String("value"), i->second); + writeStartElement(QStringLiteral("p:Parameter")); + writeAttribute(QStringLiteral("name"), i->first); + writeAttribute(QStringLiteral("value"), i->second); writeEndElement(); } } @@ -128,7 +128,7 @@ void OpenSearchWriter::write(OpenSearchEngine *engine) } if (!engine->imageUrl().isEmpty()) - writeTextElement(QLatin1String("Image"), engine->imageUrl()); + writeTextElement(QStringLiteral("Image"), engine->imageUrl()); writeEndElement(); writeEndDocument(); diff --git a/src/permissionbar.cpp b/src/permissionbar.cpp new file mode 100644 index 00000000..ec620781 --- /dev/null +++ b/src/permissionbar.cpp @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "permissionbar.h" + +#include +#include +#include +#include +#include + +static const int defaultHeight = 30; + +static QString textForPermissionType(QWebEnginePage::Feature type) +{ + switch (type) { + case QWebEnginePage::Notifications: + return QObject::tr("use desktop notifications"); + case QWebEnginePage::Geolocation: + return QObject::tr("use your position"); + case QWebEnginePage::MediaAudioCapture: + return QObject::tr("use your microphone"); + case QWebEnginePage::MediaVideoCapture: + return QObject::tr("use your camera"); + case QWebEnginePage::MediaAudioVideoCapture: + return QObject::tr("use your camera and microphone"); + case QWebEnginePage::MouseLock: + return QObject::tr("lock your mouse"); + default: + Q_UNREACHABLE(); + } + return QString(); +} + +PermissionBar::PermissionBar(QWidget *view) + : QWidget(view) + , m_messageLabel(new QLabel(this)) +{ + setAutoFillBackground(true); + QHBoxLayout *l = new QHBoxLayout; + setLayout(l); + l->setContentsMargins(defaultHeight, 0, 0, 0); + l->addWidget(m_messageLabel); + l->addStretch(); + QPushButton *allowButton = new QPushButton(tr("Allow"), this); + QPushButton *denyButton = new QPushButton(tr("Deny"), this); + QPushButton *discardButton = new QPushButton(QIcon(QStringLiteral(":closetab.png")), QString(), this); + connect(allowButton, &QPushButton::clicked, this, &PermissionBar::permissionGranted); + connect(denyButton, &QPushButton::clicked, this, &PermissionBar::permissionDenied); + connect(discardButton, &QPushButton::clicked, this, &PermissionBar::permissionUnknown); + connect(allowButton, &QPushButton::clicked, this, &QObject::deleteLater); + connect(denyButton, &QPushButton::clicked, this, &QObject::deleteLater); + connect(discardButton, &QPushButton::clicked, this, &QObject::deleteLater); + l->addWidget(denyButton); + l->addWidget(allowButton); + l->addWidget(discardButton); + setGeometry(0, -defaultHeight, view->width(), defaultHeight); +} + +void PermissionBar::requestPermission(const QUrl &securityOrigin, QWebEnginePage::Feature feature) +{ + m_securityOrigin = securityOrigin; + m_feature = feature; + m_messageLabel->setText(tr("%1 wants to %2.").arg(securityOrigin.host()).arg(textForPermissionType(feature))); + show(); + // Ease in + QPropertyAnimation *animation = new QPropertyAnimation(this); + animation->setTargetObject(this); + animation->setPropertyName(QByteArrayLiteral("pos")); + animation->setDuration(300); + animation->setStartValue(QVariant::fromValue(pos())); + animation->setEndValue(QVariant::fromValue(QPoint(0,0))); + animation->setEasingCurve(QEasingCurve::InOutQuad); + animation->start(QPropertyAnimation::DeleteWhenStopped); +} + +void PermissionBar::permissionDenied() +{ + Q_EMIT featurePermissionProvided(m_securityOrigin, m_feature, QWebEnginePage::PermissionDeniedByUser); +} + +void PermissionBar::permissionGranted() +{ + Q_EMIT featurePermissionProvided(m_securityOrigin, m_feature, QWebEnginePage::PermissionGrantedByUser); +} + +void PermissionBar::permissionUnknown() +{ + Q_EMIT featurePermissionProvided(m_securityOrigin, m_feature, QWebEnginePage::PermissionUnknown); +} diff --git a/src/permissionbar.h b/src/permissionbar.h new file mode 100644 index 00000000..3bf50fab --- /dev/null +++ b/src/permissionbar.h @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtWebEngine module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PERMISSIONBAR_H +#define PERMISSIONBAR_H + +#include +#include + +QT_BEGIN_NAMESPACE +class QLabel; +class QPushButton; +QT_END_NAMESPACE + +class PermissionBar : public QWidget { + Q_OBJECT + +public: + PermissionBar(QWidget*); + void requestPermission(const QUrl &, QWebEnginePage::Feature feature); + +Q_SIGNALS: + void featurePermissionProvided(const QUrl &securityOrigin, QWebEnginePage::Feature, QWebEnginePage::PermissionPolicy); + +private Q_SLOTS: + void permissionDenied(); + void permissionGranted(); + void permissionUnknown(); + +private: + QWebEnginePage::Feature m_feature; + QLabel *m_messageLabel; + QUrl m_securityOrigin; +}; + +#endif // PERMISSIONBAR_H diff --git a/src/plaintexteditsearch.cpp b/src/plaintexteditsearch.cpp index 04c900d6..a1bb8217 100644 --- a/src/plaintexteditsearch.cpp +++ b/src/plaintexteditsearch.cpp @@ -19,8 +19,8 @@ #include "plaintexteditsearch.h" -#include -#include +#include +#include PlainTextEditSearch::PlainTextEditSearch(QPlainTextEdit *plainTextEdit, QWidget *parent) : SearchBar(parent) @@ -31,7 +31,7 @@ PlainTextEditSearch::PlainTextEditSearch(QPlainTextEdit *plainTextEdit, QWidget void PlainTextEditSearch::findNext() { - find(0); + find(QTextDocument::FindFlags()); } void PlainTextEditSearch::findPrevious() diff --git a/src/plaintexteditsearch.h b/src/plaintexteditsearch.h index 95527517..186f17c9 100644 --- a/src/plaintexteditsearch.h +++ b/src/plaintexteditsearch.h @@ -22,7 +22,7 @@ #include "searchbar.h" -#include +#include class QPlainTextEdit; class PlainTextEditSearch : public SearchBar @@ -30,9 +30,9 @@ class PlainTextEditSearch : public SearchBar Q_OBJECT public: - PlainTextEditSearch(QPlainTextEdit *plainTextEdit, QWidget *parent = 0); + PlainTextEditSearch(QPlainTextEdit *plainTextEdit, QWidget *parent = nullptr); -public slots: +public Q_SLOTS: void findNext(); void findPrevious(); diff --git a/src/qwebplugins/endorphinwebplugin.cpp b/src/qwebplugins/endorphinwebplugin.cpp deleted file mode 100644 index 6a389a81..00000000 --- a/src/qwebplugins/endorphinwebplugin.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "endorphinwebplugin.h" - -EndorphinWebPlugin::EndorphinWebPlugin() -{ -} - -EndorphinWebPlugin::~EndorphinWebPlugin() -{ -} - -bool EndorphinWebPlugin::isAnonymous() const -{ - return false; -} diff --git a/src/qwebplugins/endorphinwebplugin.h b/src/qwebplugins/endorphinwebplugin.h deleted file mode 100644 index 97b1fe90..00000000 --- a/src/qwebplugins/endorphinwebplugin.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef ENDORPHINWEBPLUGIN_H -#define ENDORPHINWEBPLUGIN_H - -#include - -class EndorphinWebPlugin -{ - -public: - EndorphinWebPlugin(); - virtual ~EndorphinWebPlugin(); - - virtual QWebPluginFactory::Plugin metaPlugin() = 0; - virtual QWidget *create(const QString &mimeType, const QUrl &url, - const QStringList &argumentNames, const QStringList &argumentValues) = 0; - virtual void configure() = 0; - virtual bool isAnonymous() const; -}; - -#endif // ENDORPHINWEBPLUGIN_H - diff --git a/src/qwebplugins/qwebplugins.pri b/src/qwebplugins/qwebplugins.pri deleted file mode 100644 index e663df8f..00000000 --- a/src/qwebplugins/qwebplugins.pri +++ /dev/null @@ -1,11 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - endorphinwebplugin.h \ - webpluginfactory.h - -SOURCES += \ - endorphinwebplugin.cpp \ - webpluginfactory.cpp diff --git a/src/qwebplugins/webpluginfactory.cpp b/src/qwebplugins/webpluginfactory.cpp deleted file mode 100644 index f6ff9f7a..00000000 --- a/src/qwebplugins/webpluginfactory.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "webpluginfactory.h" - -#include -#include -#include - -// #define WEBPLUGINFACTORY_DEBUG - -WebPluginFactory::WebPluginFactory(QObject *parent) - : QWebPluginFactory(parent) - , m_loaded(false) -{ -} - -WebPluginFactory::~WebPluginFactory() -{ - qDeleteAll(m_plugins); - m_plugins.clear(); -} - -QObject *WebPluginFactory::create(const QString &mimeType, const QUrl &url, const QStringList &argumentNames, const QStringList &argumentValues) const -{ - if (!m_loaded) - init(); - -#ifdef WEBPLUGINFACTORY_DEBUG - qDebug() << "WebPluginFactory::" << __FUNCTION__ << mimeType << url << argumentNames << argumentValues; -#endif - EndorphinWebPlugin *plugin = m_pluginsCache[mimeType]; - if (plugin) - return plugin->create(mimeType, url, argumentNames, argumentValues); -#ifdef WEBPLUGINFACTORY_DEBUG - qDebug() << "WebPluginFactory::" << __FUNCTION__ << "No match"; -#endif - return 0; -} - -QList WebPluginFactory::plugins() const -{ -#ifdef WEBPLUGINFACTORY_DEBUG - qDebug() << "WebPluginFactory::" << __FUNCTION__; -#endif - if (!m_loaded) - init(); - QList plugins; - foreach (EndorphinWebPlugin *plugin, m_plugins) { - QWebPluginFactory::Plugin pluginInfo = plugin->metaPlugin(); - if (!plugin->isAnonymous()) - plugins.append(pluginInfo); - } - return plugins; -} - -void WebPluginFactory::refreshPlugins() -{ -#ifdef WEBPLUGINFACTORY_DEBUG - qDebug() << "WebPluginFactory::" << __FUNCTION__; -#endif - init(); - QWebPluginFactory::refreshPlugins(); -} - -void WebPluginFactory::init() const -{ - m_loaded = true; - m_pluginsCache.clear(); - qDeleteAll(m_plugins); - m_plugins.clear(); - foreach (EndorphinWebPlugin *plugin, m_plugins) { - foreach (const QWebPluginFactory::MimeType &pluginMimeType, plugin->metaPlugin().mimeTypes) - m_pluginsCache.insert(pluginMimeType.name, plugin); - } -} diff --git a/src/qwebplugins/webpluginfactory.h b/src/qwebplugins/webpluginfactory.h deleted file mode 100644 index b6859b6c..00000000 --- a/src/qwebplugins/webpluginfactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#ifndef WEBPLUGINFACTORY_H -#define WEBPLUGINFACTORY_H - -#include -#include - -#include "endorphinwebplugin.h" - -class WebPluginFactory : public QWebPluginFactory -{ - Q_OBJECT - -public: - WebPluginFactory(QObject *parent = 0); - ~WebPluginFactory(); - - QObject *create(const QString &mimeType, const QUrl &url, - const QStringList &argumentNames, const QStringList &argumentValues) const; - QList plugins() const; - void refreshPlugins(); - -private: - void init() const; - mutable bool m_loaded; - mutable QList m_plugins; - mutable QHash m_pluginsCache; -}; - -#endif // WEBPLUGINFACTORY_H - diff --git a/src/savepagedialog.cpp b/src/savepagedialog.cpp new file mode 100644 index 00000000..6023e2a5 --- /dev/null +++ b/src/savepagedialog.cpp @@ -0,0 +1,139 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "savepagedialog.h" +#include "ui_savepagedialog.h" + +#include +#include + +const QWebEngineDownloadItem::SavePageFormat SavePageDialog::m_indexToFormatTable[] = { + QWebEngineDownloadItem::SingleHtmlSaveFormat, + QWebEngineDownloadItem::CompleteHtmlSaveFormat, + QWebEngineDownloadItem::MimeHtmlSaveFormat +}; + +SavePageDialog::SavePageDialog(QWidget *parent, QWebEngineDownloadItem::SavePageFormat format, + const QString &filePath) + : QDialog(parent) + , ui(new Ui::SavePageDialog) +{ + ui->setupUi(this); + ui->formatComboBox->setCurrentIndex(formatToIndex(format)); + setFilePath(filePath); +} + +SavePageDialog::~SavePageDialog() +{ + delete ui; +} + +QWebEngineDownloadItem::SavePageFormat SavePageDialog::pageFormat() const +{ + return indexToFormat(ui->formatComboBox->currentIndex()); +} + +QString SavePageDialog::filePath() const +{ + return QDir::fromNativeSeparators(ui->filePathLineEdit->text()); +} + +void SavePageDialog::on_chooseFilePathButton_clicked() +{ + QFileInfo fi(filePath()); + QFileDialog dlg(this, tr("Save Page As"), fi.absolutePath()); + dlg.setAcceptMode(QFileDialog::AcceptSave); + dlg.setDefaultSuffix(suffixOfFormat(pageFormat())); + dlg.selectFile(fi.absoluteFilePath()); + if (dlg.exec() != QDialog::Accepted) + return; + setFilePath(dlg.selectedFiles().first()); + ensureFileSuffix(pageFormat()); +} + +void SavePageDialog::on_formatComboBox_currentIndexChanged(int idx) +{ + ensureFileSuffix(indexToFormat(idx)); +} + +int SavePageDialog::formatToIndex(QWebEngineDownloadItem::SavePageFormat format) +{ + for (auto i : m_indexToFormatTable) { + if (m_indexToFormatTable[i] == format) + return i; + } + Q_UNREACHABLE(); +} + +QWebEngineDownloadItem::SavePageFormat SavePageDialog::indexToFormat(int idx) +{ + Q_ASSERT(idx >= 0 && size_t(idx) < (sizeof(m_indexToFormatTable) + / sizeof(QWebEngineDownloadItem::SavePageFormat))); + return m_indexToFormatTable[idx]; +} + +QString SavePageDialog::suffixOfFormat(QWebEngineDownloadItem::SavePageFormat format) +{ + if (format == QWebEngineDownloadItem::MimeHtmlSaveFormat) + return QStringLiteral(".mhtml"); + return QStringLiteral(".html"); +} + +void SavePageDialog::setFilePath(const QString &filePath) +{ + ui->filePathLineEdit->setText(QDir::toNativeSeparators(filePath)); +} + +void SavePageDialog::ensureFileSuffix(QWebEngineDownloadItem::SavePageFormat format) +{ + QFileInfo fi(filePath()); + setFilePath(fi.absolutePath() + QChar('/') + fi.completeBaseName() + + suffixOfFormat(format)); +} diff --git a/src/savepagedialog.h b/src/savepagedialog.h new file mode 100644 index 00000000..03bb8935 --- /dev/null +++ b/src/savepagedialog.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SAVEPAGEDIALOG_H +#define SAVEPAGEDIALOG_H + +#include +#include + +QT_BEGIN_NAMESPACE +namespace Ui { +class SavePageDialog; +} +QT_END_NAMESPACE + +class SavePageDialog : public QDialog +{ + Q_OBJECT + +public: + explicit SavePageDialog(QWidget *parent, QWebEngineDownloadItem::SavePageFormat format, + const QString &filePath); + ~SavePageDialog(); + + QWebEngineDownloadItem::SavePageFormat pageFormat() const; + QString filePath() const; + +private Q_SLOTS: + void on_chooseFilePathButton_clicked(); + void on_formatComboBox_currentIndexChanged(int idx); + +private: + static int formatToIndex(QWebEngineDownloadItem::SavePageFormat format); + static QWebEngineDownloadItem::SavePageFormat indexToFormat(int idx); + static QString suffixOfFormat(QWebEngineDownloadItem::SavePageFormat format); + void setFilePath(const QString &filePath); + void ensureFileSuffix(QWebEngineDownloadItem::SavePageFormat format); + + static const QWebEngineDownloadItem::SavePageFormat m_indexToFormatTable[]; + Ui::SavePageDialog *ui; +}; + +#endif // SAVEPAGEDIALOG_H diff --git a/src/savepagedialog.ui b/src/savepagedialog.ui new file mode 100644 index 00000000..9aa7cbe5 --- /dev/null +++ b/src/savepagedialog.ui @@ -0,0 +1,139 @@ + + + SavePageDialog + + + + 0 + 0 + 400 + 121 + + + + Dialog + + + + + + + + &Format: + + + formatComboBox + + + + + + + + Single HTML + + + + + Complete HTML + + + + + MIME HTML + + + + + + + + &Save to: + + + filePathLineEdit + + + + + + + + + + + + ... + + + + + + + + + + + Qt::Vertical + + + + 20 + 12 + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + formatComboBox + filePathLineEdit + chooseFilePathButton + + + + + buttonBox + accepted() + SavePageDialog + accept() + + + 227 + 104 + + + 157 + 120 + + + + + buttonBox + rejected() + SavePageDialog + reject() + + + 295 + 110 + + + 286 + 120 + + + + + diff --git a/src/searchbar.cpp b/src/searchbar.cpp index e2ed93d0..fd28790c 100644 --- a/src/searchbar.cpp +++ b/src/searchbar.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,16 +19,17 @@ #include "searchbar.h" -#include -#include -#include +#include +#include +#include +#include -#include +#include SearchBar::SearchBar(QWidget *parent) : QWidget(parent) - , m_object(0) - , m_widget(0) + , m_object(nullptr) + , m_widget(nullptr) , m_timeLine(new QTimeLine(150, this)) { initializeSearchWidget(); @@ -61,9 +62,9 @@ void SearchBar::initializeSearchWidget() m_widget->setContentsMargins(0, 0, 0, 0); ui.setupUi(m_widget); ui.previousButton->setText(m_widget->layoutDirection() - == Qt::LeftToRight? QChar(9664): QChar(9654)); + == Qt::LeftToRight? QChar(9664): QChar(9654)); ui.nextButton->setText(m_widget->layoutDirection() - == Qt::LeftToRight? QChar(9654): QChar(9664)); + == Qt::LeftToRight? QChar(9654): QChar(9664)); ui.searchInfo->setText(QString()); setMinimumWidth(m_widget->minimumWidth()); setMaximumWidth(m_widget->maximumWidth()); diff --git a/src/searchbar.h b/src/searchbar.h index 21865282..4b61e436 100644 --- a/src/searchbar.h +++ b/src/searchbar.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef SEARCHBAR_H #define SEARCHBAR_H -#include +#include #include "ui_searchbanner.h" @@ -33,11 +33,11 @@ class SearchBar : public QWidget Q_OBJECT public: - SearchBar(QWidget *parent = 0); + SearchBar(QWidget *parent = nullptr); void setSearchObject(QObject *object); QObject *searchObject() const; -public slots: +public Q_SLOTS: void animateHide(); void clear(); void showFind(); @@ -48,7 +48,7 @@ public slots: void resizeEvent(QResizeEvent *event); Ui_SearchBanner ui; -private slots: +private Q_SLOTS: void frameChanged(int frame); private: diff --git a/src/searchbutton.cpp b/src/searchbutton.cpp index 89ba0a34..c053c974 100644 --- a/src/searchbutton.cpp +++ b/src/searchbutton.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,10 +19,10 @@ #include "searchbutton.h" -#include -#include -#include -#include +#include +#include +#include +#include #include SearchButton::SearchButton(QWidget *parent) diff --git a/src/searchbutton.h b/src/searchbutton.h index 347cac53..18802553 100644 --- a/src/searchbutton.h +++ b/src/searchbutton.h @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ #ifndef SEARCHBUTTON_H #define SEARCHBUTTON_H -#include +#include class QCompleter; class SearchButton : public QAbstractButton @@ -28,7 +28,7 @@ class SearchButton : public QAbstractButton Q_OBJECT public: - SearchButton(QWidget *parent = 0); + SearchButton(QWidget *parent = nullptr); void setImage(const QImage &image); void setShowMenuTriangle(bool show); bool showMenuTriangle() const; diff --git a/src/searchlineedit.cpp b/src/searchlineedit.cpp index f6dd469a..5d1e9610 100644 --- a/src/searchlineedit.cpp +++ b/src/searchlineedit.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright (c) 2020, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * diff --git a/src/searchlineedit.h b/src/searchlineedit.h index 9b7f4ec7..13b95dda 100644 --- a/src/searchlineedit.h +++ b/src/searchlineedit.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright (c) 2020, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -38,7 +38,7 @@ class SearchLineEdit : public LineEdit Q_OBJECT public: - SearchLineEdit(QWidget *parent = 0); + SearchLineEdit(QWidget *parent = nullptr); ClearButton *clearButton() const; SearchButton *searchButton() const; diff --git a/src/settings.cpp b/src/settings.cpp index 6d9c6743..efcf1da3 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,44 +63,34 @@ #include "settings.h" #include "acceptlanguagedialog.h" -#include "autofilldialog.h" -#include "autofillmanager.h" #include "browserapplication.h" #include "browsermainwindow.h" -#include "cookiedialog.h" -#include "cookieexceptionsdialog.h" -#include "cookiejar.h" #include "historymanager.h" -#include "networkaccessmanager.h" #include "tabwidget.h" -#include "webpluginfactory.h" #include "webpage.h" #include "webview.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent) , m_cacheEnabled(false) { setupUi(this); - connect(exceptionsButton, SIGNAL(clicked()), this, SLOT(showExceptions())); connect(setHomeToCurrentPageButton, SIGNAL(clicked()), this, SLOT(setHomeToCurrentPage())); - connect(cookiesButton, SIGNAL(clicked()), this, SLOT(showCookies())); connect(standardFontButton, SIGNAL(clicked()), this, SLOT(chooseFont())); connect(fixedFontButton, SIGNAL(clicked()), this, SLOT(chooseFixedFont())); connect(languageButton, SIGNAL(clicked()), this, SLOT(chooseAcceptLanguage())); connect(downloadDirectoryButton, SIGNAL(clicked()), this, SLOT(chooseDownloadDirectory())); connect(externalDownloadBrowse, SIGNAL(clicked()), this, SLOT(chooseDownloadProgram())); connect(styleSheetBrowseButton, SIGNAL(clicked()), this, SLOT(chooseStyleSheet())); - - connect(editAutoFillUserButton, SIGNAL(clicked()), this, SLOT(editAutoFillUser())); + connect(newSettings, SIGNAL(clicked()), this, SLOT(openModernSettings())); loadDefaults(); loadFromSettings(); @@ -108,29 +98,24 @@ SettingsDialog::SettingsDialog(QWidget *parent) void SettingsDialog::loadDefaults() { - QWebSettings *defaultSettings = QWebSettings::globalSettings(); - QString standardFontFamily = defaultSettings->fontFamily(QWebSettings::StandardFont); - int standardFontSize = defaultSettings->fontSize(QWebSettings::DefaultFontSize); + QWebEngineSettings *defaultSettings = QWebEngineSettings::globalSettings(); + QString standardFontFamily = defaultSettings->fontFamily(QWebEngineSettings::StandardFont); + int standardFontSize = defaultSettings->fontSize(QWebEngineSettings::DefaultFontSize); m_standardFont = QFont(standardFontFamily, standardFontSize); - standardLabel->setText(QString(QLatin1String("%1 %2")).arg(m_standardFont.family()).arg(m_standardFont.pointSize())); + standardLabel->setText(QString(QStringLiteral("%1 %2")).arg(m_standardFont.family()).arg(m_standardFont.pointSize())); - QString fixedFontFamily = defaultSettings->fontFamily(QWebSettings::FixedFont); - int fixedFontSize = defaultSettings->fontSize(QWebSettings::DefaultFixedFontSize); + QString fixedFontFamily = defaultSettings->fontFamily(QWebEngineSettings::FixedFont); + int fixedFontSize = defaultSettings->fontSize(QWebEngineSettings::DefaultFixedFontSize); m_fixedFont = QFont(fixedFontFamily, fixedFontSize); - fixedLabel->setText(QString(QLatin1String("%1 %2")).arg(m_fixedFont.family()).arg(m_fixedFont.pointSize())); + fixedLabel->setText(QString(QStringLiteral("%1 %2")).arg(m_fixedFont.family()).arg(m_fixedFont.pointSize())); downloadsLocation->setText(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); - blockPopupWindows->setChecked(!defaultSettings->testAttribute(QWebSettings::JavascriptCanOpenWindows)); - enableJavascript->setChecked(defaultSettings->testAttribute(QWebSettings::JavascriptEnabled)); - enablePlugins->setChecked(defaultSettings->testAttribute(QWebSettings::PluginsEnabled)); - enableImages->setChecked(defaultSettings->testAttribute(QWebSettings::AutoLoadImages)); - enableLocalStorage->setChecked(defaultSettings->testAttribute(QWebSettings::LocalStorageEnabled)); - clickToFlash->setChecked(false); - cookieSessionCombo->setCurrentIndex(0); - filterTrackingCookiesCheckbox->setChecked(false); + blockPopupWindows->setChecked(!defaultSettings->testAttribute(QWebEngineSettings::JavascriptCanOpenWindows)); + enableJavascript->setChecked(defaultSettings->testAttribute(QWebEngineSettings::JavascriptEnabled)); + enableImages->setChecked(defaultSettings->testAttribute(QWebEngineSettings::AutoLoadImages)); + enableLocalStorage->setChecked(defaultSettings->testAttribute(QWebEngineSettings::LocalStorageEnabled)); - autoFillPasswordFormsCheckBox->setChecked(false); minimFontSizeCheckBox->setChecked(false); minimumFontSizeSpinBox->setValue(9); } @@ -138,308 +123,251 @@ void SettingsDialog::loadDefaults() void SettingsDialog::loadFromSettings() { QSettings settings; - settings.beginGroup(QLatin1String("Settings")); - tabWidget->setCurrentIndex(settings.value(QLatin1String("currentTab"), 0).toInt()); + settings.beginGroup(QStringLiteral("Settings")); + tabWidget->setCurrentIndex(settings.value(QStringLiteral("currentTab"), 0).toInt()); settings.endGroup(); - settings.beginGroup(QLatin1String("MainWindow")); - QString defaultHome = QLatin1String("about:home"); - homeLineEdit->setText(settings.value(QLatin1String("home"), defaultHome).toString()); - startupBehavior->setCurrentIndex(settings.value(QLatin1String("startupBehavior"), 0).toInt()); + settings.beginGroup(QStringLiteral("MainWindow")); + QString defaultHome = QStringLiteral("about:home"); + homeLineEdit->setText(settings.value(QStringLiteral("home"), defaultHome).toString()); + startupBehavior->setCurrentIndex(settings.value(QStringLiteral("startupBehavior"), 0).toInt()); settings.endGroup(); - settings.beginGroup(QLatin1String("history")); - int historyExpire = settings.value(QLatin1String("historyLimit")).toInt(); + settings.beginGroup(QStringLiteral("history")); + int historyExpire = settings.value(QStringLiteral("historyLimit")).toInt(); int idx = 0; switch (historyExpire) { - case 1: idx = 0; break; - case 7: idx = 1; break; - case 14: idx = 2; break; - case 30: idx = 3; break; - case 365: idx = 4; break; - case -1: idx = 5; break; - case -2: idx = 6; break; + case 1: + idx = 0; + break; + case 7: + idx = 1; + break; + case 14: + idx = 2; + break; + case 30: + idx = 3; + break; + case 365: + idx = 4; + break; + case -1: + idx = 5; + break; + case -2: + idx = 6; + break; default: idx = 5; } expireHistory->setCurrentIndex(idx); settings.endGroup(); - settings.beginGroup(QLatin1String("urlloading")); - bool search = settings.value(QLatin1String("searchEngineFallback"), false).toBool(); + settings.beginGroup(QStringLiteral("urlloading")); + bool search = settings.value(QStringLiteral("searchEngineFallback"), true).toBool(); searchEngineFallback->setChecked(search); settings.endGroup(); - settings.beginGroup(QLatin1String("downloadmanager")); - bool alwaysPromptForFileName = settings.value(QLatin1String("alwaysPromptForFileName"), false).toBool(); + settings.beginGroup(QStringLiteral("downloadmanager")); + bool alwaysPromptForFileName = settings.value(QStringLiteral("alwaysPromptForFileName"), false).toBool(); downloadAsk->setChecked(alwaysPromptForFileName); - QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), downloadsLocation->text()).toString(); + QString downloadDirectory = settings.value(QStringLiteral("downloadDirectory"), downloadsLocation->text()).toString(); downloadsLocation->setText(downloadDirectory); - externalDownloadButton->setChecked(settings.value(QLatin1String("external"), false).toBool()); - externalDownloadPath->setText(settings.value(QLatin1String("externalPath")).toString()); + externalDownloadButton->setChecked(settings.value(QStringLiteral("external"), false).toBool()); + externalDownloadPath->setText(settings.value(QStringLiteral("externalPath")).toString()); settings.endGroup(); // Appearance - settings.beginGroup(QLatin1String("websettings")); - m_fixedFont = settings.value(QLatin1String("fixedFont"), m_fixedFont).value(); - m_standardFont = settings.value(QLatin1String("standardFont"), m_standardFont).value(); - - standardLabel->setText(QString(QLatin1String("%1 %2")).arg(m_standardFont.family()).arg(m_standardFont.pointSize())); - fixedLabel->setText(QString(QLatin1String("%1 %2")).arg(m_fixedFont.family()).arg(m_fixedFont.pointSize())); - - blockPopupWindows->setChecked(settings.value(QLatin1String("blockPopupWindows"), blockPopupWindows->isChecked()).toBool()); - enableJavascript->setChecked(settings.value(QLatin1String("enableJavascript"), enableJavascript->isChecked()).toBool()); - enablePlugins->setChecked(settings.value(QLatin1String("enablePlugins"), enablePlugins->isChecked()).toBool()); - enableImages->setChecked(settings.value(QLatin1String("enableImages"), enableImages->isChecked()).toBool()); - enableLocalStorage->setChecked(settings.value(QLatin1String("enableLocalStorage"), enableLocalStorage->isChecked()).toBool()); - userStyleSheet->setText(QString::fromUtf8(settings.value(QLatin1String("userStyleSheet")).toUrl().toEncoded())); - int minimumFontSize = settings.value(QLatin1String("minimumFontSize"), 0).toInt(); + settings.beginGroup(QStringLiteral("websettings")); + m_fixedFont = settings.value(QStringLiteral("fixedFont"), m_fixedFont).value(); + m_standardFont = settings.value(QStringLiteral("standardFont"), m_standardFont).value(); + + standardLabel->setText(QString(QStringLiteral("%1 %2")).arg(m_standardFont.family()).arg(m_standardFont.pointSize())); + fixedLabel->setText(QString(QStringLiteral("%1 %2")).arg(m_fixedFont.family()).arg(m_fixedFont.pointSize())); + + blockPopupWindows->setChecked(settings.value(QStringLiteral("blockPopupWindows"), blockPopupWindows->isChecked()).toBool()); + enableJavascript->setChecked(settings.value(QStringLiteral("enableJavascript"), enableJavascript->isChecked()).toBool()); + enableImages->setChecked(settings.value(QStringLiteral("enableImages"), enableImages->isChecked()).toBool()); + enableLocalStorage->setChecked(settings.value(QStringLiteral("enableLocalStorage"), enableLocalStorage->isChecked()).toBool()); + userStyleSheet->setText(QString::fromUtf8(settings.value(QStringLiteral("userStyleSheet")).toUrl().toEncoded())); + int minimumFontSize = settings.value(QStringLiteral("minimumFontSize"), 0).toInt(); minimFontSizeCheckBox->setChecked(minimumFontSize != 0); if (minimumFontSize != 0) minimumFontSizeSpinBox->setValue(minimumFontSize); settings.endGroup(); - - // Privacy - settings.beginGroup(QLatin1String("cookies")); - - QByteArray value = settings.value(QLatin1String("acceptCookies"), QLatin1String("AcceptOnlyFromSitesNavigatedTo")).toByteArray(); - QMetaEnum acceptPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("AcceptPolicy")); - CookieJar::AcceptPolicy acceptCookies = acceptPolicyEnum.keyToValue(value) == -1 ? - CookieJar::AcceptOnlyFromSitesNavigatedTo : - static_cast(acceptPolicyEnum.keyToValue(value)); - switch (acceptCookies) { - case CookieJar::AcceptAlways: - acceptCombo->setCurrentIndex(0); - break; - case CookieJar::AcceptNever: - acceptCombo->setCurrentIndex(1); - break; - case CookieJar::AcceptOnlyFromSitesNavigatedTo: - acceptCombo->setCurrentIndex(2); - break; - } - - value = settings.value(QLatin1String("keepCookiesUntil"), QLatin1String("Expire")).toByteArray(); - QMetaEnum keepPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("KeepPolicy")); - CookieJar::KeepPolicy keepCookies = keepPolicyEnum.keyToValue(value) == -1 ? - CookieJar::KeepUntilExpire : - static_cast(keepPolicyEnum.keyToValue(value)); - switch (keepCookies) { - case CookieJar::KeepUntilExpire: - keepUntilCombo->setCurrentIndex(0); - break; - case CookieJar::KeepUntilExit: - keepUntilCombo->setCurrentIndex(1); - break; - case CookieJar::KeepUntilTimeLimit: - keepUntilCombo->setCurrentIndex(2); - break; - } - int sessionLength = settings.value(QLatin1String("sessionLength"), -1).toInt(); - switch (sessionLength) { - case 1: cookieSessionCombo->setCurrentIndex(1); break; - case 2: cookieSessionCombo->setCurrentIndex(2); break; - case 3: cookieSessionCombo->setCurrentIndex(3); break; - case 7: cookieSessionCombo->setCurrentIndex(4); break; - case 30: cookieSessionCombo->setCurrentIndex(5); break; - default: - case 0: cookieSessionCombo->setCurrentIndex(0); break; + // UI Appearance + settings.beginGroup(QStringLiteral("appearance")); + urlBarType->setCurrentIndex(settings.value(QStringLiteral("urlBarType"), 0).toInt()); + settings.endGroup(); + if(urlBarType->currentIndex() == 1) { + // Required so URL bar accepts search terms + settings.beginGroup(QStringLiteral("urlloading")); + settings.setValue(QStringLiteral("searchEngineFallback"), true); + searchEngineFallback->setChecked(true); + searchEngineFallback->setEnabled(false); + } else { + searchEngineFallback->setEnabled(true); } - filterTrackingCookiesCheckbox->setChecked(settings.value(QLatin1String("filterTrackingCookies"), false).toBool()); settings.endGroup(); // Network - settings.beginGroup(QLatin1String("network")); - m_cacheEnabled = settings.value(QLatin1String("cacheEnabled"), true).toBool(); + settings.beginGroup(QStringLiteral("network")); + m_cacheEnabled = settings.value(QStringLiteral("cacheEnabled"), true).toBool(); networkCache->setChecked(m_cacheEnabled); - networkCacheMaximumSizeSpinBox->setValue(settings.value(QLatin1String("maximumCacheSize"), 50).toInt()); + networkCacheMaximumSizeSpinBox->setValue(settings.value(QStringLiteral("maximumCacheSize"), 50).toInt()); settings.endGroup(); // Proxy - settings.beginGroup(QLatin1String("proxy")); - proxySupport->setChecked(settings.value(QLatin1String("enabled"), false).toBool()); - proxyType->setCurrentIndex(settings.value(QLatin1String("type"), 0).toInt()); - proxyHostName->setText(settings.value(QLatin1String("hostName")).toString()); - proxyPort->setValue(settings.value(QLatin1String("port"), 1080).toInt()); - proxyUserName->setText(settings.value(QLatin1String("userName")).toString()); - proxyPassword->setText(settings.value(QLatin1String("password")).toString()); + settings.beginGroup(QStringLiteral("proxy")); + proxySupport->setChecked(settings.value(QStringLiteral("enabled"), false).toBool()); + proxyType->setCurrentIndex(settings.value(QStringLiteral("type"), 0).toInt()); + proxyHostName->setText(settings.value(QStringLiteral("hostName")).toString()); + proxyPort->setValue(settings.value(QStringLiteral("port"), 1080).toInt()); + proxyUserName->setText(settings.value(QStringLiteral("userName")).toString()); + proxyPassword->setText(settings.value(QStringLiteral("password")).toString()); settings.endGroup(); // Tabs - settings.beginGroup(QLatin1String("tabs")); - selectTabsWhenCreated->setChecked(settings.value(QLatin1String("selectNewTabs"), false).toBool()); - confirmClosingMultipleTabs->setChecked(settings.value(QLatin1String("confirmClosingMultipleTabs"), true).toBool()); - oneCloseButton->setChecked(settings.value(QLatin1String("oneCloseButton"),false).toBool()); - quitAsLastTabClosed->setChecked(settings.value(QLatin1String("quitAsLastTabClosed"), true).toBool()); - openTargetBlankLinksIn->setCurrentIndex(settings.value(QLatin1String("openTargetBlankLinksIn"), TabWidget::NewSelectedTab).toInt()); - openLinksFromAppsIn->setCurrentIndex(settings.value(QLatin1String("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); + settings.beginGroup(QStringLiteral("tabs")); + selectTabsWhenCreated->setChecked(settings.value(QStringLiteral("selectNewTabs"), false).toBool()); + confirmClosingMultipleTabs->setChecked(settings.value(QStringLiteral("confirmClosingMultipleTabs"), true).toBool()); + oneCloseButton->setChecked(settings.value(QStringLiteral("oneCloseButton"),false).toBool()); + quitAsLastTabClosed->setChecked(settings.value(QStringLiteral("quitAsLastTabClosed"), true).toBool()); + openTargetBlankLinksIn->setCurrentIndex(settings.value(QStringLiteral("openTargetBlankLinksIn"), TabWidget::NewSelectedTab).toInt()); + openLinksFromAppsIn->setCurrentIndex(settings.value(QStringLiteral("openLinksFromAppsIn"), TabWidget::NewSelectedTab).toInt()); settings.endGroup(); // Accessibility - settings.beginGroup(QLatin1String("WebView")); - enableAccessKeys->setChecked(settings.value(QLatin1String("enableAccessKeys"), true).toBool()); - settings.endGroup(); - - settings.beginGroup(QLatin1String("autofill")); - autoFillPasswordFormsCheckBox->setChecked(settings.value(QLatin1String("passwordForms"), true).toBool()); + settings.beginGroup(QStringLiteral("WebView")); + enableAccessKeys->setChecked(settings.value(QStringLiteral("enableAccessKeys"), true).toBool()); settings.endGroup(); } void SettingsDialog::saveToSettings() { QSettings settings; - settings.beginGroup(QLatin1String("Settings")); - settings.setValue(QLatin1String("currentTab"), tabWidget->currentIndex()); + settings.beginGroup(QStringLiteral("Settings")); + settings.setValue(QStringLiteral("currentTab"), tabWidget->currentIndex()); settings.endGroup(); - settings.beginGroup(QLatin1String("MainWindow")); - settings.setValue(QLatin1String("home"), homeLineEdit->text()); - settings.setValue(QLatin1String("startupBehavior"), startupBehavior->currentIndex()); + settings.beginGroup(QStringLiteral("MainWindow")); + settings.setValue(QStringLiteral("home"), homeLineEdit->text()); + settings.setValue(QStringLiteral("startupBehavior"), startupBehavior->currentIndex()); settings.endGroup(); - settings.beginGroup(QLatin1String("downloadmanager")); - settings.setValue(QLatin1String("alwaysPromptForFileName"), downloadAsk->isChecked()); - settings.setValue(QLatin1String("downloadDirectory"), downloadsLocation->text()); - settings.setValue(QLatin1String("external"), externalDownloadButton->isChecked()); - settings.setValue(QLatin1String("externalPath"), externalDownloadPath->text()); + settings.beginGroup(QStringLiteral("downloadmanager")); + settings.setValue(QStringLiteral("alwaysPromptForFileName"), downloadAsk->isChecked()); + settings.setValue(QStringLiteral("downloadDirectory"), downloadsLocation->text()); + settings.setValue(QStringLiteral("external"), externalDownloadButton->isChecked()); + settings.setValue(QStringLiteral("externalPath"), externalDownloadPath->text()); settings.endGroup(); - settings.beginGroup(QLatin1String("history")); + settings.beginGroup(QStringLiteral("history")); int historyExpire = expireHistory->currentIndex(); int idx = -1; switch (historyExpire) { - case 0: idx = 1; break; - case 1: idx = 7; break; - case 2: idx = 14; break; - case 3: idx = 30; break; - case 4: idx = 365; break; - case 5: idx = -1; break; - case 6: idx = -2; break; + case 0: + idx = 1; + break; + case 1: + idx = 7; + break; + case 2: + idx = 14; + break; + case 3: + idx = 30; + break; + case 4: + idx = 365; + break; + case 5: + idx = -1; + break; + case 6: + idx = -2; + break; } - settings.setValue(QLatin1String("historyLimit"), idx); + settings.setValue(QStringLiteral("historyLimit"), idx); settings.endGroup(); - settings.beginGroup(QLatin1String("urlloading")); - settings.setValue(QLatin1String("searchEngineFallback"), searchEngineFallback->isChecked()); + settings.beginGroup(QStringLiteral("urlloading")); + settings.setValue(QStringLiteral("searchEngineFallback"), searchEngineFallback->isChecked()); settings.endGroup(); // Appearance - settings.beginGroup(QLatin1String("websettings")); - settings.setValue(QLatin1String("fixedFont"), m_fixedFont); - settings.setValue(QLatin1String("standardFont"), m_standardFont); - - settings.setValue(QLatin1String("blockPopupWindows"), blockPopupWindows->isChecked()); - settings.setValue(QLatin1String("enableJavascript"), enableJavascript->isChecked()); - settings.setValue(QLatin1String("enablePlugins"), enablePlugins->isChecked()); - settings.setValue(QLatin1String("enableImages"), enableImages->isChecked()); - settings.setValue(QLatin1String("enableLocalStorage"), enableLocalStorage->isChecked()); + settings.beginGroup(QStringLiteral("websettings")); + settings.setValue(QStringLiteral("fixedFont"), m_fixedFont); + settings.setValue(QStringLiteral("standardFont"), m_standardFont); + + settings.setValue(QStringLiteral("blockPopupWindows"), blockPopupWindows->isChecked()); + settings.setValue(QStringLiteral("enableJavascript"), enableJavascript->isChecked()); + settings.setValue(QStringLiteral("enableImages"), enableImages->isChecked()); + settings.setValue(QStringLiteral("enableLocalStorage"), enableLocalStorage->isChecked()); QString userStyleSheetString = userStyleSheet->text(); if (QFile::exists(userStyleSheetString)) - settings.setValue(QLatin1String("userStyleSheet"), QUrl::fromLocalFile(userStyleSheetString)); + settings.setValue(QStringLiteral("userStyleSheet"), QUrl::fromLocalFile(userStyleSheetString)); else - settings.setValue(QLatin1String("userStyleSheet"), QUrl::fromEncoded(userStyleSheetString.toUtf8())); - settings.setValue(QLatin1String("enableClickToFlash"), clickToFlash->isChecked()); + settings.setValue(QStringLiteral("userStyleSheet"), QUrl::fromEncoded(userStyleSheetString.toUtf8())); if (minimFontSizeCheckBox->isChecked()) - settings.setValue(QLatin1String("minimumFontSize"), minimumFontSizeSpinBox->value()); + settings.setValue(QStringLiteral("minimumFontSize"), minimumFontSizeSpinBox->value()); else - settings.setValue(QLatin1String("minimumFontSize"), 0); + settings.setValue(QStringLiteral("minimumFontSize"), 0); settings.endGroup(); - - // Privacy - settings.beginGroup(QLatin1String("cookies")); - CookieJar::AcceptPolicy acceptCookies; - switch (acceptCombo->currentIndex()) { - default: - case 0: - acceptCookies = CookieJar::AcceptAlways; - break; - case 1: - acceptCookies = CookieJar::AcceptNever; - break; - case 2: - acceptCookies = CookieJar::AcceptOnlyFromSitesNavigatedTo; - break; - } - - QMetaEnum acceptPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("AcceptPolicy")); - settings.setValue(QLatin1String("acceptCookies"), QLatin1String(acceptPolicyEnum.valueToKey(acceptCookies))); - - CookieJar::KeepPolicy keepPolicy; - switch (keepUntilCombo->currentIndex()) { - default: - case 0: - keepPolicy = CookieJar::KeepUntilExpire; - break; - case 1: - keepPolicy = CookieJar::KeepUntilExit; - break; - case 2: - keepPolicy = CookieJar::KeepUntilTimeLimit; - break; - } - - QMetaEnum keepPolicyEnum = CookieJar::staticMetaObject.enumerator(CookieJar::staticMetaObject.indexOfEnumerator("KeepPolicy")); - settings.setValue(QLatin1String("keepCookiesUntil"), QLatin1String(keepPolicyEnum.valueToKey(keepPolicy))); - int sessionLength = cookieSessionCombo->currentIndex(); - switch (sessionLength) { - case 1: sessionLength = 1; break; - case 2: sessionLength = 2; break; - case 3: sessionLength = 3; break; - case 4: sessionLength = 7; break; - case 5: sessionLength = 30; break; - default: - case 0: sessionLength = -1; break; + // UI Appearance + settings.beginGroup(QStringLiteral("appearance")); + settings.setValue(QStringLiteral("urlBarType"), urlBarType->currentIndex()); + settings.endGroup(); + if(urlBarType->currentIndex() == 1) { + // Required so URL bar accepts search terms + settings.beginGroup(QStringLiteral("urlloading")); + settings.setValue(QStringLiteral("searchEngineFallback"), true); + searchEngineFallback->setChecked(true); + searchEngineFallback->setEnabled(false); + } else { + searchEngineFallback->setEnabled(true); } - settings.setValue(QLatin1String("sessionLength"), sessionLength); - settings.setValue(QLatin1String("filterTrackingCookies"), filterTrackingCookiesCheckbox->isChecked()); settings.endGroup(); + // Network - settings.beginGroup(QLatin1String("network")); - settings.setValue(QLatin1String("cacheEnabled"), networkCache->isChecked()); - settings.setValue(QLatin1String("maximumCacheSize"), networkCacheMaximumSizeSpinBox->value()); + settings.beginGroup(QStringLiteral("network")); + settings.setValue(QStringLiteral("cacheEnabled"), networkCache->isChecked()); + settings.setValue(QStringLiteral("maximumCacheSize"), networkCacheMaximumSizeSpinBox->value()); settings.endGroup(); // proxy - settings.beginGroup(QLatin1String("proxy")); - settings.setValue(QLatin1String("enabled"), proxySupport->isChecked()); - settings.setValue(QLatin1String("type"), proxyType->currentIndex()); - settings.setValue(QLatin1String("hostName"), proxyHostName->text()); - settings.setValue(QLatin1String("port"), proxyPort->text()); - settings.setValue(QLatin1String("userName"), proxyUserName->text()); - settings.setValue(QLatin1String("password"), proxyPassword->text()); + settings.beginGroup(QStringLiteral("proxy")); + settings.setValue(QStringLiteral("enabled"), proxySupport->isChecked()); + settings.setValue(QStringLiteral("type"), proxyType->currentIndex()); + settings.setValue(QStringLiteral("hostName"), proxyHostName->text()); + settings.setValue(QStringLiteral("port"), proxyPort->text()); + settings.setValue(QStringLiteral("userName"), proxyUserName->text()); + settings.setValue(QStringLiteral("password"), proxyPassword->text()); settings.endGroup(); // Tabs - settings.beginGroup(QLatin1String("tabs")); - settings.setValue(QLatin1String("selectNewTabs"), selectTabsWhenCreated->isChecked()); - settings.setValue(QLatin1String("confirmClosingMultipleTabs"), confirmClosingMultipleTabs->isChecked()); - settings.setValue(QLatin1String("oneCloseButton"), oneCloseButton->isChecked()); - settings.setValue(QLatin1String("quitAsLastTabClosed"), quitAsLastTabClosed->isChecked()); - settings.setValue(QLatin1String("openTargetBlankLinksIn"), openTargetBlankLinksIn->currentIndex()); - settings.setValue(QLatin1String("openLinksFromAppsIn"), openLinksFromAppsIn->currentIndex()); - settings.endGroup(); - - settings.beginGroup(QLatin1String("autofill")); - settings.setValue(QLatin1String("passwordForms"), autoFillPasswordFormsCheckBox->isChecked()); + settings.beginGroup(QStringLiteral("tabs")); + settings.setValue(QStringLiteral("selectNewTabs"), selectTabsWhenCreated->isChecked()); + settings.setValue(QStringLiteral("confirmClosingMultipleTabs"), confirmClosingMultipleTabs->isChecked()); + settings.setValue(QStringLiteral("oneCloseButton"), oneCloseButton->isChecked()); + settings.setValue(QStringLiteral("quitAsLastTabClosed"), quitAsLastTabClosed->isChecked()); + settings.setValue(QStringLiteral("openTargetBlankLinksIn"), openTargetBlankLinksIn->currentIndex()); + settings.setValue(QStringLiteral("openLinksFromAppsIn"), openLinksFromAppsIn->currentIndex()); settings.endGroup(); // Accessibility - settings.beginGroup(QLatin1String("WebView")); - settings.setValue(QLatin1String("enableAccessKeys"), enableAccessKeys->isChecked()); + settings.beginGroup(QStringLiteral("WebView")); + settings.setValue(QStringLiteral("enableAccessKeys"), enableAccessKeys->isChecked()); settings.endGroup(); BrowserApplication::instance()->loadSettings(); - BrowserApplication::networkAccessManager()->loadSettings(); - BrowserApplication::cookieJar()->loadSettings(); BrowserApplication::historyManager()->loadSettings(); - BrowserApplication::autoFillManager()->loadSettings(); - - WebPage::webPluginFactory()->refreshPlugins(); QList list = BrowserApplication::instance()->mainWindows(); - foreach (BrowserMainWindow *mainWindow, list) { + Q_FOREACH (BrowserMainWindow *mainWindow, list) { mainWindow->tabWidget()->loadSettings(); } } @@ -450,18 +378,6 @@ void SettingsDialog::accept() QDialog::accept(); } -void SettingsDialog::showCookies() -{ - CookieDialog dialog(BrowserApplication::cookieJar(), this); - dialog.exec(); -} - -void SettingsDialog::showExceptions() -{ - CookieExceptionsDialog dialog(BrowserApplication::cookieJar(), this); - dialog.exec(); -} - void SettingsDialog::chooseDownloadDirectory() { QString fileName = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), downloadsLocation->text()); @@ -471,8 +387,8 @@ void SettingsDialog::chooseDownloadDirectory() void SettingsDialog::chooseDownloadProgram() { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose Program"), externalDownloadPath->text()); - if (fileName.contains(QLatin1Char(' '))) - fileName = QString(QLatin1String("\"%1\"")).arg(fileName); + if (fileName.contains(QChar(' '))) + fileName = QString(QStringLiteral("\"%1\"")).arg(fileName); externalDownloadPath->setText(fileName); } @@ -482,7 +398,7 @@ void SettingsDialog::chooseFont() QFont font = QFontDialog::getFont(&ok, m_standardFont, this); if (ok) { m_standardFont = font; - standardLabel->setText(QString(QLatin1String("%1 %2")).arg(font.family()).arg(font.pointSize())); + standardLabel->setText(QString(QStringLiteral("%1 %2")).arg(font.family()).arg(font.pointSize())); } } @@ -492,7 +408,7 @@ void SettingsDialog::chooseFixedFont() QFont font = QFontDialog::getFont(&ok, m_fixedFont, this); if (ok) { m_fixedFont = font; - fixedLabel->setText(QString(QLatin1String("%1 %2")).arg(font.family()).arg(font.pointSize())); + fixedLabel->setText(QString(QStringLiteral("%1 %2")).arg(font.family()).arg(font.pointSize())); } } @@ -517,9 +433,8 @@ void SettingsDialog::chooseStyleSheet() userStyleSheet->setText(QString::fromUtf8(QUrl::fromLocalFile(fileName).toEncoded())); } -void SettingsDialog::editAutoFillUser() -{ - AutoFillDialog dialog; - dialog.exec(); +void SettingsDialog::openModernSettings() { + BrowserMainWindow *mw = static_cast(parent()); + mw->tabWidget()->loadUrl(QUrl("qrc:/settings.html"), TabWidget::NewSelectedTab, "Settings"); + close(); } - diff --git a/src/settings.h b/src/settings.h index fae23c3b..c0c18402 100644 --- a/src/settings.h +++ b/src/settings.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,7 +63,7 @@ #ifndef SETTINGS_H #define SETTINGS_H -#include +#include #include "ui_settings.h" class SettingsDialog : public QDialog, public Ui_Settings @@ -71,17 +71,15 @@ class SettingsDialog : public QDialog, public Ui_Settings Q_OBJECT public: - SettingsDialog(QWidget *parent = 0); + SettingsDialog(QWidget *parent = nullptr); void accept(); -private slots: +private Q_SLOTS: void loadDefaults(); void loadFromSettings(); void saveToSettings(); void setHomeToCurrentPage(); - void showCookies(); - void showExceptions(); void chooseDownloadDirectory(); void chooseDownloadProgram(); @@ -90,7 +88,7 @@ private slots: void chooseAcceptLanguage(); void chooseStyleSheet(); - void editAutoFillUser(); + void openModernSettings(); private: QFont m_standardFont; diff --git a/src/settings.ui b/src/settings.ui index 43275b52..1d62f94f 100644 --- a/src/settings.ui +++ b/src/settings.ui @@ -7,7 +7,7 @@ 0 0 677 - 442 + 445 @@ -29,78 +29,86 @@ 2 + + + true + + + Information + + + + + 10 + 10 + 641 + 341 + + + + + + + + + Open the new settings + + + + + + + + Open Sans Light + 25 + 50 + false + PreferDefault + true + + + + The settings are moving! + + + Qt::AlignCenter + + + + + + + The settings here will be moved soon. We're modernizing and redesigning this browser currently, and we're moving the settings into a web page. In the future, the settings will only be accessible at endorphin://settings. You can already try using the experimental version by pressing the button below, but not all settings are available there yet. + + + Qt::AlignCenter + + + true + + + + + + + + General - - - - On startup: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - Show my home page - - - - - Show a blank page - - - - - Restore windows and tabs from last time - - - - - - + + - Home Page: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - Qt::LeftToRight + Use the default search engine as fallback when the URL given by the user is invalid - - - - - - Set to current page + + false - - - - Qt::Horizontal - - - - 280 - 18 - - - - - + Remove history items: @@ -110,63 +118,7 @@ - - - - - After one day - - - - - After one week - - - - - After two weeks - - - - - After one month - - - - - After one year - - - - - Manually - - - - - On application exit - - - - - - - - Use the default search engine as fallback when the URL given by the user is invalid - - - false - - - - - - Enable access keys - - - - Downloads @@ -228,22 +180,108 @@ - - - - Qt::Vertical - - - - 608 - 15 - - - - + + + + On startup: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Set to current page + + + + + + + Qt::LeftToRight + + + + + + + Home Page: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Show my home page + + + + + Show a blank page + + + + + Restore windows and tabs from last time + + + + + + + + Enable access keys + + + + + + + + After one day + + + + + After one week + + + + + After two weeks + + + + + After one month + + + + + After one year + + + + + Manually + + + + + On application exit + + + + @@ -261,19 +299,33 @@ - - - - - 0 - 0 - + + + + Fixed-width font: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Select... + + + + + + + true QFrame::StyledPanel - Times 16 + Courier 13 Qt::AlignCenter @@ -287,40 +339,52 @@ - - + + - Fixed-width font: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Minimum Font size: - - + + + + + 0 + 0 + + + + true + QFrame::StyledPanel - Courier 13 + Times 16 Qt::AlignCenter - - + + - Select... + Preferred languages for viewing webpages in: - - - - Preferred languages for viewing webpages in: + + + + false + + + 1 + + + 9 @@ -331,14 +395,31 @@ - - + + - Minimum Font size: + URL bar type - + + + + 0 + + + + Seperate Search and URL bar + + + + + One input for URL and search term + + + + + Qt::Vertical @@ -351,19 +432,6 @@ - - - - false - - - 1 - - - 9 - - - @@ -377,10 +445,10 @@ Web Content - - + + - Block Popup Windows + Persistent Data Storage true @@ -388,51 +456,6 @@ - - - Enable Plugins - - - true - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - 0 - 0 - - - - If you enable this option, no flash objects will be loaded by default. Instead, each will be replaced by a button, allowing you to control which objects to load, and which not. - - - Use ClickToFlash on flash plugins - - - true - - - - Enable Javascript @@ -442,169 +465,24 @@ - - - - View Images - - - true - - - - - - - Persistent Data Storage - - - true - - - - - - - - - - Cookies - - - - - - Accept Cookies: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - Always - - - - - Never - - - - - Only from sites you navigate to - - - - - - - - Exceptions... - - - - - - - Keep Cookies Until: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - They expire - - - - - I exit the application - - - - - At most 90 days - - - - - - - - Cookies... - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Filter Tracking Cookies - - - - - - - A cookie session ends: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - - When I exit the application - - - - - 1 day - - - - - 2 days - - - - - 3 days - - - - - 7 days - - - - - 30 days - - + + + + Block Popup Windows + + + true + + + + + + + View Images + + + true + @@ -773,17 +651,14 @@ true - - - - Type: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + Qt::LeftToRight - + @@ -802,6 +677,16 @@ + + + + User Name: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + @@ -812,14 +697,17 @@ - - + + Qt::LeftToRight + + QLineEdit::Password + - + Port: @@ -829,138 +717,67 @@ - - - - 65535 + + + + Password: - - 1080 + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - Qt::Horizontal + + + + + 430 + 0 + - 293 - 20 + 139 + 36 - - - - - - User Name: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - Qt::LeftToRight - - - - Password: + + + + 65535 - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + 1080 - - - - Qt::LeftToRight + + + + Type: - - QLineEdit::Password + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - Qt::Vertical - - - - 20 - 8 - - - - - - - - - AutoFill - - - - - - AutoFill web forms: - - - - - - - - 0 - 0 - - - - User names and passwords - - - - - - - Edit... - - - - - + + Qt::Vertical 20 - 244 - - - - - - - - Qt::Horizontal - - - - 40 - 20 + 8 @@ -1025,23 +842,10 @@ - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + Qt::Vertical @@ -1063,7 +867,6 @@ startupBehavior homeLineEdit - setHomeToCurrentPageButton expireHistory searchEngineFallback downloadAsk @@ -1073,15 +876,8 @@ fixedFontButton languageButton blockPopupWindows - enablePlugins - clickToFlash enableJavascript enableImages - acceptCombo - exceptionsButton - keepUntilCombo - cookiesButton - filterTrackingCookiesCheckbox selectTabsWhenCreated confirmClosingMultipleTabs oneCloseButton @@ -1091,7 +887,6 @@ proxySupport proxyType proxyHostName - proxyPort proxyUserName proxyPassword userStyleSheet @@ -1134,162 +929,146 @@ - downloadDestination + externalDownloadButton toggled(bool) - downloadsLocation + externalDownloadPath setEnabled(bool) - 79 - 289 + 161 + 315 - 280 - 291 + 388 + 315 - enablePlugins + externalDownloadButton toggled(bool) - clickToFlash - setEnabled(bool) + downloadDirectoryButton + setDisabled(bool) - 104 - 125 + 194 + 311 - 162 - 154 + 569 + 276 - minimFontSizeCheckBox + externalDownloadButton toggled(bool) - minimumFontSizeSpinBox + externalDownloadBrowse setEnabled(bool) - 31 - 153 + 161 + 315 - 189 - 151 + 554 + 315 - downloadDestination + externalDownloadButton toggled(bool) - downloadDirectoryButton - setEnabled(bool) + downloadAsk + setDisabled(bool) - 182 - 282 + 102 + 311 - 620 - 292 + 105 + 252 - externalDownloadButton + minimFontSizeCheckBox toggled(bool) - externalDownloadPath + minimumFontSizeSpinBox setEnabled(bool) - 161 - 315 + 31 + 153 - 388 - 315 + 189 + 151 - externalDownloadButton + downloadDestination toggled(bool) - externalDownloadBrowse + downloadDirectoryButton setEnabled(bool) - 161 - 315 + 182 + 282 - 554 - 315 + 620 + 292 externalDownloadButton toggled(bool) - downloadAsk + downloadDestination setDisabled(bool) - 102 - 311 + 170 + 313 - 105 - 252 + 169 + 285 - externalDownloadButton + downloadDestination toggled(bool) downloadsLocation - setDisabled(bool) - - - 198 - 315 - - - 386 - 279 - - - - - externalDownloadButton - toggled(bool) - downloadDestination - setDisabled(bool) + setEnabled(bool) - 170 - 313 + 79 + 289 - 169 - 285 + 280 + 291 externalDownloadButton toggled(bool) - downloadDirectoryButton + downloadsLocation setDisabled(bool) - 194 - 311 + 198 + 315 - 569 - 276 + 386 + 279 diff --git a/src/sourcehighlighter.cpp b/src/sourcehighlighter.cpp deleted file mode 100644 index d61ffa07..00000000 --- a/src/sourcehighlighter.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2008 Christian Franke - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "sourcehighlighter.h" - -#include - -SourceHighlighter::SourceHighlighter(QTextDocument *document) - : QSyntaxHighlighter(document) -{ - QPalette palette; - QColor foreground = palette.text().color(); - QColor background = palette.base().color(); - - QTextCharFormat entityFormat; - QColor entityColor; - entityColor.setRed((foreground.red() + background.red()) / 2); - entityColor.setGreen( - (foreground.green() + background.green()) / 2); - entityColor.setBlue( - (foreground.blue() + background.blue()) / 2); - if (abs(entityColor.red() - background.red()) > 80) - entityColor.setRed(foreground.red()); - else if (abs(entityColor.green()-background.green()) > 80) - entityColor.setGreen(foreground.green()); - else entityColor.setBlue(foreground.blue()); - entityFormat.setForeground(entityColor); - entityFormat.setFontWeight(QFont::Normal); - setFormatFor(Entity, entityFormat); - - QTextCharFormat tagFormat; - QColor tagColor; - tagColor.setRed(foreground.red() + (background.red() - foreground.red()) / 4); - tagColor.setGreen( - foreground.green() + (background.green() - foreground.green()) / 4); - tagColor.setBlue( - foreground.blue() + (background.blue() - foreground.blue()) / 4); - tagFormat.setForeground(tagColor); - tagFormat.setFontWeight(QFont::Bold); - setFormatFor(Tag, tagFormat); - - QTextCharFormat commentFormat; - QColor commentColor; - commentColor.setRed(background.red() + (foreground.red() - background.red()) / 3); - commentColor.setGreen( - background.green() + (foreground.green() - background.green()) / 3); - commentColor.setBlue( - background.blue() + (foreground.blue() - background.blue()) / 3); - commentFormat.setForeground(commentColor); - commentFormat.setFontWeight(QFont::Normal); - setFormatFor(Comment, commentFormat); - - QTextCharFormat attributeFormat; - QColor attributeColor; - attributeColor.setRed((foreground.red() + background.red()) / 2); - attributeColor.setGreen( - (foreground.green() + background.green()) / 2); - attributeColor.setBlue( - (foreground.blue() + background.blue()) / 2); - if (abs(attributeColor.red() - background.red()) > 80) - attributeColor.setRed(background.red()); - else if (abs(attributeColor.green() - background.green()) > 80) - attributeColor.setGreen(background.green()); - else attributeColor.setBlue(background.blue()); - attributeFormat.setForeground(attributeColor); - attributeFormat.setFontWeight(QFont::Normal); - setFormatFor(Attribute, attributeFormat); -} - -QTextCharFormat SourceHighlighter::getFormatFor(Construct construct) -{ - return formats[construct]; -} - -void SourceHighlighter::setFormatFor(Construct construct, - QTextCharFormat &format) -{ - formats[construct] = format; -} - -void SourceHighlighter::highlightBlock(const QString &text) -{ - int state = previousBlockState(); - int len = text.length(); - int start = 0; - int pos = 0; - QRegExp regex; - - while (pos >= 0 && pos < len && len > 0) { - switch (state) { - default: - case Normal: - regex.setPattern(QLatin1String("[<&]")); - pos = regex.indexIn(text, pos); - if (pos >= 0) { - if (text.at(pos) == QLatin1Char('<')) { - start = pos; - if (text.mid(pos, 4) == QLatin1String("")); - pos = regex.indexIn(text, pos); - if (pos >= 0) { - state = Normal; - pos += 3; - setFormat(start, pos - start, formats[Comment]); - ++pos; - } else { - setFormat(start, len - start, formats[Comment]); - } - break; - case InTag: - regex.setPattern(QLatin1String("[>\"]")); - pos = regex.indexIn(text, pos); - if (pos >= 0) { - if (text.at(pos) == QLatin1Char('>')) { - state = Normal; - ++pos; - setFormat(start, pos - start, formats[Tag]); - } else if (text.at(pos) == QLatin1Char('"')) { - setFormat(start, pos - start, formats[Tag]); - start = pos; - state = InAttribute; - ++pos; - } - } else { - setFormat(start, len-start, formats[Tag]); - } - break; - case InAttribute: - regex.setPattern(QLatin1String("\"")); - pos = regex.indexIn(text, pos); - if (pos >= 0) { - setFormat(start, pos - start, formats[Attribute]); - state = InTag; - start = ++pos; - } else { - setFormat(start, len - start, formats[Attribute]); - } - break; - } - } - setCurrentBlockState(state); -} diff --git a/src/sourcehighlighter.h b/src/sourcehighlighter.h deleted file mode 100644 index d6783e68..00000000 --- a/src/sourcehighlighter.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2008 Christian Franke - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#ifndef SOURCEHIGHLIGHTER_H -#define SOURCEHIGHLIGHTER_H - -#include - -class SourceHighlighter : public QSyntaxHighlighter -{ - Q_OBJECT - -public: - enum Construct { - Entity, - Tag, - Comment, - Attribute, - LastConstruct = Attribute - }; - SourceHighlighter(QTextDocument *document); - - QTextCharFormat getFormatFor(Construct construct); - void setFormatFor(Construct construct, QTextCharFormat &format); - -protected: - enum State { - Normal = -1, - InComment, - InTag, - InAttribute - }; - void highlightBlock(const QString &text); - -private: - QTextCharFormat formats[LastConstruct + 1]; -}; - -#endif diff --git a/src/sourceviewer.cpp b/src/sourceviewer.cpp deleted file mode 100644 index b90d5f11..00000000 --- a/src/sourceviewer.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2008 Christian Franke - * Copyright 2008-2009 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "sourceviewer.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "browserapplication.h" -#include "networkaccessmanager.h" -#include "plaintexteditsearch.h" -#include "sourcehighlighter.h" - -SourceViewer::SourceViewer(const QString &source, const QString &title, - const QUrl &url, QWidget *parent) - : QDialog(parent) - , m_edit(new QPlainTextEdit(tr("Loading..."), this)) - , m_highlighter(new SourceHighlighter(m_edit->document())) - , m_plainTextEditSearch(new PlainTextEditSearch(m_edit, this)) - , m_layout(new QVBoxLayout(this)) - , m_menuBar(new QMenuBar(this)) - , m_editMenu(new QMenu(tr("&Edit"), m_menuBar)) - , m_findAction(new QAction(tr("&Find"), m_editMenu)) - , m_source(source) -{ - setWindowTitle(tr("Source of Page %1").arg(title)); - - QSettings settings; - settings.beginGroup(QLatin1String("SourceViewer")); - QSize size = settings.value(QLatin1String("size"), QSize(640, 480)).toSize(); - resize(size); - - m_edit->setLineWrapMode(QPlainTextEdit::WidgetWidth); - m_edit->setReadOnly(true); - QFont font = m_edit->font(); - font.setFamily(QLatin1String("Monospace")); - m_edit->setFont(font); - m_edit->setLineWidth(0); - m_edit->setFrameShape(QFrame::NoFrame); - - m_menuBar->addMenu(m_editMenu); - m_editMenu->addAction(m_findAction); - m_findAction->setShortcuts(QKeySequence::Find); - connect(m_findAction, SIGNAL(triggered()), - m_plainTextEditSearch, SLOT(showFind())); - - m_layout->setSpacing(0); - m_layout->setContentsMargins(0, 0, 0, 0); - m_layout->addWidget(m_menuBar); - m_layout->addWidget(m_plainTextEditSearch); - m_layout->addWidget(m_edit); - setLayout(m_layout); - - QNetworkRequest request(url); - request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); - m_reply = BrowserApplication::networkAccessManager()->get(request); - connect(m_reply, SIGNAL(finished()), this, SLOT(loadingFinished())); - m_reply->setParent(this); -} - -SourceViewer::~SourceViewer() -{ - QSettings settings; - settings.beginGroup(QLatin1String("SourceViewer")); - settings.setValue(QLatin1String("size"), size()); -} - -void SourceViewer::loadingFinished() -{ - QWebPage page; - QByteArray response = m_reply->readAll(); - page.mainFrame()->setContent(response, QString(), m_reply->request().url()); - - /* If original request was POST or a different problem is there, fall - back to modified version of QWebFrame.toHtml() */ - if (page.mainFrame()->toHtml() != m_source) - m_edit->setPlainText(m_source); - else - m_edit->setPlainText(QLatin1String(response)); - - m_reply->close(); -} diff --git a/src/sourceviewer.h b/src/sourceviewer.h deleted file mode 100644 index a4b654a3..00000000 --- a/src/sourceviewer.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2008 Christian Franke - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#ifndef SOURCEVIEWER_H -#define SOURCEVIEWER_H - -#include - -class QVBoxLayout; -class SourceHighlighter; -class PlainTextEditSearch; -class QPlainTextEdit; -class QMenuBar; -class QMenu; -class QUrl; -class QAction; -class QNetworkReply; -class SourceViewer : public QDialog -{ - Q_OBJECT - -public: - SourceViewer(const QString &source, const QString &title, - const QUrl &url, QWidget *parent = 0); - ~SourceViewer(); - -private: - QPlainTextEdit *m_edit; - SourceHighlighter *m_highlighter; - PlainTextEditSearch *m_plainTextEditSearch; - QVBoxLayout *m_layout; - QMenuBar *m_menuBar; - QMenu *m_editMenu; - QAction *m_findAction; - QMenu *m_viewMenu; - QNetworkReply *m_reply; - QString m_source; - -private slots: - void loadingFinished(); -}; - -#endif diff --git a/src/src.pri b/src/src.pri deleted file mode 100644 index 92681683..00000000 --- a/src/src.pri +++ /dev/null @@ -1,135 +0,0 @@ -CONFIG += qt warn_on -contains(QT_BUILD_PARTS, tools): CONFIG += uitools -else : DEFINES += QT_NO_UITOOLS - -win32|os2 : Debug : CONFIG += console - -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD - -QT += webkit network webkitwidgets printsupport uitools - -# Share object files for faster compiling -RCC_DIR = $$PWD/.rcc -UI_DIR = $$PWD/.ui -MOC_DIR = $$PWD/.moc -OBJECTS_DIR = $$PWD/.obj - -exists(../.git/HEAD) { - GITVERSION=$$system(git log -n1 --pretty=format:%h) - !isEmpty(GITVERSION) { - GITCHANGENUMBER=$$system(git log --pretty=format:%h | wc -l) - DEFINES += GITVERSION=\"\\\"$$GITVERSION\\\"\" - DEFINES += GITCHANGENUMBER=\"\\\"$$GITCHANGENUMBER\\\"\" - } -} - -VPATH += $$PWD - -FORMS += \ - aboutdialog.ui \ - autofilldialog.ui \ - acceptlanguagedialog.ui \ - downloaditem.ui \ - downloads.ui \ - searchbanner.ui \ - settings.ui - -HEADERS += \ - aboutdialog.h \ - acceptlanguagedialog.h \ - autosaver.h \ - autofilldialog.h \ - autofillmanager.h \ - browserapplication.h \ - browsermainwindow.h \ - clearprivatedata.h \ - clearbutton.h \ - downloadmanager.h \ - modelmenu.h \ - modeltoolbar.h \ - plaintexteditsearch.h \ - searchbar.h \ - searchbutton.h \ - searchlineedit.h \ - settings.h \ - sourcehighlighter.h \ - sourceviewer.h \ - tabbar.h \ - tabwidget.h \ - toolbarsearch.h \ - webactionmapper.h \ - webpage.h \ - webview.h \ - webviewsearch.h - -SOURCES += \ - aboutdialog.cpp \ - acceptlanguagedialog.cpp \ - autosaver.cpp \ - autofilldialog.cpp \ - autofillmanager.cpp \ - browserapplication.cpp \ - browsermainwindow.cpp \ - clearprivatedata.cpp \ - clearbutton.cpp \ - downloadmanager.cpp \ - modelmenu.cpp \ - modeltoolbar.cpp \ - plaintexteditsearch.cpp \ - searchbar.cpp \ - searchbutton.cpp \ - searchlineedit.cpp \ - settings.cpp \ - sourcehighlighter.cpp \ - sourceviewer.cpp \ - tabbar.cpp \ - tabwidget.cpp \ - toolbarsearch.cpp \ - webactionmapper.cpp \ - webpage.cpp \ - webview.cpp \ - webviewsearch.cpp - -include(adblock/adblock.pri) -include(bookmarks/bookmarks.pri) -include(history/history.pri) -include(locationbar/locationbar.pri) -include(network/network.pri) -include(opensearch/opensearch.pri) -include(qwebplugins/qwebplugins.pri) -include(utils/utils.pri) -include(useragent/useragent.pri) - -RESOURCES += \ - $$PWD/data/data.qrc \ - $$PWD/data/graphics/graphics.qrc \ - $$PWD/data/searchengines/searchengines.qrc \ - $$PWD/htmls/htmls.qrc - -DISTFILES += ../AUTHORS \ - ../ChangeLog \ - ../LICENSE.GPL2 \ - ../LICENSE.GPL3 \ - ../README - -win32 { - RC_FILE = $$PWD/browser.rc - LIBS += -luser32 -} - -mac { - ICON = browser.icns - QMAKE_INFO_PLIST = $$PWD/Info_mac.plist -} - -include(../webkittrunk.pri) - -unix { - PKGDATADIR = $$DATADIR/endorphin - DEFINES += DATADIR=\\\"$$DATADIR\\\" PKGDATADIR=\\\"$$PKGDATADIR\\\" -} - -win32 { - LIBS += -ladvapi32 -} diff --git a/src/src.pro b/src/src.pro deleted file mode 100644 index 7a50418f..00000000 --- a/src/src.pro +++ /dev/null @@ -1,63 +0,0 @@ -TEMPLATE = app - -TARGET = endorphin -mac { - TARGET = Endorphin - QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.10 -} - -DEFINES += \ - QT_STRICT_ITERATORS \ - -include(../install.pri) - -include(src.pri) - -SOURCES += main.cpp - -DESTDIR = ../ - -include(locale/locale.pri) - -!mac { -unix { - INSTALLS += translations desktop iconxpm iconsvg icon16 icon32 icon128 man man-compress - - translations.path = $$PKGDATADIR - translations.files += .qm/locale - - desktop.path = $$DATADIR/applications - desktop.files += endorphin.desktop - - iconxpm.path = $$DATADIR/pixmaps - iconxpm.files += data/endorphin.xpm - - iconsvg.path = $$DATADIR/icons/hicolor/scalable/apps - iconsvg.files += data/endorphin.svg - - icon16.path = $$DATADIR/icons/hicolor/16x16/apps - icon16.files += data/16x16/endorphin.png - - icon32.path = $$DATADIR/icons/hicolor/32x32/apps - icon32.files += data/32x32/endorphin.png - - icon128.path = $$DATADIR/icons/hicolor/128x128/apps - icon128.files += data/128x128/endorphin.png - - man.path = $$DATADIR/man/man1 - man.files += data/endorphin.1 - - man-compress.path = $$DATADIR/man/man1 - man-compress.extra = "" "gzip -9 -f \$(INSTALL_ROOT)/$$DATADIR/man/man1/endorphin.1" "" - man-compress.depends = install_man - - GNOME_DEFAULT_APPS_PATH = $$system(pkg-config --variable=defappsdir gnome-default-applications) - - !isEmpty(GNOME_DEFAULT_APPS_PATH) { - INSTALLS += gnome-default-app - - gnome-default-app.path = $$GNOME_DEFAULT_APPS_PATH - gnome-default-app.files = data/endorphin.xml - } -} -} diff --git a/src/tabbar.cpp b/src/tabbar.cpp index c08e7819..771ba42b 100644 --- a/src/tabbar.cpp +++ b/src/tabbar.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -64,17 +64,17 @@ #include "tabwidget.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include +#include TabShortcut::TabShortcut(int tab, const QKeySequence &key, QWidget *parent) : QShortcut(key, parent) @@ -89,7 +89,7 @@ int TabShortcut::tab() TabBar::TabBar(QWidget *parent) : QTabBar(parent) - , m_viewTabBarAction(0) + , m_viewTabBarAction(nullptr) , m_showTabBarWhenOneTab(true) { setContextMenuPolicy(Qt::CustomContextMenu); @@ -99,7 +99,7 @@ TabBar::TabBar(QWidget *parent) connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(contextMenuRequested(const QPoint &))); - QString alt = QLatin1String("Ctrl+%1"); + QString alt = QStringLiteral("Ctrl+%1"); for (int i = 0; i < 9; ++i) { int key = i + 1; TabShortcut *tabShortCut = new TabShortcut(i, alt.arg(key), this); @@ -132,7 +132,7 @@ QAction *TabBar::viewTabBarAction() const QTabBar::ButtonPosition TabBar::freeSide() { - QTabBar::ButtonPosition side = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this); + QTabBar::ButtonPosition side = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this); side = (side == QTabBar::LeftSide) ? QTabBar::RightSide : QTabBar::LeftSide; return side; } @@ -199,7 +199,7 @@ void TabBar::cloneTab() { if (QAction *action = qobject_cast(sender())) { int index = action->data().toInt(); - emit cloneTab(index); + Q_EMIT cloneTab(index); } } @@ -207,7 +207,7 @@ void TabBar::closeTab() { if (QAction *action = qobject_cast(sender())) { int index = action->data().toInt(); - emit closeTab(index); + Q_EMIT closeTab(index); } } @@ -215,15 +215,15 @@ void TabBar::closeOtherTabs() { if (QAction *action = qobject_cast(sender())) { int index = action->data().toInt(); - emit closeOtherTabs(index); + Q_EMIT closeOtherTabs(index); } } void TabBar::mouseDoubleClickEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton - && tabAt(event->pos()) == -1) { - emit newTab(); + && tabAt(event->pos()) == -1) { + Q_EMIT newTab(); return; } QTabBar::mouseDoubleClickEvent(event); @@ -234,12 +234,12 @@ void TabBar::mouseReleaseEvent(QMouseEvent *event) if (event->button() == Qt::MidButton) { int index = tabAt(event->pos()); if (index != -1) { - emit closeTab(index); + Q_EMIT closeTab(index); return; } else { QUrl url(QApplication::clipboard()->text(QClipboard::Selection)); if (!url.isEmpty() && url.isValid() && !url.scheme().isEmpty()) - emit loadUrl(url, TabWidget::NewTab); + Q_EMIT loadUrl(url, TabWidget::NewTab); } } @@ -259,8 +259,8 @@ void TabBar::mouseMoveEvent(QMouseEvent *event) int diffX = event->pos().x() - m_dragStartPos.x(); int diffY = event->pos().y() - m_dragStartPos.y(); if ((event->pos() - m_dragStartPos).manhattanLength() > QApplication::startDragDistance() - && diffX < 3 && diffX > -3 - && diffY < -10) { + && diffX < 3 && diffX > -3 + && diffY < -10) { QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; QList urls; @@ -269,7 +269,7 @@ void TabBar::mouseMoveEvent(QMouseEvent *event) urls.append(url); mimeData->setUrls(urls); mimeData->setText(tabText(index)); - mimeData->setData(QLatin1String("action"), "tab-reordering"); + mimeData->setData(QStringLiteral("action"), "tab-reordering"); drag->setMimeData(mimeData); drag->exec(); } @@ -300,9 +300,9 @@ void TabBar::dropEvent(QDropEvent *event) int index = tabAt(event->pos()); if (-1 != index) { setCurrentIndex(index); - emit loadUrl(url, TabWidget::CurrentTab); + Q_EMIT loadUrl(url, TabWidget::CurrentTab); } else { - emit loadUrl(url, TabWidget::NewSelectedTab); + Q_EMIT loadUrl(url, TabWidget::NewSelectedTab); } } @@ -313,14 +313,14 @@ QSize TabBar::tabSizeHint(int index) const { QSize sizeHint = QTabBar::tabSizeHint(index); QFontMetrics fm = fontMetrics(); - return sizeHint.boundedTo(QSize(fm.horizontalAdvance(QLatin1Char('M')) * 18, sizeHint.height())); + return sizeHint.boundedTo(QSize(fm.horizontalAdvance(QChar('M')) * 18, sizeHint.height())); } void TabBar::reloadTab() { if (QAction *action = qobject_cast(sender())) { int index = action->data().toInt(); - emit reloadTab(index); + Q_EMIT reloadTab(index); } } @@ -345,3 +345,12 @@ void TabBar::updateVisibility() updateViewToolBarAction(); } +void TabBar::wheelEvent(QWheelEvent *event) +{ + int index = currentIndex(); + if (index != -1) { + index += event->angleDelta().y() > 0 ? -1 : 1; + if (index >= 0 && index < count()) + setCurrentIndex(index); + } +} diff --git a/src/tabbar.h b/src/tabbar.h index 8438c60a..4336b46a 100644 --- a/src/tabbar.h +++ b/src/tabbar.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,7 +63,7 @@ #ifndef TABBAR_H #define TABBAR_H -#include +#include #include "tabwidget.h" @@ -74,7 +74,7 @@ class TabBar : public QTabBar { Q_OBJECT -signals: +Q_SIGNALS: void newTab(); void cloneTab(int index); void closeTab(int index); @@ -84,12 +84,13 @@ class TabBar : public QTabBar void loadUrl(const QUrl &url, TabWidget::OpenUrlIn tab); public: - TabBar(QWidget *parent = 0); + TabBar(QWidget *parent = nullptr); bool showTabBarWhenOneTab() const; void setShowTabBarWhenOneTab(bool enabled); QAction *viewTabBarAction() const; QTabBar::ButtonPosition freeSide(); + void wheelEvent(QWheelEvent *event) override; protected: void mouseDoubleClickEvent(QMouseEvent *event); @@ -102,7 +103,7 @@ class TabBar : public QTabBar void tabInserted(int position); void tabRemoved(int position); -private slots: +private Q_SLOTS: void selectTabAction(); void cloneTab(); void closeTab(); @@ -122,7 +123,7 @@ private slots: }; -#include +#include /* Shortcut to switch directly to a tab by index diff --git a/src/tabwidget.cpp b/src/tabwidget.cpp index 008c49e6..874a7744 100644 --- a/src/tabwidget.cpp +++ b/src/tabwidget.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -7,7 +7,7 @@ * (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 iQ_WS_X11mplied warranty of + * 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. * @@ -59,6 +59,32 @@ ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ +/* +** The URL validation regex is licensed under the following license: +** +** Copyright (c) 2010-2018 Diego Perini (http://www.iport.it) +** +** Permission is hereby granted, free of charge, to any person +** obtaining a copy of this software and associated documentation +** files (the "Software"), to deal in the Software without +** restriction, including without limitation the rights to use, +** copy, modify, merge, publish, distribute, sublicense, and/or sell +** copies of the Software, and to permit persons to whom the +** Software is furnished to do so, subject to the following +** conditions: +** +** The above copyright notice and this permission notice shall be +** included in all copies or substantial portions of the Software. +** +** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +** OTHER DEALINGS IN THE SOFTWARE. +*/ #include "tabwidget.h" @@ -68,8 +94,9 @@ #include "bookmarksmodel.h" #include "browserapplication.h" #include "browsermainwindow.h" +#include "downloadmanager.h" #include "history.h" -#include "historycompleter.h" +#include "locationcompleter.h" #include "historymanager.h" #include "locationbar.h" #include "opensearchengine.h" @@ -80,38 +107,43 @@ #include "webpage.h" #include "webview.h" #include "webviewsearch.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include "savepagedialog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include //#define USERMODIFIEDBEHAVIOR_DEBUG -TabWidget::TabWidget(QWidget *parent) +TabWidget::TabWidget(QWidget *parent, QWebEngineProfile *profile) : QTabWidget(parent) - , m_recentlyClosedTabsAction(0) - , m_newTabAction(0) - , m_closeTabAction(0) - , m_bookmarkTabsAction(0) - , m_nextTabAction(0) - , m_previousTabAction(0) - , m_recentlyClosedTabsMenu(0) - , m_lineEditCompleter(0) - , m_locationBars(0) + , m_recentlyClosedTabsAction(nullptr) + , m_newTabAction(nullptr) + , m_closeTabAction(nullptr) + , m_bookmarkTabsAction(nullptr) + , m_nextTabAction(nullptr) + , m_previousTabAction(nullptr) + , m_recentlyClosedTabsMenu(nullptr) + , m_lineEditCompleter(nullptr) + , m_locationBars(nullptr) , m_tabBar(new TabBar(this)) - , addTabButton(0) - , closeTabButton(0) + , addTabButton(nullptr) + , closeTabButton(nullptr) + , m_profile(profile) { setElideMode(Qt::ElideRight); @@ -120,21 +152,20 @@ TabWidget::TabWidget(QWidget *parent) connect(m_tabBar, SIGNAL(loadUrl(const QUrl&, TabWidget::OpenUrlIn)), this, SLOT(loadUrl(const QUrl&, TabWidget::OpenUrlIn))); - connect(m_tabBar, SIGNAL(newTab()), this, SLOT(newTab())); + connect(m_tabBar, &TabBar::newTab, this, &TabWidget::newTab); connect(m_tabBar, SIGNAL(closeTab(int)), this, SLOT(closeTab(int))); connect(m_tabBar, SIGNAL(cloneTab(int)), this, SLOT(cloneTab(int))); connect(m_tabBar, SIGNAL(closeOtherTabs(int)), this, SLOT(closeOtherTabs(int))); connect(m_tabBar, SIGNAL(reloadTab(int)), this, SLOT(reloadTab(int))); - connect(m_tabBar, SIGNAL(reloadAllTabs()), this, SLOT(reloadAllTabs())); + connect(m_tabBar, &TabBar::reloadAllTabs, this, &TabWidget::reloadAllTabs); setTabBar(m_tabBar); setDocumentMode(true); - connect(m_tabBar, SIGNAL(tabMoved(int, int)), - this, SLOT(moveTab(int, int))); + connect(m_tabBar, &TabBar::tabMoved, this, &TabWidget::moveTab); // Actions m_newTabAction = new QAction(this); m_newTabAction->setShortcuts(QKeySequence::AddTab); - connect(m_newTabAction, SIGNAL(triggered()), this, SLOT(newTab())); + connect(m_newTabAction, &QAction::triggered, this, &TabWidget::newTab); m_closeTabAction = new QAction(this); m_closeTabAction->setShortcuts(QKeySequence::Close); @@ -142,10 +173,10 @@ TabWidget::TabWidget(QWidget *parent) #if !defined(Q_WS_X11) m_closeTabAction->setIconVisibleInMenu(false); #endif - connect(m_closeTabAction, SIGNAL(triggered()), this, SLOT(closeTab())); + connect(m_closeTabAction, &QAction::triggered, this, &TabWidget::closeTab); m_bookmarkTabsAction = new QAction(this); - connect(m_bookmarkTabsAction, SIGNAL(triggered()), this, SLOT(bookmarkTabs())); + connect(m_bookmarkTabsAction, &QAction::triggered, this, &TabWidget::bookmarkTabs); m_newTabAction->setIcon(QIcon(QLatin1String(":graphics/addtab.png"))); #if !defined(Q_WS_X11) @@ -153,18 +184,18 @@ TabWidget::TabWidget(QWidget *parent) #endif m_nextTabAction = new QAction(this); - connect(m_nextTabAction, SIGNAL(triggered()), this, SLOT(nextTab())); + connect(m_nextTabAction, &QAction::triggered, this, &TabWidget::nextTab); m_previousTabAction = new QAction(this); - connect(m_previousTabAction, SIGNAL(triggered()), this, SLOT(previousTab())); + connect(m_previousTabAction, &QAction::triggered, this, &TabWidget::previousTab); #if defined(Q_WS_X11) m_previousTabAction->setIcon(QIcon::fromTheme(QLatin1String("go-previous"))); m_nextTabAction->setIcon(QIcon::fromTheme(QLatin1String("go-next"))); #endif m_recentlyClosedTabsMenu = new QMenu(this); - connect(m_recentlyClosedTabsMenu, SIGNAL(aboutToShow()), - this, SLOT(aboutToShowRecentTabsMenu())); + connect(m_recentlyClosedTabsMenu, &QMenu::aboutToShow, + this, &TabWidget::aboutToShowRecentTabsMenu); connect(m_recentlyClosedTabsMenu, SIGNAL(triggered(QAction *)), this, SLOT(aboutToShowRecentTriggeredAction(QAction *))); m_recentlyClosedTabsAction = new QAction(this); @@ -176,24 +207,41 @@ TabWidget::TabWidget(QWidget *parent) addTabButton->setDefaultAction(m_newTabAction); addTabButton->setAutoRaise(true); addTabButton->setToolButtonStyle(Qt::ToolButtonIconOnly); - addTabButton->setIconSize(QSize(50, 100)); #endif - connect(m_tabBar, SIGNAL(tabCloseRequested(int)), - this, SLOT(closeTab(int))); + connect(m_tabBar, &TabBar::tabCloseRequested, + this, &TabWidget::closeTab); connect(this, SIGNAL(currentChanged(int)), this, SLOT(currentChanged(int))); + connect(this, &TabWidget::currentChanged, + this, &TabWidget::currentChanged); + m_locationBars = new QStackedWidget(this); - connect(BrowserApplication::historyManager(), SIGNAL(historyCleared()), - this, SLOT(historyCleared())); + connect(BrowserApplication::historyManager(), &HistoryManager::historyCleared, + this, &TabWidget::historyCleared); // Initialize Actions' labels retranslate(); loadSettings(); + initScripts(); } +void TabWidget::initScripts() { + QFile file(":qwebchannel.js"); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + qDebug() << "Couldn't read qwebchannel.js, window.external and window.endorphin won't be available"; + QTextStream out(&file); + + QWebEngineScript script; + script.setName("WebChannel loader"); + script.setInjectionPoint(QWebEngineScript::DocumentCreation); + script.setRunsOnSubFrames(true); + script.setWorldId(QWebEngineScript::MainWorld); + script.setSourceCode(out.readAll()); + m_profile->scripts()->insert(script); +} void TabWidget::historyCleared() { m_recentlyClosedTabs.clear(); @@ -233,7 +281,7 @@ void TabWidget::moveTab(int fromIndex, int toIndex) m_locationBars->insertWidget(toIndex, lineEdit); } -void TabWidget::addWebAction(QAction *action, QWebPage::WebAction webAction) +void TabWidget::addWebAction(QAction *action, QWebEnginePage::WebAction webAction) { if (!action) return; @@ -250,29 +298,29 @@ void TabWidget::currentChanged(int index) WebView *oldWebView = this->webView(m_locationBars->currentIndex()); if (oldWebView) { - disconnect(oldWebView, SIGNAL(statusBarMessage(const QString&)), - this, SIGNAL(showStatusBarMessage(const QString&))); - disconnect(oldWebView->page(), SIGNAL(linkHovered(const QString&, const QString&, const QString&)), - this, SIGNAL(linkHovered(const QString&))); - disconnect(oldWebView, SIGNAL(loadProgress(int)), - this, SIGNAL(loadProgress(int))); + disconnect(oldWebView->page(), &WebPage::linkHovered, + this, &TabWidget::linkHovered); + disconnect(oldWebView, &WebView::loadProgress, + this, &TabWidget::loadProgress); + disconnect(oldWebView->page()->profile(), &QWebEngineProfile::downloadRequested, + this, &TabWidget::downloadRequested); } - connect(webView, SIGNAL(statusBarMessage(const QString&)), - this, SIGNAL(showStatusBarMessage(const QString&))); - connect(webView->page(), SIGNAL(linkHovered(const QString&, const QString&, const QString&)), - this, SIGNAL(linkHovered(const QString&))); - connect(webView, SIGNAL(loadProgress(int)), - this, SIGNAL(loadProgress(int))); + connect(webView->page(), &WebPage::linkHovered, + this, &TabWidget::linkHovered); + connect(webView, &WebView::loadProgress, + this, &TabWidget::loadProgress); + connect(webView->page()->profile(), &QWebEngineProfile::downloadRequested, + this, &TabWidget::downloadRequested); for (int i = 0; i < m_actions.count(); ++i) { WebActionMapper *mapper = m_actions[i]; mapper->updateCurrent(webView->page()); } - emit setCurrentTitle(webView->title()); + Q_EMIT setCurrentTitle(webView->title()); m_locationBars->setCurrentIndex(index); - emit loadProgress(webView->progress()); - emit showStatusBarMessage(webView->lastStatusBarText()); + Q_EMIT loadProgress(webView->progress()); + Q_EMIT showStatusBarMessage(webView->lastStatusBarText()); if (webView->url().isEmpty() && webView->hasFocus()) { m_locationBars->currentWidget()->setFocus(); } else if (!webView->url().isEmpty()) { @@ -336,7 +384,7 @@ WebView *TabWidget::webView(int index) const if (WebViewWithSearch *webViewWithSearch = qobject_cast(widget)) { return webViewWithSearch->m_webView; } - return 0; + return nullptr; } WebViewSearch *TabWidget::webViewSearch(int index) const @@ -345,7 +393,7 @@ WebViewSearch *TabWidget::webViewSearch(int index) const if (WebViewWithSearch *webViewWithSearch = qobject_cast(widget)) { return webViewWithSearch->m_webViewSearch; } - return 0; + return nullptr; } int TabWidget::webViewIndex(WebView *webView) const @@ -370,13 +418,16 @@ WebView *TabWidget::makeNewTab(bool makeCurrent) // line edit LocationBar *locationBar = new LocationBar; if (!m_lineEditCompleter) { - HistoryCompletionModel *completionModel = new HistoryCompletionModel(this); + LocationCompletionModel *completionModel = new LocationCompletionModel(this); completionModel->setSourceModel(BrowserApplication::historyManager()->historyFilterModel()); - m_lineEditCompleter = new HistoryCompleter(completionModel, this); + m_lineEditCompleter = new LocationCompleter(completionModel, this); connect(m_lineEditCompleter, SIGNAL(activated(const QString &)), this, SLOT(loadString(const QString &))); // Should this be in Qt by default? QAbstractItemView *popup = m_lineEditCompleter->popup(); + popup->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + popup->verticalScrollBar()->hide(); + popup->verticalScrollBar()->resize(0, 0); QListView *listView = qobject_cast(popup); if (listView) { // Urls are always LeftToRight @@ -385,7 +436,7 @@ WebView *TabWidget::makeNewTab(bool makeCurrent) } } locationBar->setCompleter(m_lineEditCompleter); - connect(locationBar, SIGNAL(returnPressed()), this, SLOT(lineEditReturnPressed())); + connect(locationBar, &LocationBar::returnPressed, this, &TabWidget::lineEditReturnPressed); m_locationBars->addWidget(locationBar); m_locationBars->setSizePolicy(locationBar->sizePolicy()); @@ -395,33 +446,21 @@ WebView *TabWidget::makeNewTab(bool makeCurrent) // webview WebView *webView = new WebView; + webView->setPage(new WebPage(m_profile, webView)); locationBar->setWebView(webView); - connect(webView, SIGNAL(loadStarted()), - this, SLOT(webViewLoadStarted())); - connect(webView, SIGNAL(loadProgress(int)), - this, SLOT(webViewLoadProgress(int))); + connect(webView, &WebView::loadStarted, this, &TabWidget::webViewLoadStarted); + connect(webView, &WebView::loadProgress, this, &TabWidget::webViewLoadProgress); connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(webViewLoadFinished(bool))); - connect(webView, SIGNAL(iconChanged()), - this, SLOT(webViewIconChanged())); - connect(webView, SIGNAL(titleChanged(const QString &)), - this, SLOT(webViewTitleChanged(const QString &))); - connect(webView, SIGNAL(urlChanged(const QUrl &)), - this, SLOT(webViewUrlChanged(const QUrl &))); + connect(webView, &WebView::iconChanged, this, &TabWidget::webViewIconChanged); + connect(webView, &WebView::titleChanged, this, &TabWidget::webViewTitleChanged); + connect(webView, &WebView::urlChanged, this, &TabWidget::webViewUrlChanged); connect(webView, SIGNAL(search(const QUrl&, TabWidget::OpenUrlIn)), this, SLOT(loadUrl(const QUrl&, TabWidget::OpenUrlIn))); - connect(webView->page(), SIGNAL(windowCloseRequested()), - this, SLOT(windowCloseRequested())); - connect(webView->page(), SIGNAL(printRequested(QWebFrame *)), - this, SIGNAL(printRequested(QWebFrame *))); - connect(webView->page(), SIGNAL(geometryChangeRequested(const QRect &)), - this, SLOT(geometryChangeRequestedCheck(const QRect &))); - connect(webView->page(), SIGNAL(menuBarVisibilityChangeRequested(bool)), - this, SLOT(menuBarVisibilityChangeRequestedCheck(bool))); - connect(webView->page(), SIGNAL(statusBarVisibilityChangeRequested(bool)), - this, SLOT(statusBarVisibilityChangeRequestedCheck(bool))); - connect(webView->page(), SIGNAL(toolBarVisibilityChangeRequested(bool)), - this, SLOT(toolBarVisibilityChangeRequestedCheck(bool))); + connect(webView->page(), &WebPage::windowCloseRequested, this, &TabWidget::windowCloseRequested); + connect(webView->page(), &WebPage::printRequested, this, &TabWidget::printRequested); + connect(webView->page(), &WebPage::geometryChangeRequested, this, &TabWidget::geometryChangeRequestedCheck); + connect(webView, &WebView::devToolsRequested, this, &TabWidget::devToolsRequested); WebViewWithSearch *webViewWithSearch = new WebViewWithSearch(webView, this); addTab(webViewWithSearch, tr("Untitled")); @@ -436,32 +475,14 @@ WebView *TabWidget::makeNewTab(bool makeCurrent) if (count() == 1) currentChanged(currentIndex()); - emit tabsChanged(); + Q_EMIT tabsChanged(); return webView; } void TabWidget::geometryChangeRequestedCheck(const QRect &geometry) { if (count() == 1) - emit geometryChangeRequested(geometry); -} - -void TabWidget::menuBarVisibilityChangeRequestedCheck(bool visible) -{ - if (count() == 1) - emit menuBarVisibilityChangeRequested(visible); -} - -void TabWidget::statusBarVisibilityChangeRequestedCheck(bool visible) -{ - if (count() == 1) - emit statusBarVisibilityChangeRequested(visible); -} - -void TabWidget::toolBarVisibilityChangeRequestedCheck(bool visible) -{ - if (count() == 1) - emit toolBarVisibilityChangeRequested(visible); + Q_EMIT geometryChangeRequested(geometry); } void TabWidget::reloadAllTabs() @@ -558,8 +579,17 @@ void TabWidget::closeTab(int index) bool hasFocus = false; WebView *tab = webView(index); + hasFocus = tab->hasFocus(); + + if (m_profile == QWebEngineProfile::defaultProfile()) { + m_recentlyClosedTabsAction->setEnabled(true); + m_recentlyClosedTabs.prepend(tab->url()); + if (m_recentlyClosedTabs.size() >= TabWidget::m_recentlyClosedTabsSize) + m_recentlyClosedTabs.removeLast(); + } if (tab && !tab->url().isEmpty()) { + /* if (tab->isModified()) { QMessageBox closeConfirmation(tab); closeConfirmation.setWindowFlags(Qt::Sheet); @@ -573,6 +603,7 @@ void TabWidget::closeTab(int index) if (closeConfirmation.exec() == QMessageBox::No) return; } + */ hasFocus = tab->hasFocus(); m_recentlyClosedTabsAction->setEnabled(true); @@ -590,32 +621,60 @@ void TabWidget::closeTab(int index) QWidget *webViewWithSearch = widget(index); removeTab(index); - webViewWithSearch->setParent(0); + webViewWithSearch->setParent(nullptr); webViewWithSearch->deleteLater(); - emit tabsChanged(); + Q_EMIT tabsChanged(); if (hasFocus && count() > 0 && currentWebView()) currentWebView()->setFocus(); if (count() == 0) - emit lastTabClosed(); + Q_EMIT lastTabClosed(); +} + +void TabWidget::setProfile(QWebEngineProfile *profile) +{ + m_profile = profile; + for (int i = 0; i < count(); ++i) { + QWidget *tabWidget = widget(i); + if (WebView *tab = qobject_cast(tabWidget)) { + WebPage* webPage = new WebPage(m_profile, tab); + setupPage(webPage); + webPage->load(tab->page()->url()); + tab->setPage(webPage); + } + } +} + +void TabWidget::setupPage(QWebEnginePage* page) +{ + connect(page, &QWebEnginePage::windowCloseRequested, + this, &TabWidget::windowCloseRequested); + connect(page, &QWebEnginePage::geometryChangeRequested, + this, &TabWidget::geometryChangeRequested); + + // webview actions + for (int i = 0; i < m_actions.count(); ++i) { + WebActionMapper *mapper = m_actions[i]; + mapper->addChild(page->action(mapper->webAction())); + } } QLabel *TabWidget::animationLabel(int index, bool addMovie) { if (-1 == index) - return 0; + return nullptr; QTabBar::ButtonPosition side = m_tabBar->freeSide(); QLabel *loadingAnimation = qobject_cast(m_tabBar->tabButton(index, side)); if (!loadingAnimation) { loadingAnimation = new QLabel(this); } if (addMovie && !loadingAnimation->movie()) { - QMovie *movie = new QMovie(QLatin1String(":graphics/loading.gif"), QByteArray(), loadingAnimation); + QMovie *movie = new QMovie(QStringLiteral(":graphics/loading.gif"), QByteArray(), loadingAnimation); movie->setSpeed(50); loadingAnimation->setMovie(movie); movie->start(); } - m_tabBar->setTabButton(index, side, 0); + m_tabBar->setTabButton(index, side, nullptr); m_tabBar->setTabButton(index, side, loadingAnimation); return loadingAnimation; } @@ -633,7 +692,7 @@ void TabWidget::webViewLoadStarted() if (index != currentIndex()) return; - emit showStatusBarMessage(tr("Loading...")); + Q_EMIT showStatusBarMessage(tr("Loading...")); } void TabWidget::webViewLoadProgress(int progress) @@ -642,13 +701,14 @@ void TabWidget::webViewLoadProgress(int progress) int index = webViewIndex(webView); if (index != currentIndex() - || index < 0) + || index < 0) return; - double totalBytes = (double) webView->webPage()->totalBytes() / 1024; + //double totalBytes = (double) webView->webPage()->totalBytes() / 1024; - QString message = tr("Loading %1% (%2 %3)...").arg(progress).arg(totalBytes, 0, 'f', 2).arg(QLatin1String("kB")); - emit showStatusBarMessage(message); + //QString message = tr("Loading %1% (%2 %3)...").arg(progress).arg(totalBytes, 0, 'f', 2).arg(QStringLiteral("kB")); + QString message = tr("Loading ..."); + Q_EMIT showStatusBarMessage(message); } void TabWidget::webViewLoadFinished(bool ok) @@ -672,9 +732,9 @@ void TabWidget::webViewLoadFinished(bool ok) return; if (ok) - emit showStatusBarMessage(tr("Finished loading")); + Q_EMIT showStatusBarMessage(tr("Finished loading")); else - emit showStatusBarMessage(tr("Failed to load")); + Q_EMIT showStatusBarMessage(tr("Failed to load")); } void TabWidget::webViewIconChanged() @@ -687,7 +747,7 @@ void TabWidget::webViewIconChanged() QLabel *label = animationLabel(index, false); QMovie *movie = label->movie(); delete movie; - label->setMovie(0); + label->setMovie(nullptr); label->setPixmap(icon.pixmap(16, 16)); #endif } @@ -702,11 +762,11 @@ void TabWidget::webViewTitleChanged(const QString &title) QString tabTitle = title; if (title.isEmpty()) tabTitle = QString::fromUtf8(webView->url().toEncoded()); - tabTitle.replace(QLatin1Char('&'), QLatin1String("&&")); + tabTitle.replace(QChar('&'), QStringLiteral("&&")); setTabText(index, tabTitle); setTabToolTip(index, tabTitle); if (currentIndex() == index) - emit setCurrentTitle(title); + Q_EMIT setCurrentTitle(title); BrowserApplication::historyManager()->updateHistoryEntry(webView->url(), title); } @@ -714,10 +774,13 @@ void TabWidget::webViewUrlChanged(const QUrl &url) { WebView *webView = qobject_cast(sender()); int index = webViewIndex(webView); - if (-1 == index) - return; - m_tabBar->setTabData(index, url); - emit tabsChanged(); + if (-1 != index) { + m_tabBar->setTabData(index, url); + HistoryManager *manager = BrowserApplication::historyManager(); + if (url.isValid()) + manager->addHistoryEntry(url.toString()); + } + Q_EMIT tabsChanged(); } void TabWidget::openLastTab() @@ -807,9 +870,9 @@ QUrl TabWidget::guessUrlFromString(const QString &string) url = QUrl::fromUserInput(string); - if (url.scheme() == QLatin1String("about") - && url.path() == QLatin1String("home")) - url = QUrl(QLatin1String("qrc:/startpage.html")); + if (url.scheme() == QStringLiteral("about") + && url.path() == QStringLiteral("home")) + url = QUrl(QStringLiteral("endorphin://startpage")); // QUrl::isValid() is too much tolerant. // We actually want to check if the url conforms to the RFC, which QUrl::isValid() doesn't state. @@ -817,13 +880,13 @@ QUrl TabWidget::guessUrlFromString(const QString &string) return url; QSettings settings; - settings.beginGroup(QLatin1String("urlloading")); - bool search = settings.value(QLatin1String("searchEngineFallback"), false).toBool(); + settings.beginGroup(QStringLiteral("urlloading")); + bool search = settings.value(QStringLiteral("searchEngineFallback"), true).toBool(); if (search) { url = ToolbarSearch::openSearchManager()->currentEngine()->searchUrl(string.trimmed()); } else { - QString urlString = QLatin1String("http://") + string.trimmed(); + QString urlString = QStringLiteral("http://") + string.trimmed(); url = QUrl::fromEncoded(urlString.toUtf8(), QUrl::TolerantMode); } @@ -850,14 +913,14 @@ void TabWidget::loadSettings() } QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - bool newTabButtonInRightCorner = settings.value(QLatin1String("newTabButtonInRightCorner"), true).toBool(); + settings.beginGroup(QStringLiteral("tabs")); + bool newTabButtonInRightCorner = settings.value(QStringLiteral("newTabButtonInRightCorner"), true).toBool(); #ifndef Q_WS_MAC setCornerWidget(addTabButton, newTabButtonInRightCorner ? Qt::TopRightCorner : Qt::TopLeftCorner); addTabButton->show(); #endif - bool oneCloseButton = settings.value(QLatin1String("oneCloseButton"), false).toBool(); + bool oneCloseButton = settings.value(QStringLiteral("oneCloseButton"), false).toBool(); if (oneCloseButton) { if (!closeTabButton) { closeTabButton = new QToolButton(this); @@ -868,7 +931,7 @@ void TabWidget::loadSettings() setCornerWidget(closeTabButton, newTabButtonInRightCorner ? Qt::TopLeftCorner : Qt::TopRightCorner); closeTabButton->setVisible(oneCloseButton); } else { - setCornerWidget(0, newTabButtonInRightCorner ? Qt::TopLeftCorner : Qt::TopRightCorner); + setCornerWidget(nullptr, newTabButtonInRightCorner ? Qt::TopLeftCorner : Qt::TopRightCorner); } m_tabBar->setTabsClosable(!oneCloseButton); } @@ -891,8 +954,8 @@ TabWidget::OpenUrlIn TabWidget::modifyWithUserBehavior(OpenUrlIn tab) { tab = NewWindow; } else { QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - bool select = settings.value(QLatin1String("selectNewTabs"), false).toBool(); + settings.beginGroup(QStringLiteral("tabs")); + bool select = settings.value(QStringLiteral("selectNewTabs"), false).toBool(); if (modifiers & Qt::ShiftModifier) tab = !select ? NewSelectedTab : NewNotSelectedTab; else @@ -902,7 +965,7 @@ TabWidget::OpenUrlIn TabWidget::modifyWithUserBehavior(OpenUrlIn tab) { #ifdef USERMODIFIEDBEHAVIOR_DEBUG qDebug() << __FUNCTION__ << "end" << modifiers << buttons << tab; #endif - BrowserApplication::instance()->setEventKeyboardModifiers(0); + BrowserApplication::instance()->setEventKeyboardModifiers(Qt::NoModifier); BrowserApplication::instance()->setEventMouseButtons(Qt::NoButton); return tab; } @@ -933,45 +996,45 @@ void TabWidget::loadUrl(const QUrl &url, OpenUrlIn tab, const QString &title) */ WebView *TabWidget::getView(OpenUrlIn tab, WebView *currentView) { - WebView *webView = 0; + WebView *webView = nullptr; switch (tab) { - case NewWindow: { + case NewWindow: { #ifdef USERMODIFIEDBEHAVIOR_DEBUG - qDebug() << __FUNCTION__ << "NewWindow"; + qDebug() << __FUNCTION__ << "NewWindow"; #endif - BrowserMainWindow *newMainWindow = BrowserApplication::instance()->newMainWindow(); - webView = newMainWindow->currentTab(); - webView->setFocus(); - break; - } + BrowserMainWindow *newMainWindow = BrowserApplication::instance()->newMainWindow(); + webView = newMainWindow->currentTab(); + webView->setFocus(); + break; + } - case NewSelectedTab: { + case NewSelectedTab: { #ifdef USERMODIFIEDBEHAVIOR_DEBUG - qDebug() << __FUNCTION__ << "NewSelectedTab"; + qDebug() << __FUNCTION__ << "NewSelectedTab"; #endif - webView = makeNewTab(true); - webView->setFocus(); - break; - } + webView = makeNewTab(true); + webView->setFocus(); + break; + } - case NewNotSelectedTab: { + case NewNotSelectedTab: { #ifdef USERMODIFIEDBEHAVIOR_DEBUG - qDebug() << __FUNCTION__ << "NewNotSelectedTab"; + qDebug() << __FUNCTION__ << "NewNotSelectedTab"; #endif - webView = makeNewTab(false); - break; - } + webView = makeNewTab(false); + break; + } - case CurrentTab: - default: + case CurrentTab: + default: #ifdef USERMODIFIEDBEHAVIOR_DEBUG - qDebug() << __FUNCTION__ << "CurrentTab"; + qDebug() << __FUNCTION__ << "CurrentTab"; #endif - webView = currentView; - if (!webView) - return 0; - webView->setFocus(); - break; + webView = currentView; + if (!webView) + return nullptr; + webView->setFocus(); + break; } return webView; } @@ -1075,3 +1138,19 @@ void TabWidget::createTab(const QByteArray &historyState, TabWidget::OpenUrlIn t } } +void TabWidget::downloadRequested(QWebEngineDownloadItem *download) +{ + if (download->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat) { + QString file = QDir::cleanPath(download->downloadDirectory() + QDir::separator() + download->downloadFileName()); + SavePageDialog dlg(this, download->savePageFormat(), file); + if (dlg.exec() != SavePageDialog::Accepted) + return; + download->setSavePageFormat(dlg.pageFormat()); + QFileInfo *info = new QFileInfo(dlg.filePath()); + download->setDownloadFileName(info->fileName()); + download->setDownloadDirectory(info->absolutePath()); + } + + BrowserApplication::downloadManager()->download(download); + download->accept(); +} diff --git a/src/tabwidget.h b/src/tabwidget.h index 644d23be..5e0b506a 100644 --- a/src/tabwidget.h +++ b/src/tabwidget.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -65,8 +65,8 @@ #include -#include -#include +#include +#include QT_BEGIN_NAMESPACE class QCompleter; @@ -82,7 +82,7 @@ class WebView; class WebActionMapper; class WebViewSearch; class QToolButton; - +class QWebEngineDownloadItem; /*! TabWidget that contains WebViews and a stack widget of associated line edits. @@ -93,7 +93,7 @@ class TabWidget : public QTabWidget { Q_OBJECT -signals: +Q_SIGNALS: // tab widget signals void tabsChanged(); void lastTabClosed(); @@ -104,10 +104,8 @@ class TabWidget : public QTabWidget void linkHovered(const QString &link); void loadProgress(int progress); void geometryChangeRequested(const QRect &geometry); - void menuBarVisibilityChangeRequested(bool visible); - void statusBarVisibilityChangeRequested(bool visible); - void toolBarVisibilityChangeRequested(bool visible); - void printRequested(QWebFrame *frame); + void printRequested(); + void devToolsRequested(QWebEnginePage *source); public: enum OpenUrlIn { @@ -119,12 +117,14 @@ class TabWidget : public QTabWidget NewTab = NewNotSelectedTab }; - TabWidget(QWidget *parent = 0); + TabWidget(QWidget *parent = nullptr, QWebEngineProfile *profile = QWebEngineProfile::defaultProfile()); void loadSettings(); - TabBar *tabBar() { return m_tabBar; } + TabBar *tabBar() { + return m_tabBar; + } void clear(); - void addWebAction(QAction *action, QWebPage::WebAction webAction); + void addWebAction(QAction *action, QWebEnginePage::WebAction webAction); QAction *newTabAction() const; QAction *closeTabAction() const; @@ -148,10 +148,15 @@ class TabWidget : public QTabWidget static OpenUrlIn modifyWithUserBehavior(OpenUrlIn tab); WebView *getView(OpenUrlIn tab, WebView *currentView); + void setProfile(QWebEngineProfile *profile); + + void initScripts(); + QWebEngineProfile* profile(); + protected: void changeEvent(QEvent *event); -public slots: +public Q_SLOTS: void loadString(const QString &string, OpenUrlIn tab = CurrentTab); void loadUrlFromUser(const QUrl &url, const QString &title = QString()); void loadUrl(const QUrl &url, TabWidget::OpenUrlIn tab = CurrentTab, const QString &title = QString()); @@ -166,7 +171,7 @@ public slots: void previousTab(); void bookmarkTabs(); -private slots: +private Q_SLOTS: void currentChanged(int index); void openLastTab(); void aboutToShowRecentTabsMenu(); @@ -181,12 +186,12 @@ private slots: void windowCloseRequested(); void moveTab(int fromIndex, int toIndex); void geometryChangeRequestedCheck(const QRect &geometry); - void menuBarVisibilityChangeRequestedCheck(bool visible); - void statusBarVisibilityChangeRequestedCheck(bool visible); - void toolBarVisibilityChangeRequestedCheck(bool visible); void historyCleared(); + void downloadRequested(QWebEngineDownloadItem *download); private: + void setupPage(QWebEnginePage* page); + static QUrl guessUrlFromString(const QString &url); QLabel *animationLabel(int index, bool addMovie); void retranslate(); @@ -209,6 +214,8 @@ private slots: TabBar *m_tabBar; QToolButton *addTabButton; QToolButton *closeTabButton; + + QWebEngineProfile *m_profile; }; #endif // TABWIDGET_H diff --git a/src/toolbarsearch.cpp b/src/toolbarsearch.cpp index d105ada5..84638f45 100644 --- a/src/toolbarsearch.cpp +++ b/src/toolbarsearch.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -64,9 +64,7 @@ #include "toolbarsearch.h" #include "autosaver.h" -#include "browserapplication.h" #include "browsermainwindow.h" -#include "networkaccessmanager.h" #include "opensearchengine.h" #include "opensearchengineaction.h" #include "opensearchmanager.h" @@ -74,17 +72,18 @@ #include "webpage.h" #include "webview.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -OpenSearchManager *ToolbarSearch::s_openSearchManager = 0; +OpenSearchManager *ToolbarSearch::s_openSearchManager = nullptr; /* ToolbarSearch is a search widget that also contains a small history @@ -96,10 +95,10 @@ ToolbarSearch::ToolbarSearch(QWidget *parent) , m_autosaver(new AutoSaver(this)) , m_maxSavedSearches(10) , m_model(new QStandardItemModel(this)) - , m_suggestionsItem(0) - , m_recentSearchesItem(0) - , m_suggestTimer(0) - , m_completer(0) + , m_suggestionsItem(nullptr) + , m_recentSearchesItem(nullptr) + , m_suggestTimer(nullptr) + , m_completer(nullptr) { connect(openSearchManager(), SIGNAL(currentEngineChanged()), this, SLOT(currentEngineChanged())); @@ -193,20 +192,20 @@ ToolbarSearch::~ToolbarSearch() void ToolbarSearch::save() { QSettings settings; - settings.beginGroup(QLatin1String("toolbarsearch")); - settings.setValue(QLatin1String("recentSearches"), m_recentSearches); - settings.setValue(QLatin1String("maximumSaved"), m_maxSavedSearches); + settings.beginGroup(QStringLiteral("toolbarsearch")); + settings.setValue(QStringLiteral("recentSearches"), m_recentSearches); + settings.setValue(QStringLiteral("maximumSaved"), m_maxSavedSearches); settings.endGroup(); } void ToolbarSearch::load() { QSettings settings; - settings.beginGroup(QLatin1String("toolbarsearch")); - m_recentSearches = settings.value(QLatin1String("recentSearches")).toStringList(); - m_maxSavedSearches = settings.value(QLatin1String("maximumSaved"), m_maxSavedSearches).toInt(); + settings.beginGroup(QStringLiteral("toolbarsearch")); + m_recentSearches = settings.value(QStringLiteral("recentSearches")).toStringList(); + m_maxSavedSearches = settings.value(QStringLiteral("maximumSaved"), m_maxSavedSearches).toInt(); - m_suggestionsEnabled = settings.value(QLatin1String("useSuggestions"), true).toBool(); + m_suggestionsEnabled = settings.value(QStringLiteral("useSuggestions"), true).toBool(); if (m_suggestionsEnabled) { connect(this, SIGNAL(textEdited(const QString &)), this, SLOT(textEdited(const QString &))); @@ -239,7 +238,7 @@ void ToolbarSearch::getSuggestions() return; if (!engine->networkAccessManager()) - engine->setNetworkAccessManager(BrowserApplication::networkAccessManager()); + engine->setNetworkAccessManager(new QNetworkAccessManager()); engine->requestSuggestions(text()); } @@ -253,24 +252,24 @@ void ToolbarSearch::searchNow() QString searchText = text(); - QWebSettings *globalSettings = QWebSettings::globalSettings(); - if (!globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled)) { - QStringList newList = m_recentSearches; - if (newList.contains(searchText)) - newList.removeAt(newList.indexOf(searchText)); - newList.prepend(searchText); - if (newList.size() >= m_maxSavedSearches) - newList.removeLast(); - - m_recentSearches = newList; - m_autosaver->changeOccurred(); - } +// QWebEngineSettings *globalSettings = QWebEngineSettings::globalSettings(); +// if (!globalSettings->testAttribute(QWebEngineSettings::PrivateBrowsingEnabled)) { + QStringList newList = m_recentSearches; + if (newList.contains(searchText)) + newList.removeAt(newList.indexOf(searchText)); + newList.prepend(searchText); + if (newList.size() >= m_maxSavedSearches) + newList.removeLast(); + + m_recentSearches = newList; + m_autosaver->changeOccurred(); +// } QUrl searchUrl = engine->searchUrl(searchText); TabWidget::OpenUrlIn tab = TabWidget::CurrentTab; if (qApp->keyboardModifiers() == Qt::AltModifier) tab = TabWidget::NewSelectedTab; - emit search(searchUrl, tab); + Q_EMIT search(searchUrl, tab); } void ToolbarSearch::newSuggestions(const QStringList &suggestions) @@ -316,33 +315,33 @@ void ToolbarSearch::showEnginesMenu() action->setChecked(true); } } + /* + WebView *webView = BrowserMainWindow::parentWindow(this)->currentTab(); + QList engines = webView->webPage()->linkedResources(QStringLiteral("search")); - WebView *webView = BrowserMainWindow::parentWindow(this)->currentTab(); - QList engines = webView->webPage()->linkedResources(QLatin1String("search")); - - if (!engines.empty()) - menu.addSeparator(); + if (!engines.empty()) + menu.addSeparator(); - for (int i = 0; i < engines.count(); ++i) { - WebPageLinkedResource engine = engines.at(i); + for (int i = 0; i < engines.count(); ++i) { + WebPageLinkedResource engine = engines.at(i); - QUrl url = engine.href; - QString title = engine.title; - QString mimetype = engine.type; + QUrl url = engine.href; + QString title = engine.title; + QString mimetype = engine.type; - if (mimetype != QLatin1String("application/opensearchdescription+xml")) - continue; - if (url.isEmpty()) - continue; + if (mimetype != QStringLiteral("application/opensearchdescription+xml")) + continue; + if (url.isEmpty()) + continue; - if (title.isEmpty()) - title = webView->title().isEmpty() ? url.host() : webView->title(); - - QAction *action = menu.addAction(tr("Add '%1'").arg(title), this, SLOT(addEngineFromUrl())); - action->setData(url); - action->setIcon(webView->icon()); - } + if (title.isEmpty()) + title = webView->title().isEmpty() ? url.host() : webView->title(); + QAction *action = menu.addAction(tr("Add '%1'").arg(title), this, SLOT(addEngineFromUrl())); + action->setData(url); + action->setIcon(webView->icon()); + } + */ menu.addSeparator(); if (BrowserMainWindow *window = BrowserMainWindow::parentWindow(this)) menu.addAction(window->searchManagerAction()); @@ -377,10 +376,10 @@ void ToolbarSearch::addEngineFromUrl() void ToolbarSearch::setupList() { if (m_suggestions.isEmpty() - || (m_model->rowCount() > 0 - && m_model->item(0) != m_suggestionsItem)) { + || (m_model->rowCount() > 0 + && m_model->item(0) != m_suggestionsItem)) { m_model->clear(); - m_suggestionsItem = 0; + m_suggestionsItem = nullptr; } else { m_model->removeRows(1, m_model->rowCount() - 1); } diff --git a/src/toolbarsearch.h b/src/toolbarsearch.h index c4d74bce..bc24d75c 100644 --- a/src/toolbarsearch.h +++ b/src/toolbarsearch.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -79,19 +79,19 @@ class ToolbarSearch : public SearchLineEdit { Q_OBJECT -signals: +Q_SIGNALS: void search(const QUrl &url, TabWidget::OpenUrlIn tab); public: - ToolbarSearch(QWidget *parent = 0); + ToolbarSearch(QWidget *parent = nullptr); ~ToolbarSearch(); static OpenSearchManager *openSearchManager(); -public slots: +public Q_SLOTS: void clear(); void searchNow(); -private slots: +private Q_SLOTS: void currentEngineChanged(); void save(); void textEdited(const QString &); diff --git a/src/useragent/useragent.pri b/src/useragent/useragent.pri deleted file mode 100644 index 01eb3d92..00000000 --- a/src/useragent/useragent.pri +++ /dev/null @@ -1,12 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - useragentmenu.h - -SOURCES += \ - useragentmenu.cpp - -RESOURCES += \ - useragents.qrc diff --git a/src/useragent/useragentmenu.cpp b/src/useragent/useragentmenu.cpp index d6fc497b..9f6dd3c4 100644 --- a/src/useragent/useragentmenu.cpp +++ b/src/useragent/useragentmenu.cpp @@ -1,6 +1,6 @@ /** * Copyright (c) 2010, William C. Witt - * Copyright (c) 2010, Aaron Dewes + * Copyright (c) 2010, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,12 +31,12 @@ #include "webpage.h" -#include -#include -#include +#include +#include +#include #include -#include +#include UserAgentMenu::UserAgentMenu(QWidget *parent) : QMenu(parent) @@ -54,11 +54,11 @@ void UserAgentMenu::populateMenu() defaultUserAgent->setCheckable(true); connect(defaultUserAgent, SIGNAL(triggered()), this, SLOT(switchToDefaultUserAgent())); QSettings settings; - defaultUserAgent->setChecked(settings.value(QLatin1String("userAgent")).toString().isEmpty()); + defaultUserAgent->setChecked(settings.value(QStringLiteral("userAgent")).toString().isEmpty()); addAction(defaultUserAgent); // Add default extra user agents - addActionsFromFile(QLatin1String(":/useragents/useragents.xml")); + addActionsFromFile(QStringLiteral(":/useragents/useragents.xml")); // Add other action addSeparator(); @@ -70,7 +70,7 @@ void UserAgentMenu::populateMenu() bool usingCustomUserAgent = true; QActionGroup *actionGroup = new QActionGroup(this); - foreach (QAction *action, actions()) { + Q_FOREACH (QAction *action, actions()) { actionGroup->addAction(action); if (action->isChecked()) { usingCustomUserAgent = false; @@ -89,14 +89,14 @@ void UserAgentMenu::addActionsFromFile(const QString &fileName) QXmlStreamReader xml(&file); while (!xml.atEnd()) { xml.readNext(); - if (xml.isStartElement() && xml.name() == QLatin1String("separator")) { + if (xml.isStartElement() && xml.name() == QStringLiteral("separator")) { addSeparator(); continue; } - if (xml.isStartElement() && xml.name() == QLatin1String("useragent")) { + if (xml.isStartElement() && xml.name() == QStringLiteral("useragent")) { QXmlStreamAttributes attributes = xml.attributes(); - QString title = attributes.value(QLatin1String("description")).toString(); - QString userAgent = attributes.value(QLatin1String("useragent")).toString(); + QString title = attributes.value(QStringLiteral("description")).toString(); + QString userAgent = attributes.value(QStringLiteral("useragent")).toString(); QAction *action = new QAction(this); action->setText(title); @@ -110,7 +110,7 @@ void UserAgentMenu::addActionsFromFile(const QString &fileName) } if (xml.hasError()) { qDebug() << "Error reading custom user agents" << xml.errorString(); - // ... do error handling + // ... do error handling } } @@ -130,8 +130,8 @@ void UserAgentMenu::switchToOtherUserAgent() { bool ok; QString text = QInputDialog::getText(this, tr("Custom user agent"), - tr("User agent:"), QLineEdit::Normal, - WebPage::userAgent(), &ok, Qt::Sheet); + tr("User agent:"), QLineEdit::Normal, + WebPage::userAgent(), &ok, Qt::Sheet); if (ok) { WebPage::setUserAgent(text); } diff --git a/src/useragent/useragentmenu.h b/src/useragent/useragentmenu.h index b5ddfc3a..4c0694fd 100644 --- a/src/useragent/useragentmenu.h +++ b/src/useragent/useragentmenu.h @@ -1,6 +1,6 @@ /** * Copyright (c) 2010, William C. Witt - * Copyright (c) 2010, Aaron Dewes + * Copyright (c) 2010, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,16 +30,16 @@ #ifndef USERAGENTMENU_H #define USERAGENTMENU_H -#include +#include class UserAgentMenu : public QMenu { Q_OBJECT public: - UserAgentMenu(QWidget *parent = 0); + UserAgentMenu(QWidget *parent = nullptr); -private slots: +private Q_SLOTS: void populateMenu(); void changeUserAgent(); void switchToDefaultUserAgent(); diff --git a/src/utils/editlistview.cpp b/src/utils/editlistview.cpp index 68749d18..6ce5c0a6 100644 --- a/src/utils/editlistview.cpp +++ b/src/utils/editlistview.cpp @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -28,7 +28,8 @@ #include "editlistview.h" -#include +#include +#include EditListView::EditListView(QWidget *parent) : QListView(parent) diff --git a/src/utils/editlistview.h b/src/utils/editlistview.h index e719ea1f..8bee8c6f 100644 --- a/src/utils/editlistview.h +++ b/src/utils/editlistview.h @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,17 +29,17 @@ #ifndef EDITLISTVIEW_H #define EDITLISTVIEW_H -#include +#include class EditListView : public QListView { Q_OBJECT public: - EditListView(QWidget *parent = 0); + EditListView(QWidget *parent = nullptr); void keyPressEvent(QKeyEvent *event); -public slots: +public Q_SLOTS: void removeSelected(); void removeAll(); }; diff --git a/src/utils/edittableview.cpp b/src/utils/edittableview.cpp index b2438ded..876441a8 100644 --- a/src/utils/edittableview.cpp +++ b/src/utils/edittableview.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008, Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright (c) 2009, Jakub Wieczorek * * Redistribution and use in source and binary forms, with or without @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,7 +29,8 @@ #include "edittableview.h" -#include +#include +#include EditTableView::EditTableView(QWidget *parent) : QTableView(parent) diff --git a/src/utils/edittableview.h b/src/utils/edittableview.h index 9ec1a0b0..bb2a144c 100644 --- a/src/utils/edittableview.h +++ b/src/utils/edittableview.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008, Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright (c) 2009, Jakub Wieczorek * * Redistribution and use in source and binary forms, with or without @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -30,17 +30,17 @@ #ifndef EDITTABLEVIEW_H #define EDITTABLEVIEW_H -#include +#include class EditTableView : public QTableView { Q_OBJECT public: - EditTableView(QWidget *parent = 0); + EditTableView(QWidget *parent = nullptr); void keyPressEvent(QKeyEvent *event); -public slots: +public Q_SLOTS: void removeSelected(); void removeAll(); }; diff --git a/src/utils/edittreeview.cpp b/src/utils/edittreeview.cpp index d5377146..4afb1eb1 100644 --- a/src/utils/edittreeview.cpp +++ b/src/utils/edittreeview.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008, Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright (c) 2009, Jakub Wieczorek * * Redistribution and use in source and binary forms, with or without @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,7 +29,8 @@ #include "edittreeview.h" -#include +#include +#include EditTreeView::EditTreeView(QWidget *parent) : QTreeView(parent) diff --git a/src/utils/edittreeview.h b/src/utils/edittreeview.h index 5a037545..5b617e6c 100644 --- a/src/utils/edittreeview.h +++ b/src/utils/edittreeview.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008, Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright (c) 2009, Jakub Wieczorek * * Redistribution and use in source and binary forms, with or without @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -37,10 +37,10 @@ class EditTreeView : public QTreeView Q_OBJECT public: - EditTreeView(QWidget *parent = 0); + EditTreeView(QWidget *parent = nullptr); void keyPressEvent(QKeyEvent *event); -public slots: +public Q_SLOTS: void removeSelected(); void removeAll(); diff --git a/src/utils/explorerstyle.cpp b/src/utils/explorerstyle.cpp index 9bd1fd3f..6d4f11be 100644 --- a/src/utils/explorerstyle.cpp +++ b/src/utils/explorerstyle.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -41,10 +41,10 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include @@ -56,7 +56,7 @@ typedef HANDLE (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList); typedef HRESULT (WINAPI *PtrDrawThemeBackground)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, - const RECT *pRect, OPTIONAL const RECT *pClipRect); + const RECT *pRect, OPTIONAL const RECT *pClipRect); typedef bool (WINAPI *PtrIsAppThemed)(); static PtrDrawThemeBackground pDrawThemeBackground = 0; @@ -81,7 +81,7 @@ ExplorerStyle::ExplorerStyle() : QWindowsVistaStyle() { #ifdef Q_OS_WIN - QLibrary themeLib(QLatin1String("uxtheme")); + QLibrary themeLib(QStringLiteral("uxtheme")); themeLib.load(); if (themeLib.isLoaded()) { //resolve uxtheme functions pIsAppThemed = (PtrIsAppThemed)themeLib.resolve("IsAppThemed"); @@ -95,8 +95,8 @@ ExplorerStyle::ExplorerStyle() void drawRebarBackground(const QRect &rect, QPainter *painter) { if (rect.isEmpty()) return; - QString cacheKey = QLatin1String("q_rebar_") + QString::number(rect.size().width()) - + QLatin1Char('x') + QString::number(rect.size().height()); + QString cacheKey = QStringLiteral("q_rebar_") + QString::number(rect.size().width()) + + QChar('x') + QString::number(rect.size().height()); QPixmap pixmap; if (!QPixmapCache::find(cacheKey, pixmap)) { pixmap = QPixmap(rect.size()); @@ -116,7 +116,7 @@ void drawRebarBackground(const QRect &rect, QPainter *painter) { } void ExplorerStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const + QPainter *painter, const QWidget *widget) const { QRect rect = option->rect; switch (element) { @@ -135,7 +135,7 @@ void ExplorerStyle::drawPrimitive(PrimitiveElement element, const QStyleOption * //We need the bounding rect for all toolbars QList toolbars = qFindChildren(window); - foreach (const QToolBar *tb, toolbars) { + Q_FOREACH (const QToolBar *tb, toolbars) { if (!tb->isFloating()) { QRect rect(tb->mapToParent(tb->rect().topLeft()), tb->rect().size()); if (window->toolBarArea(const_cast(tb)) == Qt::TopToolBarArea) @@ -179,7 +179,7 @@ void ExplorerStyle::drawPrimitive(PrimitiveElement element, const QStyleOption * } void ExplorerStyle::drawControl(ControlElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const + QPainter *painter, const QWidget *widget) const { QColor shadow = option->palette.dark().color(); shadow.setAlpha(120); @@ -233,7 +233,7 @@ void ExplorerStyle::drawControl(ControlElement element, const QStyleOption *opti adjustedToolBar.palette.setBrush(QPalette::All, QPalette::Dark, shadow); QWindowsXPStyle::drawControl(element, &adjustedToolBar, painter, widget); } - break; + break; } //fall through default: @@ -246,7 +246,7 @@ void ExplorerStyle::drawControl(ControlElement element, const QStyleOption *opti } void ExplorerStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, - QPainter *painter, const QWidget *widget) const + QPainter *painter, const QWidget *widget) const { if (vista) QWindowsVistaStyle::drawComplexControl(control, option, painter, widget); @@ -255,7 +255,7 @@ void ExplorerStyle::drawComplexControl(ComplexControl control, const QStyleOptio } QSize ExplorerStyle::sizeFromContents(ContentsType type, const QStyleOption *option, - const QSize &size, const QWidget *widget) const + const QSize &size, const QWidget *widget) const { if (vista) return QWindowsVistaStyle::sizeFromContents(type, option, size, widget); @@ -272,7 +272,7 @@ QRect ExplorerStyle::subElementRect(SubElement element, const QStyleOption *opti } QRect ExplorerStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option, - SubControl subControl, const QWidget *widget) const + SubControl subControl, const QWidget *widget) const { if (vista) return QWindowsVistaStyle::subControlRect(control, option, subControl, widget); @@ -281,7 +281,7 @@ QRect ExplorerStyle::subControlRect(ComplexControl control, const QStyleOptionCo } QStyle::SubControl ExplorerStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, - const QPoint &pos, const QWidget *widget) const + const QPoint &pos, const QWidget *widget) const { if (vista) return QWindowsVistaStyle::hitTestComplexControl(control, option, pos, widget); diff --git a/src/utils/explorerstyle.h b/src/utils/explorerstyle.h index f3a51452..fc633ae0 100644 --- a/src/utils/explorerstyle.h +++ b/src/utils/explorerstyle.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -58,7 +58,7 @@ class ExplorerStyle : public QWindowsVistaStyle QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *widget) const; SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, - const QPoint &pos, const QWidget *widget = 0) const; + const QPoint &pos, const QWidget *widget = 0) const; QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget = 0) const; int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const; diff --git a/src/utils/languagemanager.cpp b/src/utils/languagemanager.cpp index eeaf5c3b..03e37626 100644 --- a/src/utils/languagemanager.cpp +++ b/src/utils/languagemanager.cpp @@ -1,6 +1,6 @@ /* * Copyright 2008-2009 Diego Iastrubni, elcuco, at, kde.org - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,25 +29,25 @@ #include "languagemanager.h" -#include -#include +#include +#include #include #include -#include +#include #include -#include +#include #include -#include +#include #include -#include +#include // #define LANGUAGEMANAGER_DEBUG LanguageManager::LanguageManager(QObject *parent) : QObject(parent) - , m_sysTranslator(0) - , m_appTranslator(0) + , m_sysTranslator(nullptr) + , m_appTranslator(nullptr) , m_loaded(false) { #ifdef LANGUAGEMANAGER_DEBUG @@ -89,8 +89,8 @@ bool LanguageManager::isLanguageAvailable(const QString &language) const // optimization so we don't have to load all the languages if (!m_loaded) { - foreach (const QString &dir, m_localeDirectories) { - QString file = dir + QLatin1Char('/') + language + QLatin1String(".qm"); + Q_FOREACH (const QString &dir, m_localeDirectories) { + QString file = dir + QChar('/') + language + QStringLiteral(".qm"); if (QFile::exists(file)) return true; } @@ -110,9 +110,9 @@ QString LanguageManager::convertStringToLanguageFile(const QString &string) cons #endif loadAvailableLanguages(); if (m_languages.contains(string)) - return string; + return string; QLocale locale(string); - QString fallback = locale.name().split(QLatin1Char('_')).value(0); + QString fallback = locale.name().split(QChar('_')).value(0); if (!string.contains(fallback)) return QString(); #ifdef LANGUAGEMANAGER_DEBUG @@ -122,8 +122,8 @@ QString LanguageManager::convertStringToLanguageFile(const QString &string) cons return fallback; // See if any language file matches the country - foreach (const QString &language, m_languages) { - QString country = QLocale(language).name().split(QLatin1Char('_')).value(0); + Q_FOREACH (const QString &language, m_languages) { + QString country = QLocale(language).name().split(QChar('_')).value(0); if (country == fallback) return language; } @@ -137,21 +137,20 @@ bool LanguageManager::setCurrentLanguage(const QString &language) qDebug() << "LanguageManager::" << __FUNCTION__ << language; #endif if (m_currentLanguage == language - || !isLanguageAvailable(language)) + || !isLanguageAvailable(language)) return false; m_currentLanguage = language; QSettings settings; - settings.beginGroup(QLatin1String("LanguageManager")); - settings.setValue(QLatin1String("language"), m_currentLanguage); + settings.beginGroup(QStringLiteral("LanguageManager")); + settings.setValue(QStringLiteral("language"), m_currentLanguage); if (m_currentLanguage.isEmpty()) { delete m_appTranslator; delete m_sysTranslator; - m_appTranslator = 0; - m_sysTranslator = 0; - emit languageChanged(currentLanguage()); + m_appTranslator = nullptr; + m_sysTranslator = nullptr; return true; } @@ -159,17 +158,17 @@ bool LanguageManager::setCurrentLanguage(const QString &language) QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); QString languageFile = convertStringToLanguageFile(m_currentLanguage); bool loaded = false; - foreach (const QString &dir, m_localeDirectories) { + Q_FOREACH (const QString &dir, m_localeDirectories) { loaded = newAppTranslator->load(languageFile, dir); if (loaded) break; } QTranslator *newSysTranslator = new QTranslator(this); - QString translatorFileName = QLatin1String("qt_") + languageFile; + QString translatorFileName = QStringLiteral("qt_") + languageFile; if (!newSysTranslator->load(translatorFileName, resourceDir)) { delete newSysTranslator; - newSysTranslator = 0; + newSysTranslator = nullptr; } if (!loaded) { @@ -189,7 +188,6 @@ bool LanguageManager::setCurrentLanguage(const QString &language) qApp->installTranslator(newSysTranslator); m_appTranslator = newAppTranslator; m_sysTranslator = newSysTranslator; - emit languageChanged(currentLanguage()); return true; } @@ -209,9 +207,9 @@ void LanguageManager::loadLanguageFromSettings() #endif QSettings settings; - settings.beginGroup(QLatin1String("LanguageManager")); - if (settings.contains(QLatin1String("language"))) { - QString selectedLanguage = settings.value(QLatin1String("language")).toString(); + settings.beginGroup(QStringLiteral("LanguageManager")); + if (settings.contains(QStringLiteral("language"))) { + QString selectedLanguage = settings.value(QStringLiteral("language")).toString(); #ifdef LANGUAGEMANAGER_DEBUG qDebug() << "LanguageManager::" << __FUNCTION__ << "Loading language from settings" << selectedLanguage; #endif @@ -221,7 +219,7 @@ void LanguageManager::loadLanguageFromSettings() #ifdef LANGUAGEMANAGER_DEBUG qDebug() << "LanguageManager::" << __FUNCTION__ << "Failed to load language"; #endif - settings.remove(QLatin1String("language")); + settings.remove(QStringLiteral("language")); } } else if (!currentLanguage().isEmpty()) { setCurrentLanguage(currentLanguage()); @@ -236,9 +234,9 @@ void LanguageManager::chooseNewLanguage() loadAvailableLanguages(); if (m_languages.isEmpty()) { QMessageBox messageBox; - QLatin1String separator = QLatin1String(", "); + QString separator = QStringLiteral(", "); messageBox.setText(tr("No translation files are installed at %1.") - .arg(m_localeDirectories.join(separator))); + .arg(m_localeDirectories.join(separator))); messageBox.setStandardButtons(QMessageBox::Ok); messageBox.exec(); return; @@ -247,29 +245,29 @@ void LanguageManager::chooseNewLanguage() QStringList items; int defaultItem = -1; QString current = currentLanguage(); - foreach (const QString &name, m_languages) { + Q_FOREACH (const QString &name, m_languages) { QLocale locale(name); - QString string = QString(QLatin1String("%1, %2 (%3) %4")) - .arg(QLocale::languageToString(locale.language())) - .arg(QLocale::countryToString(locale.country())) - .arg(name) - // this is for pretty RTL support - .arg(QChar(0x200E)); // LRM = 0x200E + QString string = QString(QStringLiteral("%1, %2 (%3) %4")) + .arg(QLocale::languageToString(locale.language()), + QLocale::countryToString(locale.country()), + name, + // this is for pretty RTL support + QChar(0x200E)); // LRM = 0x200E if (name == current) defaultItem = items.count(); items << string; } - items << QLatin1String("English (en_US)"); + items << QStringLiteral("English (en_US)"); if (defaultItem == -1) defaultItem = items.count() - 1; bool ok; - QString item = QInputDialog::getItem(0, - tr("Choose language"), - tr("

    You can run with a different language than
    " - "the operating system default.

    " - "

    Please choose the language which should be used

    "), - items, defaultItem, false, &ok); + QString item = QInputDialog::getItem(nullptr, + tr("Choose language"), + tr("

    You can run with a different language than
    " + "the operating system default.

    " + "

    Please choose the language which should be used

    "), + items, defaultItem, false, &ok); if (!ok) return; @@ -289,11 +287,11 @@ void LanguageManager::loadAvailableLanguages() const qDebug() << "LanguageManager::" << __FUNCTION__; #endif - foreach (const QString &dir, m_localeDirectories) { + Q_FOREACH (const QString &dir, m_localeDirectories) { QDirIterator it(dir); while (it.hasNext()) { QString fileName = it.next(); - if (!fileName.endsWith(QLatin1String(".qm"))) + if (!fileName.endsWith(QStringLiteral(".qm"))) continue; const QFileInfo info = it.fileInfo(); QString language = info.completeBaseName(); diff --git a/src/utils/languagemanager.h b/src/utils/languagemanager.h index 76ad3b16..a93d372c 100644 --- a/src/utils/languagemanager.h +++ b/src/utils/languagemanager.h @@ -1,6 +1,6 @@ /* * Copyright 2008-2009 Diego Iastrubni, elcuco, at, kde.org - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +10,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -30,7 +30,7 @@ #ifndef LANGUAGEMANAGER_H #define LANGUAGEMANAGER_H -#include +#include #include @@ -38,13 +38,13 @@ class QTranslator; class LanguageManager : public QObject { Q_OBJECT - Q_PROPERTY(QString currentLanguage READ currentLanguage WRITE setCurrentLanguage) + Q_PROPERTY(QString currentLanguage READ currentLanguage WRITE setCurrentLanguage NOTIFY languageChanged) -signals: +Q_SIGNALS: void languageChanged(const QString &language); public: - LanguageManager(QObject *parent = 0); + LanguageManager(QObject *parent = nullptr); void addLocaleDirectory(const QString &directory); QStringList localeDirectories() const; @@ -55,7 +55,7 @@ class LanguageManager : public QObject QStringList languages() const; bool isLanguageAvailable(const QString &language) const; -public slots: +public Q_SLOTS: void loadLanguageFromSettings(); void chooseNewLanguage(); diff --git a/src/utils/lineedit.cpp b/src/utils/lineedit.cpp index b98183d4..9a11f110 100644 --- a/src/utils/lineedit.cpp +++ b/src/utils/lineedit.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008 - 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,12 +29,12 @@ #include "lineedit.h" #include "lineedit_p.h" -#include -#include +#include +#include #include -#include +#include -#include +#include SideWidget::SideWidget(QWidget *parent) : QWidget(parent) @@ -44,24 +44,24 @@ SideWidget::SideWidget(QWidget *parent) bool SideWidget::event(QEvent *event) { if (event->type() == QEvent::LayoutRequest) - emit sizeHintChanged(); + Q_EMIT sizeHintChanged(); return QWidget::event(event); } LineEdit::LineEdit(QWidget *parent) : QLineEdit(parent) - , m_leftLayout(0) - , m_rightLayout(0) + , m_leftLayout(nullptr) + , m_rightLayout(nullptr) { init(); } LineEdit::LineEdit(const QString &contents, QWidget *parent) : QLineEdit(contents, parent) - , m_leftWidget(0) - , m_rightWidget(0) - , m_leftLayout(0) - , m_rightLayout(0) + , m_leftWidget(nullptr) + , m_rightWidget(nullptr) + , m_leftLayout(nullptr) + , m_rightLayout(nullptr) { init(); } diff --git a/src/utils/lineedit.h b/src/utils/lineedit.h index c42a4d87..a2581da9 100644 --- a/src/utils/lineedit.h +++ b/src/utils/lineedit.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008 - 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,7 +29,7 @@ #ifndef LINEEDIT_H #define LINEEDIT_H -#include +#include class QHBoxLayout; @@ -47,7 +47,10 @@ class SideWidget; class LineEdit : public QLineEdit { Q_OBJECT - Q_PROPERTY(QString inactiveText READ inactiveText WRITE setInactiveText) + Q_PROPERTY(QString inactiveText READ inactiveText WRITE setInactiveText NOTIFY inactiveTextChanged) + +Q_SIGNALS: + void inactiveTextChanged(); public: enum WidgetPosition { @@ -55,8 +58,8 @@ class LineEdit : public QLineEdit RightSide }; - LineEdit(QWidget *parent = 0); - LineEdit(const QString &contents, QWidget *parent = 0); + LineEdit(QWidget *parent = nullptr); + LineEdit(const QString &contents, QWidget *parent = nullptr); void addWidget(QWidget *widget, WidgetPosition position); void removeWidget(QWidget *widget); @@ -72,7 +75,7 @@ class LineEdit : public QLineEdit void resizeEvent(QResizeEvent *event); bool event(QEvent *event); -protected slots: +protected Q_SLOTS: void updateTextMargins(); private: diff --git a/src/utils/lineedit_p.h b/src/utils/lineedit_p.h index a03a5ba2..e5ed2fe5 100644 --- a/src/utils/lineedit_p.h +++ b/src/utils/lineedit_p.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008 - 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,17 +29,17 @@ #ifndef LINEEDIT_P_H #define LINEEDIT_P_H -#include +#include class SideWidget : public QWidget { Q_OBJECT -signals: +Q_SIGNALS: void sizeHintChanged(); public: - SideWidget(QWidget *parent = 0); + SideWidget(QWidget *parent = nullptr); protected: bool event(QEvent *event); diff --git a/src/utils/networkaccessmanagerproxy.cpp b/src/utils/networkaccessmanagerproxy.cpp deleted file mode 100644 index d44caaa4..00000000 --- a/src/utils/networkaccessmanagerproxy.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "networkaccessmanagerproxy.h" -#include "networkaccessmanagerproxy_p.h" - -#include "webpageproxy.h" - -#include -#include - -NetworkAccessManagerProxy *NetworkAccessManagerProxy::m_primaryManager = 0; - -/* - NetworkAccessManagerProxy inserts a pointer to the QWebPage in the - QNetworkRequest before passing it on. - */ -NetworkAccessManagerProxy::NetworkAccessManagerProxy(QObject *parent) - : QNetworkAccessManager(parent) - , m_webPage(0) -{ -} - -void NetworkAccessManagerProxy::setWebPage(WebPageProxy *page) -{ - Q_ASSERT(page); - m_webPage = page; -} - -void NetworkAccessManagerProxy::setPrimaryNetworkAccessManager(NetworkAccessManagerProxy *manager) -{ - Q_ASSERT(manager); - m_primaryManager = manager; - setCookieJar(new NetworkCookieJarProxy(this)); - - connect(this, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), - m_primaryManager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*))); - connect(this, SIGNAL(finished(QNetworkReply *)), - m_primaryManager, SIGNAL(finished(QNetworkReply *))); - connect(this, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*)), - m_primaryManager, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*))); -#ifndef QT_NO_OPENSSL - connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList&)), - m_primaryManager, SIGNAL(sslErrors(QNetworkReply*, const QList&))); -#endif -} - -QNetworkReply *NetworkAccessManagerProxy::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) -{ - if (m_primaryManager && m_webPage) { - QNetworkRequest pageRequest = request; - m_webPage->populateNetworkRequest(pageRequest); - return m_primaryManager->createRequest(op, pageRequest, outgoingData); - } - return QNetworkAccessManager::createRequest(op, request, outgoingData); -} - diff --git a/src/utils/networkaccessmanagerproxy.h b/src/utils/networkaccessmanagerproxy.h deleted file mode 100644 index 69afc0de..00000000 --- a/src/utils/networkaccessmanagerproxy.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef NETWORKACCESSMANAGERPROXY_H -#define NETWORKACCESSMANAGERPROXY_H - -#include - -class WebPageProxy; -class NetworkAccessManagerProxy : public QNetworkAccessManager -{ - Q_OBJECT - -public: - NetworkAccessManagerProxy(QObject *parent = 0); - - void setPrimaryNetworkAccessManager(NetworkAccessManagerProxy *primaryManager); - NetworkAccessManagerProxy *primaryNetworkAccessManager() const { return m_primaryManager; } - - void setWebPage(WebPageProxy *page); - WebPageProxy *webPage() const { return m_webPage; }; - -protected: - QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0); - -private: - friend class NetworkCookieJarProxy; - static NetworkAccessManagerProxy *m_primaryManager; - WebPageProxy *m_webPage; - -}; - -#endif // NETWORKACCESSMANAGERPROXY_H - diff --git a/src/utils/networkaccessmanagerproxy_p.h b/src/utils/networkaccessmanagerproxy_p.h deleted file mode 100644 index 8981bfb7..00000000 --- a/src/utils/networkaccessmanagerproxy_p.h +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef NETWORKACCESSMANAGERPROXY_P_H -#define NETWORKACCESSMANAGERPROXY_P_H - -#include -#include - -#include "networkaccessmanagerproxy.h" - -class NetworkCookieJarProxy : public QNetworkCookieJar -{ - Q_OBJECT - -public: - NetworkCookieJarProxy(QObject *parent = 0) - : QNetworkCookieJar(parent) { } - - inline QList cookiesForUrl(const QUrl &url) const - { return NetworkAccessManagerProxy::m_primaryManager->cookieJar()->cookiesForUrl(url); } - - inline bool setCookiesFromUrl(const QList &cookieList, const QUrl &url) - { return NetworkAccessManagerProxy::m_primaryManager->cookieJar()->setCookiesFromUrl(cookieList, url); } - -}; - -#endif // NETWORKACCESSMANAGERPROXY_P_H - diff --git a/src/utils/singleapplication.cpp b/src/utils/singleapplication.cpp index 4b98afee..ee3819d6 100644 --- a/src/utils/singleapplication.cpp +++ b/src/utils/singleapplication.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008-2009, Aaron Dewes + * Copyright (c) 2020, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -28,11 +28,11 @@ #include "singleapplication.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #ifndef Q_OS_WIN #include @@ -44,7 +44,7 @@ SingleApplication::SingleApplication(int &argc, char **argv) : QApplication(argc, argv) - , m_localServer(0) + , m_localServer(nullptr) { } @@ -70,7 +70,7 @@ bool SingleApplication::sendMessage(const QByteArray &message, int waitMsecsForR if (success) { socket.waitForReadyRead(waitMsecsForReply); if (socket.bytesAvailable() > 0) - emit messageReceived(&socket); + Q_EMIT messageReceived(&socket); } return success; } @@ -88,7 +88,7 @@ bool SingleApplication::startSingleServer() if (QAbstractSocket::AddressInUseError == m_localServer->serverError()) { // cleanup from a segfaulted server #ifdef Q_OS_UNIX - QString fullServerName = QDir::tempPath() + QLatin1String("/") + serverName(); + QString fullServerName = QDir::tempPath() + QStringLiteral("/") + serverName(); if (QFile::exists(fullServerName)) QFile::remove(fullServerName); #endif @@ -114,14 +114,14 @@ bool SingleApplication::startSingleServer() if (!success) { delete m_localServer; - m_localServer = 0; + m_localServer = nullptr; } return success; } bool SingleApplication::isRunning() const { - return (0 != m_localServer); + return (nullptr != m_localServer); } void SingleApplication::newConnection() @@ -130,7 +130,7 @@ void SingleApplication::newConnection() if (!socket) return; socket->waitForReadyRead(); - emit messageReceived(socket); + Q_EMIT messageReceived(socket); delete socket; } @@ -139,10 +139,10 @@ QString SingleApplication::serverName() const QString serverName = QCoreApplication::applicationName(); Q_ASSERT(!serverName.isEmpty()); #ifdef Q_WS_QWS - serverName += QLatin1String("_qws"); + serverName += QStringLiteral("_qws"); #endif #ifndef Q_OS_WIN - serverName += QString(QLatin1String("_%1_%2")).arg(getuid()).arg(getgid()); + serverName += QString(QStringLiteral("_%1_%2")).arg(getuid()).arg(getgid()); #else static QString login; if (login.isEmpty()) { diff --git a/src/utils/singleapplication.h b/src/utils/singleapplication.h index 4d9048fd..a6f133f7 100644 --- a/src/utils/singleapplication.h +++ b/src/utils/singleapplication.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2008-2009, Aaron Dewes + * Copyright (c) 2020, Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,7 +29,7 @@ #ifndef SINGLEAPPLICATION_H #define SINGLEAPPLICATION_H -#include +#include /* QApplication subclass that should be used when you only want one @@ -41,7 +41,7 @@ class SingleApplication : public QApplication { Q_OBJECT -signals: +Q_SIGNALS: void messageReceived(QLocalSocket *socket); public: @@ -51,7 +51,7 @@ class SingleApplication : public QApplication bool startSingleServer(); bool isRunning() const; -private slots: +private Q_SLOTS: void newConnection(); private: diff --git a/src/utils/squeezelabel.cpp b/src/utils/squeezelabel.cpp index 196f8d85..32cc08d5 100644 --- a/src/utils/squeezelabel.cpp +++ b/src/utils/squeezelabel.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * diff --git a/src/utils/squeezelabel.h b/src/utils/squeezelabel.h index 3cac3d1f..2e76bcc4 100644 --- a/src/utils/squeezelabel.h +++ b/src/utils/squeezelabel.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,7 +29,7 @@ #ifndef SQUEEZELABEL_H #define SQUEEZELABEL_H -#include +#include /* A label that will squeeze the set text to fit within the size of the @@ -40,7 +40,7 @@ class SqueezeLabel : public QLabel Q_OBJECT public: - SqueezeLabel(QWidget *parent = 0); + SqueezeLabel(QWidget *parent = nullptr); protected: void paintEvent(QPaintEvent *event); diff --git a/src/utils/treesortfilterproxymodel.cpp b/src/utils/treesortfilterproxymodel.cpp index 166a7c53..b5cf9dff 100644 --- a/src/utils/treesortfilterproxymodel.cpp +++ b/src/utils/treesortfilterproxymodel.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * diff --git a/src/utils/treesortfilterproxymodel.h b/src/utils/treesortfilterproxymodel.h index 859ab713..2a8b89b3 100644 --- a/src/utils/treesortfilterproxymodel.h +++ b/src/utils/treesortfilterproxymodel.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2009, Aaron Dewes + * Copyright 2020 Aaron Dewes * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -9,7 +9,7 @@ * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors + * 3. Neither the name of Endorphin nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -29,14 +29,14 @@ #ifndef TREESORTFILTERPROXYMODEL_H #define TREESORTFILTERPROXYMODEL_H -#include +#include class TreeSortFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT public: - TreeSortFilterProxyModel(QObject *parent = 0); + TreeSortFilterProxyModel(QObject *parent = nullptr); protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; diff --git a/src/utils/utils.pri b/src/utils/utils.pri deleted file mode 100644 index d2e54f26..00000000 --- a/src/utils/utils.pri +++ /dev/null @@ -1,35 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -VPATH += $$PWD - -HEADERS += \ - editlistview.h \ - edittableview.h \ - edittreeview.h \ - languagemanager.h \ - lineedit.h \ - lineedit_p.h \ - networkaccessmanagerproxy.h \ - networkaccessmanagerproxy_p.h \ - singleapplication.h \ - squeezelabel.h \ - treesortfilterproxymodel.h \ - webpageproxy.h - -SOURCES += \ - editlistview.cpp \ - edittableview.cpp \ - edittreeview.cpp \ - languagemanager.cpp \ - lineedit.cpp \ - networkaccessmanagerproxy.cpp \ - singleapplication.cpp \ - squeezelabel.cpp \ - treesortfilterproxymodel.cpp \ - webpageproxy.cpp - -win32 { - HEADERS += explorerstyle.h - SOURCES += explorerstyle.cpp - LIBS += -lgdi32 -} diff --git a/src/utils/webpageproxy.cpp b/src/utils/webpageproxy.cpp deleted file mode 100644 index da8b1e64..00000000 --- a/src/utils/webpageproxy.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "webpageproxy.h" - -#include -#include - -#define ATTRIBUTE_ID QNetworkRequest::User + 100 - -WebPageProxy::WebPageProxy(QObject *parent) - : QWebPage(parent) -{ -} - -int WebPageProxy::pageAttributeId() -{ - return ATTRIBUTE_ID; -} - -void WebPageProxy::populateNetworkRequest(QNetworkRequest &request) -{ - QVariant variant = QVariant::fromValue((void *) this); - request.setAttribute((QNetworkRequest::Attribute)(pageAttributeId()), variant); -} - diff --git a/src/utils/webpageproxy.h b/src/utils/webpageproxy.h deleted file mode 100644 index c0e93a47..00000000 --- a/src/utils/webpageproxy.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2009, Aaron Dewes - * - * 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. - * 3. Neither the name of the Aaron Dewes nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. - */ - -#ifndef WEBPAGEPROXY_H -#define WEBPAGEPROXY_H - -#include -#include -#include - -class WebPageProxy : public QWebPage -{ - Q_OBJECT - -public: - WebPageProxy(QObject *parent = 0); - static int pageAttributeId(); - -protected: - friend class NetworkAccessManagerProxy; - virtual void populateNetworkRequest(QNetworkRequest &request); -}; - -#endif // WEBPAGEPROXY_H diff --git a/src/webactionmapper.cpp b/src/webactionmapper.cpp index 8ea6da44..af58d88d 100644 --- a/src/webactionmapper.cpp +++ b/src/webactionmapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -62,11 +62,11 @@ #include "webactionmapper.h" -#include +#include -WebActionMapper::WebActionMapper(QAction *root, QWebPage::WebAction webAction, QObject *parent) +WebActionMapper::WebActionMapper(QAction *root, QWebEnginePage::WebAction webAction, QObject *parent) : QObject(parent) - , m_currentParent(0) + , m_currentParent(nullptr) , m_root(root) , m_webAction(webAction) { @@ -79,12 +79,12 @@ WebActionMapper::WebActionMapper(QAction *root, QWebPage::WebAction webAction, Q void WebActionMapper::rootDestroyed() { - m_root = 0; + m_root = nullptr; } void WebActionMapper::currentDestroyed() { - updateCurrent(0); + updateCurrent(nullptr); } void WebActionMapper::addChild(QAction *action) @@ -94,7 +94,7 @@ void WebActionMapper::addChild(QAction *action) connect(action, SIGNAL(changed()), this, SLOT(childChanged())); } -QWebPage::WebAction WebActionMapper::webAction() const +QWebEnginePage::WebAction WebActionMapper::webAction() const { return m_webAction; } @@ -111,15 +111,15 @@ void WebActionMapper::childChanged() { if (QAction *source = qobject_cast(sender())) { if (m_root - && m_currentParent - && source->parent() == m_currentParent) { + && m_currentParent + && source->parent() == m_currentParent) { m_root->setChecked(source->isChecked()); m_root->setEnabled(source->isEnabled()); } } } -void WebActionMapper::updateCurrent(QWebPage *currentParent) +void WebActionMapper::updateCurrent(QWebEnginePage *currentParent) { if (m_currentParent) disconnect(m_currentParent, SIGNAL(destroyed(QObject *)), diff --git a/src/webactionmapper.h b/src/webactionmapper.h index 9d4b2ed7..bd5cb102 100644 --- a/src/webactionmapper.h +++ b/src/webactionmapper.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,7 +63,7 @@ #ifndef WEBACTIONMAPPER_H #define WEBACTIONMAPPER_H -#include +#include QT_BEGIN_NAMESPACE class QAction; @@ -81,21 +81,21 @@ class WebActionMapper : public QObject Q_OBJECT public: - WebActionMapper(QAction *root, QWebPage::WebAction webAction, QObject *parent); - QWebPage::WebAction webAction() const; + WebActionMapper(QAction *root, QWebEnginePage::WebAction webAction, QObject *parent); + QWebEnginePage::WebAction webAction() const; void addChild(QAction *action); - void updateCurrent(QWebPage *currentParent); + void updateCurrent(QWebEnginePage *currentParent); -private slots: +private Q_SLOTS: void rootTriggered(); void childChanged(); void rootDestroyed(); void currentDestroyed(); private: - QWebPage *m_currentParent; + QWebEnginePage *m_currentParent; QAction *m_root; - QWebPage::WebAction m_webAction; + QWebEnginePage::WebAction m_webAction; }; #endif // WEBACTIONMAPPER_H diff --git a/src/webpage.cpp b/src/webpage.cpp index f9a9432b..344289b5 100644 --- a/src/webpage.cpp +++ b/src/webpage.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020-2021 Aaron Dewes * Copyright 2009 Jakub Wieczorek * * This program is free software; you can redistribute it and/or modify @@ -23,41 +23,32 @@ #include "browserapplication.h" #include "downloadmanager.h" #include "historymanager.h" -#include "networkaccessmanager.h" #include "opensearchengine.h" #include "opensearchmanager.h" #include "tabwidget.h" #include "toolbarsearch.h" -#include "webpluginfactory.h" #include "webview.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include +#include +#include +#include +#include +#include +#include -WebPluginFactory *WebPage::s_webPluginFactory = 0; QString WebPage::s_userAgent; -JavaScriptExternalObject::JavaScriptExternalObject(QObject *parent) - : QObject(parent) -{ -} - -void JavaScriptExternalObject::AddSearchProvider(const QString &url) -{ - ToolbarSearch::openSearchManager()->addEngine(QUrl(url)); -} - Q_DECLARE_METATYPE(OpenSearchEngine*) -JavaScriptEndorphinObject::JavaScriptEndorphinObject(QObject *parent) +JavaScriptEndorphinObject::JavaScriptEndorphinObject(QObject *parent, WebPage *page) : QObject(parent) + , m_page(page) { static const char *translations[] = { QT_TR_NOOP("Welcome to Endorphin!"), @@ -72,6 +63,54 @@ JavaScriptEndorphinObject::JavaScriptEndorphinObject(QObject *parent) qRegisterMetaType("OpenSearchEngine*"); } +void JavaScriptEndorphinObject::addSearchProvider(const QString &url) +{ + ToolbarSearch::openSearchManager()->addEngine(QUrl(url)); +} + +QString JavaScriptEndorphinObject::getSetting(const QString &name, const QString &group) +{ + if (m_page->url().toString() != "qrc:/settings.html") + return nullptr; + QSettings settings; + settings.beginGroup(group); + return settings.value(name).toString(); + settings.endGroup(); +} + +int JavaScriptEndorphinObject::setSetting(const QString &name, const QString &group, const QString &value) +{ + if (m_page->url().toString() != "qrc:/settings.html") + return 1; + QSettings settings; + settings.beginGroup(group); + settings.setValue(name, value); + settings.endGroup(); + return 0; +} + +int JavaScriptEndorphinObject::setSetting(const QString &name, const QString &group, const int &value) +{ + if (m_page->url().toString() != "qrc:/settings.html") + return 1; + QSettings settings; + settings.beginGroup(group); + settings.setValue(name, value); + settings.endGroup(); + return 0; +} + +int JavaScriptEndorphinObject::setSetting(const QString &name, const QString &group, const bool value) +{ + if (m_page->url().toString() != "qrc:/settings.html") + return 1; + QSettings settings; + settings.beginGroup(group); + settings.setValue(name, value); + settings.endGroup(); + return 0; +} + QString JavaScriptEndorphinObject::translate(const QString &string) { QString translatedString = tr(string.toUtf8().constData()); @@ -95,72 +134,33 @@ QString JavaScriptEndorphinObject::searchUrl(const QString &string) const return QString::fromUtf8(ToolbarSearch::openSearchManager()->currentEngine()->searchUrl(string).toEncoded()); } - - -QString JavaScriptEndorphinObject::getSetting(const QString &string) -{ - QSettings settings; - return settings.value(string).toString(); -} - -int JavaScriptEndorphinObject::setSetting(const QString &string, const QString &value) -{ - QSettings settings; - settings.setValue(string, value); - return 0; -} - -int JavaScriptEndorphinObject::setSetting(const QString &string, const int &value) -{ - QSettings settings; - settings.setValue(string, value); - return 0; -} - -WebPage::WebPage(QObject *parent) - : WebPageProxy(parent) +WebPage::WebPage(QWebEngineProfile *profile, QObject *parent) + : QWebEnginePage(profile, parent) , m_openTargetBlankLinksIn(TabWidget::NewWindow) - , m_javaScriptExternalObject(0) - , m_javaScriptEndorphinObject(0) { - setPluginFactory(webPluginFactory()); - NetworkAccessManagerProxy *networkManagerProxy = new NetworkAccessManagerProxy(this); - networkManagerProxy->setWebPage(this); - networkManagerProxy->setPrimaryNetworkAccessManager(BrowserApplication::networkAccessManager()); - setNetworkAccessManager(networkManagerProxy); - connect(this, SIGNAL(unsupportedContent(QNetworkReply *)), - this, SLOT(handleUnsupportedContent(QNetworkReply *))); - connect(this, SIGNAL(frameCreated(QWebFrame *)), - this, SLOT(addExternalBinding(QWebFrame *))); - addExternalBinding(mainFrame()); + QWebChannel *channel = new QWebChannel(this); + channel->registerObject("endorphin", new JavaScriptEndorphinObject(this, this)); + setWebChannel(channel); loadSettings(); } WebPage::~WebPage() { - setNetworkAccessManager(0); -} - -WebPluginFactory *WebPage::webPluginFactory() -{ - if (!s_webPluginFactory) - s_webPluginFactory = new WebPluginFactory(BrowserApplication::instance()); - return s_webPluginFactory; } - +/* QList WebPage::linkedResources(const QString &relation) { QList resources; QUrl baseUrl = mainFrame()->baseUrl(); - QWebElementCollection linkElements = mainFrame()->findAllElements(QLatin1String("html > head > link")); + QWebElementCollection linkElements = mainFrame()->findAllElements(QStringLiteral("html > head > link")); - foreach (const QWebElement &linkElement, linkElements) { - QString rel = linkElement.attribute(QLatin1String("rel")); - QString href = linkElement.attribute(QLatin1String("href")); - QString type = linkElement.attribute(QLatin1String("type")); - QString title = linkElement.attribute(QLatin1String("title")); + Q_FOREACH (const QWebElement &linkElement, linkElements) { + QString rel = linkElement.attribute(QStringLiteral("rel")); + QString href = linkElement.attribute(QStringLiteral("href")); + QString type = linkElement.attribute(QStringLiteral("type")); + QString title = linkElement.attribute(QStringLiteral("title")); if (href.isEmpty() || type.isEmpty()) continue; @@ -178,37 +178,7 @@ QList WebPage::linkedResources(const QString &relation) return resources; } - -void WebPage::populateNetworkRequest(QNetworkRequest &request) -{ - if (request == lastRequest) { - request.setAttribute((QNetworkRequest::Attribute)(pageAttributeId() + 1), lastRequestType); - } - WebPageProxy::populateNetworkRequest(request); -} - -void WebPage::addExternalBinding(QWebFrame *frame) -{ - if (!m_javaScriptExternalObject) - m_javaScriptExternalObject = new JavaScriptExternalObject(this); - - if (frame == 0) { // called from QWebFrame::javaScriptWindowObjectCleared - frame = qobject_cast(sender()); - - if (frame->url().scheme() == QLatin1String("qrc")) { - - if (!m_javaScriptEndorphinObject) - m_javaScriptEndorphinObject = new JavaScriptEndorphinObject(this); - - frame->addToJavaScriptWindowObject(QLatin1String("endorphin"), m_javaScriptEndorphinObject); - } - } else { // called from QWebPage::frameCreated - connect(frame, SIGNAL(javaScriptWindowObjectCleared()), - this, SLOT(addExternalBinding())); - } - frame->addToJavaScriptWindowObject(QLatin1String("external"), m_javaScriptExternalObject); -} - +*/ QString WebPage::userAgent() { return s_userAgent; @@ -221,9 +191,9 @@ void WebPage::setUserAgent(const QString &userAgent) QSettings settings; if (userAgent.isEmpty()) { - settings.remove(QLatin1String("userAgent")); + settings.remove(QStringLiteral("userAgent")); } else { - settings.setValue(QLatin1String("userAgent"), userAgent); + settings.setValue(QStringLiteral("userAgent"), userAgent); } s_userAgent = userAgent; @@ -231,59 +201,65 @@ void WebPage::setUserAgent(const QString &userAgent) QString WebPage::userAgentForUrl(const QUrl &url) const { + if (s_userAgent.isEmpty()) - s_userAgent = QWebPage::userAgentForUrl(url); + //s_userAgent = QWebEnginePage::userAgentForUrl(url); + s_userAgent = ""; return s_userAgent; } +/* bool WebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type) +*/ +bool WebPage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) { - lastRequest = request; - lastRequestType = type; - - QString scheme = request.url().scheme(); - if (scheme == QLatin1String("mailto") - || scheme == QLatin1String("ftp")) { - BrowserApplication::instance()->askDesktopToOpenUrl(request.url()); + /* + lastRequest = request; + lastRequestType = type; + */ + QString scheme = url.scheme(); + if (scheme == QStringLiteral("mailto") + || scheme == QStringLiteral("ftp")) { + BrowserApplication::instance()->askDesktopToOpenUrl(url); return false; } - - if (type == QWebPage::NavigationTypeFormResubmitted) { - QMessageBox::StandardButton button = QMessageBox::warning(view(), tr("Resending POST request"), - tr("In order to display the site, the request along with all the data must be sent once again, " - "which may lead to some unexpected behaviour of the site e.g. the same action might be " - "performed once again. Do you want to continue anyway?"), QMessageBox::Yes | QMessageBox::No); - if (button != QMessageBox::Yes) - return false; - } - - TabWidget::OpenUrlIn openIn = frame ? TabWidget::CurrentTab : TabWidget::NewWindow; + /* + if (type == QWebEnginePage::NavigationTypeFormResubmitted) { + QMessageBox::StandardButton button = QMessageBox::warning(view(), tr("Resending POST request"), + tr("In order to display the site, the request along with all the data must be sent once again, " + "which may lead to some unexpected behaviour of the site e.g. the same action might be " + "performed once again. Do you want to continue anyway?"), QMessageBox::Yes | QMessageBox::No); + if (button != QMessageBox::Yes) + return false; + } + */ + TabWidget::OpenUrlIn openIn = isMainFrame ? TabWidget::CurrentTab : TabWidget::NewWindow; openIn = TabWidget::modifyWithUserBehavior(openIn); // handle the case where we want to do something different then - // what qwebpage would do + // what QWebEnginePage would do if (openIn == TabWidget::NewSelectedTab - || openIn == TabWidget::NewNotSelectedTab - || (frame && openIn == TabWidget::NewWindow)) { + || openIn == TabWidget::NewNotSelectedTab + || (openIn == TabWidget::NewWindow)) { if (WebView *webView = qobject_cast(view())) { TabWidget *tabWidget = webView->tabWidget(); if (tabWidget) { WebView *newView = tabWidget->getView(openIn, webView); - QWebPage *page = 0; + QWebEnginePage *page = nullptr; if (newView) page = newView->page(); - if (page && page->mainFrame()) - page->mainFrame()->load(request); + if (page) + page->load(url); } } return false; } - bool accepted = QWebPage::acceptNavigationRequest(frame, request, type); - if (accepted && frame == mainFrame()) { - m_requestedUrl = request.url(); - emit aboutToLoadUrl(request.url()); + bool accepted = QWebEnginePage::acceptNavigationRequest(url, type, isMainFrame); + if (accepted && isMainFrame) { + m_requestedUrl = url; + Q_EMIT aboutToLoadUrl(url); } return accepted; @@ -292,14 +268,14 @@ bool WebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &r void WebPage::loadSettings() { QSettings settings; - settings.beginGroup(QLatin1String("tabs")); - m_openTargetBlankLinksIn = (TabWidget::OpenUrlIn)settings.value(QLatin1String("openTargetBlankLinksIn"), - TabWidget::NewSelectedTab).toInt(); + settings.beginGroup(QStringLiteral("tabs")); + m_openTargetBlankLinksIn = (TabWidget::OpenUrlIn)settings.value(QStringLiteral("openTargetBlankLinksIn"), + TabWidget::NewSelectedTab).toInt(); settings.endGroup(); - s_userAgent = settings.value(QLatin1String("userAgent")).toString(); + s_userAgent = settings.value(QStringLiteral("userAgent")).toString(); } -QWebPage *WebPage::createWindow(QWebPage::WebWindowType type) +QWebEnginePage *WebPage::createWindow(QWebEnginePage::WebWindowType type) { Q_UNUSED(type); if (WebView *webView = qobject_cast(view())) { @@ -310,123 +286,5 @@ QWebPage *WebPage::createWindow(QWebPage::WebWindowType type) return tabWidget->getView(openIn, webView)->page(); } } - return 0; -} - -QObject *WebPage::createPlugin(const QString &classId, const QUrl &url, - const QStringList ¶mNames, const QStringList ¶mValues) -{ - Q_UNUSED(classId); - Q_UNUSED(url); - Q_UNUSED(paramNames); - Q_UNUSED(paramValues); -#if !defined(QT_NO_UITOOLS) - QUiLoader loader; - return loader.createWidget(classId, view()); -#else - return 0; -#endif -} - -// The chromium guys have documented many examples of incompatibilities that -// different browsers have when they mime sniff. -// http://src.chromium.org/viewvc/chrome/trunk/src/net/base/mime_sniffer.cc -// -// All WebKit ports should share a common set of rules to sniff content. -// By having this here we are yet another browser that has different behavior :( -// But sadly QtWebKit does no sniffing at all so we are forced to do something. -static bool contentSniff(const QByteArray &data) -{ - if (data.contains("url(); - - if (replyUrl.scheme() == QLatin1String("abp")) - return; - - switch (reply->error()) { - case QNetworkReply::NoError: - if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) { - BrowserApplication::downloadManager()->handleUnsupportedContent(reply); - return; - } - break; - case QNetworkReply::ProtocolUnknownError: { - QSettings settings; - settings.beginGroup(QLatin1String("WebView")); - QStringList externalSchemes = settings.value(QLatin1String("externalSchemes")).toStringList(); - if (externalSchemes.contains(replyUrl.scheme())) { - QDesktopServices::openUrl(replyUrl); - return; - } - break; - } - default: - break; - } - - // Find the frame that has the unsupported content - if (replyUrl.isEmpty() || replyUrl != m_requestedUrl) - return; - - QWebFrame *notFoundFrame = mainFrame(); - if (!notFoundFrame) - return; - - if (reply->header(QNetworkRequest::ContentTypeHeader).toString().isEmpty()) { - // do evil - QByteArray data = reply->readAll(); - if (contentSniff(data)) { - notFoundFrame->setHtml(QLatin1String(data), replyUrl); - return; - } - } - - // Generate translated not found error page with an image - QFile notFoundErrorFile(QLatin1String(":/notfound.html")); - if (!notFoundErrorFile.open(QIODevice::ReadOnly)) - return; - QString title = tr("Error loading page: %1").arg(QString::fromUtf8(replyUrl.toEncoded())); - QString html = QLatin1String(notFoundErrorFile.readAll()); - QPixmap pixmap = qApp->style()->standardIcon(QStyle::SP_MessageBoxWarning, 0, view()).pixmap(QSize(32, 32)); - QBuffer imageBuffer; - imageBuffer.open(QBuffer::ReadWrite); - if (pixmap.save(&imageBuffer, "PNG")) { - html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"), - QLatin1String(imageBuffer.buffer().toBase64())); - } - html = html.arg(title, - reply->errorString(), - tr("When connecting to: %1.").arg(QString::fromUtf8(replyUrl.toEncoded())), - tr("Check the address for errors such as ww.example.com instead of www.example.com"), - tr("If the address is correct, try checking the network connection."), - tr("If your computer or network is protected by a firewall or proxy, make sure that the browser is permitted to access the network.")); - notFoundFrame->setHtml(html, replyUrl); - // Don't put error pages to the history. - BrowserApplication::instance()->historyManager()->removeHistoryEntry(replyUrl, notFoundFrame->title()); + return nullptr; } - diff --git a/src/webpage.h b/src/webpage.h index 439fe061..3cbc4e66 100644 --- a/src/webpage.h +++ b/src/webpage.h @@ -1,5 +1,5 @@ /* - * Copyright 2009 Aaron Dewes + * Copyright 2020-2021 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,97 +20,86 @@ #ifndef WEBPAGE_H #define WEBPAGE_H -#include "webpageproxy.h" #include "tabwidget.h" -#include -#include - -class WebPageLinkedResource -{ -public: - QString rel; - QString type; - QUrl href; - QString title; -}; - -class OpenSearchEngine; -class QNetworkReply; -class WebPluginFactory; -// See https://developer.mozilla.org/en/adding_search_engines_from_web_pages -class JavaScriptExternalObject : public QObject -{ - Q_OBJECT - -public: - JavaScriptExternalObject(QObject *parent = 0); - -public slots: - void AddSearchProvider(const QString &url); -}; +#include +#include +#include +class WebPage; class JavaScriptEndorphinObject : public QObject { Q_OBJECT - Q_PROPERTY(QObject *currentEngine READ currentEngine) + Q_PROPERTY(QObject *currentEngine READ currentEngine NOTIFY currentEngineChanged) + +Q_SIGNALS: + void currentEngineChanged(); public: - JavaScriptEndorphinObject(QObject *parent = 0); + JavaScriptEndorphinObject(QObject *parent = nullptr, WebPage *page = nullptr); -public slots: +public Q_SLOTS: QString translate(const QString &string); QObject *currentEngine() const; QString searchUrl(const QString &string) const; - QString getSetting(const QString &string); - int setSetting(const QString &string, const int &value); - int setSetting(const QString &string, const QString &value); + void addSearchProvider(const QString &url); + QString getSetting(const QString &name, const QString &group); + int setSetting(const QString &name, const QString &group, const int &value); + int setSetting(const QString &name, const QString &group, const QString &value); + int setSetting(const QString &name, const QString &group, const bool value); + +private: + WebPage *m_page; +}; +class WebPageLinkedResource +{ +public: + QString rel; + QString type; + QUrl href; + QString title; }; -class WebPage : public WebPageProxy +class OpenSearchEngine; +class QNetworkReply; + +class WebPage : public QWebEnginePage { Q_OBJECT -signals: +Q_SIGNALS: void aboutToLoadUrl(const QUrl &url); public: - WebPage(QObject *parent = 0); + WebPage(QWebEngineProfile *profile, QObject *parent = 0); ~WebPage(); void loadSettings(); - static WebPluginFactory *webPluginFactory(); - QList linkedResources(const QString &relation = QString()); +// QList linkedResources(const QString &relation = QString()); static QString userAgent(); static void setUserAgent(const QString &userAgent); protected: QString userAgentForUrl(const QUrl &url) const; - bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, - NavigationType type); - QObject *createPlugin(const QString &classId, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); - QWebPage *createWindow(QWebPage::WebWindowType type); - -protected slots: - void handleUnsupportedContent(QNetworkReply *reply); - void addExternalBinding(QWebFrame *frame = 0); + /* + bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, + NavigationType type); + */ + bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame); + QWebEnginePage *createWindow(QWebEnginePage::WebWindowType type); protected: - void populateNetworkRequest(QNetworkRequest &request); static QString s_userAgent; - static WebPluginFactory *s_webPluginFactory; TabWidget::OpenUrlIn m_openTargetBlankLinksIn; QUrl m_requestedUrl; - JavaScriptExternalObject *m_javaScriptExternalObject; - JavaScriptEndorphinObject *m_javaScriptEndorphinObject; private: QNetworkRequest lastRequest; - QWebPage::NavigationType lastRequestType; + QWebEnginePage::NavigationType lastRequestType; }; diff --git a/src/webview.cpp b/src/webview.cpp index 605ff533..dc3e94c5 100644 --- a/src/webview.cpp +++ b/src/webview.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Jason A. Donenfeld * Copyright 2008 Ariya Hidayat * @@ -62,86 +62,140 @@ ** ****************************************************************************/ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "webview.h" -#include "adblockdialog.h" -#include "adblockmanager.h" -#include "adblockpage.h" -#include "autofillmanager.h" #include "addbookmarkdialog.h" #include "bookmarksmanager.h" #include "browserapplication.h" #include "browsermainwindow.h" #include "downloadmanager.h" +#include "locationbar.h" #include "opensearchengine.h" #include "opensearchengineaction.h" #include "opensearchmanager.h" #include "toolbarsearch.h" #include "webpage.h" +#include "permissionbar.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include -#include +#include -WebView::WebView(QWidget *parent) - : QWebView(parent) +#include +#include + +WebView::WebView(QWidget* parent) + : QWebEngineView(parent) , m_progress(0) - , m_currentZoom(100) - , m_page(new WebPage(this)) - , m_enableAccessKeys(true) - , m_accessKeysPressed(false) -{ - setPage(m_page); - QPalette p; - connect(page(), SIGNAL(statusBarMessage(const QString&)), - SLOT(setStatusBarText(const QString&))); + , m_page(0) +{ connect(this, SIGNAL(loadProgress(int)), this, SLOT(setProgress(int))); connect(this, SIGNAL(loadFinished(bool)), - this, SLOT(loadFinished())); - connect(page(), SIGNAL(aboutToLoadUrl(const QUrl &)), - this, SIGNAL(urlChanged(const QUrl &))); - connect(page(), SIGNAL(downloadRequested(const QNetworkRequest &)), - this, SLOT(downloadRequested(const QNetworkRequest &))); - connect(BrowserApplication::instance(), SIGNAL(zoomTextOnlyChanged(bool)), - this, SLOT(applyZoom())); - page()->setForwardUnsupportedContent(true); - setAcceptDrops(true); - - // the zoom values (in percent) are chosen to be like in Mozilla Firefox 3 - m_zoomLevels << 30 << 50 << 67 << 80 << 90; - m_zoomLevels << 100; - m_zoomLevels << 110 << 120 << 133 << 150 << 170 << 200 << 240 << 300; - connect(m_page, SIGNAL(loadStarted()), - this, SLOT(hideAccessKeys())); - connect(m_page, SIGNAL(scrollRequested(int, int, const QRect &)), - this, SLOT(hideAccessKeys())); - loadSettings(); + this, SLOT(loadFinished(bool))); + connect(this, &QWebEngineView::renderProcessTerminated, + [=](QWebEnginePage::RenderProcessTerminationStatus termStatus, int statusCode) { + const char *status = ""; + switch (termStatus) { + case QWebEnginePage::NormalTerminationStatus: + status = "(normal exit)"; + break; + case QWebEnginePage::AbnormalTerminationStatus: + status = "(abnormal exit)"; + break; + case QWebEnginePage::CrashedTerminationStatus: + status = "(crashed)"; + break; + case QWebEnginePage::KilledTerminationStatus: + status = "(killed)"; + break; + } + + qInfo() << "Render process exited with code" << statusCode << status; + QTimer::singleShot(0, [this] { reload(); }); + }); +} + +void WebView::setPage(WebPage *_page) +{ + m_page = _page; + QWebEngineView::setPage(_page); + connect(page(), &WebPage::featurePermissionRequested, this, &WebView::onFeaturePermissionRequested); } void WebView::loadSettings() { + /* QSettings settings; - settings.beginGroup(QLatin1String("WebView")); - m_enableAccessKeys = settings.value(QLatin1String("enableAccessKeys"), m_enableAccessKeys).toBool(); + settings.beginGroup(QStringLiteral("WebView")); + m_enableAccessKeys = settings.value(QStringLiteral("enableAccessKeys"), m_enableAccessKeys).toBool(); if (!m_enableAccessKeys) hideAccessKeys(); + */ m_page->loadSettings(); } @@ -153,47 +207,43 @@ TabWidget *WebView::tabWidget() const return tw; widget = widget->parent(); } - return 0; + return nullptr; } void WebView::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = new QMenu(this); - QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos()); - - if (!r.linkUrl().isEmpty()) { + if (!page()->contextMenuData().linkUrl().isEmpty()) { QAction *newWindowAction = menu->addAction(tr("Open in New &Window"), this, SLOT(openActionUrlInNewWindow())); - newWindowAction->setData(r.linkUrl()); + newWindowAction->setData(page()->contextMenuData().linkUrl()); QAction *newTabAction = menu->addAction(tr("Open in New &Tab"), this, SLOT(openActionUrlInNewTab())); - newTabAction->setData(r.linkUrl()); + newTabAction->setData(page()->contextMenuData().linkUrl()); menu->addSeparator(); menu->addAction(tr("Save Lin&k"), this, SLOT(downloadLinkToDisk())); - menu->addAction(tr("&Bookmark This Link"), this, SLOT(bookmarkLink()))->setData(r.linkUrl()); + menu->addAction(tr("&Bookmark This Link"), this, SLOT(bookmarkLink()))->setData(page()->contextMenuData().linkUrl()); menu->addSeparator(); if (!page()->selectedText().isEmpty()) - menu->addAction(pageAction(QWebPage::Copy)); + menu->addAction(pageAction(QWebEnginePage::Copy)); menu->addAction(tr("&Copy Link Location"), this, SLOT(copyLinkToClipboard())); } - if (!r.imageUrl().isEmpty()) { + if (page()->contextMenuData().mediaType() == QWebEngineContextMenuData::MediaTypeImage) { if (!menu->isEmpty()) menu->addSeparator(); QAction *newWindowAction = menu->addAction(tr("Open Image in New &Window"), this, SLOT(openActionUrlInNewWindow())); - newWindowAction->setData(r.imageUrl()); + newWindowAction->setData(page()->contextMenuData().mediaUrl()); QAction *newTabAction = menu->addAction(tr("Open Image in New &Tab"), this, SLOT(openActionUrlInNewTab())); - newTabAction->setData(r.imageUrl()); + newTabAction->setData(page()->contextMenuData().mediaUrl()); menu->addSeparator(); menu->addAction(tr("&Save Image"), this, SLOT(downloadImageToDisk())); menu->addAction(tr("&Copy Image"), this, SLOT(copyImageToClipboard())); - menu->addAction(tr("C&opy Image Location"), this, SLOT(copyImageLocationToClipboard()))->setData(r.imageUrl().toString()); - menu->addSeparator(); - menu->addAction(tr("Block Image"), this, SLOT(blockImage()))->setData(r.imageUrl().toString()); + menu->addAction(tr("C&opy Image Location"), this, SLOT(copyImageLocationToClipboard()))->setData(page()->contextMenuData().mediaUrl().toString()); } if (!page()->selectedText().isEmpty()) { if (menu->isEmpty()) { - menu->addAction(pageAction(QWebPage::Copy)); + menu->addAction(pageAction(QWebEnginePage::Copy)); } else { menu->addSeparator(); } @@ -210,30 +260,34 @@ void WebView::contextMenuEvent(QContextMenuEvent *event) connect(searchMenu, SIGNAL(triggered(QAction *)), this, SLOT(searchRequested(QAction *))); } + /* + QWebElement element = r.element(); + if (!element.isNull() + && element.tagName().toLower() == QStringLiteral("input") + && element.attribute(QStringLiteral("type"), QStringLiteral("text")) == QStringLiteral("text")) { + if (menu->isEmpty()) { + menu->addAction(pageAction(QWebEnginePage::Copy)); + } else { + menu->addSeparator(); + } - QWebElement element = r.element(); - if (!element.isNull() - && element.tagName().toLower() == QLatin1String("input") - && element.attribute(QLatin1String("type"), QLatin1String("text")) == QLatin1String("text")) { - if (menu->isEmpty()) { - menu->addAction(pageAction(QWebPage::Copy)); - } else { - menu->addSeparator(); + QVariant variant; + variant.setValue(element); + menu->addAction(tr("Add to the toolbar search"), this, SLOT(addSearchEngine()))->setData(variant); } - - QVariant variant; - variant.setValue(element); - menu->addAction(tr("Add to the toolbar search"), this, SLOT(addSearchEngine()))->setData(variant); - } - + */ if (menu->isEmpty()) { delete menu; menu = page()->createStandardContextMenu(); - } else { - if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled)) - menu->addAction(pageAction(QWebPage::InspectElement)); } + QAction *action = new QAction(menu); + action->setText("Inspect Element"); + connect(action, &QAction::triggered, [this]() { + Q_EMIT devToolsRequested(page()); + }); + menu->addAction(action); + if (!menu->isEmpty()) { if (BrowserMainWindow::parentWindow(tabWidget())->menuBar()->isHidden()) { menu->addSeparator(); @@ -246,75 +300,73 @@ void WebView::contextMenuEvent(QContextMenuEvent *event) } delete menu; - QWebView::contextMenuEvent(event); + QWebEngineView::contextMenuEvent(event); } void WebView::wheelEvent(QWheelEvent *event) { if (event->modifiers() & Qt::ControlModifier) { - int numDegrees = event->delta() / 8; + int numDegrees = event->angleDelta().y() / 8; int numSteps = numDegrees / 15; m_currentZoom = m_currentZoom + numSteps * 10; applyZoom(); event->accept(); return; } - QWebView::wheelEvent(event); + QWebEngineView::wheelEvent(event); } void WebView::resizeEvent(QResizeEvent *event) { - int offset = event->size().height() - event->oldSize().height(); - int currentValue = page()->mainFrame()->scrollBarValue(Qt::Vertical); - setUpdatesEnabled(false); - page()->mainFrame()->setScrollBarValue(Qt::Vertical, currentValue - offset); - setUpdatesEnabled(true); - QWebView::resizeEvent(event); + /* + int offset = event->size().height() - event->oldSize().height(); + int currentValue = page()->mainFrame()->scrollBarValue(Qt::Vertical); + setUpdatesEnabled(false); + page()->mainFrame()->setScrollBarValue(Qt::Vertical, currentValue - offset); + setUpdatesEnabled(true); + */ + QWebEngineView::resizeEvent(event); } void WebView::downloadLinkToDisk() { - pageAction(QWebPage::DownloadLinkToDisk)->trigger(); + pageAction(QWebEnginePage::DownloadLinkToDisk)->trigger(); } void WebView::copyLinkToClipboard() { - pageAction(QWebPage::CopyLinkToClipboard)->trigger(); + pageAction(QWebEnginePage::CopyLinkToClipboard)->trigger(); } void WebView::openActionUrlInNewTab() { if (QAction *action = qobject_cast(sender())) { - QWebPage *page = tabWidget()->getView(TabWidget::NewNotSelectedTab, this)->page(); - QNetworkRequest request(action->data().toUrl()); - request.setRawHeader("Referer", url().toEncoded()); - page->mainFrame()->load(request); + QWebEnginePage *page = tabWidget()->getView(TabWidget::NewNotSelectedTab, this)->page(); + page->load(action->data().toUrl()); } } void WebView::openActionUrlInNewWindow() { if (QAction *action = qobject_cast(sender())) { - QWebPage *page = tabWidget()->getView(TabWidget::NewWindow, this)->page(); - QNetworkRequest request(action->data().toUrl()); - request.setRawHeader("Referer", url().toEncoded()); - page->mainFrame()->load(request); + QWebEnginePage *page = tabWidget()->getView(TabWidget::NewWindow, this)->page(); + page->load(action->data().toUrl()); } } void WebView::openImageInNewWindow() { - pageAction(QWebPage::OpenImageInNewWindow)->trigger(); + //pageAction(QWebEnginePage::OpenImageInNewWindow)->trigger(); } void WebView::downloadImageToDisk() { - pageAction(QWebPage::DownloadImageToDisk)->trigger(); + pageAction(QWebEnginePage::DownloadImageToDisk)->trigger(); } void WebView::copyImageToClipboard() { - pageAction(QWebPage::CopyImageToClipboard)->trigger(); + pageAction(QWebEnginePage::CopyImageToClipboard)->trigger(); } void WebView::copyImageLocationToClipboard() @@ -324,15 +376,6 @@ void WebView::copyImageLocationToClipboard() } } -void WebView::blockImage() -{ - if (QAction *action = qobject_cast(sender())) { - QString imageUrl = action->data().toString(); - AdBlockDialog *dialog = AdBlockManager::instance()->showDialog(); - dialog->addCustomRule(imageUrl); - } -} - void WebView::bookmarkLink() { if (QAction *action = qobject_cast(sender())) { @@ -353,10 +396,10 @@ void WebView::searchRequested(QAction *action) if (index.canConvert()) { OpenSearchEngine *engine = ToolbarSearch::openSearchManager()->engine(index.toString()); - emit search(engine->searchUrl(searchText), TabWidget::NewSelectedTab); + Q_EMIT search(engine->searchUrl(searchText), TabWidget::NewSelectedTab); } } - +/* void WebView::addSearchEngine() { QAction *action = qobject_cast(sender()); @@ -368,55 +411,55 @@ void WebView::addSearchEngine() return; QWebElement element = qvariant_cast(variant); - QString elementName = element.attribute(QLatin1String("name")); + QString elementName = element.attribute(QStringLiteral("name")); QWebElement formElement = element; - while (formElement.tagName().toLower() != QLatin1String("form")) + while (formElement.tagName().toLower() != QStringLiteral("form")) formElement = formElement.parent(); - if (formElement.isNull() || formElement.attribute(QLatin1String("action")).isEmpty()) + if (formElement.isNull() || formElement.attribute(QStringLiteral("action")).isEmpty()) return; - QString method = formElement.attribute(QLatin1String("method"), QLatin1String("get")).toLower(); - if (method != QLatin1String("get")) { + QString method = formElement.attribute(QStringLiteral("method"), QStringLiteral("get")).toLower(); + if (method != QStringLiteral("get")) { QMessageBox::warning(this, tr("Method not supported"), tr("%1 method is not supported.").arg(method.toUpper())); return; } - QUrl searchUrl(page()->mainFrame()->baseUrl().resolved(QUrl(formElement.attribute(QLatin1String("action"))))); + QUrl searchUrl(page()->mainFrame()->baseUrl().resolved(QUrl(formElement.attribute(QStringLiteral("action"))))); QMap searchEngines; - QWebElementCollection inputFields = formElement.findAll(QLatin1String("input")); + QWebElementCollection inputFields = formElement.findAll(QStringLiteral("input")); QUrlQuery query(searchUrl.query()); - foreach (QWebElement inputField, inputFields) { - QString type = inputField.attribute(QLatin1String("type"), QLatin1String("text")); - QString name = inputField.attribute(QLatin1String("name")); - QString value = inputField.evaluateJavaScript(QLatin1String("this.value")).toString(); + Q_FOREACH (QWebElement inputField, inputFields) { + QString type = inputField.attribute(QStringLiteral("type"), QStringLiteral("text")); + QString name = inputField.attribute(QStringLiteral("name")); + QString value = inputField.evaluateJavaScript(QStringLiteral("this.value")).toString(); - if (type == QLatin1String("submit")) { + if (type == QStringLiteral("submit")) { searchEngines.insert(value, name); - } else if (type == QLatin1String("text")) { + } else if (type == QStringLiteral("text")) { if (inputField == element) - value = QLatin1String("{searchTerms}"); + value = QStringLiteral("{searchTerms}"); query.addQueryItem(name, value); - } else if (type == QLatin1String("checkbox") || type == QLatin1String("radio")) { - if (inputField.evaluateJavaScript(QLatin1String("this.checked")).toBool()) { + } else if (type == QStringLiteral("checkbox") || type == QStringLiteral("radio")) { + if (inputField.evaluateJavaScript(QStringLiteral("this.checked")).toBool()) { query.addQueryItem(name, value); } - } else if (type == QLatin1String("hidden")) { + } else if (type == QStringLiteral("hidden")) { query.addQueryItem(name, value); } } - QWebElementCollection selectFields = formElement.findAll(QLatin1String("select")); - foreach (QWebElement selectField, selectFields) { - QString name = selectField.attribute(QLatin1String("name")); - int selectedIndex = selectField.evaluateJavaScript(QLatin1String("this.selectedIndex")).toInt(); + QWebElementCollection selectFields = formElement.findAll(QStringLiteral("select")); + Q_FOREACH (QWebElement selectField, selectFields) { + QString name = selectField.attribute(QStringLiteral("name")); + int selectedIndex = selectField.evaluateJavaScript(QStringLiteral("this.selectedIndex")).toInt(); if (selectedIndex == -1) continue; - QWebElementCollection options = selectField.findAll(QLatin1String("option")); + QWebElementCollection options = selectField.findAll(QStringLiteral("option")); QString value = options.at(selectedIndex).toPlainText(); query.addQueryItem(name, value); } @@ -434,7 +477,7 @@ void WebView::addSearchEngine() searchUrl.setQuery(query); QString engineName; - QWebElementCollection labels = formElement.findAll(QString(QLatin1String("label[for=\"%1\"]")).arg(elementName)); + QWebElementCollection labels = formElement.findAll(QString(QStringLiteral("label[for=\"%1\"]")).arg(elementName)); if (labels.count() > 0) engineName = labels.at(0).toPlainText(); @@ -451,7 +494,7 @@ void WebView::addSearchEngine() ToolbarSearch::openSearchManager()->addEngine(engine); } - +*/ void WebView::setProgress(int progress) { m_progress = progress; @@ -509,42 +552,51 @@ void WebView::resetZoom() applyZoom(); } -void WebView::loadFinished() +void WebView::loadFinished(bool success) { if (100 != m_progress) { qWarning() << "Received finished signal while progress is still:" << progress() << "Url:" << url(); } m_progress = 0; - AdBlockManager::instance()->page()->applyRulesToPage(page()); - BrowserApplication::instance()->autoFillManager()->fill(page()); } void WebView::loadUrl(const QUrl &url, const QString &title) { - if (url.scheme() == QLatin1String("javascript")) { + if (url.scheme() == QStringLiteral("javascript")) { QString scriptSource = QUrl::fromPercentEncoding(url.toString(Q_FLAGS(QUrl::TolerantMode|QUrl::RemoveScheme)).toLatin1()); - QVariant result = page()->mainFrame()->evaluateJavaScript(scriptSource); + QEventLoop loop; + QObject::connect(this, SIGNAL(notifyRanJavaScript()), &loop, SLOT(quit())); + page()->runJavaScript(scriptSource, [this](const QVariant &v) + { + this->ranJavaScript(); + }); + loop.exec(); return; } m_initialUrl = url; if (!title.isEmpty()) - emit titleChanged(tr("Loading...")); + Q_EMIT titleChanged(tr("Loading...")); else - emit titleChanged(title); + Q_EMIT titleChanged(title); QUrl oldurl = QUrl(url.toString()); QUrl newurl = QUrl(url.toString()); - if(newurl.toString().startsWith(QLatin1String("endorphin://"))) { + if(newurl.toString().startsWith(QStringLiteral("endorphin://"))) { QString url_tmp = newurl.toString().mid(12); - newurl = QUrl(QLatin1String("qrc:/") + url_tmp); + newurl = QUrl(QStringLiteral("qrc:/") + url_tmp); QString urlstr = newurl.toString(); - if(!urlstr.endsWith(QLatin1String(".html"))) { - newurl = QUrl(urlstr + QLatin1String(".html")); + if(!urlstr.endsWith(QStringLiteral(".html"))) { + newurl = QUrl(urlstr + QStringLiteral(".html")); } } load(newurl); } +void WebView::ranJavaScript() +{ + Q_EMIT notifyRanJavaScript(); +} + QString WebView::lastStatusBarText() const { return m_statusBarText; @@ -552,7 +604,7 @@ QString WebView::lastStatusBarText() const QUrl WebView::url() const { - QUrl url = QWebView::url(); + QUrl url = QWebEngineView::url(); if (!url.isEmpty()) return url; @@ -563,7 +615,7 @@ void WebView::mousePressEvent(QMouseEvent *event) { BrowserApplication::instance()->setEventMouseButtons(event->buttons()); BrowserApplication::instance()->setEventKeyboardModifiers(event->modifiers()); - + LocationBar::resetFirstSelectAll(); switch (event->button()) { case Qt::XButton1: pageAction(WebPage::Back)->trigger(); @@ -572,7 +624,7 @@ void WebView::mousePressEvent(QMouseEvent *event) pageAction(WebPage::Forward)->trigger(); break; default: - QWebView::mousePressEvent(event); + QWebEngineView::mousePressEvent(event); break; } } @@ -595,16 +647,16 @@ void WebView::dragMoveEvent(QDragMoveEvent *event) } } if (!event->isAccepted()) { - QWebView::dragMoveEvent(event); + QWebEngineView::dragMoveEvent(event); } } void WebView::dropEvent(QDropEvent *event) { - QWebView::dropEvent(event); + QWebEngineView::dropEvent(event); if (!event->isAccepted() - && event->source() != this - && event->possibleActions() & Qt::CopyAction) { + && event->source() != this + && event->possibleActions() & Qt::CopyAction) { QUrl url; if (!event->mimeData()->urls().isEmpty()) @@ -621,9 +673,9 @@ void WebView::dropEvent(QDropEvent *event) void WebView::mouseReleaseEvent(QMouseEvent *event) { const bool isAccepted = event->isAccepted(); - m_page->event(event); + page()->event(event); if (!event->isAccepted() - && (BrowserApplication::instance()->eventMouseButtons() & Qt::MidButton)) { + && (BrowserApplication::instance()->eventMouseButtons() & Qt::MidButton)) { QUrl url(QApplication::clipboard()->text(QClipboard::Selection)); if (!url.isEmpty() && url.isValid() && !url.scheme().isEmpty()) { BrowserApplication::instance()->setEventMouseButtons(Qt::NoButton); @@ -638,13 +690,14 @@ void WebView::setStatusBarText(const QString &string) m_statusBarText = string; } -void WebView::downloadRequested(const QNetworkRequest &request) +void WebView::downloadRequested(QWebEngineDownloadItem *download) { - BrowserApplication::downloadManager()->download(request); + BrowserApplication::downloadManager()->download(download); } void WebView::keyPressEvent(QKeyEvent *event) { + /* if (m_enableAccessKeys) { m_accessKeysPressed = (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Control); @@ -659,9 +712,10 @@ void WebView::keyPressEvent(QKeyEvent *event) QTimer::singleShot(300, this, SLOT(accessKeyShortcut())); } } - QWebView::keyPressEvent(event); + */ + QWebEngineView::keyPressEvent(event); } - +/* void WebView::accessKeyShortcut() { if (!hasFocus() @@ -675,23 +729,28 @@ void WebView::accessKeyShortcut() } m_accessKeysPressed = false; } - +*/ void WebView::keyReleaseEvent(QKeyEvent *event) { - if (m_enableAccessKeys) - m_accessKeysPressed = event->key() == Qt::Key_Control; - QWebView::keyReleaseEvent(event); + /* + if (m_enableAccessKeys) + m_accessKeysPressed = event->key() == Qt::Key_Control; + */ + QWebEngineView::keyReleaseEvent(event); } void WebView::focusOutEvent(QFocusEvent *event) { - if (m_accessKeysPressed) { - hideAccessKeys(); - m_accessKeysPressed = false; - } - QWebView::focusOutEvent(event); + /* + if (m_accessKeysPressed) { + hideAccessKeys(); + m_accessKeysPressed = false; + } + */ + QWebEngineView::focusOutEvent(event); } +/* bool WebView::checkForAccessKey(QKeyEvent *event) { if (m_accessKeyLabels.isEmpty()) @@ -737,32 +796,32 @@ void WebView::hideAccessKeys() void WebView::showAccessKeys() { QStringList supportedElement; - supportedElement << QLatin1String("input") - << QLatin1String("a") - << QLatin1String("area") - << QLatin1String("button") - << QLatin1String("label") - << QLatin1String("legend") - << QLatin1String("textarea"); + supportedElement << QStringLiteral("input") + << QStringLiteral("a") + << QStringLiteral("area") + << QStringLiteral("button") + << QStringLiteral("label") + << QStringLiteral("legend") + << QStringLiteral("textarea"); QList unusedKeys; for (char c = 'A'; c <= 'Z'; ++c) - unusedKeys << QLatin1Char(c); + unusedKeys << QChar(c); for (char c = '0'; c <= '9'; ++c) - unusedKeys << QLatin1Char(c); + unusedKeys << QChar(c); - QRect viewport = QRect(m_page->mainFrame()->scrollPosition(), m_page->viewportSize()); + QRect viewport = QRect(page()->mainFrame()->scrollPosition(), page()->viewportSize()); // Priority first goes to elements with accesskey attributes QList alreadyLabeled; - foreach (const QString &elementType, supportedElement) { + Q_FOREACH (const QString &elementType, supportedElement) { QList result = page()->mainFrame()->findAllElements(elementType).toList(); - foreach (const QWebElement &element, result) { + Q_FOREACH (const QWebElement &element, result) { const QRect geometry = element.geometry(); if (geometry.size().isEmpty() || !viewport.contains(geometry.topLeft())) { continue; } - QString accessKeyAttribute = element.attribute(QLatin1String("accesskey")).toUpper(); + QString accessKeyAttribute = element.attribute(QStringLiteral("accesskey")).toUpper(); if (accessKeyAttribute.isEmpty()) continue; QChar accessKey; @@ -783,9 +842,9 @@ void WebView::showAccessKeys() // Pick an access key first from the letters in the text and then from the // list of unused access keys - foreach (const QString &elementType, supportedElement) { + Q_FOREACH (const QString &elementType, supportedElement) { QWebElementCollection result = page()->mainFrame()->findAllElements(elementType); - foreach (const QWebElement &element, result) { + Q_FOREACH (const QWebElement &element, result) { const QRect geometry = element.geometry(); if (unusedKeys.isEmpty() || alreadyLabeled.contains(element) @@ -813,7 +872,7 @@ void WebView::showAccessKeys() void WebView::makeAccessKeyLabel(const QChar &accessKey, const QWebElement &element) { QLabel *label = new QLabel(this); - label->setText(QString(QLatin1String("%1")).arg(accessKey)); + label->setText(QString(QStringLiteral("%1")).arg(accessKey)); QPalette p = QToolTip::palette(); QColor color(Qt::yellow); @@ -824,7 +883,7 @@ void WebView::makeAccessKeyLabel(const QChar &accessKey, const QWebElement &elem label->setAutoFillBackground(true); label->setFrameStyle(QFrame::Box | QFrame::Plain); QPoint point = element.geometry().center(); - point -= m_page->mainFrame()->scrollPosition(); + point -= page()->mainFrame()->scrollPosition(); label->move(point); label->show(); point.setX(point.x() - label->width() / 2); @@ -832,3 +891,15 @@ void WebView::makeAccessKeyLabel(const QChar &accessKey, const QWebElement &elem m_accessKeyLabels.append(label); m_accessKeyNodes[accessKey] = element; } +*/ + +void WebView::onFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature) +{ + PermissionBar *permissionBar = new PermissionBar(this); + connect(permissionBar, &PermissionBar::featurePermissionProvided, page(), &QWebEnginePage::setFeaturePermission); + + // Discard the bar on new loads (if we navigate away or reload). + connect(page(), &QWebEnginePage::loadStarted, permissionBar, &QObject::deleteLater); + + permissionBar->requestPermission(securityOrigin, feature); +} \ No newline at end of file diff --git a/src/webview.h b/src/webview.h index fa722580..4bd2e05a 100644 --- a/src/webview.h +++ b/src/webview.h @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * Copyright 2008 Ariya Hidayat * * This program is free software; you can redistribute it and/or modify @@ -64,23 +64,26 @@ #ifndef WEBVIEW_H #define WEBVIEW_H -#include +#include #include "tabwidget.h" -#include class QLabel; class BrowserMainWindow; class TabWidget; class WebPage; -class WebView : public QWebView +//class QWebElement; +class WebView : public QWebEngineView { Q_OBJECT public: - WebView(QWidget *parent = 0); - WebPage *webPage() const { return m_page; } + WebView(QWidget *parent = nullptr); + void setPage(WebPage *page); + WebPage *webPage() const { + return m_page; + } void loadSettings(); @@ -91,13 +94,18 @@ class WebView : public QWebView QUrl url() const; QString lastStatusBarText() const; - inline int progress() const { return m_progress; } + inline int progress() const { + return m_progress; + } TabWidget *tabWidget() const; + void ranJavaScript(); -signals: +Q_SIGNALS: void search(const QUrl &searchUrl, TabWidget::OpenUrlIn openIn); + void notifyRanJavaScript(); + void devToolsRequested(QWebEnginePage *source); -public slots: +public Q_SLOTS: void zoomIn(); void zoomOut(); void resetZoom(); @@ -117,11 +125,11 @@ public slots: private: int levelForZoom(int zoom); -private slots: +private Q_SLOTS: void setProgress(int progress); - void loadFinished(); + void loadFinished(bool success); void setStatusBarText(const QString &string); - void downloadRequested(const QNetworkRequest &request); + void downloadRequested(QWebEngineDownloadItem *download); void openActionUrlInNewTab(); void openActionUrlInNewWindow(); void downloadLinkToDisk(); @@ -130,12 +138,11 @@ private slots: void downloadImageToDisk(); void copyImageToClipboard(); void copyImageLocationToClipboard(); - void blockImage(); void bookmarkLink(); void searchRequested(QAction *action); - void addSearchEngine(); - void hideAccessKeys(); - void accessKeyShortcut(); +// void addSearchEngine(); +// void hideAccessKeys(); +// void accessKeyShortcut(); private: QString m_statusBarText; @@ -145,13 +152,15 @@ private slots: QList m_zoomLevels; WebPage *m_page; - bool m_enableAccessKeys; - bool checkForAccessKey(QKeyEvent *event); - void showAccessKeys(); - void makeAccessKeyLabel(const QChar &accessKey, const QWebElement &element); - QList m_accessKeyLabels; - QHash m_accessKeyNodes; - bool m_accessKeysPressed; + void onFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature); + + //bool m_enableAccessKeys; + //bool checkForAccessKey(QKeyEvent *event); + //void showAccessKeys(); + //void makeAccessKeyLabel(const QChar &accessKey, const QWebElement &element); + //QList m_accessKeyLabels; + //QHash m_accessKeyNodes; + //bool m_accessKeysPressed; }; #endif diff --git a/src/webviewsearch.cpp b/src/webviewsearch.cpp index a494c3e8..c3bf0c58 100644 --- a/src/webviewsearch.cpp +++ b/src/webviewsearch.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,58 +19,52 @@ #include "webviewsearch.h" -#include -#include -#include +#include +#include +#include -#include -#include +#include -#include +#include -WebViewSearch::WebViewSearch(QWebView *webView, QWidget *parent) +WebViewSearch::WebViewSearch(QWebEngineView *webView, QWidget *parent) : SearchBar(parent) { setSearchObject(webView); - ui.highlightAllButton->setVisible(true); - connect(ui.highlightAllButton, SIGNAL(toggled(bool)), - this, SLOT(highlightAll())); - connect(ui.searchLineEdit, SIGNAL(textEdited(const QString &)), - this, SLOT(highlightAll())); } void WebViewSearch::findNext() { - find(QWebPage::FindWrapsAroundDocument); + find(QWebEnginePage::FindFlags()); } void WebViewSearch::findPrevious() { - find(QWebPage::FindBackward | QWebPage::FindWrapsAroundDocument); + find(QWebEnginePage::FindBackward); } -void WebViewSearch::highlightAll() +void WebViewSearch::find(QWebEnginePage::FindFlags flags) { - webView()->findText(QString(), QWebPage::HighlightAllOccurrences); - - if (ui.highlightAllButton->isChecked()) - find(QWebPage::HighlightAllOccurrences); + if(!ui.searchLineEdit->text().isEmpty()) { + QString searchString = ui.searchLineEdit->text(); + webView()->findText(searchString, flags, [this](bool found) { + handleSearchResult(found); + }); + } } -void WebViewSearch::find(QWebPage::FindFlags flags) +void WebViewSearch::handleSearchResult(bool found) { - QString searchString = ui.searchLineEdit->text(); - if (!searchObject() || searchString.isEmpty()) - return; QString infoString; - if (!webView()->findText(searchString, flags)) + if (!found) infoString = tr("Not Found"); + ui.searchInfo->setText(infoString); } -QWebView *WebViewSearch::webView() const +QWebEngineView *WebViewSearch::webView() const { - return qobject_cast(searchObject()); + return qobject_cast(searchObject()); } WebViewWithSearch::WebViewWithSearch(WebView *webView, QWidget *parent) diff --git a/src/webviewsearch.h b/src/webviewsearch.h index 67d84d23..0442fa90 100644 --- a/src/webviewsearch.h +++ b/src/webviewsearch.h @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,10 +22,10 @@ #include "searchbar.h" -#include +#include QT_BEGIN_NAMESPACE -class QWebView; +class QWebEngineView; QT_END_NAMESPACE class WebViewSearch : public SearchBar @@ -33,16 +33,16 @@ class WebViewSearch : public SearchBar Q_OBJECT public: - WebViewSearch(QWebView *webView, QWidget *parent = 0); + WebViewSearch(QWebEngineView *webView, QWidget *parent = nullptr); -public slots: +public Q_SLOTS: void findNext(); void findPrevious(); - void highlightAll(); private: - void find(QWebPage::FindFlags flags); - QWebView *webView() const; + void find(QWebEnginePage::FindFlags flags); + QWebEngineView *webView() const; + void handleSearchResult(bool found); }; #include "webview.h" @@ -52,7 +52,7 @@ class WebViewWithSearch : public QWidget Q_OBJECT public: - WebViewWithSearch(WebView *webView, QWidget *parent = 0); + WebViewWithSearch(WebView *webView, QWidget *parent = nullptr); WebView *m_webView; WebViewSearch *m_webViewSearch; }; diff --git a/tools/.qmake.conf b/tools/.qmake.conf deleted file mode 100644 index 7c1d952d..00000000 --- a/tools/.qmake.conf +++ /dev/null @@ -1,2 +0,0 @@ -QMAKEPATH += /usr/local/opt/qtwebkit -QMAKE_MAC_SDK = macosx10.13 diff --git a/tools/cacheinfo/CMakeLists.txt b/tools/cacheinfo/CMakeLists.txt index 3d706ebd..98cc8d19 100644 --- a/tools/cacheinfo/CMakeLists.txt +++ b/tools/cacheinfo/CMakeLists.txt @@ -1,10 +1,12 @@ project(endorphin-cacheinfo) +include(GNUInstallDirs) find_package(Qt5Widgets REQUIRED) find_package(Qt5Core REQUIRED) find_package(Qt5Gui REQUIRED) find_package(Qt5Network REQUIRED) add_executable(endorphin-cacheinfo main.cpp) -qt5_use_modules(endorphin-cacheinfo Widgets) -qt5_use_modules(endorphin-cacheinfo Core) -qt5_use_modules(endorphin-cacheinfo Gui) -qt5_use_modules(endorphin-cacheinfo Network) +target_link_libraries(endorphin-cacheinfo Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Network) + +install(TARGETS endorphin-cacheinfo + DESTINATION ${CMAKE_INSTALL_BINDIR} +) diff --git a/tools/cacheinfo/cacheinfo.pro b/tools/cacheinfo/cacheinfo.pro deleted file mode 100644 index 03470ab1..00000000 --- a/tools/cacheinfo/cacheinfo.pro +++ /dev/null @@ -1,32 +0,0 @@ -TEMPLATE = app -TARGET = endorphin-cacheinfo -DEPENDPATH += . -INCLUDEPATH += . - -win32|os2: CONFIG += console -mac:CONFIG -= app_bundle - -QT += network - -# Input -SOURCES += main.cpp - -RCC_DIR = $$PWD/.rcc -UI_DIR = $$PWD/.ui -MOC_DIR = $$PWD/.moc -OBJECTS_DIR = $$PWD/.obj - -include(../../install.pri) - -!mac { -unix { - INSTALLS += man man-compress - - man.path = $$DATADIR/man/man1 - man.files += data/endorphin-cacheinfo.1 - - man-compress.path = $$DATADIR/man/man1 - man-compress.extra = "" "gzip -9 -f \$(INSTALL_ROOT)/$$DATADIR/man/man1/endorphin-cacheinfo.1" "" - man-compress.depends = install_man -} -} diff --git a/tools/cacheinfo/main.cpp b/tools/cacheinfo/main.cpp index 1ef19ea6..fc2707e5 100644 --- a/tools/cacheinfo/main.cpp +++ b/tools/cacheinfo/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2008 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,23 +17,24 @@ * Boston, MA 02110-1301 USA */ -#include -#include -#include +#include +#include class NetworkDiskCache : public QNetworkDiskCache { public: QNetworkCacheMetaData _fileMetaData(const QString &fileName) - { return fileMetaData(fileName); } + { + return fileMetaData(fileName); + } }; int main(int argc, char **argv) { QCoreApplication application(argc, argv); - QCoreApplication::setOrganizationDomain(QLatin1String("aarondewes.github.io/endorphin/")); - QCoreApplication::setApplicationName(QLatin1String("Endorphin")); + QCoreApplication::setOrganizationDomain(QStringLiteral("EndorphinBrowser.gitlab.io/")); + QCoreApplication::setApplicationName(QStringLiteral("Endorphin")); QStringList args = application.arguments(); args.takeFirst(); @@ -45,7 +46,7 @@ int main(int argc, char **argv) } NetworkDiskCache diskCache; - QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/browser/"); + QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/browser/"); diskCache.setCacheDirectory(location); QNetworkCacheMetaData metaData; @@ -59,8 +60,8 @@ int main(int argc, char **argv) } if (!args.isEmpty() - && args.count() >= 1 - && args.first() == QLatin1String("-o")) { + && args.count() >= 1 + && args.first() == QStringLiteral("-o")) { QUrl url = metaData.url(); QIODevice *device = diskCache.data(url); if (!device) { @@ -97,7 +98,7 @@ int main(int argc, char **argv) stream << "Last Modified Date: " << metaData.lastModified().toString() << Qt::endl; stream << "Save to disk: " << metaData.saveToDisk() << Qt::endl; stream << "Headers:" << Qt::endl; - foreach (const QNetworkCacheMetaData::RawHeader &header, metaData.rawHeaders()) + Q_FOREACH (const QNetworkCacheMetaData::RawHeader &header, metaData.rawHeaders()) stream << "\t" << header.first << ": " << header.second << Qt::endl; QIODevice *device = diskCache.data(metaData.url()); if (device) { diff --git a/tools/htmlToXBel b/tools/htmlToXBel new file mode 160000 index 00000000..42abe794 --- /dev/null +++ b/tools/htmlToXBel @@ -0,0 +1 @@ +Subproject commit 42abe79428a802d7536eb0585351ee1f7abfeaf5 diff --git a/tools/htmlToXBel/.gitignore b/tools/htmlToXBel/.gitignore deleted file mode 100644 index b611ba2d..00000000 --- a/tools/htmlToXBel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -htmlToXBel diff --git a/tools/htmlToXBel/CMakeLists.txt b/tools/htmlToXBel/CMakeLists.txt deleted file mode 100644 index d031b8f0..00000000 --- a/tools/htmlToXBel/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -project(htmlToXBel) -find_package(Qt5Widgets REQUIRED) -find_package(Qt5Core REQUIRED) -find_package(Qt5Gui REQUIRED) -find_package(Qt5WebEngine REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5WebEngineWidgets REQUIRED) -add_executable(htmlToXBel main.cpp mainapp.cpp source.qrc) -qt5_use_modules(htmlToXBel Core) -qt5_use_modules(htmlToXBel Widgets) -qt5_use_modules(htmlToXBel Sql) -qt5_use_modules(htmlToXBel WebEngine) -qt5_use_modules(htmlToXBel Network) -qt5_use_modules(htmlToXBel WebEngineWidgets) diff --git a/tools/htmlToXBel/data/htmlToXBel.1 b/tools/htmlToXBel/data/htmlToXBel.1 deleted file mode 100644 index 6f98602d..00000000 --- a/tools/htmlToXBel/data/htmlToXBel.1 +++ /dev/null @@ -1,33 +0,0 @@ -.TH HTMLTOXBEL "1" "July 2009" - -.SH NAME -htmlToXBel - a tool to convert bookmarks stored in the html format into the xbel format. - -.SH SYNOPSIS -.B htmlToXBel [stdin|htmlfile] [stdout|-o outFile] - -.SH DESCRIPTION -.B htmlToXBel -is a tool to convert bookmarks stored in the html format into the xbel format. Many browser have the ability to export their bookmarks as a html file. htmlToXBel takes that file as an input and will output those bookmarks in the XML Bookmark Exchange Language (XBEL) format. - -.SH OPTIONS -.TP -.B -o outFile -Write the resulting XBEL to the file \fBoutFile\fR -.TP - -.SH BUGS -Please report bugs to \fIhttps://github.com/AaronDewes/endorphin-browser/issues\fR. - -.SH AUTHOR -The author of htmlToXBel is Aaron Dewes . -.PP -This manual page was written by Aaron Dewes -.PP -Permission is granted to copy, distribute and/or modify this document under the -terms of the -GNU General Public License, Version 2 or any later version published by the Free -Software Foundation. -.PP -On Debian systems, the complete text of the GNU General Public License can be -found in /usr/share/common-licenses/GPL. diff --git a/tools/htmlToXBel/extract.js b/tools/htmlToXBel/extract.js deleted file mode 100644 index 08b9ef24..00000000 --- a/tools/htmlToXBel/extract.js +++ /dev/null @@ -1,48 +0,0 @@ - -function walk() { - var parent = arguments[0]; - var indent = arguments[1]; - - var result = ""; - var children = parent.childNodes; - var folderName = ""; - var folded = ""; - for (var i = 0; i < children.length; i++) { - var object = children.item(i); - if (object.nodeName == "HR") { - result += indent + "\n"; - } - if (object.nodeName == "H3") { - folderName = object.innerHTML; - folded = object.folded; - if (object.folded == undefined) - folded = "false"; - else - folded = "true"; - } - if (object.nodeName == "A") { - result += indent + "\n"; - result += indent + indent + "" + object.innerHTML + "\n"; - result += indent + "\n"; - } - - var currentIndent = indent; - if (object.nodeName == "DL") { - result += indent + "\n"; - indent += " "; - result += indent + "" + folderName + "\n"; - } - result += walk(object, indent); - if (object.nodeName == "DL") { - result += currentIndent + "\n"; - } - } - return result; -} -var xbel = walk(document, " "); - -if (xbel != "") { - xbel = "\n\n\n" + xbel + "\n"; -} - -xbel; diff --git a/tools/htmlToXBel/htmlToXBel.pro b/tools/htmlToXBel/htmlToXBel.pro deleted file mode 100644 index 8fc2fb3c..00000000 --- a/tools/htmlToXBel/htmlToXBel.pro +++ /dev/null @@ -1,35 +0,0 @@ -TEMPLATE = app -TARGET = htmlToXBel -DEPENDPATH += . -INCLUDEPATH += . - -win32|os2: CONFIG += console -mac:CONFIG -= app_bundle - -QT += network webkit webkitwidgets - -# Input -SOURCES += main.cpp - -RCC_DIR = $$PWD/.rcc -UI_DIR = $$PWD/.ui -MOC_DIR = $$PWD/.moc -OBJECTS_DIR = $$PWD/.obj - -RESOURCES += source.qrc - -include(../../install.pri) -include(../../webkittrunk.pri) - -!mac { -unix { - INSTALLS += man man-compress - - man.path = $$DATADIR/man/man1 - man.files += data/htmlToXBel.1 - - man-compress.path = $$DATADIR/man/man1 - man-compress.extra = "" "gzip -9 -f \$(INSTALL_ROOT)/$$DATADIR/man/man1/htmlToXBel.1" "" - man-compress.depends = install_man -} -} diff --git a/tools/htmlToXBel/main.cpp b/tools/htmlToXBel/main.cpp deleted file mode 100644 index cbee06a8..00000000 --- a/tools/htmlToXBel/main.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2020 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include -#include -#include -#include -#include - -/*! - A tool to convert html bookmark files into the xbel format. - - The html bookmark files should be DOCTYPE: NETSCAPE-Bookmark-file-1 - - More information about XBel can be found here: http://pyxml.sourceforge.net/topics/xbel/ -*/ -int main(int argc, char **argv) -{ - QApplication application(argc, argv); - - QFile inFile; - QFile outFile; - QTextStream in(&inFile); - QTextStream out(&outFile); - - // Either read in from stdin and output to stdout - // or read in from a file and output to a file - // Example: ./app foo.html -o bar.xbel - bool setInput = false; - bool setOutput = false; - QStringList args = application.arguments(); - args.pop_front(); - foreach (const QString &arg, args) { - if (arg == QLatin1String("-o")) { - setOutput = true; - } else if (setOutput) { - outFile.setFileName(arg); - outFile.open(QIODevice::WriteOnly); - } else if (QFile::exists(arg)) { - setInput = true; - inFile.setFileName(arg); - inFile.open(QIODevice::ReadOnly); - } else { - qWarning() << "Usage: htmlToXBel" - << "[stdin|htmlfile]" << "[stdout|-o outFile]"; - return 1; - } - } - - if (!setInput) - inFile.open(stdin, QIODevice::ReadOnly); - if (!setOutput) - outFile.open(stdout, QIODevice::WriteOnly); - if (inFile.openMode() == QIODevice::NotOpen - || outFile.openMode() == QIODevice::NotOpen) { - qWarning() << "Unable to open streams"; - return 1; - } - MainApp m_MainApp; - QString input = inFile.readAll(); - out << m_MainApp.get(input); - return 0; -} diff --git a/tools/htmlToXBel/mainapp.cpp b/tools/htmlToXBel/mainapp.cpp deleted file mode 100644 index 9a2cdb87..00000000 --- a/tools/htmlToXBel/mainapp.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2020 Aaron Dewes - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA - */ - -#include "mainapp.h" -#include -#include -#include -#include -#include - -MainApp::MainApp(QObject *parent) : QObject(parent) -{ -} - -QString result; - -QString MainApp::get(QString &input) -{ - QWebEnginePage webPage; - QEventLoop loop; - connect(&webPage, &QWebEnginePage::loadFinished, &loop, &QEventLoop::quit); - webPage.setHtml(input); - loop.exec(); - QEventLoop loop2; - QObject::connect(this, SIGNAL(notifyRanJavaScript()), &loop2, SLOT(quit())); - QFile jsFile(":/extract.js"); - if (!jsFile.open(QFile::ReadOnly)) { - qWarning() << "Unable to load javascript to extract bookmarks."; - exit(1); - } - webPage.runJavaScript(jsFile.readAll(), [this](const QVariant &v) - { - QString tmp = v.toString(); - this->ranJavaScript(tmp); - }); - loop2.exec(); - return result; -} - -void MainApp::ranJavaScript(QString &value) -{ - result = value; - emit notifyRanJavaScript(); -} \ No newline at end of file diff --git a/tools/htmlToXBel/source.qrc b/tools/htmlToXBel/source.qrc deleted file mode 100644 index 5f5bd7df..00000000 --- a/tools/htmlToXBel/source.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - extract.js - - - diff --git a/tools/htmlToXBel/tests/firefox3-bookmarks.html b/tools/htmlToXBel/tests/firefox3-bookmarks.html deleted file mode 100644 index 5352a48c..00000000 --- a/tools/htmlToXBel/tests/firefox3-bookmarks.html +++ /dev/null @@ -1,47 +0,0 @@ - - - -Bookmarks -

    Bookmarks Menu

    - -

    -

    Recently Bookmarked -
    Recent Tags -
    -
    Get Bookmark Add-ons -
    -

    Mozilla Firefox

    -

    -

    Help and Tutorials -
    Customize Firefox -
    Get Involved -
    About Us -

    -

    Mozilla Firefox Start Page -
    Mozilla Firefox Start Page -

    Bookmarks Toolbar

    -
    Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar -

    -

    Most Visited -

    Smart Bookmarks

    -

    -

    Most Visited -
    Recently Bookmarked -
    -
    Recent Tags -

    -

    Getting Started -
    Latest Headlines -

    -

    Unfiled Bookmarks

    -

    -

    reddit.com: Apple pushes Windows Safari via iTunes updater -
    -
    reddit.com: what's new online! -
    -
    xkcd - A webcomic of romance, sarcasm, math, and language - By Randall Munroe -
    -

    -

    diff --git a/tools/htmlToXBel/tests/ie7-bookmarks.html b/tools/htmlToXBel/tests/ie7-bookmarks.html deleted file mode 100644 index c4a55152..00000000 --- a/tools/htmlToXBel/tests/ie7-bookmarks.html +++ /dev/null @@ -1,30 +0,0 @@ - - -Bookmarks -

    Bookmarks

    -

    -

    Links

    -

    -

    Customize Links -
    Free Hotmail -
    Windows Marketplace -
    Windows Media -
    Windows -

    -

    Microsoft Websites

    -

    -

    IE Add-on site -
    IE site on Microsoft.com -
    Marketplace -
    Microsoft At Home -
    Microsoft At Work -
    Welcome to IE7 -

    -

    Yahoo!

    -

    -

    -

    MSN.com -
    Radio Station Guide -

    diff --git a/tools/htmlToXBel/tests/opera9-bookmarks.html b/tools/htmlToXBel/tests/opera9-bookmarks.html deleted file mode 100644 index 5cf7b85f..00000000 --- a/tools/htmlToXBel/tests/opera9-bookmarks.html +++ /dev/null @@ -1,20 +0,0 @@ - - - -Bookmarks -

    Bookmarks

    -

    -

    Opera

    -

    -

    Download Opera -
    Opera Community -
    Opera Web Mail -
    Support Desk -

    -

    Download.com -
    Amazon.com -
    eBay -
    Yahoo! -

    diff --git a/tools/placesimport/CMakeLists.txt b/tools/placesimport/CMakeLists.txt index d954e8ee..980e4936 100644 --- a/tools/placesimport/CMakeLists.txt +++ b/tools/placesimport/CMakeLists.txt @@ -1,23 +1,30 @@ project(endorphin-placesimport) +include(GNUInstallDirs) find_package(Qt5Core REQUIRED) find_package(Qt5Widgets REQUIRED) find_package(Qt5Sql REQUIRED) -find_package(Qt5WebKit REQUIRED) -find_package(Qt5WebKitWidgets REQUIRED) +find_package(Qt5WebEngine REQUIRED) +find_package(Qt5WebEngineWidgets REQUIRED) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../../src ${CMAKE_CURRENT_SOURCE_DIR}/../../src/history ${CMAKE_CURRENT_SOURCE_DIR}/../../src/utils) add_definitions(-DNO_BROWSERAPPLICATION) set(placesimport_SRCS main_placesimport.cpp ../../src/autosaver.cpp + ../../src/clearbutton.cpp + ../../src/searchbutton.cpp ../../src/modelmenu.cpp + ../../src/searchlineedit.cpp ../../src/history/history.cpp ../../src/history/historymanager.cpp + ../../src/utils/edittreeview.cpp + ../../src/utils/lineedit.cpp ../../src/utils/singleapplication.cpp + ../../src/utils/treesortfilterproxymodel.cpp ) -add_executable(endorphin-placesimport ${placesimport_SRCS} ${UIS} ${RSCS} ${TRS} ${MOCS}) -qt5_use_modules(endorphin-placesimport Core) -qt5_use_modules(endorphin-placesimport Widgets) -qt5_use_modules(endorphin-placesimport Sql) -qt5_use_modules(endorphin-placesimport WebKit) -qt5_use_modules(endorphin-placesimport WebKitWidgets) +add_executable(endorphin-placesimport ${placesimport_SRCS}) +target_link_libraries(endorphin-placesimport Qt5::Core Qt5::Widgets Qt5::Sql Qt5::WebEngine Qt5::WebEngineWidgets) + +install(TARGETS endorphin-placesimport + DESTINATION ${CMAKE_INSTALL_BINDIR} +) diff --git a/tools/placesimport/main_placesimport.cpp b/tools/placesimport/main_placesimport.cpp index 7e30f9e8..53961d08 100644 --- a/tools/placesimport/main_placesimport.cpp +++ b/tools/placesimport/main_placesimport.cpp @@ -1,6 +1,6 @@ /* * Copyright 2008-2009 Benjamin K. Stuhl - * Copyright 2009 Aaron Dewes + * Copyright 2020 Aaron Dewes * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,14 +18,14 @@ * Boston, MA 02110-1301 USA */ -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include -#include +#include #include #include "singleapplication.h" @@ -42,8 +42,8 @@ static HistoryEntry formatEntry(QByteArray url, QByteArray title, qlonglong prda int main(int argc, char **argv) { SingleApplication application(argc, argv); - QCoreApplication::setOrganizationDomain(QLatin1String("aarondewes.github.io/endorphin/")); - QCoreApplication::setApplicationName(QLatin1String("Endorphin")); + QCoreApplication::setOrganizationDomain(QStringLiteral("EndorphinBrowser.gitlab.io/")); + QCoreApplication::setApplicationName(QStringLiteral("Endorphin")); if (application.sendMessage(QByteArray())) { qWarning() << "To prevent the loss of any history please exit Endorphin while this is tool is being run"; @@ -54,8 +54,8 @@ int main(int argc, char **argv) args.takeFirst(); if (args.isEmpty()) { QTextStream stream(stdout); - stream << "endorphin-placesimport is a tool for importing browser history from Firefox 3 and up" << endl; - stream << "endorphin-placesinfo ~/.mozilla/firefox/[profile-dir]/places.sqlite" << endl; + stream << "endorphin-placesimport is a tool for importing browser history from Firefox 3 and up" << Qt::endl; + stream << "endorphin-placesinfo ~/.mozilla/firefox/[profile-dir]/places.sqlite" << Qt::endl; return 0; } diff --git a/tools/placesimport/placesimport.pro b/tools/placesimport/placesimport.pro deleted file mode 100644 index 7998a518..00000000 --- a/tools/placesimport/placesimport.pro +++ /dev/null @@ -1,30 +0,0 @@ -TEMPLATE = app -TARGET = endorphin-placesimport -DEPENDPATH += . -INCLUDEPATH += . - -win32|os2: CONFIG += console -mac:CONFIG -= app_bundle - -QT += sql - -# Input -SOURCES += main_placesimport.cpp - -include(../../install.pri) -# This can be improved to just include the history manager and utility classes -# once the history classes are separated out into individual files. -include(../../src/src.pri) - -!mac { -unix { - INSTALLS += man man-compress - - man.path = $$DATADIR/man/man1 - man.files += data/endorphin-placesimport.1 - - man-compress.path = $$DATADIR/man/man1 - man-compress.extra = "" "gzip -9 -f \$(INSTALL_ROOT)/$$DATADIR/man/man1/endorphin-placesimport.1" "" - man-compress.depends = install_man -} -} diff --git a/tools/tools.pro b/tools/tools.pro deleted file mode 100644 index 428f211c..00000000 --- a/tools/tools.pro +++ /dev/null @@ -1,4 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = cacheinfo htmlToXBel placesimport - -CONFIG += ordered diff --git a/ts_lst_file b/ts_lst_file new file mode 100644 index 00000000..007faa3c --- /dev/null +++ b/ts_lst_file @@ -0,0 +1,74 @@ +-Isrc/utils +-Isrc/useragent +-Isrc/opensearch +-Isrc/locationbar +-Isrc/htmls +-Isrc/history +-Isrc/data +-Isrc/bookmarks/xbel +-Isrc/bookmarks +-Itools/cacheinfo +-Itools/placesimport +-Itools/htmlToXBel +tools/cacheinfo/main.cpp +tools/placesimport/main_placesimport.cpp +tools/htmlToXBel/mainapp.cpp +tools/htmlToXBel/main.cpp +src/modeltoolbar.cpp +src/main.cpp +src/browsermainwindow.cpp +src/modelmenu.cpp +src/searchlineedit.cpp +src/opensearch/opensearchenginemodel.cpp +src/opensearch/opensearchengine.cpp +src/opensearch/opensearchmanager.cpp +src/opensearch/opensearchengineaction.cpp +src/opensearch/opensearchreader.cpp +src/opensearch/opensearchwriter.cpp +src/opensearch/opensearchenginedelegate.cpp +src/opensearch/opensearchdialog.cpp +src/webactionmapper.cpp +src/webviewsearch.cpp +src/plaintexteditsearch.cpp +src/clearprivatedata.cpp +src/acceptlanguagedialog.cpp +src/settings.cpp +src/browserapplication.cpp +src/webview.cpp +src/webpage.cpp +src/locationcompleter.cpp +src/useragent/useragentmenu.cpp +src/searchbutton.cpp +src/tabwidget.cpp +src/bookmarks/bookmarkstoolbar.cpp +src/bookmarks/bookmarksmanager.cpp +src/bookmarks/bookmarknode.cpp +src/bookmarks/bookmarksdialog.cpp +src/bookmarks/addbookmarkdialog.cpp +src/bookmarks/xbel/xbelreader.cpp +src/bookmarks/xbel/xbelwriter.cpp +src/bookmarks/bookmarksmodel.cpp +src/bookmarks/bookmarksmenu.cpp +src/tabbar.cpp +src/permissionbar.cpp +src/devtoolswindow.cpp +src/aboutdialog.cpp +src/history/historymanager.cpp +src/history/history.cpp +src/searchbar.cpp +src/toolbarsearch.cpp +src/autosaver.cpp +src/downloadmanager.cpp +src/locationbar/locationbarsiteicon.cpp +src/locationbar/privacyindicator.cpp +src/locationbar/locationbar.cpp +src/utils/languagemanager.cpp +src/utils/editlistview.cpp +src/utils/explorerstyle.cpp +src/utils/edittreeview.cpp +src/utils/lineedit.cpp +src/utils/squeezelabel.cpp +src/utils/singleapplication.cpp +src/utils/edittableview.cpp +src/utils/treesortfilterproxymodel.cpp +src/clearbutton.cpp diff --git a/webkittrunk.pri b/webkittrunk.pri deleted file mode 100644 index d1974af1..00000000 --- a/webkittrunk.pri +++ /dev/null @@ -1,47 +0,0 @@ -# To build Endorphin against WebKit trunk: -# export QT_WEBKIT=webkit_trunk -# export WEBKITDIR=$HOME/dev/webkit -# -# Optional: -# export WEBKITOUTPUTDIR=$HOME/build/webkit -# export WEBKITBRANCH=some_cool_git_branch_of_webkit -# -CONFIG += $$(QT_WEBKIT) -webkit_trunk { - WEBKITDIR = $$(WEBKITDIR) - isEmpty(WEBKITDIR): error(Please point WEBKITDIR at the root of your WebKit source tree) - - OUTPUT_DIR = $$(WEBKITOUTPUTDIR) - isEmpty(OUTPUT_DIR): OUTPUT_DIR = $$WEBKITDIR/WebKitBuild - - WEBKITBRANCH = $$(WEBKITBRANCH) - !isEmpty(WEBKITBRANCH) { - OUTPUT_DIR = $$OUTPUT_DIR/$$WEBKITBRANCH - } - - # When building in debug try to link to the debug version of webkit - # and vice versa in release, but when they can not be paired up - # because webkit only has release or debug libs fall back to the other one - CONFIG(debug) { - exists($$OUTPUT_DIR/Debug) { - OUTPUT_DIR = $$OUTPUT_DIR/Debug - } else { - OUTPUT_DIR = $$OUTPUT_DIR/Release - } - } else:CONFIG(release) { - exists($$OUTPUT_DIR/Release) { - OUTPUT_DIR = $$OUTPUT_DIR/Release - } else { - OUTPUT_DIR = $$OUTPUT_DIR/Debug - } - } - - message(Using WebKit Trunk at $$WEBKITDIR) - message(Using WebKit Build at $$OUTPUT_DIR) - - QT -= webkit - DEFINES += WEBKIT_TRUNK - include($$WEBKITDIR/WebKit.pri) - QMAKE_RPATHDIR = $$OUTPUT_DIR/lib $$QMAKE_RPATHDIR -} -