diff --git a/CMakeLists.txt b/CMakeLists.txt index b1f04314..40496d66 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,14 +18,9 @@ kde4_optional_add_subdirectory(about-distro) kde4_optional_add_subdirectory(ark) kde4_optional_add_subdirectory(filelight) kde4_optional_add_subdirectory(gwenview) -kde4_optional_add_subdirectory(kcalc) kde4_optional_add_subdirectory(kdeplasma-addons) kde4_optional_add_subdirectory(kemu) -kde4_optional_add_subdirectory(kget) -kde4_optional_add_subdirectory(krdc) -kde4_optional_add_subdirectory(krfb) kde4_optional_add_subdirectory(ksnapshot) -kde4_optional_add_subdirectory(kvkbd) kde4_optional_add_subdirectory(okular) kde4_optional_add_subdirectory(partitionmanager) kde4_optional_add_subdirectory(thumbnailers) diff --git a/ark/app/ark.desktop.cmake b/ark/app/ark.desktop.cmake index 88ba11e2..013fbaf2 100755 --- a/ark/app/ark.desktop.cmake +++ b/ark/app/ark.desktop.cmake @@ -154,6 +154,5 @@ Type=Application Terminal=false StartupNotify=true X-KDE-HasTempFileOption=true -X-KDE-HasTrayOption=true Categories=Qt;KDE;Utility;Archiving;Compression;X-KDE-Utilities-File; InitialPreference=3 diff --git a/filelight/misc/filelight.desktop b/filelight/misc/filelight.desktop index 5c102e52..2deef914 100755 --- a/filelight/misc/filelight.desktop +++ b/filelight/misc/filelight.desktop @@ -159,4 +159,3 @@ MimeType=inode/directory; X-DocPath=filelight/index.html Categories=Qt;KDE;Utility; StartupNotify=true -X-KDE-HasTrayOption=true diff --git a/gwenview/app/gwenview.desktop b/gwenview/app/gwenview.desktop index 89fccb83..af99e454 100644 --- a/gwenview/app/gwenview.desktop +++ b/gwenview/app/gwenview.desktop @@ -182,4 +182,3 @@ X-DocPath=gwenview/index.html # primary applications for folders. InitialPreference=8 StartupNotify=true -X-KDE-HasTrayOption=true diff --git a/kcalc/CMakeLists.txt b/kcalc/CMakeLists.txt deleted file mode 100644 index 34770d30..00000000 --- a/kcalc/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -project(kcalc) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - include(FeatureSummary) - - find_package(KDELibs4 4.23.0 REQUIRED) - - include_directories(${KDE4_INCLUDES}) - add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -endif() - -set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${KDE4_ENABLE_EXCEPTIONS}") - -find_package(GMP) -set_package_properties(GMP PROPERTIES - DESCRIPTION "The GNU Multiple Precision Arithmetic Library" - URL "http://gmplib.org/" - PURPOSE "Required for building KCalc" - TYPE REQUIRED -) - -include(CheckTypeSize) - -check_type_size("signed long" SIZEOF_SIGNED_LONG) -check_type_size("unsigned long" SIZEOF_UNSIGNED_LONG) - -configure_file( - config-kcalc.h.cmake - ${CMAKE_CURRENT_BINARY_DIR}/config-kcalc.h -) - -include_directories( - ${CMAKE_CURRENT_BINARY_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/knumber - ${GMP_INCLUDE_DIR} -) - -########### next target ############### - -# Needs absolute paths due to the test program for knumber -set(libknumber_la_SRCS - ${kcalc_SOURCE_DIR}/knumber/knumber.cpp - ${kcalc_SOURCE_DIR}/knumber/knumber_error.cpp - ${kcalc_SOURCE_DIR}/knumber/knumber_float.cpp - ${kcalc_SOURCE_DIR}/knumber/knumber_fraction.cpp - ${kcalc_SOURCE_DIR}/knumber/knumber_integer.cpp - ${kcalc_SOURCE_DIR}/knumber/knumber_operators.cpp -) - -add_subdirectory( knumber ) -# add_subdirectory( tests ) - -set(kcalc_SRCS ${libknumber_la_SRCS} - kcalc.cpp - bitbutton.cpp - kcalc_bitset.cpp - kcalc_button.cpp - kcalc_const_button.cpp - kcalc_const_menu.cpp - kcalc_core.cpp - kcalcdisplay.cpp - stats.cpp - kcalc.ui - constants.ui - colors.ui - fonts.ui - general.ui -) - -kde4_add_kcfg_files(kcalc_SRCS kcalc_settings.kcfgc) - -add_executable(kcalc ${kcalc_SRCS}) - -target_link_libraries(kcalc - KDE4::kdeui - ${QT_QTXML_LIBRARY} - ${GMP_LIBRARIES} -) - -install( - TARGETS kcalc - DESTINATION ${KDE4_BIN_INSTALL_DIR} -) - -########### install files ############### - -install( - PROGRAMS kcalc.desktop - DESTINATION ${KDE4_XDG_APPS_INSTALL_DIR} -) - -install( - FILES kcalcui.rc - DESTINATION ${KDE4_DATA_INSTALL_DIR}/kcalc -) - -install( - FILES scienceconstants.xml - DESTINATION ${KDE4_DATA_INSTALL_DIR}/kcalc -) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) -endif() diff --git a/kcalc/COPYING b/kcalc/COPYING deleted file mode 100644 index 5185fd3f..00000000 --- a/kcalc/COPYING +++ /dev/null @@ -1,346 +0,0 @@ -NOTE! The GPL below is copyrighted by the Free Software Foundation, but -the instance of code that it refers to (the kde programs) are copyrighted -by the authors who actually wrote it. - ---------------------------------------------------------------------------- - - 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 Library 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) 19yy - - 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) 19yy 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 Library General -Public License instead of this License. diff --git a/kcalc/COPYING.LIB b/kcalc/COPYING.LIB deleted file mode 100644 index 2d2d780e..00000000 --- a/kcalc/COPYING.LIB +++ /dev/null @@ -1,510 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations -below. - - When we speak of free software, we are referring to freedom of use, -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 and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it -becomes a de-facto standard. To achieve this, non-free programs must -be allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control -compilation and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least - three years, to give the same user the materials specified in - Subsection 6a, above, for a charge no more than the cost of - performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply, and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License -may add an explicit geographical distribution limitation excluding those -countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms -of the ordinary General Public License). - - To apply these terms, attach the following notices to the library. -It is safest to attach them to the start of each source file to most -effectively convey the exclusion of warranty; and each file should -have at least the "copyright" line and a pointer to where the full -notice is found. - - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the library, -if necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James - Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/kcalc/Messages.sh b/kcalc/Messages.sh deleted file mode 100644 index 3e5c454d..00000000 --- a/kcalc/Messages.sh +++ /dev/null @@ -1,5 +0,0 @@ -#! /bin/sh -$EXTRACTRC *.rc *.ui *.kcfg >> rc.cpp -$EXTRACTATTR --attr=constant,name scienceconstants.xml >>rc.cpp ||exit 11 -$XGETTEXT *.cpp -o $podir/kcalc.pot -rm -f rc.cpp diff --git a/kcalc/README b/kcalc/README deleted file mode 100644 index eb64d7c6..00000000 --- a/kcalc/README +++ /dev/null @@ -1,8 +0,0 @@ -KCalc -===== -KCalc is currently covered under the GPL version 2. A copy of this -license can be found in a file named COPYING, in the toplevel directory. - -Have fun with kcalc! - - diff --git a/kcalc/bitbutton.cpp b/kcalc/bitbutton.cpp deleted file mode 100644 index 21365fc7..00000000 --- a/kcalc/bitbutton.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright (C) 2012 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2006 Michel Marti - mma@objectxp.com - -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, see . -*/ - -#include "bitbutton.h" -#include - -#include "moc_bitbutton.cpp" - -//------------------------------------------------------------------------------ -// Name: BitButton -// Desc: constructor -//------------------------------------------------------------------------------ -BitButton::BitButton(QWidget *parent) : QAbstractButton(parent), on_(false) { - - // too many bits for tab focus - setFocusPolicy(Qt::ClickFocus); - - // size button by font - QSize size = fontMetrics().size(0, QLatin1String("M")); - - if (size.width() < size.height()) { - size.setHeight(size.width()); - } else { - size.setWidth(size.height()); - } - - setFixedSize(size.expandedTo(QApplication::globalStrut())); -} - -//------------------------------------------------------------------------------ -// Name: isOn -// Desc: returns true if this bit-button is "on" -//------------------------------------------------------------------------------ -bool BitButton::isOn() const { - - return on_; -} - -//------------------------------------------------------------------------------ -// Name: setOn -// Desc: changes the "on" value for the bitset -//------------------------------------------------------------------------------ -void BitButton::setOn(bool value) { - - on_ = value; - update(); -} diff --git a/kcalc/bitbutton.h b/kcalc/bitbutton.h deleted file mode 100644 index dece54ac..00000000 --- a/kcalc/bitbutton.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 2012 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2006 Michel Marti - mma@objectxp.com - -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, see . -*/ - -#ifndef BITBUTTON_H_20120104_ -#define BITBUTTON_H_20120104_ - -#include - -class BitButton : public QAbstractButton { - Q_OBJECT - -public: - explicit BitButton(QWidget *parent = 0); - bool isOn() const; - void setOn(bool value); - -protected: - void paintEvent(QPaintEvent *event); - -private: - bool on_; -}; - -#endif diff --git a/kcalc/colors.ui b/kcalc/colors.ui deleted file mode 100644 index 3e942bbc..00000000 --- a/kcalc/colors.ui +++ /dev/null @@ -1,275 +0,0 @@ - - Colors - - - - 0 - 0 - 240 - 344 - - - - - - - Display Colors - - - - - - - - &Foreground: - - - false - - - kcfg_ForeColor - - - - - - - - - - - 0 - 0 - 0 - - - - - - - - &Background: - - - false - - - kcfg_BackColor - - - - - - - - - - - 189 - 255 - 180 - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Button Colors - - - - - - - - &Functions: - - - false - - - kcfg_FunctionButtonsColor - - - - - - - - - - - - - - St&atistic functions: - - - false - - - kcfg_StatButtonsColor - - - - - - - - - - - - - - He&xadecimals: - - - false - - - kcfg_HexButtonsColor - - - - - - - - - - - - - - &Numbers: - - - false - - - kcfg_NumberButtonsColor - - - - - - - - - - - - - - &Memory: - - - false - - - kcfg_MemoryButtonsColor - - - - - - - - - - - - - - O&perations: - - - false - - - kcfg_OperationButtonsColor - - - - - - - - - - - - - - - - Qt::Horizontal - - - - 31 - 20 - - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 151 - 70 - - - - - - - - - KColorButton - QPushButton -
kcolorbutton.h
-
-
- - kcfg_ForeColor - kcfg_BackColor - kcfg_FunctionButtonsColor - kcfg_StatButtonsColor - kcfg_HexButtonsColor - kcfg_NumberButtonsColor - kcfg_MemoryButtonsColor - kcfg_OperationButtonsColor - - -
diff --git a/kcalc/config-kcalc.h.cmake b/kcalc/config-kcalc.h.cmake deleted file mode 100644 index 847aa3f9..00000000 --- a/kcalc/config-kcalc.h.cmake +++ /dev/null @@ -1,5 +0,0 @@ -/* The size of a `signed long', as computed by sizeof. */ -#define SIZEOF_SIGNED_LONG ${SIZEOF_SIGNED_LONG} - -/* The size of a `unsigned long', as computed by sizeof. */ -#define SIZEOF_UNSIGNED_LONG ${SIZEOF_UNSIGNED_LONG} diff --git a/kcalc/constants.ui b/kcalc/constants.ui deleted file mode 100644 index 68d27582..00000000 --- a/kcalc/constants.ui +++ /dev/null @@ -1,173 +0,0 @@ - - Constants - - - - 0 - 0 - 185 - 273 - - - - Constants - - - - - - Constants - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - 6 - - - - - - - 40 - - - - - - - Predefined - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 20 - 40 - - - - - - - - kpushbutton.h - - - diff --git a/kcalc/fonts.ui b/kcalc/fonts.ui deleted file mode 100644 index 8c054f51..00000000 --- a/kcalc/fonts.ui +++ /dev/null @@ -1,83 +0,0 @@ - - Fonts - - - - 0 - 0 - 288 - 74 - - - - - - - QFormLayout::ExpandingFieldsGrow - - - - - &Button font: - - - kcfg_ButtonFont - - - - - - - Qt::WheelFocus - - - The font to use for the buttons - - - - - - - &Display font: - - - kcfg_DisplayFont - - - - - - - Qt::WheelFocus - - - The font to use in the display - - - - - - - - - Qt::Vertical - - - - 20 - 0 - - - - - - - - - KFontRequester - QWidget -
kfontrequester.h
-
-
- -
diff --git a/kcalc/general.ui b/kcalc/general.ui deleted file mode 100644 index 5a0cf543..00000000 --- a/kcalc/general.ui +++ /dev/null @@ -1,239 +0,0 @@ - - - General - - - - 0 - 0 - 293 - 319 - - - - General - - - - - - Precision - - - - - - - - &Maximum number of digits: - - - false - - - kcfg_Precision - - - - - - - Maximum number of digits displayed - - - KCalc can compute with many more digits than the number that fits on the display. This setting gives the maximum number of digits displayed, before KCalc starts using scientific notation, i.e. notation of the type 2.34e12. - - - - - - - Whether to use fixed decimal places - - - Set &decimal precision - - - - - - - false - - - Number of fixed decimal digits - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Grouping - - - - - - - - Whether to group digits - - - Group digits - - - true - - - - - - - - - true - - - Binary - - - - - - - Octal - - - - - - - Hexadecimal - - - - - - - - - - - - - - - - - - - - - - - Misc - - - - - - - - Whether to beep on error - - - &Beep on error - - - true - - - - - - - Whether to show the result in the window title - - - Show &result in window title - - - - - - - Whether to use Two's Complement for non-decimal numbers - - - Select to use Two's Complement notation for Binary, Octal and Hexidecimal numbers. This is a common notation to represent negative numbers for non-decimal numbers in computers. - - - Two's complement - - - true - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - kcfg_Precision - kcfg_Fixed - kcfg_FixedPrecision - - - - kcfg_Fixed - toggled(bool) - kcfg_FixedPrecision - setEnabled(bool) - - - 97 - 76 - - - 256 - 94 - - - - - diff --git a/kcalc/kcalc.cpp b/kcalc/kcalc.cpp deleted file mode 100644 index e553cc9b..00000000 --- a/kcalc/kcalc.cpp +++ /dev/null @@ -1,2327 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2006 Michel Marti - mma@objectxp.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#include "kcalc.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 "kcalc_bitset.h" -#include "kcalc_const_menu.h" -#include "kcalc_settings.h" -#include "kcalcdisplay.h" -#include "version.h" - -namespace { -const char description[] = I18N_NOOP("KDE Calculator"); -const char version[] = KCALCVERSION; -const int maxprecision = 1000; -} - - -//------------------------------------------------------------------------------ -// Name: KCalculator -// Desc: constructor -//------------------------------------------------------------------------------ -KCalculator::KCalculator(QWidget *parent) : - KXmlGuiWindow(parent), - shift_mode_(false), - hyp_mode_(false), - memory_num_(0.0), - constants_menu_(0), - constants_(0), - core() { - - // central widget to contain all the elements - QWidget *const central = new QWidget(this); - central->setLayoutDirection(Qt::LeftToRight); - setCentralWidget(central); - KAcceleratorManager::setNoAccel(central); - - // load science constants_ from xml-file - KCalcConstMenu::init_consts(); - - // setup interface (order is critical) - setupUi(central); - setupMainActions(); - setupStatusbar(); - createGUI(); - setupKeys(); - - toolBar()->hide(); // hide by default - - // create button groups - base_choose_group_ = new QButtonGroup(this); - base_choose_group_->setExclusive(true); - base_choose_group_->addButton(hexRadio, HexMode); - base_choose_group_->addButton(decRadio, DecMode); - base_choose_group_->addButton(octRadio, OctMode); - base_choose_group_->addButton(binRadio, BinMode); - connect(base_choose_group_, SIGNAL(buttonClicked(int)), - SLOT(slotBaseSelected(int))); - - angle_choose_group_ = new QButtonGroup(this); - angle_choose_group_->setExclusive(true); - angle_choose_group_->addButton(degRadio, DegMode); - angle_choose_group_->addButton(radRadio, RadMode); - angle_choose_group_->addButton(gradRadio, GradMode); - connect(angle_choose_group_, SIGNAL(buttonClicked(int)), - SLOT(slotAngleSelected(int))); - - // additional menu setup - constants_menu_ = createConstantsMenu(); - menuBar()->insertMenu((menuBar()->actions)()[2], constants_menu_); - - // misc setup - setColors(); - setFonts(); - - // Show the result in the app's caption in taskbar (wishlist - bug #52858) - if (KCalcSettings::captionResult() == true) { - connect(calc_display, SIGNAL(changedText(QString)), SLOT(setCaption(QString))); - } - - calc_display->changeSettings(); - setPrecision(); - - updateGeometry(); - - setFixedSize(minimumSize()); - - updateDisplay(UPDATE_FROM_CORE); - - // misc settings - KCalcSettings::EnumCalculatorMode::type calculatorMode = KCalcSettings::calculatorMode(); - - switch (calculatorMode) { - case KCalcSettings::EnumCalculatorMode::science: - action_mode_science_->setChecked(true); - break; - case KCalcSettings::EnumCalculatorMode::statistics: - action_mode_statistic_->setChecked(true); - break; - case KCalcSettings::EnumCalculatorMode::numeral: - action_mode_numeral_->setChecked(true); - break; - case KCalcSettings::EnumCalculatorMode::simple: - default: - action_mode_simple_->setChecked(true); - } - - setAngle(); - setBase(); - - // connections - connect(KGlobalSettings::self(), SIGNAL(kdisplayPaletteChanged()), SLOT(setColors())); - connect(KGlobalSettings::self(), SIGNAL(kdisplayFontChanged()), SLOT(setFonts())); - - calc_display->setFocus(); -} - -//------------------------------------------------------------------------------ -// Name: ~KCalculator -// Desc: deconstructor -//------------------------------------------------------------------------------ -KCalculator::~KCalculator() { - - KCalcSettings::self()->writeConfig(); -} - -//------------------------------------------------------------------------------ -// Name: setupMainActions -// Desc: connects all of the basic actions -//------------------------------------------------------------------------------ -void KCalculator::setupMainActions() { - - // file menu - KStandardAction::quit(this, SLOT(close()), actionCollection()); - - // edit menu - KStandardAction::undo(calc_display, SLOT(slotHistoryBack()), actionCollection()); - KStandardAction::redo(calc_display, SLOT(slotHistoryForward()), actionCollection()); - KStandardAction::cut(calc_display, SLOT(slotCut()), actionCollection()); - KStandardAction::copy(calc_display, SLOT(slotCopy()), actionCollection()); - KStandardAction::paste(calc_display, SLOT(slotPaste()), actionCollection()); - - // mode menu - QActionGroup *modeGroup = new QActionGroup(this); - - action_mode_simple_ = actionCollection()->add(QLatin1String("mode_simple")); - action_mode_simple_->setActionGroup(modeGroup); - action_mode_simple_->setText(i18n("Simple Mode")); - connect(action_mode_simple_, SIGNAL(toggled(bool)), SLOT(slotSetSimpleMode())); - - action_mode_science_ = actionCollection()->add(QLatin1String("mode_science")); - action_mode_science_->setActionGroup(modeGroup); - action_mode_science_->setText(i18n("Science Mode")); - connect(action_mode_science_, SIGNAL(toggled(bool)), SLOT(slotSetScienceMode())); - - action_mode_statistic_ = actionCollection()->add(QLatin1String("mode_statistics")); - action_mode_statistic_->setActionGroup(modeGroup); - action_mode_statistic_->setText(i18n("Statistic Mode")); - connect(action_mode_statistic_, SIGNAL(toggled(bool)), SLOT(slotSetStatisticMode())); - - action_mode_numeral_ = actionCollection()->add(QLatin1String("mode_numeral")); - action_mode_numeral_->setActionGroup(modeGroup); - action_mode_numeral_->setText(i18n("Numeral System Mode")); - connect(action_mode_numeral_, SIGNAL(toggled(bool)), SLOT(slotSetNumeralMode())); - - // settings menu - action_constants_show_ = actionCollection()->add(QLatin1String("show_constants")); - action_constants_show_->setText(i18n("Constants &Buttons")); - action_constants_show_->setChecked(true); - connect(action_constants_show_, SIGNAL(toggled(bool)), SLOT(slotConstantsShow(bool))); - - action_bitset_show_ = actionCollection()->add(QLatin1String("show_bitset")); - action_bitset_show_->setText(i18n("Show B&it Edit")); - action_bitset_show_->setChecked(true); - connect(action_bitset_show_, SIGNAL(toggled(bool)), SLOT(slotBitsetshow(bool))); - - KStandardAction::preferences(this, SLOT(showSettings()), actionCollection()); - KStandardAction::keyBindings(guiFactory(), SLOT(configureShortcuts()), actionCollection()); -} - -//------------------------------------------------------------------------------ -// Name: createConstantsMenu -// Desc: creates and returns a pointer to the constant menu -//------------------------------------------------------------------------------ -KCalcConstMenu *KCalculator::createConstantsMenu() { - - KCalcConstMenu *const menu = new KCalcConstMenu(i18n("&Constants"), this); - connect(menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotConstantToDisplay(science_constant))); - return menu; -} - -//------------------------------------------------------------------------------ -// Name: setupStatusbar -// Desc: sets up the status bar with default text -//------------------------------------------------------------------------------ -void KCalculator::setupStatusbar() { - - // Status bar contents - statusBar()->insertPermanentFixedItem(QLatin1String(" NORM "), ShiftField); - statusBar()->setItemAlignment(ShiftField, Qt::AlignCenter); - - statusBar()->insertPermanentFixedItem(QLatin1String(" HEX "), BaseField); - statusBar()->setItemAlignment(BaseField, Qt::AlignCenter); - - statusBar()->insertPermanentFixedItem(QLatin1String(" DEG "), AngleField); - statusBar()->setItemAlignment(AngleField, Qt::AlignCenter); - - statusBar()->insertPermanentFixedItem(QLatin1String(" \xa0\xa0 "), MemField); // nbsp - statusBar()->setItemAlignment(MemField, Qt::AlignCenter); -} - -//------------------------------------------------------------------------------ -// Name: setupNumberKeys -// Desc: sets up number keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupNumberKeys() { - - num_button_group_ = new QButtonGroup(this); - connect(num_button_group_, SIGNAL(buttonClicked(int)), SLOT(slotNumberclicked(int))); - - num_button_group_->addButton(pb0, 0); - num_button_group_->addButton(pb1, 1); - num_button_group_->addButton(pb2, 2); - num_button_group_->addButton(pb3, 3); - num_button_group_->addButton(pb4, 4); - num_button_group_->addButton(pb5, 5); - num_button_group_->addButton(pb6, 6); - num_button_group_->addButton(pb7, 7); - num_button_group_->addButton(pb8, 8); - num_button_group_->addButton(pb9, 9); - num_button_group_->addButton(pbA, 0xA); - num_button_group_->addButton(pbB, 0xB); - num_button_group_->addButton(pbC, 0xC); - num_button_group_->addButton(pbD, 0xD); - num_button_group_->addButton(pbE, 0xE); - num_button_group_->addButton(pbF, 0xF); - connect(this, SIGNAL(switchShowAccels(bool)), pb0, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb1, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb2, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb3, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb4, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb5, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb6, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb7, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb8, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pb9, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbA, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbB, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbC, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbD, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbE, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbF, SLOT(slotSetAccelDisplayMode(bool))); -} - -//------------------------------------------------------------------------------ -// Name: setupRightKeypad -// Desc: sets up right keypad keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupRightKeypad() { - - connect(pbShift, SIGNAL(toggled(bool)), SLOT(slotShifttoggled(bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbShift, SLOT(slotSetAccelDisplayMode(bool))); - - pbBackspace->setShortcut(QKeySequence(Qt::Key_Backspace)); - new QShortcut(Qt::Key_PageUp, pbBackspace, SLOT(animateClick())); - connect(pbBackspace, SIGNAL(clicked()), SLOT(slotBackspaceclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbBackspace, SLOT(slotSetAccelDisplayMode(bool))); - - pbClear->setShortcut(QKeySequence(Qt::Key_Escape)); - new QShortcut(Qt::Key_PageUp, pbClear, SLOT(animateClick())); - connect(pbClear, SIGNAL(clicked()), SLOT(slotClearclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbClear, SLOT(slotSetAccelDisplayMode(bool))); - - pbAllClear->setShortcut(QKeySequence(Qt::Key_Delete)); - new QShortcut(Qt::Key_PageDown, pbAllClear, SLOT(animateClick())); - connect(pbAllClear, SIGNAL(clicked()), SLOT(slotAllClearclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbAllClear, SLOT(slotSetAccelDisplayMode(bool))); - - pbParenOpen->setShortcut(QKeySequence(Qt::Key_ParenLeft)); - connect(pbParenOpen, SIGNAL(clicked()), SLOT(slotParenOpenclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbParenOpen, SLOT(slotSetAccelDisplayMode(bool))); - - pbParenClose->setShortcut(QKeySequence(Qt::Key_ParenRight)); - connect(pbParenClose, SIGNAL(clicked()), SLOT(slotParenCloseclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbParenClose, SLOT(slotSetAccelDisplayMode(bool))); - - pbMemRecall->setDisabled(true); // nothing in memory at start - connect(pbMemRecall, SIGNAL(clicked()), SLOT(slotMemRecallclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMemRecall, SLOT(slotSetAccelDisplayMode(bool))); - - connect(pbMemClear, SIGNAL(clicked()), SLOT(slotMemClearclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMemClear, SLOT(slotSetAccelDisplayMode(bool))); - - pbMemPlusMinus->addMode(ModeNormal, i18nc("Add display to memory", "M+"), i18n("Add display to memory")); - pbMemPlusMinus->addMode(ModeShift, i18nc("Subtract from memory", "M\xe2\x88\x92"), i18n("Subtract from memory")); - connect(pbMemPlusMinus, SIGNAL(clicked()), SLOT(slotMemPlusMinusclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMemPlusMinus, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbMemPlusMinus, SLOT(slotSetMode(ButtonModeFlags,bool))); - - connect(pbMemStore, SIGNAL(clicked()), SLOT(slotMemStoreclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMemStore, SLOT(slotSetAccelDisplayMode(bool))); - - pbPercent->setShortcut(QKeySequence(Qt::Key_Percent)); - connect(pbPercent, SIGNAL(clicked()), SLOT(slotPercentclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbPercent, SLOT(slotSetAccelDisplayMode(bool))); - - pbPlusMinus->setShortcut(QKeySequence(Qt::Key_Backslash)); - connect(pbPlusMinus, SIGNAL(clicked()), SLOT(slotPlusMinusclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbPlusMinus, SLOT(slotSetAccelDisplayMode(bool))); -} - -//------------------------------------------------------------------------------ -// Name: setupNumericKeypad -// Desc: sets up numeric keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupNumericKeypad() { - - pbCube->addMode(ModeNormal, i18nc("Third power", "x3"), i18n("Third power")); - pbCube->addMode(ModeShift, QLatin1String("3√x"), i18n("Cube root")); - connect(pbCube, SIGNAL(clicked()), SLOT(slotCubeclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbCube, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbCube, SLOT(slotSetMode(ButtonModeFlags,bool))); - - pbDivision->setShortcut(QKeySequence(Qt::Key_Slash)); - new QShortcut(Qt::Key_division, pbDivision, SLOT(animateClick())); - connect(pbDivision, SIGNAL(clicked()), SLOT(slotDivisionclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbDivision, SLOT(slotSetAccelDisplayMode(bool))); - - pbMultiplication->setShortcut(QKeySequence(Qt::Key_Asterisk)); - new QShortcut(Qt::Key_X, pbMultiplication, SLOT(animateClick())); - new QShortcut(Qt::Key_multiply, pbMultiplication, SLOT(animateClick())); - connect(pbMultiplication, SIGNAL(clicked()), SLOT(slotMultiplicationclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMultiplication, SLOT(slotSetAccelDisplayMode(bool))); - - pbMinus->setShortcut(QKeySequence(Qt::Key_Minus)); - connect(pbMinus, SIGNAL(clicked()), SLOT(slotMinusclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbMinus, SLOT(slotSetAccelDisplayMode(bool))); - - pbPlus->setShortcut(QKeySequence(Qt::Key_Plus)); - connect(pbPlus, SIGNAL(clicked()), SLOT(slotPlusclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbPlus, SLOT(slotSetAccelDisplayMode(bool))); - - const QString decimalPoint = KGlobal::locale()->toLocale().decimalPoint(); - pbPeriod->setText(decimalPoint); - pbPeriod->setShortcut(decimalPoint); - - // TODO: is this needed? the above line look slike it should do the right thing? - /* - if (decimalPoint == QLatin1String(".")) { - new QShortcut(Qt::Key_Comma, pbPeriod, SLOT(animateClick())); - } else if (decimalPoint == QLatin1String(",")) { - new QShortcut(Qt::Key_Period, pbPeriod, SLOT(animateClick())); - } - */ - - connect(pbPeriod, SIGNAL(clicked()), SLOT(slotPeriodclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbPeriod, SLOT(slotSetAccelDisplayMode(bool))); - - pbEqual->setShortcut(QKeySequence(Qt::Key_Enter)); - new QShortcut(Qt::Key_Equal, pbEqual, SLOT(animateClick())); - new QShortcut(Qt::Key_Return, pbEqual, SLOT(animateClick())); - connect(pbEqual, SIGNAL(clicked()), SLOT(slotEqualclicked())); - connect(this, SIGNAL(switchShowAccels(bool)), pbEqual, SLOT(slotSetAccelDisplayMode(bool))); -} - -//------------------------------------------------------------------------------ -// Name: setupLogicKeys -// Desc: sets up logic keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupLogicKeys() { - - logic_buttons_.append(pbAND); - logic_buttons_.append(pbOR); - logic_buttons_.append(pbXOR); - logic_buttons_.append(pbLsh); - logic_buttons_.append(pbRsh); - logic_buttons_.append(pbCmp); - - pbAND->setShortcut(QKeySequence(Qt::Key_Ampersand)); - connect(this, SIGNAL(switchShowAccels(bool)), pbAND, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbAND, SIGNAL(clicked()), SLOT(slotANDclicked())); - - pbOR->setShortcut(QKeySequence(Qt::Key_Bar)); - connect(this, SIGNAL(switchShowAccels(bool)), pbOR, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbOR, SIGNAL(clicked()), SLOT(slotORclicked())); - - connect(this, SIGNAL(switchShowAccels(bool)), pbXOR, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbXOR, SIGNAL(clicked()), SLOT(slotXORclicked())); - - pbLsh->setShortcut(QKeySequence(Qt::Key_Less)); - connect(this, SIGNAL(switchShowAccels(bool)), pbLsh, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbLsh, SIGNAL(clicked()), SLOT(slotLeftShiftclicked())); - - pbRsh->setShortcut(QKeySequence(Qt::Key_Greater)); - connect(this, SIGNAL(switchShowAccels(bool)), pbRsh, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbRsh, SIGNAL(clicked()), SLOT(slotRightShiftclicked())); - - pbCmp->setShortcut(QKeySequence(Qt::Key_AsciiTilde)); - connect(this, SIGNAL(switchShowAccels(bool)), pbCmp, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbCmp, SIGNAL(clicked()), SLOT(slotNegateclicked())); -} - -//------------------------------------------------------------------------------ -// Name: setupLogicKeys -// Desc: sets up scientific keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupScientificKeys() { - - scientific_buttons_.append(pbHyp); - scientific_buttons_.append(pbSin); - scientific_buttons_.append(pbCos); - scientific_buttons_.append(pbTan); - scientific_buttons_.append(pbLog); - scientific_buttons_.append(pbLn); - - connect(this, SIGNAL(switchShowAccels(bool)), pbHyp, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbHyp, SIGNAL(toggled(bool)), SLOT(slotHyptoggled(bool))); - - pbSin->addMode(ModeNormal, i18nc("Sine", "Sin"), i18n("Sine")); - pbSin->addMode(ModeShift, i18nc("Arc sine", "Asin"), i18n("Arc sine")); - pbSin->addMode(ModeHyperbolic, i18nc("Hyperbolic sine", "Sinh"), i18n("Hyperbolic sine")); - pbSin->addMode(ButtonModeFlags(ModeShift | ModeHyperbolic), i18nc("Inverse hyperbolic sine", "Asinh"), i18n("Inverse hyperbolic sine")); - connect(this, SIGNAL(switchShowAccels(bool)), pbSin, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbSin, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbSin, SIGNAL(clicked()), SLOT(slotSinclicked())); - - pbCos->addMode(ModeNormal, i18nc("Cosine", "Cos"), i18n("Cosine")); - pbCos->addMode(ModeShift, i18nc("Arc cosine", "Acos"), i18n("Arc cosine")); - pbCos->addMode(ModeHyperbolic, i18nc("Hyperbolic cosine", "Cosh"), i18n("Hyperbolic cosine")); - pbCos->addMode(ButtonModeFlags(ModeShift | ModeHyperbolic), i18nc("Inverse hyperbolic cosine", "Acosh"), i18n("Inverse hyperbolic cosine")); - connect(this, SIGNAL(switchShowAccels(bool)), pbCos, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbCos, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbCos, SIGNAL(clicked()), SLOT(slotCosclicked())); - - pbTan->addMode(ModeNormal, i18nc("Tangent", "Tan"), i18n("Tangent")); - pbTan->addMode(ModeShift, i18nc("Arc tangent", "Atan"), i18n("Arc tangent")); - pbTan->addMode(ModeHyperbolic, i18nc("Hyperbolic tangent", "Tanh"), i18n("Hyperbolic tangent")); - pbTan->addMode(ButtonModeFlags(ModeShift | ModeHyperbolic), i18nc("Inverse hyperbolic tangent", "Atanh"), i18n("Inverse hyperbolic tangent")); - connect(this, SIGNAL(switchShowAccels(bool)), pbTan, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbTan, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbTan, SIGNAL(clicked()), SLOT(slotTanclicked())); - - pbLog->addMode(ModeNormal, i18nc("Logarithm to base 10", "Log"), i18n("Logarithm to base 10")); - pbLog->addMode(ModeShift, i18nc("10 to the power of x", "10x"), i18n("10 to the power of x")); - connect(this, SIGNAL(switchShowAccels(bool)), pbLog, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbLog, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbLog, SIGNAL(clicked()), SLOT(slotLogclicked())); - pbLn->addMode(ModeNormal, i18nc("Natural log", "Ln"), i18n("Natural log")); - pbLn->addMode(ModeShift, i18nc("Exponential function", "ex"), i18n("Exponential function")); - connect(this, SIGNAL(switchShowAccels(bool)), pbLn, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbLn, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbLn, SIGNAL(clicked()), SLOT(slotLnclicked())); -} - -//------------------------------------------------------------------------------ -// Name: setupStatisticKeys -// Desc: sets up statistical keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupStatisticKeys() { - - stat_buttons_.append(pbNData); - stat_buttons_.append(pbMean); - stat_buttons_.append(pbSd); - stat_buttons_.append(pbMed); - stat_buttons_.append(pbDat); - stat_buttons_.append(pbCSt); - - pbNData->addMode(ModeNormal, i18nc("Number of data entered", "N"), i18n("Number of data entered")); - pbNData->addMode(ModeShift, QString::fromUtf8("\xce\xa3") + QLatin1Char('x'), i18n("Sum of all data items")); - connect(this, SIGNAL(switchShowAccels(bool)), pbNData, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbNData, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbNData, SIGNAL(clicked()), SLOT(slotStatNumclicked())); - - pbMean->addMode(ModeNormal, i18nc("Mean", "Mea"), i18n("Mean")); - pbMean->addMode(ModeShift, QString::fromUtf8("\xce\xa3") + QLatin1String("x2"), i18n("Sum of all data items squared")); - connect(this, SIGNAL(switchShowAccels(bool)), pbMean, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbMean, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbMean, SIGNAL(clicked()), SLOT(slotStatMeanclicked())); - - pbSd->addMode(ModeNormal, QString::fromUtf8("\xcf\x83") + QLatin1String("N"), i18n("Standard deviation")); - pbSd->addMode(ModeShift, QString::fromUtf8("\xcf\x83") + QLatin1String("N-1"), i18n("Sample standard deviation")); - connect(this, SIGNAL(switchShowAccels(bool)), pbSd, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbSd, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbSd, SIGNAL(clicked()), SLOT(slotStatStdDevclicked())); - - connect(this, SIGNAL(switchShowAccels(bool)), pbMed, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbMed, SIGNAL(clicked()), SLOT(slotStatMedianclicked())); - - pbDat->addMode(ModeNormal, i18nc("Enter data", "Dat"), i18n("Enter data")); - pbDat->addMode(ModeShift, i18nc("Delete last data item", "CDat"), i18n("Delete last data item")); - connect(this, SIGNAL(switchShowAccels(bool)), pbDat, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbDat, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbDat, SIGNAL(clicked()), SLOT(slotStatDataInputclicked())); - - connect(this, SIGNAL(switchShowAccels(bool)), pbCSt, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbCSt, SIGNAL(clicked()), SLOT(slotStatClearDataclicked())); -} - -//------------------------------------------------------------------------------ -// Name: setupConstantsKeys -// Desc: sets up constants keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupConstantsKeys() { - - const_buttons_.append(pbC1); - const_buttons_.append(pbC2); - const_buttons_.append(pbC3); - const_buttons_.append(pbC4); - const_buttons_.append(pbC5); - const_buttons_.append(pbC6); - - pbC1->setButtonNumber(0); - connect(this, SIGNAL(switchShowAccels(bool)), pbC1, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC1, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC1, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - pbC2->setButtonNumber(1); - connect(this, SIGNAL(switchShowAccels(bool)), pbC2, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC2, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC2, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - pbC3->setButtonNumber(2); - connect(this, SIGNAL(switchShowAccels(bool)), pbC3, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC3, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC3, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - pbC4->setButtonNumber(3); - connect(this, SIGNAL(switchShowAccels(bool)), pbC4, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC4, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC4, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - pbC5->setButtonNumber(4); - connect(this, SIGNAL(switchShowAccels(bool)), pbC5, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC5, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC5, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - pbC6->setButtonNumber(5); - connect(this, SIGNAL(switchShowAccels(bool)), pbC6, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbC6, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbC6, SIGNAL(clicked(int)), this, SLOT(slotConstclicked(int))); - - changeButtonNames(); -} - -//------------------------------------------------------------------------------ -// Name: setupMiscKeys -// Desc: sets up misc keys and related shortcuts -//------------------------------------------------------------------------------ -void KCalculator::setupMiscKeys() { - - pbMod->addMode(ModeNormal, i18nc("Modulo", "Mod"), i18n("Modulo")); - pbMod->addMode(ModeShift, i18nc("Integer division", "IntDiv"), i18n("Integer division")); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbMod, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbMod, SLOT(slotSetAccelDisplayMode(bool))); - pbMod->setShortcut(QKeySequence(Qt::Key_Colon)); - connect(pbMod, SIGNAL(clicked()), SLOT(slotModclicked())); - - pbReci->addMode(ModeNormal, i18nc("Reciprocal", "1/x"), i18n("Reciprocal")); - pbReci->addMode(ModeShift, i18nc("n Choose m", "nCm"), i18n("n Choose m")); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbReci, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(this, SIGNAL(switchShowAccels(bool)), pbReci, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbReci, SIGNAL(clicked()), SLOT(slotReciclicked())); - - pbFactorial->addMode(ModeNormal, i18nc("Factorial", "x!"), i18n("Factorial")); - pbFactorial->addMode(ModeShift, QLatin1String("Γ"), i18n("Gamma")); - pbFactorial->setShortcut(QKeySequence(Qt::Key_Exclam)); - connect(this, SIGNAL(switchShowAccels(bool)), pbFactorial, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbFactorial, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbFactorial, SIGNAL(clicked()), SLOT(slotFactorialclicked())); - - pbSquare->addMode(ModeNormal, i18nc("Square", "x2"), i18n("Square")); - pbSquare->addMode(ModeShift, QLatin1String("√x"), i18n("Square root")); - pbSquare->setShortcut(QKeySequence(Qt::Key_BracketLeft)); - new QShortcut(Qt::Key_twosuperior, pbSquare, SLOT(animateClick())); - connect(this, SIGNAL(switchShowAccels(bool)), pbSquare, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbSquare, SLOT(slotSetMode(ButtonModeFlags,bool))); - connect(pbSquare, SIGNAL(clicked()), SLOT(slotSquareclicked())); - - pbPower->addMode(ModeNormal, i18nc("x to the power of y", "xy"), i18n("x to the power of y")); - pbPower->addMode(ModeShift, i18nc("x to the power of 1/y", "x1/y"), i18n("x to the power of 1/y")); - connect(this, SIGNAL(switchShowAccels(bool)), pbPower, SLOT(slotSetAccelDisplayMode(bool))); - connect(this, SIGNAL(switchMode(ButtonModeFlags,bool)), pbPower, SLOT(slotSetMode(ButtonModeFlags,bool))); - pbPower->setShortcut(QKeySequence(Qt::Key_AsciiCircum)); - connect(pbPower, SIGNAL(clicked()), SLOT(slotPowerclicked())); - - pbEE->addMode(ModeNormal, QLatin1String("x" "\xb7" "10y"), i18n("Exponent")); - connect(this, SIGNAL(switchShowAccels(bool)), pbEE, SLOT(slotSetAccelDisplayMode(bool))); - connect(pbEE, SIGNAL(clicked()), SLOT(slotEEclicked())); -} - -//------------------------------------------------------------------------------ -// Name: createConstantsMenu -// Desc: additional setup for button keys -// NOTE: all alphanumeric shorts set in ui file -//------------------------------------------------------------------------------ -void KCalculator::setupKeys() { - - setupNumberKeys(); - setupRightKeypad(); - setupNumericKeypad(); - setupLogicKeys(); - setupScientificKeys(); - setupStatisticKeys(); - setupConstantsKeys(); - setupMiscKeys(); - - // other button lists - - function_button_list_.append(pbHyp); - function_button_list_.append(pbShift); - function_button_list_.append(pbEE); - function_button_list_.append(pbSin); - function_button_list_.append(pbPlusMinus); - function_button_list_.append(pbCos); - function_button_list_.append(pbReci); - function_button_list_.append(pbTan); - function_button_list_.append(pbFactorial); - function_button_list_.append(pbLog); - function_button_list_.append(pbSquare); - function_button_list_.append(pbLn); - function_button_list_.append(pbPower); - function_button_list_.append(pbCube); - - mem_button_list_.append(pbMemRecall); - mem_button_list_.append(pbMemPlusMinus); - mem_button_list_.append(pbMemStore); - mem_button_list_.append(pbMemClear); - mem_button_list_.append(pbClear); - mem_button_list_.append(pbAllClear); - - operation_button_list_.append(pbMultiplication); - operation_button_list_.append(pbParenOpen); - operation_button_list_.append(pbParenClose); - operation_button_list_.append(pbAND); - operation_button_list_.append(pbDivision); - operation_button_list_.append(pbOR); - operation_button_list_.append(pbXOR); - operation_button_list_.append(pbPlus); - operation_button_list_.append(pbMinus); - operation_button_list_.append(pbLsh); - operation_button_list_.append(pbRsh); - operation_button_list_.append(pbPeriod); - operation_button_list_.append(pbEqual); - operation_button_list_.append(pbPercent); - operation_button_list_.append(pbCmp); - operation_button_list_.append(pbMod); -} - -//------------------------------------------------------------------------------ -// Name: updateGeometry -// Desc: makes all the buttons have reasonable sizes -//------------------------------------------------------------------------------ -void KCalculator::updateGeometry() { - - const QSize em = pbAND->fontMetrics().size(0, QLatin1String("M")); - int margin = QApplication::style()->pixelMetric(QStyle::PM_ButtonMargin, 0, 0); - margin = qMax(qMin(margin / 2, 3), 3); - - // left pad - foreach(QObject *obj, leftPad->children()) { - if (KCalcButton *const button = qobject_cast(obj)) { - button->setFixedWidth(em.width() * 4 + margin * 2); - button->installEventFilter(this); - } - } - - // right pad - foreach(QObject *obj, rightPad->children()) { - KCalcButton *const button = qobject_cast(obj); - // let Shift expand freely - if (button && button != pbShift) { - button->setFixedWidth(em.width() * 3 + margin * 2); - button->installEventFilter(this); - } - } - - // numeric pad - foreach(QObject *obj, numericPad->children()) { - if (KCalcButton *const button = qobject_cast(obj)) { - // let pb0 expand freely - if (button != pb0) { - button->setFixedWidth(em.width() * 3 + margin * 2); - } - button->installEventFilter(this); - } - } -} - -//------------------------------------------------------------------------------ -// Name: slotConstantToDisplay -// Desc: inserts a constant -//------------------------------------------------------------------------------ -void KCalculator::slotConstantToDisplay(const science_constant &const_chosen) { - - QString val = const_chosen.value; - val.replace(QLatin1Char('.'), KNumber::decimalSeparator()); - calc_display->setAmount(KNumber(val)); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: slotBaseSelected -// Desc: changes the selected numeric base -//------------------------------------------------------------------------------ -void KCalculator::slotBaseSelected(int base) { - - int current_base; - - // set display & statusbar (if item exist in statusbar) - switch (base) { - case BinMode: - current_base = calc_display->setBase(NumBase(2)); - statusBar()->changeItem(QLatin1String("BIN"), BaseField); - calc_display->setStatusText(BaseField, QLatin1String("Bin")); - break; - case OctMode: - current_base = calc_display->setBase(NumBase(8)); - statusBar()->changeItem(QLatin1String("OCT"), BaseField); - calc_display->setStatusText(BaseField, QLatin1String("Oct")); - break; - case DecMode: - current_base = calc_display->setBase(NumBase(10)); - statusBar()->changeItem(QLatin1String("DEC"), BaseField); - calc_display->setStatusText(BaseField, QLatin1String("Dec")); - break; - case HexMode: - current_base = calc_display->setBase(NumBase(16)); - statusBar()->changeItem(QLatin1String("HEX"), BaseField); - calc_display->setStatusText(BaseField, QLatin1String("Hex")); - break; - default: - statusBar()->changeItem(QLatin1String("Error"), BaseField); - calc_display->setStatusText(BaseField, QLatin1String("Error")); - return; - } - - // Enable the buttons available in this base - for (int i = 0; i < current_base; ++i) { - (num_button_group_->buttons()[i])->setEnabled(true); - } - - // Disable the buttons not available in this base - for (int i = current_base; i < 16; ++i) { - (num_button_group_->buttons()[i])->setEnabled(false); - } - - // Only enable the decimal point in decimal - pbPeriod->setEnabled(current_base == NB_DECIMAL); - - // Only enable the x*10^y button in decimal - pbEE->setEnabled(current_base == NB_DECIMAL); - - // Disable buttons that make only sense with floating point numbers - if (current_base != NB_DECIMAL) { - foreach(QAbstractButton *btn, scientific_buttons_) { - btn->setEnabled(false); - } - } else { - foreach(QAbstractButton *btn, scientific_buttons_) { - btn->setEnabled(true); - } - } - - KCalcSettings::setBaseMode(base); -} - -//------------------------------------------------------------------------------ -// Name: keyPressEvent -// Desc: handles keypress events -//------------------------------------------------------------------------------ -void KCalculator::keyPressEvent(QKeyEvent *e) { - - // Fix for bug #314586 - // Basically, on some keyboards such as French, even though the decimal separator - // is "," the numeric keypad has a "." key. So we fake it so people can more seemlessly - // enter numbers using the keypad - if(KNumber::decimalSeparator() != ".") { - if(e->key() == Qt::Key_Period && e->modifiers() & Qt::KeypadModifier) { - pbPeriod->animateClick(); - } - } - - - if (((e->modifiers() & Qt::NoModifier) == 0) || (e->modifiers() & Qt::ShiftModifier)) { - switch (e->key()) { - case Qt::Key_Backspace: - calc_display->deleteLastDigit(); - break; - } - } - - if (e->key() == Qt::Key_Control) { - emit switchShowAccels(true); - } -} - -//------------------------------------------------------------------------------ -// Name: keyReleaseEvent -// Desc: handles keyrelease events -//------------------------------------------------------------------------------ -void KCalculator::keyReleaseEvent(QKeyEvent *e) { - - if (e->key() == Qt::Key_Control) { - emit switchShowAccels(false); - } -} - -//------------------------------------------------------------------------------ -// Name: slotAngleSelected -// Desc: changes the selected angle system -//------------------------------------------------------------------------------ -void KCalculator::slotAngleSelected(int mode) { - - angle_mode_ = mode; - - switch (mode) { - case DegMode: - statusBar()->changeItem(QLatin1String("DEG"), AngleField); - calc_display->setStatusText(AngleField, QLatin1String("Deg")); - break; - case RadMode: - statusBar()->changeItem(QLatin1String("RAD"), AngleField); - calc_display->setStatusText(AngleField, QLatin1String("Rad")); - break; - case GradMode: - statusBar()->changeItem(QLatin1String("GRA"), AngleField); - calc_display->setStatusText(AngleField, QLatin1String("Gra")); - break; - default: // we shouldn't ever end up here - angle_mode_ = RadMode; - } - - KCalcSettings::setAngleMode(angle_mode_); -} - -//------------------------------------------------------------------------------ -// Name: slotEEclicked -// Desc: starts the entering of numers using scientific notation -//------------------------------------------------------------------------------ -void KCalculator::slotEEclicked() { - calc_display->newCharacter(QLatin1Char('e')); -} - -//------------------------------------------------------------------------------ -// Name: slotShifttoggled -// Desc: updates the shift state for alternate button functionality -//------------------------------------------------------------------------------ -void KCalculator::slotShifttoggled(bool flag) { - - shift_mode_ = flag; - - emit switchMode(ModeShift, flag); - - if (shift_mode_) { - statusBar()->changeItem(i18nc("Second button functions are active", "SHIFT"), ShiftField); - calc_display->setStatusText(ShiftField, i18n("Shift")); - } else { - statusBar()->changeItem(i18nc("Normal button functions are active", "NORM"), ShiftField); - calc_display->setStatusText(ShiftField, QString()); - } -} - -//------------------------------------------------------------------------------ -// Name: slotHyptoggled -// Desc: updates the Hyp state for alternate trig button functionality -//------------------------------------------------------------------------------ -void KCalculator::slotHyptoggled(bool flag) { - - // toggle between hyperbolic and standart trig functions - hyp_mode_ = flag; - - emit switchMode(ModeHyperbolic, flag); -} - -//------------------------------------------------------------------------------ -// Name: slotMemRecallclicked -// Desc: recalls a value from memory -//------------------------------------------------------------------------------ -void KCalculator::slotMemRecallclicked() { - - // temp. work-around - calc_display->sendEvent(KCalcDisplay::EventReset); - - calc_display->setAmount(memory_num_); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: slotMemStoreclicked -// Desc: stores a value into memory -//------------------------------------------------------------------------------ -void KCalculator::slotMemStoreclicked() { - - EnterEqual(); - - memory_num_ = calc_display->getAmount(); - calc_display->setStatusText(MemField, QLatin1String("M")); - statusBar()->changeItem(QLatin1String("M"), MemField); - pbMemRecall->setEnabled(true); -} - -//------------------------------------------------------------------------------ -// Name: slotNumberclicked -// Desc: user has entered a digit -//------------------------------------------------------------------------------ -void KCalculator::slotNumberclicked(int number_clicked) { - - calc_display->enterDigit(number_clicked); -} - -//------------------------------------------------------------------------------ -// Name: slotSinclicked -// Desc: executes the sine function -//------------------------------------------------------------------------------ -void KCalculator::slotSinclicked() { - - if (hyp_mode_) { - // sinh or arsinh - if (!shift_mode_) { - core.SinHyp(calc_display->getAmount()); - } else { - core.AreaSinHyp(calc_display->getAmount()); - } - } else { - // sine or arcsine - if (!shift_mode_) { - switch (angle_mode_) { - case DegMode: - core.SinDeg(calc_display->getAmount()); - break; - case RadMode: - core.SinRad(calc_display->getAmount()); - break; - case GradMode: - core.SinGrad(calc_display->getAmount()); - break; - } - } else { - switch (angle_mode_) { - case DegMode: - core.ArcSinDeg(calc_display->getAmount()); - break; - case RadMode: - core.ArcSinRad(calc_display->getAmount()); - break; - case GradMode: - core.ArcSinGrad(calc_display->getAmount()); - break; - } - } - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotPlusMinusclicked -// Desc: changes sign of number being displayed -//------------------------------------------------------------------------------ -void KCalculator::slotPlusMinusclicked() { - - // display can only change sign, when in input mode, otherwise we - // need the core to do this. - if (!calc_display->sendEvent(KCalcDisplay::EventChangeSign)) { - core.InvertSign(calc_display->getAmount()); - updateDisplay(UPDATE_FROM_CORE); - } -} - -//------------------------------------------------------------------------------ -// Name: slotMemPlusMinusclicked -// Desc: handles arithmetic on values stored in memory -//------------------------------------------------------------------------------ -void KCalculator::slotMemPlusMinusclicked() { - - bool tmp_shift_mode = shift_mode_; // store this, because next command deletes shift_mode_ - EnterEqual(); // finish calculation so far, to store result into MEM - - if (!tmp_shift_mode) { - memory_num_ += calc_display->getAmount(); - } else { - memory_num_ -= calc_display->getAmount(); - } - - pbShift->setChecked(false); - statusBar()->changeItem(i18n("M"), MemField); - calc_display->setStatusText(MemField, i18n("M")); - pbMemRecall->setEnabled(true); -} - -//------------------------------------------------------------------------------ -// Name: slotSinclicked -// Desc: executes the cosine function -//------------------------------------------------------------------------------ -void KCalculator::slotCosclicked() { - - if (hyp_mode_) { - // cosh or arcosh - if (!shift_mode_) { - core.CosHyp(calc_display->getAmount()); - } else { - core.AreaCosHyp(calc_display->getAmount()); - } - } else { - // cosine or arccosine - if (!shift_mode_) { - switch (angle_mode_) { - case DegMode: - core.CosDeg(calc_display->getAmount()); - break; - case RadMode: - core.CosRad(calc_display->getAmount()); - break; - case GradMode: - core.CosGrad(calc_display->getAmount()); - break; - } - } else { - switch (angle_mode_) { - case DegMode: - core.ArcCosDeg(calc_display->getAmount()); - break; - case RadMode: - core.ArcCosRad(calc_display->getAmount()); - break; - case GradMode: - core.ArcCosGrad(calc_display->getAmount()); - break; - } - } - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotSinclicked -// Desc: executes the recipricol function -//------------------------------------------------------------------------------ -void KCalculator::slotReciclicked() { - - if (shift_mode_) { - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_BINOM); - } else { - core.Reciprocal(calc_display->getAmount()); - updateDisplay(UPDATE_FROM_CORE); - return; - } - - // temp. work-around - KNumber tmp_num = calc_display->getAmount(); - calc_display->sendEvent(KCalcDisplay::EventReset); - calc_display->setAmount(tmp_num); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: slotSinclicked -// Desc: executes the tangent function -//------------------------------------------------------------------------------ -void KCalculator::slotTanclicked() { - - if (hyp_mode_) { - // tanh or artanh - if (!shift_mode_) { - core.TangensHyp(calc_display->getAmount()); - } else { - core.AreaTangensHyp(calc_display->getAmount()); - } - } else { - // tan or arctan - if (!shift_mode_) { - switch (angle_mode_) { - case DegMode: - core.TangensDeg(calc_display->getAmount()); - break; - case RadMode: - core.TangensRad(calc_display->getAmount()); - break; - case GradMode: - core.TangensGrad(calc_display->getAmount()); - break; - } - } else { - switch (angle_mode_) { - case DegMode: - core.ArcTangensDeg(calc_display->getAmount()); - break; - case RadMode: - core.ArcTangensRad(calc_display->getAmount()); - break; - case GradMode: - core.ArcTangensGrad(calc_display->getAmount()); - break; - } - } - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotFactorialclicked -// Desc: executes the factorial function -//------------------------------------------------------------------------------ -void KCalculator::slotFactorialclicked() { - - // Set WaitCursor, as this operation may take looooong - // time and UI frezes with large numbers. User needs some - // visual feedback. - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (!shift_mode_) { - core.Factorial(calc_display->getAmount()); - } else { - core.Gamma(calc_display->getAmount()); - } - QApplication::restoreOverrideCursor(); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotLogclicked -// Desc: executes the Log function -//------------------------------------------------------------------------------ -void KCalculator::slotLogclicked() { - - if (!shift_mode_) { - core.Log10(calc_display->getAmount()); - } else { - core.Exp10(calc_display->getAmount()); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotSquareclicked -// Desc: executes the x^2 function -//------------------------------------------------------------------------------ -void KCalculator::slotSquareclicked() { - - if (!shift_mode_) { - core.Square(calc_display->getAmount()); - } else { - core.SquareRoot(calc_display->getAmount()); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotCubeclicked -// Desc: executes the x^3 function -//------------------------------------------------------------------------------ -void KCalculator::slotCubeclicked() { - - if (!shift_mode_) { - core.Cube(calc_display->getAmount()); - } else { - core.CubeRoot(calc_display->getAmount()); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotCubeclicked -// Desc: executes the ln function -//------------------------------------------------------------------------------ -void KCalculator::slotLnclicked() { - - if (!shift_mode_) { - core.Ln(calc_display->getAmount()); - } else { - core.Exp(calc_display->getAmount()); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotPowerclicked -// Desc: executes the x^y function -//------------------------------------------------------------------------------ -void KCalculator::slotPowerclicked() { - - if (shift_mode_) { - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_PWR_ROOT); - pbShift->setChecked(false); - } else { - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_POWER); - } - - // temp. work-around - KNumber tmp_num = calc_display->getAmount(); - calc_display->sendEvent(KCalcDisplay::EventReset); - calc_display->setAmount(tmp_num); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: slotMemClearclicked -// Desc: executes the MC function -//------------------------------------------------------------------------------ -void KCalculator::slotMemClearclicked() { - - memory_num_ = KNumber::Zero; - statusBar()->changeItem(QLatin1String(" \xa0\xa0 "), MemField); // nbsp - calc_display->setStatusText(MemField, QString()); - pbMemRecall->setDisabled(true); -} - -//------------------------------------------------------------------------------ -// Name: slotBackspaceclicked -// Desc: removes the last input digit -//------------------------------------------------------------------------------ -void KCalculator::slotBackspaceclicked() { - - calc_display->deleteLastDigit(); -} - -//------------------------------------------------------------------------------ -// Name: slotClearclicked -// Desc: clears the display -//------------------------------------------------------------------------------ -void KCalculator::slotClearclicked() { - - calc_display->sendEvent(KCalcDisplay::EventClear); -} - -//------------------------------------------------------------------------------ -// Name: slotAllClearclicked -// Desc: clears everything -//------------------------------------------------------------------------------ -void KCalculator::slotAllClearclicked() { - - core.Reset(); - calc_display->sendEvent(KCalcDisplay::EventReset); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotParenOpenclicked -// Desc: starts a sub-expression -//------------------------------------------------------------------------------ -void KCalculator::slotParenOpenclicked() { - - core.ParenOpen(calc_display->getAmount()); -} - -//------------------------------------------------------------------------------ -// Name: slotParenCloseclicked -// Desc: ends a sub-expression -//------------------------------------------------------------------------------ -void KCalculator::slotParenCloseclicked() { - - core.ParenClose(calc_display->getAmount()); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotANDclicked -// Desc: executes a bitwise AND -//------------------------------------------------------------------------------ -void KCalculator::slotANDclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_AND); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotMultiplicationclicked -// Desc: executes multiplication -//------------------------------------------------------------------------------ -void KCalculator::slotMultiplicationclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_MULTIPLY); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotDivisionclicked -// Desc: executes division -//------------------------------------------------------------------------------ -void KCalculator::slotDivisionclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_DIVIDE); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotORclicked -// Desc: executes a bitwise OR -//------------------------------------------------------------------------------ -void KCalculator::slotORclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_OR); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotXORclicked -// Desc: executes a bitwise XOR -//------------------------------------------------------------------------------ -void KCalculator::slotXORclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_XOR); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotPlusclicked -// Desc: executes addition -//------------------------------------------------------------------------------ -void KCalculator::slotPlusclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_ADD); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotPlusclicked -// Desc: executes subtraction -//------------------------------------------------------------------------------ -void KCalculator::slotMinusclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_SUBTRACT); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotLeftShiftclicked -// Desc: executes a bitwise left shift -//------------------------------------------------------------------------------ -void KCalculator::slotLeftShiftclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_LSH); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotLeftShiftclicked -// Desc: executes a bitwise right shift -//------------------------------------------------------------------------------ -void KCalculator::slotRightShiftclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_RSH); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotPeriodclicked -// Desc: enters a decimal into the input stream -//------------------------------------------------------------------------------ -void KCalculator::slotPeriodclicked() { - - // i know this isn't locale friendly, should be converted to appropriate - // value at lower levels - calc_display->newCharacter(KGlobal::locale()->toLocale().decimalPoint()); -} - -//------------------------------------------------------------------------------ -// Name: EnterEqual -// Desc: calculates and displays the result of the pending operations -//------------------------------------------------------------------------------ -void KCalculator::EnterEqual() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_EQUAL); - updateDisplay(UPDATE_FROM_CORE | UPDATE_STORE_RESULT); -} - -//------------------------------------------------------------------------------ -// Name: slotEqualclicked -// Desc: calculates and displays the result of the pending operations -//------------------------------------------------------------------------------ -void KCalculator::slotEqualclicked() { - - EnterEqual(); -} - -//------------------------------------------------------------------------------ -// Name: slotPercentclicked -// Desc: calculates and displays the result of the pending operations as a percent -//------------------------------------------------------------------------------ -void KCalculator::slotPercentclicked() { - - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_PERCENT); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotNegateclicked -// Desc: executes a bitwise 2's compliment -// NOTE: implicitly converts the value to an unsigned quantity -//------------------------------------------------------------------------------ -void KCalculator::slotNegateclicked() { - - core.Complement(calc_display->getAmount()); - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotModclicked -// Desc: executes modulous (remainder division) -//------------------------------------------------------------------------------ -void KCalculator::slotModclicked(){ - - if (shift_mode_) { - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_INTDIV); - } else { - core.enterOperation(calc_display->getAmount(), CalcEngine::FUNC_MOD); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatNumclicked -// Desc: executes Sum function -//------------------------------------------------------------------------------ -void KCalculator::slotStatNumclicked() { - - if (!shift_mode_) { - core.StatCount(KNumber::Zero); - } else { - pbShift->setChecked(false); - core.StatSum(KNumber::Zero); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatMeanclicked -// Desc: executes Mean function -//------------------------------------------------------------------------------ -void KCalculator::slotStatMeanclicked() { - - if (!shift_mode_) { - core.StatMean(KNumber::Zero); - } else { - pbShift->setChecked(false); - core.StatSumSquares(KNumber::Zero); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatStdDevclicked -// Desc: executes STD function -//------------------------------------------------------------------------------ -void KCalculator::slotStatStdDevclicked() { - - if (shift_mode_) { - // std (n-1) - core.StatStdDeviation(KNumber::Zero); - pbShift->setChecked(false); - } else { - // std (n) - core.StatStdSample(KNumber::Zero); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatMedianclicked -// Desc: executes Median function -//------------------------------------------------------------------------------ -void KCalculator::slotStatMedianclicked() { - - if (!shift_mode_) { - // std (n-1) - core.StatMedian(KNumber::Zero); - } else { - // std (n) - core.StatMedian(KNumber::Zero); - pbShift->setChecked(false); - } - - // TODO: it seems two different modes should be implemented, but...? - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatDataInputclicked -// Desc: enters a value for statistical functions -//------------------------------------------------------------------------------ -void KCalculator::slotStatDataInputclicked() { - - if (!shift_mode_) { - core.StatDataNew(calc_display->getAmount()); - } else { - pbShift->setChecked(false); - core.StatDataDel(KNumber::Zero); - statusBar()->showMessage(i18n("Last stat item erased"), 3000); - } - - updateDisplay(UPDATE_FROM_CORE); -} - -//------------------------------------------------------------------------------ -// Name: slotStatClearDataclicked -// Desc: clears memory for statical functions -//------------------------------------------------------------------------------ -void KCalculator::slotStatClearDataclicked() { - - if (!shift_mode_) { - core.StatClearAll(KNumber::Zero); - statusBar()->showMessage(i18n("Stat mem cleared"), 3000); - } else { - pbShift->setChecked(false); - updateDisplay(0); - } -} - -//------------------------------------------------------------------------------ -// Name: slotConstclicked -// Desc: enters a constant -//------------------------------------------------------------------------------ -void KCalculator::slotConstclicked(int button) { - - if(KCalcConstButton *btn = qobject_cast(const_buttons_[button])) { - if (!shift_mode_) { - // set the display to the configured value of constant button - // internally, we deal with C locale style numbers, we need to convert - QString val = btn->constant(); - val.replace(QLatin1Char('.'), KNumber::decimalSeparator()); - calc_display->setAmount(KNumber(val)); - - } else { - pbShift->setChecked(false); - - // internally, we deal with C locale style numbers, we need to convert - QString val = calc_display->text(); - val.replace(KNumber::decimalSeparator(), QLatin1String(".")); - KCalcSettings::setValueConstant(button, val); - - // below set new tooltip - btn->setLabelAndTooltip(); - - // work around: after storing a number, pressing a digit should start - // a new number - calc_display->setAmount(calc_display->getAmount()); - } - - updateDisplay(0); - } -} - -//------------------------------------------------------------------------------ -// Name: showSettings -// Desc: opens the shows the settings dialog -//------------------------------------------------------------------------------ -void KCalculator::showSettings() { - - // Check if there is already a dialog and if so bring - // it to the foreground. - if (KConfigDialog::showDialog(QLatin1String("settings"))) { - return; - } - - // Create a new dialog with the same name as the above checking code. - KConfigDialog *const dialog = new KConfigDialog(this, QLatin1String("settings"), KCalcSettings::self()); - dialog->showButtonSeparator(true); - - // general settings - General *const general = new General(0); - general->kcfg_Precision->setMaximum(maxprecision); - dialog->addPage(general, i18n("General"), QLatin1String("accessories-calculator"), i18n("General Settings")); - - // font settings - Fonts *const fonts = new Fonts(0); - dialog->addPage(fonts, i18n("Font"), QLatin1String("preferences-desktop-font"), i18n("Select Display Font")); - - // color settings - Colors *const color = new Colors(0); - dialog->addPage(color, i18n("Colors"), QLatin1String("format-fill-color"), i18n("Button & Display Colors")); - - // constant settings - if (!constants_) { - constants_ = new Constants(0); - } - - KCalcConstMenu *tmp_menu; - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst0(science_constant))); - constants_->pushButton0->setMenu(tmp_menu); - - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst1(science_constant))); - constants_->pushButton1->setMenu(tmp_menu); - - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst2(science_constant))); - constants_->pushButton2->setMenu(tmp_menu); - - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst3(science_constant))); - constants_->pushButton3->setMenu(tmp_menu); - - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst4(science_constant))); - constants_->pushButton4->setMenu(tmp_menu); - - tmp_menu = new KCalcConstMenu(this); - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), this, SLOT(slotChooseScientificConst5(science_constant))); - constants_->pushButton5->setMenu(tmp_menu); - - dialog->addPage(constants_, i18n("Constants"), QLatin1String("preferences-kcalc-constants"), i18n("Define Constants")); - - // When the user clicks OK or Apply we want to update our settings. - connect(dialog, SIGNAL(settingsChanged(QString)), SLOT(updateSettings())); - - // Display the dialog. - dialog->show(); -} - - -// these 6 slots are just a quick hack, instead of setting the -// TextEdit fields in the configuration dialog, we are setting the -// Settingvalues themselves!! - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst0 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst0(const science_constant &chosen_const) { - constants_->kcfg_valueConstant0->setText(chosen_const.value); - constants_->kcfg_nameConstant0->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst1 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst1(const science_constant &chosen_const) { - constants_->kcfg_valueConstant1->setText(chosen_const.value); - constants_->kcfg_nameConstant1->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst2 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst2(const science_constant &chosen_const) { - constants_->kcfg_valueConstant2->setText(chosen_const.value); - constants_->kcfg_nameConstant2->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst3 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst3(const science_constant &chosen_const) { - constants_->kcfg_valueConstant3->setText(chosen_const.value); - constants_->kcfg_nameConstant3->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst4 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst4(const science_constant &chosen_const) { - constants_->kcfg_valueConstant4->setText(chosen_const.value); - constants_->kcfg_nameConstant4->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst5 -// Desc: updates constants value -//------------------------------------------------------------------------------ -void KCalculator::slotChooseScientificConst5(const science_constant &chosen_const) { - constants_->kcfg_valueConstant5->setText(chosen_const.value); - constants_->kcfg_nameConstant5->setText(chosen_const.label); -} - -//------------------------------------------------------------------------------ -// Name: slotSetSimpleMode -// Desc: sets the calculator to have a simple layout -//------------------------------------------------------------------------------ -void KCalculator::slotSetSimpleMode() { - - action_constants_show_->setChecked(false); - action_constants_show_->setEnabled(false); - action_bitset_show_->setChecked(false); - action_bitset_show_->setEnabled(false); - showMemButtons(false); - showScienceButtons(false); - showStatButtons(false); - showLogicButtons(false); - - // hide some individual buttons, which are not in one of the above groups - pbShift->hide(); - pbMod->hide(); - pbReci->hide(); - pbFactorial->hide(); - pbSquare->hide(); - pbPower->hide(); - pbCube->hide(); - pbBackspace->hide(); - pbEE->hide(); - - // delete the constant menu since it doesn't fit - delete constants_menu_; - constants_menu_ = 0; - - KCalcSettings::setCalculatorMode(KCalcSettings::EnumCalculatorMode::simple); -} - -//------------------------------------------------------------------------------ -// Name: slotSetScienceMode -// Desc: sets the calculator to science mode -//------------------------------------------------------------------------------ -void KCalculator::slotSetScienceMode() { - - action_constants_show_->setEnabled(true); - action_constants_show_->setChecked(KCalcSettings::showConstants()); - action_bitset_show_->setChecked(false); - action_bitset_show_->setEnabled(false); - - // show some individual buttons - pbShift->show(); - pbMod->show(); - pbReci->show(); - pbFactorial->show(); - pbSquare->show(); - pbPower->show(); - pbCube->show(); - pbBackspace->show(); - pbEE->show(); - - // show or hide some groups of buttons - showMemButtons(true); - showScienceButtons(true); - showStatButtons(false); - showLogicButtons(false); - - if(!constants_menu_) { - constants_menu_ = createConstantsMenu(); - menuBar()->insertMenu((menuBar()->actions)()[2], constants_menu_); - } - - KCalcSettings::setCalculatorMode(KCalcSettings::EnumCalculatorMode::science); -} - -//------------------------------------------------------------------------------ -// Name: slotSetStatisticMode -// Desc: sets the calculator to stats mode -//------------------------------------------------------------------------------ -void KCalculator::slotSetStatisticMode() { - - action_constants_show_->setEnabled(true); - action_constants_show_->setChecked(KCalcSettings::showConstants()); - action_bitset_show_->setChecked(false); - action_bitset_show_->setEnabled(false); - - // show some individual buttons - pbShift->show(); - pbMod->show(); - pbReci->show(); - pbFactorial->show(); - pbSquare->show(); - pbPower->show(); - pbCube->show(); - pbBackspace->show(); - pbEE->show(); - - // show or hide some groups of buttons - showMemButtons(true); - showScienceButtons(true); - showStatButtons(true); - showLogicButtons(false); - - if(!constants_menu_) { - constants_menu_ = createConstantsMenu(); - menuBar()->insertMenu((menuBar()->actions)()[2], constants_menu_); - } - - KCalcSettings::setCalculatorMode(KCalcSettings::EnumCalculatorMode::statistics); -} - -//------------------------------------------------------------------------------ -// Name: slotSetNumeralMode -// Desc: sets the calculator to numerical ("programmers") mode -//------------------------------------------------------------------------------ -void KCalculator::slotSetNumeralMode() { - - action_constants_show_->setChecked(false); - action_constants_show_->setEnabled(false); - action_bitset_show_->setEnabled(true); - action_bitset_show_->setChecked(KCalcSettings::showBitset()); - - // show some individual buttons - pbShift->show(); - pbMod->show(); - pbReci->show(); - pbFactorial->show(); - pbSquare->show(); - pbPower->show(); - pbCube->show(); - pbBackspace->show(); - pbEE->show(); - - // show or hide some groups of buttons - showMemButtons(true); - showScienceButtons(false); - showStatButtons(false); - showLogicButtons(true); - - if(!constants_menu_) { - constants_menu_ = createConstantsMenu(); - menuBar()->insertMenu((menuBar()->actions)()[2], constants_menu_); - } - - KCalcSettings::setCalculatorMode(KCalcSettings::EnumCalculatorMode::numeral); -} - -//------------------------------------------------------------------------------ -// Name: showMemButtons -// Desc: hides or shows the memory buttons -//------------------------------------------------------------------------------ -void KCalculator::showMemButtons(bool toggled) { - - if (toggled) { - foreach(QAbstractButton *btn, mem_button_list_) { - btn->show(); - } - } else { - foreach(QAbstractButton *btn, mem_button_list_) { - btn->hide(); - } - - // these are in the mem_button_list_ but should not be hidden - pbClear->show(); - pbAllClear->show(); - } -} - -//------------------------------------------------------------------------------ -// Name: showStatButtons -// Desc: hides or shows the stat buttons -//------------------------------------------------------------------------------ -void KCalculator::showStatButtons(bool toggled) { - - if (toggled) { - foreach(QAbstractButton *btn, stat_buttons_) { - btn->show(); - } - } else { - foreach(QAbstractButton *btn, stat_buttons_) { - btn->hide(); - } - } -} - -//------------------------------------------------------------------------------ -// Name: showScienceButtons -// Desc: hides or shows the science buttons -//------------------------------------------------------------------------------ -void KCalculator::showScienceButtons(bool toggled) { - - if (toggled) { - foreach(QAbstractButton* btn, scientific_buttons_) { - btn->show(); - } - - foreach(QAbstractButton* btn, angle_choose_group_->buttons()) { - btn->show(); - } - - setAngle(); - statusBar()->setItemFixed(AngleField, -1); - } else { - foreach(QAbstractButton* btn, scientific_buttons_) { - btn->hide(); - } - - foreach(QAbstractButton* btn, angle_choose_group_->buttons()) { - btn->hide(); - } - - statusBar()->changeItem(QString(), AngleField); - statusBar()->setItemFixed(AngleField, 0); - calc_display->setStatusText(AngleField, QString()); - } -} - -//------------------------------------------------------------------------------ -// Name: showLogicButtons -// Desc: hides or shows the logic buttons -//------------------------------------------------------------------------------ -void KCalculator::showLogicButtons(bool toggled) { - - if (toggled) { - mBitset->setEnabled(true); - connect(mBitset, SIGNAL(valueChanged(quint64)), this, SLOT(slotBitsetChanged(quint64))); - connect(calc_display, SIGNAL(changedAmount(KNumber)), SLOT(slotUpdateBitset(KNumber))); - - foreach(QAbstractButton* btn, logic_buttons_) { - btn->show(); - } - - setBase(); - statusBar()->setItemFixed(BaseField, -1); - - foreach(QAbstractButton *btn, base_choose_group_->buttons()) { - btn->show(); - } - - for (int i = 10; i < 16; ++i) { - num_button_group_->button(i)->show(); - } - } else { - mBitset->setEnabled(false); - disconnect(mBitset, SIGNAL(valueChanged(quint64)), this, SLOT(slotBitsetChanged(quint64))); - disconnect(calc_display, SIGNAL(changedAmount(KNumber)), this, SLOT(slotUpdateBitset(KNumber))); - - foreach(QAbstractButton* btn, logic_buttons_) { - btn->hide(); - } - - // Hide Hex-Buttons, but first switch back to decimal - decRadio->animateClick(0); - - foreach(QAbstractButton *btn, base_choose_group_->buttons()) { - btn->hide(); - } - - statusBar()->changeItem(QString(), BaseField); - statusBar()->setItemFixed(BaseField, 0); - calc_display->setStatusText(BaseField, QString()); - for (int i = 10; i < 16; ++i) { - num_button_group_->button(i)->hide(); - } - } -} - -//------------------------------------------------------------------------------ -// Name: slotConstantsShow -// Desc: hides or shows the constants buttons -//------------------------------------------------------------------------------ -void KCalculator::slotConstantsShow(bool toggled) { - - if (toggled) { - foreach(QAbstractButton *btn, const_buttons_) { - btn->show(); - } - } else { - foreach(QAbstractButton *btn, const_buttons_) { - btn->hide(); - } - } - - KCalcSettings::setShowConstants(toggled); -} - -//------------------------------------------------------------------------------ -// Name: slotBitsetshow -// Desc: hides or shows the bitset buttons -//------------------------------------------------------------------------------ -void KCalculator::slotBitsetshow(bool toggled) { - - mBitset->setVisible(toggled); - KCalcSettings::setShowBitset(toggled); -} - -//------------------------------------------------------------------------------ -// Name: slotBitsetshow -// Desc: This function is for setting the constant names configured in the -// kcalc settings menu. If the user doesn't enter a name for the -// constant C1 to C6 is used. -//------------------------------------------------------------------------------ -void KCalculator::changeButtonNames() { - - foreach(QAbstractButton *btn, const_buttons_) { - if (KCalcConstButton *const constbtn = qobject_cast(btn)) { - constbtn->setLabelAndTooltip(); - } - } -} - -//------------------------------------------------------------------------------ -// Name: slotBitsetChanged -// Desc: updates the bitset display -// NOTE: sets display to *unsigned* value -//------------------------------------------------------------------------------ -void KCalculator::slotBitsetChanged(quint64 value) { - - calc_display->setAmount(KNumber(value)); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: slotUpdateBitset -// Desc: updates the bitset itself -//------------------------------------------------------------------------------ -void KCalculator::slotUpdateBitset(const KNumber &nr) { - - mBitset->setValue(nr.toUint64()); -} - -//------------------------------------------------------------------------------ -// Name: updateSettings -// Desc: updates the persistent settings -//------------------------------------------------------------------------------ -void KCalculator::updateSettings() { - - changeButtonNames(); - setColors(); - setFonts(); - setPrecision(); - - // Show the result in the app's caption in taskbar (wishlist - bug #52858) - disconnect(calc_display, SIGNAL(changedText(QString)), this, 0); - - if (KCalcSettings::captionResult()) { - connect(calc_display, SIGNAL(changedText(QString)), SLOT(setCaption(QString))); - } else { - setCaption(QString()); - } - - calc_display->changeSettings(); - updateGeometry(); -} - -//------------------------------------------------------------------------------ -// Name: updateDisplay -// Desc: updates the display -//------------------------------------------------------------------------------ -void KCalculator::updateDisplay(UpdateFlags flags) { - - if(flags & UPDATE_FROM_CORE) { - calc_display->updateFromCore(core, (flags & UPDATE_STORE_RESULT) != 0); - } else { - calc_display->update(); - } - - pbShift->setChecked(false); - -} - -//------------------------------------------------------------------------------ -// Name: setColors -// Desc: set the various colours -//------------------------------------------------------------------------------ -void KCalculator::setColors() { - - calc_display->changeSettings(); - - KColorScheme schemeButtons(QPalette::Active, KColorScheme::Button); - const QColor defaultColor = schemeButtons.background().color(); - - if (KCalcSettings::numberButtonsColor() == defaultColor - && KCalcSettings::functionButtonsColor() == defaultColor - && KCalcSettings::statButtonsColor() == defaultColor - && KCalcSettings::hexButtonsColor() == defaultColor - && KCalcSettings::memoryButtonsColor() == defaultColor - && KCalcSettings::operationButtonsColor() == defaultColor) { - return; - } - - const QPalette numPal(KCalcSettings::numberButtonsColor()); - for (int i = 0; i < 10; ++i) { - num_button_group_->button(i)->setPalette(numPal); - } - - const QPalette funcPal(KCalcSettings::functionButtonsColor()); - foreach(QAbstractButton *btn, function_button_list_) { - btn->setPalette(funcPal); - } - - const QPalette statPal(KCalcSettings::statButtonsColor()); - foreach(QAbstractButton *btn, stat_buttons_) { - btn->setPalette(statPal); - } - - const QPalette hexPal(KCalcSettings::hexButtonsColor()); - for (int i = 10; i < 16; ++i) { - num_button_group_->button(i)->setPalette(hexPal); - } - - const QPalette memPal(KCalcSettings::memoryButtonsColor()); - foreach(QAbstractButton *btn, mem_button_list_) { - btn->setPalette(memPal); - } - - const QPalette opPal(KCalcSettings::operationButtonsColor()); - foreach(QAbstractButton *btn, operation_button_list_) { - btn->setPalette(opPal); - } -} - -//------------------------------------------------------------------------------ -// Name: setFonts -// Desc: set the various fonts -//------------------------------------------------------------------------------ -void KCalculator::setFonts() { - - foreach(QObject *obj, leftPad->children()) { - if (KCalcButton *const button = qobject_cast(obj)) { - button->setFont(KCalcSettings::buttonFont()); - } - } - - foreach(QObject *obj, numericPad->children()) { - if (KCalcButton *const button = qobject_cast(obj)) { - button->setFont(KCalcSettings::buttonFont()); - } - } - - foreach(QObject *obj, rightPad->children()) { - if (KCalcButton *const button = qobject_cast(obj)) { - button->setFont(KCalcSettings::buttonFont()); - } - } - - updateGeometry(); -} - -//------------------------------------------------------------------------------ -// Name: setPrecision -// Desc: set the precision of the display -//------------------------------------------------------------------------------ -void KCalculator::setPrecision() { - - KNumber::setDefaultFloatPrecision(KCalcSettings::precision()); - updateDisplay(0); -} - -//------------------------------------------------------------------------------ -// Name: setAngle -// Desc: sets the angle mode -//------------------------------------------------------------------------------ -void KCalculator::setAngle() { - - if (QAbstractButton *const btn = angle_choose_group_->button(KCalcSettings::angleMode())) { - btn->animateClick(0); - } -} - -//------------------------------------------------------------------------------ -// Name: setBase -// Desc: sets the numeric base -//------------------------------------------------------------------------------ -void KCalculator::setBase() { - if (QAbstractButton *const btn = base_choose_group_->button(KCalcSettings::baseMode())) { - btn->animateClick(0); - } -} - -//------------------------------------------------------------------------------ -// Name: eventFilter -// Desc: general event filter used to track events like drag/drop -//------------------------------------------------------------------------------ -bool KCalculator::eventFilter(QObject *o, QEvent *e) { - - switch (e->type()) { - case QEvent::DragEnter: { - QDragEnterEvent *const ev = reinterpret_cast(e); - ev->setAccepted(KColorMimeData::canDecode(ev->mimeData())); - return true; - } - case QEvent::DragLeave: { - return true; - } - // FIXME: color is not saved and restored (the color does not persist trough kcalc restart) - case QEvent::Drop: { - KCalcButton *const calcButton = qobject_cast(o); - if (!calcButton) { - return false; - } - - QDropEvent *const ev = reinterpret_cast(e); - QColor c = KColorMimeData::fromMimeData(ev->mimeData()); - - if (c.isValid()) { - QString cn = c.name(); - QString sheet = QLatin1String("background-color: %1"); - - QList *list; - const int num_but = num_button_group_->buttons().indexOf(calcButton); - if (num_but != -1) { - // Was it hex-button or normal digit?? - if (num_but < 10) { - for (int i = 0; i < 10; ++i) { - num_button_group_->button(i)->setStyleSheet(sheet.arg(cn)); - } - } else { - for (int i = 10; i < 16; ++i) { - num_button_group_->button(i)->setStyleSheet(sheet.arg(cn)); - } - } - return true; - } else if (function_button_list_.contains(calcButton)) { - list = &function_button_list_; - } else if (stat_button_list_.contains(calcButton)) { - list = &stat_button_list_; - } else if (mem_button_list_.contains(calcButton)) { - list = &mem_button_list_; - } else if (operation_button_list_.contains(calcButton)) { - list = &operation_button_list_; - } else { - return false; - } - - for (int i = 0; i < list->size(); ++i) { - list->at(i)->setStyleSheet(sheet.arg(cn)); - } - } - return true; - } - // FALL THROUGH - default: - return KXmlGuiWindow::eventFilter(o, e); - } -} - -//////////////////////////////////////////////////////////////// -// Include the meta-object code for classes in this file -// -#include "moc_kcalc.cpp" - -//------------------------------------------------------------------------------ -// Name: main -// Desc: entry point of the application -//------------------------------------------------------------------------------ -int main(int argc, char *argv[]) { - - KAboutData aboutData("kcalc", - 0, - ki18n("KCalc"), - version, - ki18n(description), - KAboutData::License_GPL, - ki18n( - "© 2008-2013, Evan Teran\n" - "© 2000-2008, The KDE Team\n" - "© 2003-2005, Klaus Niederkr" "\xc3\xbc" "ger\n" - "© 1996-2000, Bernd Johannes Wuebben")); - - // Klaus Niederkrueger - aboutData.addAuthor(ki18n("Klaus Niederkr" "\xc3\xbc" "ger"), KLocalizedString(), "kniederk@math.uni-koeln.de"); - aboutData.addAuthor(ki18n("Bernd Johannes Wuebben"), KLocalizedString(), "wuebben@kde.org"); - aboutData.addAuthor(ki18n("Evan Teran"), ki18n("Maintainer"), "eteran@alum.rit.edu"); - aboutData.addAuthor(ki18n("Espen Sand"), KLocalizedString(), "espen@kde.org"); - aboutData.addAuthor(ki18n("Chris Howells"), KLocalizedString(), "howells@kde.org"); - aboutData.addAuthor(ki18n("Aaron J. Seigo"), KLocalizedString(), "aseigo@olympusproject.org"); - aboutData.addAuthor(ki18n("Charles Samuels"), KLocalizedString(), "charles@altair.dhs.org"); - // Rene Merou - aboutData.addAuthor(ki18n("Ren" "\xc3\xa9" " M" "\xc3\xa9" "rou"), KLocalizedString(), "ochominutosdearco@yahoo.es"); - aboutData.addAuthor(ki18n("Michel Marti"), KLocalizedString(), "mma@objectxp.com"); - aboutData.addAuthor(ki18n("David Johnson"), KLocalizedString(), "david@usermode.org"); - - aboutData.setProgramIconName(QLatin1String("accessories-calculator")); - - KCmdLineArgs::init(argc, argv, &aboutData); - - KApplication app; - - // force system locale to "C" internally [bug 159168] - setlocale(LC_NUMERIC, "C"); - - const QLocale locale = KGlobal::locale()->toLocale(); - KNumber::setGroupSeparator(locale.groupSeparator()); - KNumber::setDecimalSeparator(locale.decimalPoint()); - - KCalculator *calc = new KCalculator(0); - app.setTopWidget(calc); - - calc->show(); - return app.exec(); -} diff --git a/kcalc/kcalc.desktop b/kcalc/kcalc.desktop deleted file mode 100755 index cc906dd5..00000000 --- a/kcalc/kcalc.desktop +++ /dev/null @@ -1,155 +0,0 @@ -[Desktop Entry] -Name=KCalc -Name[af]=Kcalc -Name[ar]=حاسبة ك -Name[ast]=KCalc -Name[bg]=KCalc -Name[br]=KCalc -Name[bs]=KCalc -Name[ca]=KCalc -Name[ca@valencia]=KCalc -Name[cs]=KCalc -Name[cy]=KCalc -Name[da]=KCalc -Name[de]=KCalc -Name[el]=KCalc -Name[en_GB]=KCalc -Name[eo]=KCalc -Name[es]=KCalc -Name[et]=KCalc -Name[eu]=KCalc -Name[fi]=KCalc -Name[fr]=KCalc -Name[ga]=KCalc -Name[gl]=KCalc -Name[he]=KCalc -Name[hne]=के-केल्क -Name[hr]=KCalc -Name[hu]=KCalc -Name[ia]=KCalc -Name[id]=KCalc -Name[is]=KCalc -Name[it]=KCalc -Name[ja]=KCalc -Name[kk]=KCalc -Name[km]=KCalc -Name[ko]=KCalc -Name[lt]=KCalc -Name[lv]=KCalc -Name[mk]=KCalc -Name[mr]=के-कॅल्क -Name[ms]=KCalc -Name[nb]=KCalc -Name[nds]=KCalc -Name[ne]=केडीई क्याल्क -Name[nl]=KCalc -Name[nn]=KCalc -Name[pa]=ਕੇ-ਕੈਲਕ -Name[pl]=Kalkulator -Name[pt]=KCalc -Name[pt_BR]=KCalc -Name[ro]=KCalc -Name[ru]=KCalc -Name[sk]=KCalc -Name[sl]=KCalc -Name[sq]=KCalc -Name[sr]=К‑калк -Name[sr@ijekavian]=К‑калк -Name[sr@ijekavianlatin]=KCalc -Name[sr@latin]=KCalc -Name[sv]=Kcalc -Name[ta]=கேகணிப்பான் -Name[tg]=KМошинаи ҳисобкунак -Name[th]=เครื่องคิดเลข-K -Name[tr]=KCalc -Name[ug]=KCalc -Name[uk]=KCalc -Name[uz]=Kalkulyator -Name[uz@cyrillic]=Калкулятор -Name[vi]=KCalc -Name[wa]=KCalc -Name[x-test]=xxKCalcxx -Name[zh_CN]=KCalc -Name[zh_TW]=KDE 計算機 -Exec=kcalc --icon '%i' --caption '%c' -Icon=accessories-calculator -X-DocPath=kcalc/index.html -GenericName=Scientific Calculator -GenericName[af]=Wetenskaplike Sakrekenaar -GenericName[ar]=آلة حاسبة علمية -GenericName[ast]=Calculadora Científica -GenericName[bg]=Калкулатор -GenericName[br]=Ur jederez skiantel -GenericName[bs]=Naučni kalkulator -GenericName[ca]=Calculadora científica -GenericName[ca@valencia]=Calculadora científica -GenericName[cs]=Vědecká kalkulačka -GenericName[cy]=Cyfrifydd Gwyddonol -GenericName[da]=Videnskabelig regnemaskine -GenericName[de]=Wissenschaftlicher Taschenrechner -GenericName[el]=Επιστημονικό κομπιουτεράκι -GenericName[en_GB]=Scientific Calculator -GenericName[eo]=Scienca kalkulilo -GenericName[es]=Calculadora científica -GenericName[et]=Teaduslik kalkulaator -GenericName[eu]=Kalkulagailu zientifikoa -GenericName[fa]=ماشین حساب علمی -GenericName[fi]=Tieteellinen laskin -GenericName[fr]=Calculatrice scientifique -GenericName[ga]=Áireamhán Eolaíochta -GenericName[gl]=Unha calculadora científica -GenericName[he]=מחשבון מדעי -GenericName[hne]=वैग्यानिक केल्कुलेटर -GenericName[hr]=Znanstveni kalkulator -GenericName[hu]=Tudományos számológép -GenericName[ia]=Calculator scientific -GenericName[id]=Kalkulator Ilmiah -GenericName[is]=Öflug reiknivél -GenericName[it]=Calcolatrice scientifica -GenericName[ja]=科学電卓 -GenericName[kk]=Ғылыми калькулятор -GenericName[km]=​ម៉ាស៊ីន​គិត​លេខ​​​វិទ្យាសាស្ត្រ -GenericName[ko]=공학용 계산기 -GenericName[lt]=Mokslinis skaičiuotuvas -GenericName[lv]=Zinātniskais kalkulators -GenericName[mk]=Научен калкулатор -GenericName[mr]=शास्त्रीय गणकयंत्र -GenericName[ms]=Scientific Calculator -GenericName[nb]=Vitenskapelig kalkulator -GenericName[nds]=Wetenschaplich Taschenreekner -GenericName[ne]=वैज्ञानिक गणकयन्त्र -GenericName[nl]=Wetenschappelijke rekenmachine -GenericName[nn]=Vitskapleg kalkulator -GenericName[pa]=ਵਿਗਿਆਨਿਕ ਕੈਲਕੂਲੇਟਰ -GenericName[pl]=Kalkulator naukowy -GenericName[pt]=Calculadora Cientifica -GenericName[pt_BR]=Calculadora científica -GenericName[ro]=Calculator științific -GenericName[ru]=Калькулятор -GenericName[sk]=Vedecká kalkulačka -GenericName[sl]=Znanstveno računalo -GenericName[sq]=Makinë Llogaritëse Shkencore -GenericName[sr]=Научни калкулатор -GenericName[sr@ijekavian]=Научни калкулатор -GenericName[sr@ijekavianlatin]=Naučni kalkulator -GenericName[sr@latin]=Naučni kalkulator -GenericName[sv]=Vetenskaplig miniräknare -GenericName[ta]= அறிவியல் சார்ந்த கணிப்பான் -GenericName[tg]=Мошинаи ҳисобкунаки Илмӣ -GenericName[th]=เครื่องคิดเลขทางวิทยาศาสตร์ -GenericName[tr]=Bilimsel Hesap Makinesi -GenericName[ug]=ئىلمىي ھېسابلىغۇچ -GenericName[uk]=Калькулятор для науковців -GenericName[uz]=Ilmiy kalkulyator -GenericName[uz@cyrillic]=Илмий калкулятор -GenericName[vi]=Máy Tính Khoa Học -GenericName[wa]=Carculete syintifike -GenericName[xh]=Umatshini Wokubala Ezenzululwazi -GenericName[x-test]=xxScientific Calculatorxx -GenericName[zh_CN]=科学计算器 -GenericName[zh_TW]=科學計算機 -Terminal=false -Type=Application -StartupNotify=true -X-KDE-HasTrayOption=true -Categories=Qt;KDE;Utility;X-KDE-Utilities-Desktop; diff --git a/kcalc/kcalc.h b/kcalc/kcalc.h deleted file mode 100644 index d4c6faa3..00000000 --- a/kcalc/kcalc.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#ifndef KCALC_H_ -#define KCALC_H_ - -class Constants; -#include -class KToggleAction; -class KCalcConstMenu; - -/* - Kcalc basically consist of a class for the GUI (here), a class for - the display (dlabel.h), and one for the mathematics core - (kcalc_core.h). - - When for example '+' is pressed, one sends the contents of the - Display and the '+' to the core via "core.Plus(DISPLAY_AMOUNT)". - This only updates the core. To bring the changes to the display, - use afterwards "UpdateDisplay(true)". - - "UpdateDisplay(true)" means that the amount to be displayed should - be taken from the core (get the result of some operation that was - performed), "UpdateDisplay(false)" has already the information, what - to be display (e.g. user is typing in a number). Note that in the - last case the core does not know the number typed in until some - operation button is pressed, e.g. "core.Plus(display_number)". - */ - -#include "kcalc_core.h" -#include "kcalc_button.h" -#include "kcalc_const_button.h" - -#include "ui_kcalc.h" -#include "ui_general.h" -#include "ui_fonts.h" -#include "ui_constants.h" -#include "ui_colors.h" - -#include - -#include - -class General: public QWidget, public Ui::General -{ -public: - explicit General(QWidget *parent) : QWidget(parent) { - setupUi(this); - } -}; - -class Fonts: public QWidget, public Ui::Fonts -{ -public: - explicit Fonts(QWidget *parent) : QWidget(parent) { - setupUi(this); - } -}; - -class Constants : public QWidget, public Ui::Constants -{ -public: - explicit Constants(QWidget *parent) : QWidget(parent) { - setupUi(this); - } -}; - -class Colors : public QWidget, public Ui::Colors -{ -public: - explicit Colors(QWidget *parent) : QWidget(parent) { - setupUi(this); - } -}; - - -class KCalculator : public KXmlGuiWindow, private Ui::KCalculator -{ - Q_OBJECT - -public: - explicit KCalculator(QWidget *parent = 0); - ~KCalculator(); - -signals: - void switchShift(bool); - void switchMode(ButtonModeFlags, bool); - void switchShowAccels(bool); - -public: - enum UpdateFlag { - UPDATE_FROM_CORE = 1, - UPDATE_STORE_RESULT = 2 - }; - - Q_DECLARE_FLAGS(UpdateFlags, UpdateFlag) - -private: - virtual bool eventFilter(QObject *o, QEvent *e); - void updateGeometry(); - void setupMainActions(); - void setupStatusbar(); - void setupKeys(); - void setupNumberKeys(); - void setupRightKeypad(); - void setupNumericKeypad(); - void setupLogicKeys(); - void setupScientificKeys(); - void setupStatisticKeys(); - void setupConstantsKeys(); - void setupMiscKeys(); - void keyPressEvent(QKeyEvent *e); - void keyReleaseEvent(QKeyEvent *e); - void setPrecision(); - void setAngle(); - void setBase(); - - void updateDisplay(UpdateFlags flags); - - // button sets - void showMemButtons(bool toggled); - void showStatButtons(bool toggled); - void showScienceButtons(bool toggled); - void showLogicButtons(bool toggled); - - KCalcConstMenu *createConstantsMenu(); - -protected slots: - void changeButtonNames(); - void updateSettings(); - void setColors(); - void setFonts(); - void EnterEqual(); - void showSettings(); - - // Mode - void slotSetSimpleMode(); - void slotSetScienceMode(); - void slotSetStatisticMode(); - void slotSetNumeralMode(); - - void slotConstantsShow(bool toggled); - void slotBitsetshow(bool toggled); - void slotAngleSelected(int mode); - void slotBaseSelected(int base); - void slotNumberclicked(int number_clicked); - void slotEEclicked(); - void slotShifttoggled(bool myboolean); - void slotMemRecallclicked(); - void slotMemStoreclicked(); - void slotSinclicked(); - void slotPlusMinusclicked(); - void slotMemPlusMinusclicked(); - void slotCosclicked(); - void slotReciclicked(); - void slotTanclicked(); - void slotFactorialclicked(); - void slotLogclicked(); - void slotSquareclicked(); - void slotCubeclicked(); - void slotLnclicked(); - void slotPowerclicked(); - void slotMemClearclicked(); - void slotClearclicked(); - void slotAllClearclicked(); - void slotParenOpenclicked(); - void slotParenCloseclicked(); - void slotANDclicked(); - void slotMultiplicationclicked(); - void slotDivisionclicked(); - void slotORclicked(); - void slotXORclicked(); - void slotPlusclicked(); - void slotMinusclicked(); - void slotLeftShiftclicked(); - void slotRightShiftclicked(); - void slotPeriodclicked(); - void slotEqualclicked(); - void slotPercentclicked(); - void slotNegateclicked(); - void slotModclicked(); - void slotStatNumclicked(); - void slotStatMeanclicked(); - void slotStatStdDevclicked(); - void slotStatMedianclicked(); - void slotStatDataInputclicked(); - void slotStatClearDataclicked(); - void slotHyptoggled(bool flag); - void slotConstclicked(int); - void slotBackspaceclicked(); - - void slotConstantToDisplay(const science_constant &const_chosen); - void slotChooseScientificConst0(const science_constant &); - void slotChooseScientificConst1(const science_constant &); - void slotChooseScientificConst2(const science_constant &); - void slotChooseScientificConst3(const science_constant &); - void slotChooseScientificConst4(const science_constant &); - void slotChooseScientificConst5(const science_constant &); - - void slotBitsetChanged(quint64); - void slotUpdateBitset(const KNumber &); - -private: - enum StatusField { - ShiftField = 0, - BaseField, - AngleField, - MemField - }; - - enum AngleMode { - DegMode = 0, - RadMode, - GradMode - }; - - enum BaseMode { - BinMode = 2, - OctMode = 8, - DecMode = 10, - HexMode = 16 - }; - -private: - bool shift_mode_; - bool hyp_mode_; - KNumber memory_num_; - - int angle_mode_; // angle modes for trigonometric values - - KCalcConstMenu* constants_menu_; - - Constants* constants_; // this is the dialog for configuring const buttons - - QButtonGroup* angle_choose_group_; - QButtonGroup* base_choose_group_; - // num_button_group_: 0-9 = digits, 0xA-0xF = hex-keys - QButtonGroup* num_button_group_; - - QList logic_buttons_; - QList scientific_buttons_; - QList stat_buttons_; - QList const_buttons_; - - KToggleAction *action_bitset_show_; - KToggleAction *action_constants_show_; - - KToggleAction *action_mode_simple_; - KToggleAction *action_mode_science_; - KToggleAction *action_mode_statistic_; - KToggleAction *action_mode_numeral_; - - QList function_button_list_; - QList stat_button_list_; - QList mem_button_list_; - QList operation_button_list_; - - CalcEngine core; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(KCalculator::UpdateFlags) - -#endif diff --git a/kcalc/kcalc.kcfg b/kcalc/kcalc.kcfg deleted file mode 100644 index 5dfac3b6..00000000 --- a/kcalc/kcalc.kcfg +++ /dev/null @@ -1,201 +0,0 @@ - - - KApplication - KGlobalSettings - KColorScheme - KLocale - - - - - KColorScheme schemeView(QPalette::Active, KColorScheme::View); - QColor defaultColor = schemeView.foreground().color(); - defaultColor - - - - defaultColor = schemeView.background().color(); - defaultColor - - - - KColorScheme schemeButtons(QPalette::Active, KColorScheme::Button); - QColor defaultButtonColor = schemeButtons.background().color(); - defaultButtonColor - - - - defaultButtonColor - - - - defaultButtonColor - - - - defaultButtonColor - - - - defaultButtonColor - - - - defaultButtonColor - - - - - - KGlobalSettings::generalFont() - - - - QFont(KGlobalSettings::generalFont().family(), 14, QFont::Bold) - - - - - - - KCalc can compute with many more digits than the number that - fits on the display. This setting gives the maximum number of - digits displayed, before KCalc starts using scientific notation, - i.e. notation of the type 2.34e12. - - 12 - 8 - 200 - - - - 2 - - - - false - - - - - - true - - - - false - - - - true - - - - - Select to use Two's Complement notation for Binary, Octal - and Hexidecimal numbers. This is a common notation to represent - negative numbers in computers. - - true - - - - - - A very simple mode where only the basic calculator buttons are shown - - - - Mode with science buttons and optional constants buttons - - - - Mode with additional statistics buttons and optional constants buttons - - - - Mode with logic buttons and selectable base. Optional bit edit available. - - - - - - false - - - - false - - - - 0 - - - - 10 - - - - - - - For easier readability it's possible to visible group the individual digits into pairs - for example instead of 10111001 you can display 1011 1001, by setting the setting to - 4, thus inserting a whitespace after every 4th digit. - - 4 - - - - - For easier readability it's possible to visible group the individual digits into pairs - for example instead of 42140213 you can display 4214 0213, by setting the setting to - 4, thus inserting a whitespace after every 4th digit. - - 4 - - - - - For easier readability it's possible to visible group the individual digits into pairs - for example instead of AF1C42 you can display AF 1C 42, by setting the setting to - 2, thus inserting a whitespace after every 2nd digit. - - 2 - - - - - - - - QString nameConstant0 = i18nc("Name of the user programmable constant", "C1"); - QString nameConstant1 = i18nc("Name of the user programmable constant", "C2"); - QString nameConstant2 = i18nc("Name of the user programmable constant", "C3"); - QString nameConstant3 = i18nc("Name of the user programmable constant", "C4"); - QString nameConstant4 = i18nc("Name of the user programmable constant", "C5"); - QString nameConstant5 = i18nc("Name of the user programmable constant", "C6"); - - nameConstant0 - nameConstant1 - nameConstant2 - nameConstant3 - nameConstant4 - nameConstant5 - - - - - - 0 - 0 - 0 - 0 - 0 - 0 - - - diff --git a/kcalc/kcalc.ui b/kcalc/kcalc.ui deleted file mode 100644 index 3f215784..00000000 --- a/kcalc/kcalc.ui +++ /dev/null @@ -1,1093 +0,0 @@ - - - KCalculator - - - - 0 - 0 - 701 - 320 - - - - - 0 - 0 - - - - KCalc - - - - QLayout::SetMinimumSize - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - QFrame::StyledPanel - - - QFrame::Sunken - - - - - - - - 0 - 0 - - - - Click on a Bit to toggle it. - - - - - - - - - Deg - - - - - - - Rad - - - - - - - Grad - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Switch base to hexadecimal. - - - He&x - - - - - - - Switch base to decimal. - - - &Dec - - - - - - - Switch base to octal. - - - &Oct - - - - - - - Switch base to binary. - - - &Bin - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 2 - - - 4 - - - - - Number of data entered - - - N - - - - - - - Hyperbolic mode - - - Hyp - - - H - - - true - - - - - - - Bitwise AND - - - AND - - - - - - - Modulo - - - Mod - - - - - - - A - - - A - - - - - - - C1 - - - Alt+1 - - - - - - - Mean - - - Mea - - - - - - - Sine - - - Sin - - - S - - - - - - - Bitwise OR - - - OR - - - - - - - Reciprocal - - - 1/X - - - R - - - - - - - B - - - B - - - - - - - C2 - - - Alt+2 - - - - - - - Standard deviation - - - SD - - - - - - - Cosine - - - Cos - - - C - - - - - - - Bitwise XOR - - - XOR - - - - - - - Factorial - - - x! - - - - - - - C - - - C - - - - - - - C3 - - - Alt+3 - - - - - - - Median - - - Med - - - - - - - Tangent - - - Tan - - - T - - - - - - - Left bit shift - - - Lsh - - - - - - - Square - - - x2 - - - - - - - D - - - D - - - - - - - C4 - - - Alt+4 - - - - - - - Enter data - - - Dat - - - D - - - - - - - Logarithm to base 10 - - - Log - - - L - - - - - - - Right bit shift - - - Rsh - - - - - - - x to the power of y - - - pow - - - - - - - E - - - E - - - - - - - C5 - - - Alt+5 - - - - - - - Clear data store - - - CSt - - - - - - - Natural log - - - Ln - - - N - - - - - - - One's complement - - - Cmp - - - - - - - F - - - F - - - - - - - C6 - - - Alt+6 - - - - - - - Exponent - - - EXP - - - E - - - - - - - - 0 - 0 - - - - Cube - - - x3 - - - - - - - - - - - 0 - 0 - - - - - 2 - - - 4 - - - - - - 0 - 0 - - - - 7 - - - 7 - - - - - - - - 0 - 0 - - - - 8 - - - 8 - - - - - - - - 0 - 0 - - - - 9 - - - 9 - - - - - - - - 0 - 0 - - - - 4 - - - 4 - - - - - - - - 0 - 0 - - - - 5 - - - 5 - - - - - - - - 0 - 0 - - - - 6 - - - 6 - - - - - - - - 0 - 0 - - - - 1 - - - 1 - - - - - - - - 0 - 0 - - - - 2 - - - 2 - - - - - - - - 0 - 0 - - - - 3 - - - 3 - - - - - - - - 0 - 0 - - - - 0 - - - 0 - - - - - - - - 0 - 0 - - - - Percent - - - % - - - - - - - - 0 - 0 - - - - Division - - - ÷ - - - - - - - - 0 - 0 - - - - Multiplication - - - × - - - - - - - - 0 - 0 - - - - Minus - - - - - - - - - - - 0 - 0 - - - - Plus - - - + - - - - - - - - 0 - 0 - - - - Result - - - = - - - - - - - - 0 - 0 - - - - Decimal point - - - . - - - - - - - - - - - 2 - - - 4 - - - - - Clear all - - - AC - - - - - - - Memory clear - - - MC - - - - - - - Memory recall - - - MR - - - - - - - Change sign - - - +/− - - - - - - - Open parenthesis - - - ( - - - - - - - Clear - - - C - - - - - - - Add to memory - - - M+ - - - - - - - Memory store - - - MS - - - - - - - Close parenthesis - - - ) - - - - - - - - - - Backspace - - - - - - - Second button function - - - Shift - - - Ctrl+2 - - - true - - - - - - - - - - - - - - - KCalcButton - QPushButton -
kcalc_button.h
-
- - KCalcDisplay - QFrame -
kcalcdisplay.h
- 1 -
- - KCalcBitset - QWidget -
kcalc_bitset.h
- 1 -
- - KCalcConstButton - QPushButton -
kcalc_const_button.h
-
-
- - pb0 - pb1 - pb2 - pb3 - pb4 - pb5 - pb6 - pb7 - pb8 - pb9 - pbPeriod - pbDivision - pbMultiplication - pbMinus - pbPlus - pbEqual - pbPercent - pbClear - pbAllClear - pbParenOpen - pbParenClose - pbPlusMinus - pbMemStore - pbMemClear - pbMemRecall - pbMemPlusMinus - pbHyp - pbSin - pbCos - pbTan - pbLog - pbLn - pbMod - pbReci - pbFactorial - pbSquare - pbPower - pbCube - pbEE - pbAND - pbOR - pbXOR - pbLsh - pbRsh - pbCmp - pbA - pbB - pbC - pbD - pbE - pbF - pbC1 - pbC2 - pbC3 - pbC4 - pbC5 - pbC6 - pbNData - pbMean - pbSd - pbMed - pbDat - pbCSt - degRadio - radRadio - gradRadio - hexRadio - decRadio - octRadio - binRadio - calc_display - - -
diff --git a/kcalc/kcalc_bitset.cpp b/kcalc/kcalc_bitset.cpp deleted file mode 100644 index 2bfa81d2..00000000 --- a/kcalc/kcalc_bitset.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright (C) 2012 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2006 Michel Marti - mma@objectxp.com - -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, see . -*/ - -#include "kcalc_bitset.h" -#include "bitbutton.h" - -#include -#include -#include -#include -#include -#include - -#include "moc_kcalc_bitset.cpp" - -// TODO: I think it would actually be appropriate to use a std::bitset<64> -// for the internal representation of this class perhaps -// the only real caveat is the conversion to/from quint64 - -//------------------------------------------------------------------------------ -// Name: paintEvent -// Desc: draws the button -//------------------------------------------------------------------------------ -void BitButton::paintEvent(QPaintEvent *) { - - QPainter painter(this); - QPen pen(palette().text(), 2); - pen.setJoinStyle(Qt::MiterJoin); - painter.setPen(pen); - - if (on_) { - painter.setBrush(palette().text()); - } else { - painter.setBrush(palette().base()); - } - - painter.drawRect(rect().adjusted(1, 1, -1, -1)); -} - -//------------------------------------------------------------------------------ -// Name: KCalcBitset -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcBitset::KCalcBitset(QWidget *parent) : QFrame(parent), value_(0) { - - setFrameStyle(QFrame::Panel | QFrame::Sunken); - - bit_button_group_ = new QButtonGroup(this); - connect(bit_button_group_, SIGNAL(buttonClicked(int)), SLOT(slotToggleBit(int))); - - // smaller label font - QFont fnt = font(); - if (fnt.pointSize() > 6) { - fnt.setPointSize(fnt.pointSize() - 1); - } - - // main layout - QGridLayout *layout = new QGridLayout(this); - layout->setMargin(2); - layout->setSpacing(0); - - // create bits - int bitCounter = 63; - for (int rows = 0; rows < 2; rows++) { - for (int cols = 0; cols < 4; cols++) { - // two rows of four words - QHBoxLayout *const wordlayout = new QHBoxLayout(); - wordlayout->setMargin(2); - wordlayout->setSpacing(2); - layout->addLayout(wordlayout, rows, cols); - - for (int bit = 0; bit < 8; bit++) { - BitButton *const tmpBitButton = new BitButton(this); - wordlayout->addWidget(tmpBitButton); - bit_button_group_->addButton(tmpBitButton, bitCounter); - bitCounter--; - } - - // label word - QLabel *label = new QLabel(this); - label->setText(QString::number(bitCounter + 1)); - label->setFont(fnt); - wordlayout->addWidget(label); - } - } -} - -//------------------------------------------------------------------------------ -// Name: setValue -// Desc: set the value of the bitset based on an unsigned 64-bit number -//------------------------------------------------------------------------------ -void KCalcBitset::setValue(quint64 value) { - - if (value_ == value) { - // don't waste time if there was no change.. - return; - } - - value_ = value; - - // set each bit button - for (int i = 0; i < 64; i++) { - if(BitButton *bb = qobject_cast(bit_button_group_->button(i))) { - bb->setOn(value & 1); - } - value >>= 1; - } -} - -//------------------------------------------------------------------------------ -// Name: getValue -// Desc: returns the bitset value as an unsigned 64-bit number -//------------------------------------------------------------------------------ -quint64 KCalcBitset::getValue() const { - return value_; -} - -//------------------------------------------------------------------------------ -// Name: slotToggleBit -// Desc: inverts the value of a single bit -//------------------------------------------------------------------------------ -void KCalcBitset::slotToggleBit(int bit) { - - const quint64 nv = getValue() ^(1LL << bit); - setValue(nv); - emit valueChanged(value_); -} - diff --git a/kcalc/kcalc_bitset.h b/kcalc/kcalc_bitset.h deleted file mode 100644 index daf7e5da..00000000 --- a/kcalc/kcalc_bitset.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright (C) 2012 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2006 Michel Marti - mma@objectxp.com - -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, see . -*/ - -#ifndef KCALC_BITSET_H_ -#define KCALC_BITSET_H_ - -#include - -#include - -class KCalcBitset : public QFrame { - Q_OBJECT - -public: - explicit KCalcBitset(QWidget *parent = 0); - quint64 getValue() const; - -public slots: - void setValue(quint64 value); - void slotToggleBit(int bit); - -signals: - void valueChanged(quint64 value); - -private: - QButtonGroup *bit_button_group_; - quint64 value_; -}; - -#endif diff --git a/kcalc/kcalc_button.cpp b/kcalc/kcalc_button.cpp deleted file mode 100644 index abbbcdda..00000000 --- a/kcalc/kcalc_button.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#include "kcalc_button.h" - -#include -#include -#include -#include -#include - -#include "moc_kcalc_button.cpp" - -//------------------------------------------------------------------------------ -// Name: KCalcButton -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcButton::KCalcButton(QWidget *parent) : KPushButton(parent), show_shortcut_mode_(false), mode_flags_(ModeNormal), size_() { - - setAcceptDrops(true); // allow color drops - setFocusPolicy(Qt::TabFocus); - setAutoDefault(false); - - // use preferred size policy for vertical - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred); -} - -//------------------------------------------------------------------------------ -// Name: KCalcButton -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcButton::KCalcButton(const QString &label, QWidget *parent, const QString &tooltip) : KPushButton(label, parent), show_shortcut_mode_(false), mode_flags_(ModeNormal), size_() { - - setAutoDefault(false); - addMode(ModeNormal, label, tooltip); - - // use preferred size policy for vertical - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred); -} - -//------------------------------------------------------------------------------ -// Name: addMode -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::addMode(ButtonModeFlags mode, const QString &label, const QString &tooltip) { - - if (mode_.contains(mode)) { - mode_.remove(mode); - } - - mode_[mode] = ButtonMode(label, tooltip); - calcSizeHint(); - - // Need to put each button into default mode first - if (mode == ModeNormal) { - slotSetMode(ModeNormal, true); - } -} - -//------------------------------------------------------------------------------ -// Name: slotSetMode -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::slotSetMode(ButtonModeFlags mode, bool flag) { - - ButtonModeFlags new_mode; - - if (flag) { // if the specified mode is to be set (i.e. flag = true) - new_mode = ButtonModeFlags(mode_flags_ | mode); - } else if (mode_flags_ && mode) { // if the specified mode is to be cleared (i.e. flag = false) - new_mode = ButtonModeFlags(mode_flags_ - mode); - } else { - return; // nothing to do - } - - if (mode_.contains(new_mode)) { - // save shortcut, because setting label erases it - QKeySequence current_shortcut = shortcut(); - - setText(mode_[new_mode].label); - this->setToolTip(mode_[new_mode].tooltip); - mode_flags_ = new_mode; - - // restore shortcut - setShortcut(current_shortcut); - } - - // this is necessary for people pressing CTRL and changing mode at - // the same time... - if (show_shortcut_mode_) { - slotSetAccelDisplayMode(true); - } - - update(); -} - -//------------------------------------------------------------------------------ -// Name: slotSetAccelDisplayMode -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::slotSetAccelDisplayMode(bool flag) { - - show_shortcut_mode_ = flag; - - // save shortcut, because setting label erases it - QKeySequence current_shortcut = shortcut(); - - if (flag) { - setText(shortcut().toString()); - } else { - setText(mode_[mode_flags_].label); - } - - // restore shortcut - setShortcut(current_shortcut); - update(); -} - -//------------------------------------------------------------------------------ -// Name: paintEvent -// Desc: draws the button -//------------------------------------------------------------------------------ -void KCalcButton::paintEvent(QPaintEvent *) { - - QPainter p(this); - QStyleOptionButton option; - initStyleOption(&option); - const bool is_down = isDown() || isChecked(); - const int x_offset = is_down ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option, this) : 0; - const int y_offset = is_down ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option, this) : 0; - - // draw bevel - style()->drawControl(QStyle::CE_PushButtonBevel, &option, &p, this); - - // draw label... - p.save(); - - // rant: Qt4 needs QSimpleRichText, dammit! - QTextDocument doc; - QAbstractTextDocumentLayout::PaintContext context; - doc.setHtml(QLatin1String("
") + text() + QLatin1String("
")); - doc.setDefaultFont(font()); - context.palette = palette(); - context.palette.setColor(QPalette::Text, context.palette.buttonText().color()); - - p.translate((width() / 2 - doc.size().width() / 2) + x_offset, (height() / 2 - doc.size().height() / 2) + y_offset); - doc.documentLayout()->draw(&p, context); - p.restore(); - - // draw focus - if (hasFocus()) { - QStyleOptionFocusRect fropt; - fropt.QStyleOption::operator=(option); - fropt.rect = style()->subElementRect(QStyle::SE_PushButtonFocusRect, &option, this); - style()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, &p, this); - } -} - -//------------------------------------------------------------------------------ -// Name: sizeHint -// Desc: -//------------------------------------------------------------------------------ -QSize KCalcButton::sizeHint() const { - // reimplemented to provide a smaller button - return size_; -} - -//------------------------------------------------------------------------------ -// Name: calcSizeHint -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::calcSizeHint() { - - int margin = style()->pixelMetric(QStyle::PM_ButtonMargin, 0, this); - - // want narrow margin than normal - margin = qMax(margin / 2, 3); - - // approximation because metrics doesn't account for richtext - size_ = fontMetrics().size(0, mode_[ModeNormal].label); - if (mode_.contains(ModeShift)) { - size_ = size_.expandedTo(fontMetrics().size(0, mode_[ModeShift].label)); - } - - if (mode_.contains(ModeHyperbolic)) { - size_ = size_.expandedTo(fontMetrics().size(0, mode_[ModeHyperbolic].label)); - } - - size_ += QSize(margin * 2, margin * 2); - size_ = size_.expandedTo(QApplication::globalStrut()); -} - -//------------------------------------------------------------------------------ -// Name: setFont -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::setFont(const QFont &fnt) { - - KPushButton::setFont(fnt); - calcSizeHint(); -} - -//------------------------------------------------------------------------------ -// Name: setText -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::setText(const QString &text) { - - KPushButton::setText(text); - - // normal mode may not have been explicitly set - if (mode_[ModeNormal].label.isEmpty()) { - mode_[ModeNormal].label = text; - } - - calcSizeHint(); -} - -//------------------------------------------------------------------------------ -// Name: setToolTip -// Desc: -//------------------------------------------------------------------------------ -void KCalcButton::setToolTip(const QString &tip) { - - KPushButton::setToolTip(tip); - - // normal mode may not have been explicitly set - if (mode_[ModeNormal].tooltip.isEmpty()) { - mode_[ModeNormal].tooltip = tip; - } -} diff --git a/kcalc/kcalc_button.h b/kcalc/kcalc_button.h deleted file mode 100644 index 17517a03..00000000 --- a/kcalc/kcalc_button.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -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, see . -*/ - -#ifndef KCALC_BUTTON_H_ -#define KCALC_BUTTON_H_ - -#include -#include - -// The class KCalcButton is an overridden KPushButton. It offers extra -// functionality e.g. text can be richtext, and the button can be -// told to display its shortcuts in the label, but the most important -// thing is that the button may have several modes with corresponding -// labels and tooltips. When one switches modes, the corresponding -// label is displayed. - - -enum ButtonModeFlags { - ModeNormal = 0, - ModeShift = 1, - ModeHyperbolic = 2 -}; - - -// Each kcalc button can be in one of several modes. -// The following class describes label, tooltip etc. for each mode... -class ButtonMode { -public: - ButtonMode() { - } - - ButtonMode(const QString &label, const QString &tooltip) : label(label), tooltip(tooltip) { - } - - QString label; - QString tooltip; -}; - - -class KCalcButton : public KPushButton { - Q_OBJECT - -public: - explicit KCalcButton(QWidget *parent); - KCalcButton(const QString &label, QWidget *parent, - const QString &tooltip = QString()); - - void addMode(ButtonModeFlags mode, const QString &label, - const QString &tooltip); - - virtual QSize sizeHint() const; // reimp - - void setFont(const QFont &fnt); - void setText(const QString &text); // reimp - void setToolTip(const QString &tip); // reimp - -public slots: - void slotSetMode(ButtonModeFlags mode, bool flag); - void slotSetAccelDisplayMode(bool flag); - -protected: - virtual void paintEvent(QPaintEvent *e); - -private: - void calcSizeHint(); - -private: - bool show_shortcut_mode_; - ButtonModeFlags mode_flags_; - QMap mode_; - QSize size_; -}; - -#endif diff --git a/kcalc/kcalc_const_button.cpp b/kcalc/kcalc_const_button.cpp deleted file mode 100644 index 5a843a92..00000000 --- a/kcalc/kcalc_const_button.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -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, see . -*/ - -#include "kcalc_const_button.h" -#include "kcalc_const_menu.h" -#include "kcalc_settings.h" - -#include -#include - -#include "moc_kcalc_const_button.cpp" - -//------------------------------------------------------------------------------ -// Name: KCalcConstButton -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcConstButton::KCalcConstButton(QWidget *parent) : KCalcButton(parent), button_num_(-1) { - - addMode(ModeShift, i18nc("Write display data into memory", "Store"), i18n("Write display data into memory")); - initPopupMenu(); - connect(this, SIGNAL(clicked()), SLOT(slotClicked())); -} - -//------------------------------------------------------------------------------ -// Name: KCalcConstButton -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcConstButton::KCalcConstButton(const QString &label, QWidget *parent, const QString &tooltip) : KCalcButton(label, parent, tooltip), button_num_(-1) { - - addMode(ModeShift, i18nc("Write display data into memory", "Store"), i18n("Write display data into memory")); - initPopupMenu(); -} - -//------------------------------------------------------------------------------ -// Name: constant -// Desc: get the value of the const as a QString -//------------------------------------------------------------------------------ -QString KCalcConstButton::constant() const { - - return KCalcSettings::valueConstant(button_num_); -} - -//------------------------------------------------------------------------------ -// Name: setButtonNumber -// Desc: remembers the "index" of the const button -//------------------------------------------------------------------------------ -void KCalcConstButton::setButtonNumber(int num) { - - button_num_ = num; -} - -//------------------------------------------------------------------------------ -// Name: setLabelAndTooltip -// Desc: sets both the label and the tooltip for the const button -//------------------------------------------------------------------------------ -void KCalcConstButton::setLabelAndTooltip() { - - QString new_label = QLatin1String("C") + QString::number(button_num_ + 1); - QString new_tooltip; - - new_label = (KCalcSettings::nameConstant(button_num_).isNull() ? new_label : KCalcSettings::nameConstant(button_num_)); - - new_tooltip = new_label + QLatin1Char('=') + KCalcSettings::valueConstant(button_num_); - - addMode(ModeNormal, new_label, new_tooltip); -} - -//------------------------------------------------------------------------------ -// Name: initPopupMenu -// Desc: initializes the const button popup -//------------------------------------------------------------------------------ -void KCalcConstButton::initPopupMenu() { - - QAction *const a = new QAction(this); - a->setText(i18n("Set Name")); - connect(a, SIGNAL(triggered()), this, SLOT(slotConfigureButton())); - addAction(a); - - KCalcConstMenu *const tmp_menu = new KCalcConstMenu(this); - tmp_menu->menuAction()->setText(i18n("Choose From List")); - addAction(tmp_menu->menuAction()); - setContextMenuPolicy(Qt::ActionsContextMenu); - - connect(tmp_menu, SIGNAL(triggeredConstant(science_constant)), SLOT(slotChooseScientificConst(science_constant))); - -} - -//------------------------------------------------------------------------------ -// Name: slotConfigureButton -// Desc: lets the user set the name for a constant -//------------------------------------------------------------------------------ -void KCalcConstButton::slotConfigureButton() { - - bool yes_no; - const QString input = KInputDialog::getText(i18n("New Name for Constant"), i18n("New name:"), text(), &yes_no, this); // "nameUserConstants-Dialog" - if (yes_no) { - KCalcSettings::setNameConstant(button_num_, input); - setLabelAndTooltip(); - } -} - -//------------------------------------------------------------------------------ -// Name: slotChooseScientificConst -// Desc: set the buttons's scientific constant -//------------------------------------------------------------------------------ -void KCalcConstButton::slotChooseScientificConst(const science_constant &const_chosen) { - - KCalcSettings::setValueConstant(button_num_, const_chosen.value); - KCalcSettings::setNameConstant(button_num_, const_chosen.label); - setLabelAndTooltip(); -} - -//------------------------------------------------------------------------------ -// Name: slotClicked -// Desc: constant button was clicked -//------------------------------------------------------------------------------ -void KCalcConstButton::slotClicked() { - - emit clicked(button_num_); -} - diff --git a/kcalc/kcalc_const_button.h b/kcalc/kcalc_const_button.h deleted file mode 100644 index 959b2b66..00000000 --- a/kcalc/kcalc_const_button.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#ifndef KCALC_CONST_BUTTON_H_ -#define KCALC_CONST_BUTTON_H_ - -#include "kcalc_button.h" - -struct science_constant; - - -class KCalcConstButton : public KCalcButton { - Q_OBJECT - -public: - - explicit KCalcConstButton(QWidget *parent); - - KCalcConstButton(const QString &label, QWidget *parent, - const QString &tooltip = QString()); - - QString constant() const; - - void setButtonNumber(int num); - - void setLabelAndTooltip(); - -signals: - void clicked(int num); - -private slots: - void slotConfigureButton(); - void slotChooseScientificConst(const science_constant &const_chosen); - void slotClicked(); - -private: - void initPopupMenu(); - -private: - int button_num_; -}; - - -#endif diff --git a/kcalc/kcalc_const_menu.cpp b/kcalc/kcalc_const_menu.cpp deleted file mode 100644 index a067ed4c..00000000 --- a/kcalc/kcalc_const_menu.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -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, see . -*/ - -#include "kcalc_const_menu.h" - -#include -#include -#include -#include -#include - -ConstantCategory stringToCategory(const QString &s) { - if (s == QLatin1String("mathematics")) { - return Mathematics; - } - - if (s == QLatin1String("electromagnetism")) { - return Electromagnetic; - } - - if (s == QLatin1String("nuclear")) { - return Nuclear; - } - - if (s == QLatin1String("thermodynamics")) { - return Thermodynamics; - } - - if (s == QLatin1String("gravitation")) { - return Gravitation; - } - - kDebug() << "Invalid Category For Constant: " << s; - return Mathematics; -} - -QList KCalcConstMenu::constants_; - -void KCalcConstMenu::init_consts() { - QDomDocument doc(QLatin1String("list_of_constants")); - QFile file(KGlobal::dirs()->findResource("appdata", QLatin1String("scienceconstants.xml"))); - - if (!file.open(QIODevice::ReadOnly)) { - kDebug() << "Did not find file \"scienceconstants.xml\". No constants will be available."; - return; - } - if (!doc.setContent(&file)) { - file.close(); - kDebug() << "The file \"scienceconstants.xml\" does not seem to be a valid description file. No constants will be available."; - return; - } - file.close(); - - // print out the element names of all elements that are direct children - // of the outermost element. - QDomElement docElem = doc.documentElement(); - - int i = 0; - QDomNode n = docElem.firstChild(); - while (!n.isNull()) { - QDomElement e = n.toElement(); // try to convert the node to an element. - if (!e.isNull() && e.tagName() == QLatin1String("constant")) { - science_constant tmp_const; - - tmp_const.name = I18N_NOOP(e.attributeNode(QLatin1String("name")).value()); - tmp_const.label = e.attributeNode(QLatin1String("symbol")).value(); - tmp_const.value = e.attributeNode(QLatin1String("value")).value(); - - QString tmp_str_category = e.attributeNode(QLatin1String("category")).value(); - - tmp_const.category = stringToCategory(tmp_str_category); - tmp_const.whatsthis = e.firstChildElement(QLatin1String("description")).text(); - - constants_.append(tmp_const); - } - n = n.nextSibling(); - i++; - } -} - -void KCalcConstMenu::init_all() -{ - QMenu *math_menu = addMenu(i18n("Mathematics")); - QMenu *em_menu = addMenu(i18n("Electromagnetism")); - QMenu *nuclear_menu = addMenu(i18n("Atomic && Nuclear")); - QMenu *thermo_menu = addMenu(i18n("Thermodynamics")); - QMenu *gravitation_menu = addMenu(i18n("Gravitation")); - - connect(this, SIGNAL(triggered(QAction*)), SLOT(slotPassSignalThrough(QAction*))); - - - for (int i = 0; i < constants_.size(); i++) { - QAction *tmp_action = new QAction(i18n(constants_.at(i).name.toAscii().data()), this); - tmp_action->setData(QVariant(i)); - if (constants_.at(i).category & Mathematics) - math_menu->addAction(tmp_action); - if (constants_.at(i).category & Electromagnetic) - em_menu->addAction(tmp_action); - if (constants_.at(i).category & Nuclear) - nuclear_menu->addAction(tmp_action); - if (constants_.at(i).category & Thermodynamics) - thermo_menu->addAction(tmp_action); - if (constants_.at(i).category & Gravitation) - gravitation_menu->addAction(tmp_action); - } -} - -void KCalcConstMenu::slotPassSignalThrough(QAction *chosen_const) -{ - bool tmp_bool; - int chosen_const_idx = (chosen_const->data()).toInt(& tmp_bool); - emit triggeredConstant(constants_.at(chosen_const_idx)); -} - -KCalcConstMenu::KCalcConstMenu(const QString &title, QWidget * parent) - : QMenu(title, parent) -{ - init_all(); -} - -KCalcConstMenu::KCalcConstMenu(QWidget * parent) - : QMenu(parent) -{ - init_all(); -} - - -#include "moc_kcalc_const_menu.cpp" diff --git a/kcalc/kcalc_const_menu.h b/kcalc/kcalc_const_menu.h deleted file mode 100644 index 855d79e0..00000000 --- a/kcalc/kcalc_const_menu.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -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, see . -*/ - -#ifndef KCALC_CONST_MENU_H_ -#define KCALC_CONST_MENU_H_ - -#include -#include - -enum ConstantCategory { - Mathematics = 1, - Electromagnetic = 2, - Nuclear = 4, - Thermodynamics = 8, - Gravitation = 16 -}; - -struct science_constant { - QString label; - QString name; - QString whatsthis; - QString value; - ConstantCategory category; -}; - -class KCalcConstMenu : public QMenu { - Q_OBJECT - -public: - explicit KCalcConstMenu(QWidget * parent = 0); - explicit KCalcConstMenu(const QString &title, QWidget * parent = 0); - -public: - static void init_consts(); - -signals: - void triggeredConstant(const science_constant &); - -private: - void init_all(); - -public slots: - void slotPassSignalThrough(QAction *chosen_const); - -private: - static QList constants_; -}; - -#endif diff --git a/kcalc/kcalc_core.cpp b/kcalc/kcalc_core.cpp deleted file mode 100644 index e0a21525..00000000 --- a/kcalc/kcalc_core.cpp +++ /dev/null @@ -1,886 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -Copyright (C) 1995 Martin Bartlett - -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, see . -*/ - -#include "kcalc_core.h" -#include -#include -#include - -namespace { - -KNumber Deg2Rad(const KNumber &x) { - return x * (KNumber::Pi() / KNumber(180)); -} - -KNumber Gra2Rad(const KNumber &x) { - return x * (KNumber::Pi() / KNumber(200)); -} - -KNumber Rad2Deg(const KNumber &x) { - return x * (KNumber(180) / KNumber::Pi()); -} - -KNumber Rad2Gra(const KNumber &x) { - return x * (KNumber(200) / KNumber::Pi()); -} - -bool error_; - -KNumber ExecOr(const KNumber &left_op, const KNumber &right_op) { - return left_op | right_op; -} - -KNumber ExecXor(const KNumber &left_op, const KNumber &right_op) { - return left_op ^ right_op; -} - -KNumber ExecAnd(const KNumber &left_op, const KNumber &right_op) { - return left_op & right_op; -} - -KNumber ExecLsh(const KNumber &left_op, const KNumber &right_op) { - return left_op << right_op; -} - -KNumber ExecRsh(const KNumber &left_op, const KNumber &right_op) { - return left_op >> right_op; -} - -KNumber ExecAdd(const KNumber &left_op, const KNumber &right_op) { - return left_op + right_op; -} - -KNumber ExecSubtract(const KNumber &left_op, const KNumber &right_op) { - return left_op - right_op; -} - -KNumber ExecMultiply(const KNumber &left_op, const KNumber &right_op) { - return left_op * right_op; -} - -KNumber ExecDivide(const KNumber &left_op, const KNumber &right_op) { - return left_op / right_op; -} - -KNumber ExecMod(const KNumber &left_op, const KNumber &right_op) { - return left_op % right_op; -} - -KNumber ExecIntDiv(const KNumber &left_op, const KNumber &right_op) { - return (left_op / right_op).integerPart(); -} - -KNumber ExecBinom(const KNumber &left_op, const KNumber &right_op) { - return left_op.bin(right_op); -} - -KNumber ExecPower(const KNumber &left_op, const KNumber &right_op) { - return left_op.pow(right_op); -} - -KNumber ExecPwrRoot(const KNumber &left_op, const KNumber &right_op) { - return left_op.pow(KNumber::One / right_op); -} - -KNumber ExecAddP(const KNumber &left_op, const KNumber &right_op) { - return left_op * (KNumber::One + right_op / KNumber(100)); -} - -KNumber ExecSubP(const KNumber &left_op, const KNumber &right_op) { - return left_op * (KNumber::One - right_op / KNumber(100)); -} - -KNumber ExecMultiplyP(const KNumber &left_op, const KNumber &right_op) { - return left_op * right_op / KNumber(100); -} - -KNumber ExecDivideP(const KNumber &left_op, const KNumber &right_op) { - return left_op * KNumber(100) / right_op; -} - -// move a number into the interval [0,360) by adding multiples of 360 -KNumber moveIntoDegInterval(const KNumber &num) { - KNumber tmp_num = num - (num / KNumber(360)).integerPart() * KNumber(360); - if (tmp_num < KNumber::Zero) - return tmp_num + KNumber(360); - return tmp_num; -} - -// move a number into the interval [0,400) by adding multiples of 400 -KNumber moveIntoGradInterval(const KNumber &num) { - KNumber tmp_num = num - (num / KNumber(400)).integerPart() * KNumber(400); - if (tmp_num < KNumber::Zero) - return tmp_num + KNumber(400); - return tmp_num; -} - -typedef KNumber(*Arith)(const KNumber &, const KNumber &); -typedef KNumber(*Prcnt)(const KNumber &, const KNumber &); - -struct operator_data { - int precedence; // priority of operators in " enum Operation" - Arith arith_ptr; - Prcnt prcnt_ptr; -}; - -// build precedence list -const struct operator_data Operator[] = { - { 0, NULL, NULL}, // FUNC_EQUAL - { 0, NULL, NULL}, // FUNC_PERCENT - { 0, NULL, NULL}, // FUNC_BRACKET - { 1, ExecOr, NULL}, // FUNC_OR - { 2, ExecXor, NULL}, // FUNC_XOR - { 3, ExecAnd, NULL}, // FUNC_AND - { 4, ExecLsh, NULL}, // FUNC_LSH - { 4, ExecRsh, NULL}, // FUNC_RSH - { 5, ExecAdd, ExecAddP}, // FUNC_ADD - { 5, ExecSubtract, ExecSubP}, // FUNC_SUBTRACT - { 6, ExecMultiply, ExecMultiplyP}, // FUNC_MULTIPLY - { 6, ExecDivide, ExecDivideP}, // FUNC_DIVIDE - { 6, ExecMod, NULL}, // FUNC_MOD - { 6, ExecIntDiv, NULL}, // FUNC_INTDIV - { 7, ExecBinom, NULL}, // FUNC_BINOM - { 7, ExecPower, NULL}, // FUNC_POWER - { 7, ExecPwrRoot, NULL} // FUNC_PWR_ROOT -}; - -} - - -CalcEngine::CalcEngine() : percent_mode_(false) { - - last_number_ = KNumber::Zero; - error_ = false; -} - -KNumber CalcEngine::lastOutput(bool &error) const { - error = error_; - return last_number_; -} - -void CalcEngine::ArcCosDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - - if (input.type() == KNumber::TYPE_INTEGER) { - if (input == KNumber::One) { - last_number_ = KNumber::Zero; - return; - } - if (input == - KNumber::One) { - last_number_ = KNumber(180); - return; - } - if (input == KNumber::Zero) { - last_number_ = KNumber(90); - return; - } - } - last_number_ = Rad2Deg(input.acos()); -} - -void CalcEngine::ArcCosRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - last_number_ = input.acos(); -} - -void CalcEngine::ArcCosGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - if (input.type() == KNumber::TYPE_INTEGER) { - if (input == KNumber::One) { - last_number_ = KNumber::Zero; - return; - } - if (input == - KNumber::One) { - last_number_ = KNumber(200); - return; - } - if (input == KNumber::Zero) { - last_number_ = KNumber(100); - return; - } - } - last_number_ = Rad2Gra(input.acos()); -} - -void CalcEngine::ArcSinDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || - input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - if (input.type() == KNumber::TYPE_INTEGER) { - if (input == KNumber::One) { - last_number_ = KNumber(90); - return; - } - if (input == - KNumber::One) { - last_number_ = KNumber(-90); - return; - } - if (input == KNumber::Zero) { - last_number_ = KNumber::Zero; - return; - } - } - last_number_ = Rad2Deg(input.asin()); -} - -void CalcEngine::ArcSinRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || - input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - last_number_ = input.asin(); -} - -void CalcEngine::ArcSinGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR || - input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - if (input.type() == KNumber::TYPE_INTEGER) { - if (input == KNumber::One) { - last_number_ = KNumber(100); - return; - } - if (input == - KNumber::One) { - last_number_ = KNumber(-100); - return; - } - if (input == KNumber::Zero) { - last_number_ = KNumber::Zero; - return; - } - } - last_number_ = Rad2Gra(input.asin()); -} - -void CalcEngine::ArcTangensDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber(90); - if (input == KNumber::NegInfinity) last_number_ = KNumber(-90); - return; - } - - last_number_ = Rad2Deg(input.atan()); -} - -void CalcEngine::ArcTangensRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) - last_number_ = KNumber::Pi() / KNumber(2); - if (input == KNumber::NegInfinity) - last_number_ = -KNumber::Pi() / KNumber(2); - return; - } - - last_number_ = input.atan(); -} - -void CalcEngine::ArcTangensGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber(100); - if (input == KNumber::NegInfinity) last_number_ = KNumber(-100); - return; - } - - last_number_ = Rad2Gra(input.atan()); -} - -void CalcEngine::AreaCosHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - if (input == KNumber::NegInfinity) last_number_ = KNumber::NaN; - return; - } - - if (input < KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - if (input == KNumber::One) { - last_number_ = KNumber::Zero; - return; - } - last_number_ = input.acosh(); -} - -void CalcEngine::AreaSinHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - if (input == KNumber::NegInfinity) last_number_ = KNumber::NegInfinity; - return; - } - - if (input == KNumber::Zero) { - last_number_ = KNumber::Zero; - return; - } - last_number_ = input.asinh(); -} - -void CalcEngine::AreaTangensHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - if (input < -KNumber::One || input > KNumber::One) { - last_number_ = KNumber::NaN; - return; - } - if (input == KNumber::One) { - last_number_ = KNumber::PosInfinity; - return; - } - if (input == - KNumber::One) { - last_number_ = KNumber::NegInfinity; - return; - } - last_number_ = input.atanh(); -} - -void CalcEngine::Complement(const KNumber &input) -{ - if (input.type() != KNumber::TYPE_INTEGER) { - last_number_ = KNumber::NaN; - return; - } - - last_number_ = ~input; -} - -void CalcEngine::CosDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - KNumber trunc_input = moveIntoDegInterval(input); - - if (trunc_input.type() == KNumber::TYPE_INTEGER) { - KNumber mult = trunc_input / KNumber(90); - if (mult.type() == KNumber::TYPE_INTEGER) { - if (mult == KNumber::Zero) - last_number_ = KNumber::One; - else if (mult == KNumber::One) - last_number_ = KNumber::Zero; - else if (mult == KNumber(2)) - last_number_ = KNumber::NegOne; - else if (mult == KNumber(3)) - last_number_ = KNumber::Zero; - else kDebug() << "Something wrong in CalcEngine::CosDeg"; - return; - } - } - - trunc_input = Deg2Rad(trunc_input); - last_number_ = trunc_input.cos(); -} - -void CalcEngine::CosRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - last_number_ = input.cos(); -} - -void CalcEngine::CosGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - KNumber trunc_input = moveIntoGradInterval(input); - if (trunc_input.type() == KNumber::TYPE_INTEGER) { - KNumber mult = trunc_input / KNumber(100); - if (mult.type() == KNumber::TYPE_INTEGER) { - if (mult == KNumber::Zero) - last_number_ = KNumber::One; - else if (mult == KNumber::One) - last_number_ = KNumber::Zero; - else if (mult == KNumber(2)) - last_number_ = KNumber::NegOne; - else if (mult == KNumber(3)) - last_number_ = KNumber::Zero; - else kDebug() << "Something wrong in CalcEngine::CosGrad"; - return; - } - } - trunc_input = Gra2Rad(trunc_input); - - last_number_ = trunc_input.cos(); -} - -void CalcEngine::CosHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - // YES, this should be *positive* infinity. We mimic the behavior of - // libc which says the following for cosh - // - // "If x is positive infinity or negative infinity, positive infinity is returned." - if (input == KNumber::NegInfinity) last_number_ = KNumber::PosInfinity; - return; - } - - last_number_ = input.cosh(); -} - -void CalcEngine::Cube(const KNumber &input) -{ - last_number_ = input * input * input; -} - -void CalcEngine::CubeRoot(const KNumber &input) -{ - last_number_ = input.cbrt(); -} - -void CalcEngine::Exp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - if (input == KNumber::NegInfinity) last_number_ = KNumber::Zero; - return; - } - last_number_ = KNumber::Euler().pow(input); -} - -void CalcEngine::Exp10(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - if (input == KNumber::NegInfinity) last_number_ = KNumber::Zero; - return; - } - last_number_ = KNumber(10).pow(input); -} - - -void CalcEngine::Factorial(const KNumber &input) -{ - if (input == KNumber::PosInfinity) return; - if (input < KNumber::Zero || input.type() == KNumber::TYPE_ERROR) { - error_ = true; - last_number_ = KNumber::NaN; - return; - } - - last_number_ = input.integerPart().factorial(); -} - -void CalcEngine::Gamma(const KNumber &input) -{ - if (input == KNumber::PosInfinity) return; - if (input < KNumber::Zero || input.type() == KNumber::TYPE_ERROR) { - error_ = true; - last_number_ = KNumber::NaN; - return; - } - - last_number_ = input.tgamma(); -} - -void CalcEngine::InvertSign(const KNumber &input) -{ - last_number_ = -input; -} - -void CalcEngine::Ln(const KNumber &input) -{ - if (input < KNumber::Zero) - last_number_ = KNumber::NaN; - else if (input == KNumber::Zero) - last_number_ = KNumber::NegInfinity; - else if (input == KNumber::One) - last_number_ = KNumber::Zero; - else { - last_number_ = input.ln(); - } -} - -void CalcEngine::Log10(const KNumber &input) -{ - if (input < KNumber::Zero) - last_number_ = KNumber::NaN; - else if (input == KNumber::Zero) - last_number_ = KNumber::NegInfinity; - else if (input == KNumber::One) - last_number_ = KNumber::Zero; - else { - last_number_ = input.log10(); - } -} - -void CalcEngine::ParenClose(KNumber input) -{ - // evaluate stack until corresponding opening bracket - while (!stack_.isEmpty()) { - Node tmp_node = stack_.pop(); - if (tmp_node.operation == FUNC_BRACKET) - break; - input = evalOperation(tmp_node.number, tmp_node.operation, input); - } - last_number_ = input; - return; -} - -void CalcEngine::ParenOpen(const KNumber &input) -{ - enterOperation(input, FUNC_BRACKET); -} - -void CalcEngine::Reciprocal(const KNumber &input) -{ - last_number_ = KNumber::One / input; -} - - -void CalcEngine::SinDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - KNumber trunc_input = moveIntoDegInterval(input); - if (trunc_input.type() == KNumber::TYPE_INTEGER) { - KNumber mult = trunc_input / KNumber(90); - if (mult.type() == KNumber::TYPE_INTEGER) { - if (mult == KNumber::Zero) - last_number_ = KNumber::Zero; - else if (mult == KNumber::One) - last_number_ = KNumber::One; - else if (mult == KNumber(2)) - last_number_ = KNumber::Zero; - else if (mult == KNumber(3)) - last_number_ = KNumber::NegOne; - else kDebug() << "Something wrong in CalcEngine::SinDeg"; - return; - } - } - trunc_input = Deg2Rad(trunc_input); - - last_number_ = trunc_input.sin(); -} - -void CalcEngine::SinRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - last_number_ = input.sin(); -} - -void CalcEngine::SinGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - KNumber trunc_input = moveIntoGradInterval(input); - if (trunc_input.type() == KNumber::TYPE_INTEGER) { - KNumber mult = trunc_input / KNumber(100); - if (mult.type() == KNumber::TYPE_INTEGER) { - if (mult == KNumber::Zero) - last_number_ = KNumber::Zero; - else if (mult == KNumber::One) - last_number_ = KNumber::One; - else if (mult == KNumber(2)) - last_number_ = KNumber::Zero; - else if (mult == KNumber(3)) - last_number_ = KNumber::NegOne; - else kDebug() << "Something wrong in CalcEngine::SinGrad"; - return; - } - } - - trunc_input = Gra2Rad(trunc_input); - - last_number_ = trunc_input.sin(); -} - -void CalcEngine::SinHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::PosInfinity; - if (input == KNumber::NegInfinity) last_number_ = KNumber::NegInfinity; - return; - } - - last_number_ = input.sinh(); -} - -void CalcEngine::Square(const KNumber &input) -{ - last_number_ = input * input; -} - -void CalcEngine::SquareRoot(const KNumber &input) -{ - last_number_ = input.sqrt(); -} - -void CalcEngine::StatClearAll(const KNumber &input) -{ - Q_UNUSED(input); - stats.clearAll(); -} - -void CalcEngine::StatCount(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = KNumber(stats.count()); -} - -void CalcEngine::StatDataNew(const KNumber &input) -{ - stats.enterData(input); - last_number_ = KNumber(stats.count()); -} - -void CalcEngine::StatDataDel(const KNumber &input) -{ - Q_UNUSED(input); - stats.clearLast(); - last_number_ = KNumber(stats.count()); -} - -void CalcEngine::StatMean(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.mean(); - - error_ = stats.error(); -} - -void CalcEngine::StatMedian(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.median(); - - error_ = stats.error(); -} - -void CalcEngine::StatStdDeviation(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.std(); - - error_ = stats.error(); -} - -void CalcEngine::StatStdSample(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.sample_std(); - - error_ = stats.error(); -} - -void CalcEngine::StatSum(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.sum(); -} - -void CalcEngine::StatSumSquares(const KNumber &input) -{ - Q_UNUSED(input); - last_number_ = stats.sum_of_squares(); - - error_ = stats.error(); -} - -void CalcEngine::TangensDeg(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - SinDeg(input); - KNumber arg1 = last_number_; - CosDeg(input); - KNumber arg2 = last_number_; - - last_number_ = arg1 / arg2; -} - -void CalcEngine::TangensRad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - SinRad(input); - KNumber arg1 = last_number_; - CosRad(input); - KNumber arg2 = last_number_; - - last_number_ = arg1 / arg2; -} - -void CalcEngine::TangensGrad(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - last_number_ = KNumber::NaN; - return; - } - - SinGrad(input); - KNumber arg1 = last_number_; - CosGrad(input); - KNumber arg2 = last_number_; - - last_number_ = arg1 / arg2; -} - -void CalcEngine::TangensHyp(const KNumber &input) -{ - if (input.type() == KNumber::TYPE_ERROR) { - if (input == KNumber::NaN) last_number_ = KNumber::NaN; - if (input == KNumber::PosInfinity) last_number_ = KNumber::One; - if (input == KNumber::NegInfinity) last_number_ = KNumber::NegOne; - return; - } - - last_number_ = input.tanh(); -} - -KNumber CalcEngine::evalOperation(const KNumber &arg1, Operation operation, const KNumber &arg2) -{ - if (!percent_mode_ || Operator[operation].prcnt_ptr == NULL) { - return (Operator[operation].arith_ptr)(arg1, arg2); - } else { - percent_mode_ = false; - return (Operator[operation].prcnt_ptr)(arg1, arg2); - } -} - -void CalcEngine::enterOperation(const KNumber &number, Operation func) -{ - Node tmp_node; - - if (func == FUNC_BRACKET) { - tmp_node.number = KNumber::Zero; - tmp_node.operation = FUNC_BRACKET; - - stack_.push(tmp_node); - - return; - } - - if (func == FUNC_PERCENT) { - percent_mode_ = true; - } - - tmp_node.number = number; - tmp_node.operation = func; - - stack_.push(tmp_node); - - evalStack(); -} - -bool CalcEngine::evalStack() -{ - // this should never happen - Q_ASSERT(!stack_.isEmpty()); - - Node tmp_node = stack_.pop(); - - while (! stack_.isEmpty()) { - Node tmp_node2 = stack_.pop(); - if (Operator[tmp_node.operation].precedence <= - Operator[tmp_node2.operation].precedence) { - if (tmp_node2.operation == FUNC_BRACKET) continue; - const KNumber tmp_result = evalOperation(tmp_node2.number, tmp_node2.operation, tmp_node.number); - tmp_node.number = tmp_result; - } else { - stack_.push(tmp_node2); - break; - } - - } - - if (tmp_node.operation != FUNC_EQUAL && tmp_node.operation != FUNC_PERCENT) - stack_.push(tmp_node); - - last_number_ = tmp_node.number; - return true; -} - -void CalcEngine::Reset() -{ - error_ = false; - last_number_ = KNumber::Zero; - - stack_.clear(); -} - - diff --git a/kcalc/kcalc_core.h b/kcalc/kcalc_core.h deleted file mode 100644 index 7a5776b6..00000000 --- a/kcalc/kcalc_core.h +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#ifndef KCALC_CORE_H_ -#define KCALC_CORE_H_ - -#include -#include "stats.h" -#include "knumber.h" - -class CalcEngine { -public: - // operations that can be stored in calculation stack - enum Operation { - FUNC_EQUAL, - FUNC_PERCENT, - FUNC_BRACKET, - FUNC_OR, - FUNC_XOR, - FUNC_AND, - FUNC_LSH, - FUNC_RSH, - FUNC_ADD, - FUNC_SUBTRACT, - FUNC_MULTIPLY, - FUNC_DIVIDE, - FUNC_MOD, - FUNC_INTDIV, - FUNC_BINOM, - FUNC_POWER, - FUNC_PWR_ROOT - }; - - CalcEngine(); - - KNumber lastOutput(bool &error) const; - - void enterOperation(const KNumber &num, Operation func); - - void ArcCosDeg(const KNumber &input); - void ArcCosRad(const KNumber &input); - void ArcCosGrad(const KNumber &input); - void ArcSinDeg(const KNumber &input); - void ArcSinRad(const KNumber &input); - void ArcSinGrad(const KNumber &input); - void ArcTangensDeg(const KNumber &input); - void ArcTangensRad(const KNumber &input); - void ArcTangensGrad(const KNumber &input); - void AreaCosHyp(const KNumber &input); - void AreaSinHyp(const KNumber &input); - void AreaTangensHyp(const KNumber &input); - void Complement(const KNumber &input); - void CosDeg(const KNumber &input); - void CosRad(const KNumber &input); - void CosGrad(const KNumber &input); - void CosHyp(const KNumber &input); - void Cube(const KNumber &input); - void CubeRoot(const KNumber &input); - void Exp(const KNumber &input); - void Exp10(const KNumber &input); - void Factorial(const KNumber &input); - void Gamma(const KNumber &input); - void InvertSign(const KNumber &input); - void Ln(const KNumber &input); - void Log10(const KNumber &input); - void ParenClose(KNumber input); - void ParenOpen(const KNumber &input); - void Reciprocal(const KNumber &input); - void SinDeg(const KNumber &input); - void SinGrad(const KNumber &input); - void SinRad(const KNumber &input); - void SinHyp(const KNumber &input); - void Square(const KNumber &input); - void SquareRoot(const KNumber &input); - void StatClearAll(const KNumber &input); - void StatCount(const KNumber &input); - void StatDataNew(const KNumber &input); - void StatDataDel(const KNumber &input); - void StatMean(const KNumber &input); - void StatMedian(const KNumber &input); - void StatStdDeviation(const KNumber &input); - void StatStdSample(const KNumber &input); - void StatSum(const KNumber &input); - void StatSumSquares(const KNumber &input); - void TangensDeg(const KNumber &input); - void TangensRad(const KNumber &input); - void TangensGrad(const KNumber &input); - void TangensHyp(const KNumber &input); - - void Reset(); - -private: - KStats stats; - - struct Node { - KNumber number; - Operation operation; - }; - - // Stack holds all operations and numbers that have not yet been - // processed, e.g. user types "2+3*", the calculation can not be - // executed, because "*" has a higher precedence than "+", so we - // need to wait for the next number. - // - // In the stack this would be stored as ((2,+),(3,*),...) - // - // "enterOperation": If the introduced Operation has lower priority - // than the preceding operations in the stack, then we can start to - // evaluate the stack (with "evalStack"). Otherwise we append the new - // Operation and number to the stack. - // - // E.g. "2*3+" evaluates to "6+", but "2+3*" can not be evaluated - // yet. - // - // We also take care of brackets, by writing a marker "FUNC_BRACKET" - // into the stack, each time the user opens one. When a bracket is - // closed, everything in the stack is evaluated until the first - // marker "FUNC_BRACKET" found. - QStack stack_; - - KNumber last_number_; - - bool percent_mode_; - - bool evalStack(); - - KNumber evalOperation(const KNumber &arg1, Operation operation, const KNumber &arg2); -}; - - -#endif diff --git a/kcalc/kcalc_settings.kcfgc b/kcalc/kcalc_settings.kcfgc deleted file mode 100644 index 5b131600..00000000 --- a/kcalc/kcalc_settings.kcfgc +++ /dev/null @@ -1,6 +0,0 @@ -# Code generation options for kconfig_compiler -File=kcalc.kcfg -ClassName=KCalcSettings -Singleton=true -Mutators=true -UseEnumTypes=true diff --git a/kcalc/kcalcdisplay.cpp b/kcalc/kcalcdisplay.cpp deleted file mode 100644 index a763c33d..00000000 --- a/kcalc/kcalcdisplay.cpp +++ /dev/null @@ -1,968 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#include "kcalcdisplay.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "kcalc_core.h" -#include "kcalc_settings.h" - -#include "moc_kcalcdisplay.cpp" - -//------------------------------------------------------------------------------ -// Name: KCalcDisplay -// Desc: constructor -//------------------------------------------------------------------------------ -KCalcDisplay::KCalcDisplay(QWidget *parent) : QFrame(parent), beep_(false), - groupdigits_(true), twoscomplement_(true), button_(0), lit_(false), - num_base_(NB_DECIMAL), precision_(9), fixed_precision_(-1), display_amount_(0), - history_index_(0), selection_timer_(new QTimer(this)) { - - setFocusPolicy(Qt::StrongFocus); - - setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); - - setBackgroundRole(QPalette::Base); - setForegroundRole(QPalette::Text); - setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); // set in kalc.ui - - KNumber::setDefaultFloatOutput(true); - KNumber::setDefaultFractionalInput(true); - - connect(this, SIGNAL(clicked()), this, SLOT(slotDisplaySelected())); - connect(selection_timer_, SIGNAL(timeout()), this, SLOT(slotSelectionTimedOut())); - - sendEvent(EventReset); -} - -//------------------------------------------------------------------------------ -// Name: ~KCalcDisplay -// Desc: destructor -//------------------------------------------------------------------------------ -KCalcDisplay::~KCalcDisplay() { -} - -//------------------------------------------------------------------------------ -// Name: changeSettings -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::changeSettings() { - QPalette pal = palette(); - - pal.setColor(QPalette::Text, KCalcSettings::foreColor()); - pal.setColor(QPalette::Base, KCalcSettings::backColor()); - - setPalette(pal); - - setFont(KCalcSettings::displayFont()); - - setPrecision(KCalcSettings::precision()); - - if (!KCalcSettings::fixed()) { - setFixedPrecision(-1); - } else { - setFixedPrecision(KCalcSettings::fixedPrecision()); - } - - setBeep(KCalcSettings::beep()); - setGroupDigits(KCalcSettings::groupDigits()); - setTwosComplement(KCalcSettings::twosComplement()); - setBinaryGrouping(KCalcSettings::binaryGrouping()); - setOctalGrouping(KCalcSettings::octalGrouping()); - setHexadecimalGrouping(KCalcSettings::hexadecimalGrouping()); - updateDisplay(); -} - -//------------------------------------------------------------------------------ -// Name: -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::updateFromCore(const CalcEngine &core, bool store_result_in_history) { - - bool tmp_error; - const KNumber &output = core.lastOutput(tmp_error); - -#if 0 - // TODO: do we really need explicit error tracking? - // isn't the type of the KNumber good enough? - // I think it is and that this error tracking is cruft - // left over from a LONG time ago... - if(output.type() == KNumber::TYPE_ERROR) { -#else - if (tmp_error) { -#endif - sendEvent(EventError); - } - - if (setAmount(output) && store_result_in_history && (output != KNumber::Zero)) { - // add this latest value to our history - history_list_.insert(history_list_.begin(), output); - history_index_ = 0; - } -} - -//------------------------------------------------------------------------------ -// Name: enterDigit -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::enterDigit(int data) { - - switch (data) { - case 0: newCharacter(QLatin1Char('0')); break; - case 1: newCharacter(QLatin1Char('1')); break; - case 2: newCharacter(QLatin1Char('2')); break; - case 3: newCharacter(QLatin1Char('3')); break; - case 4: newCharacter(QLatin1Char('4')); break; - case 5: newCharacter(QLatin1Char('5')); break; - case 6: newCharacter(QLatin1Char('6')); break; - case 7: newCharacter(QLatin1Char('7')); break; - case 8: newCharacter(QLatin1Char('8')); break; - case 9: newCharacter(QLatin1Char('9')); break; - case 0xa: newCharacter(QLatin1Char('A')); break; - case 0xb: newCharacter(QLatin1Char('B')); break; - case 0xc: newCharacter(QLatin1Char('C')); break; - case 0xd: newCharacter(QLatin1Char('D')); break; - case 0xe: newCharacter(QLatin1Char('E')); break; - case 0xf: newCharacter(QLatin1Char('F')); break; - default: - Q_ASSERT(0); - break; - } -} - -//------------------------------------------------------------------------------ -// Name: slotHistoryForward -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotHistoryForward() { - - if (history_list_.empty()) { - return; - } - - if (history_index_ <= 0) { - return; - } - - history_index_--; - setAmount(history_list_[history_index_]); -} - -//------------------------------------------------------------------------------ -// Name: slotHistoryBack -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotHistoryBack() { - - if (history_list_.empty()) { - return; - } - - if (history_index_ >= history_list_.size()) { - return; - } - - setAmount(history_list_[history_index_]); - history_index_++; -} - -//------------------------------------------------------------------------------ -// Name: sendEvent -// Desc: -//------------------------------------------------------------------------------ -bool KCalcDisplay::sendEvent(Event event) { - - switch (event) { - case EventClear: - case EventReset: - display_amount_ = KNumber::Zero; - str_int_ = QLatin1String("0"); - str_int_exp_.clear(); - - eestate_ = false; - period_ = false; - neg_sign_ = false; - - updateDisplay(); - - return true; - - case EventChangeSign: - return changeSign(); - - case EventError: - updateDisplay(); - return true; - - default: - return false; - } -} - -//------------------------------------------------------------------------------ -// Name: slotCut -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotCut() { - - slotCopy(); - sendEvent(EventReset); -} - -//------------------------------------------------------------------------------ -// Name: slotCopy -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotCopy() { - - QString txt = text_; - - switch(num_base_) { - case NB_HEX: - txt.prepend(QLatin1String("0x")); - txt.remove(QLatin1Char(' ')); - break; - case NB_BINARY: - txt.prepend(QLatin1String("0b")); - txt.remove(QLatin1Char(' ')); - break; - case NB_OCTAL: - txt.prepend(QLatin1String("0")); - txt.remove(QLatin1Char(' ')); - break; - case NB_DECIMAL: - break; - } - - (QApplication::clipboard())->setText(txt, QClipboard::Clipboard); - (QApplication::clipboard())->setText(txt, QClipboard::Selection); -} - -//------------------------------------------------------------------------------ -// Name: slotPaste -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotPaste(bool bClipboard) { - - QString tmp_str = (QApplication::clipboard())->text(bClipboard ? QClipboard::Clipboard : QClipboard::Selection); - - if (tmp_str.isNull()) { - if (beep_) { - KNotification::beep(); - } - return; - } - - NumBase tmp_num_base = num_base_; - - // fix up string - tmp_str = tmp_str.trimmed(); - - if (groupdigits_) { - tmp_str.remove(KGlobal::locale()->toLocale().groupSeparator()); - } - - tmp_str = tmp_str.toLower(); - - // determine base - if (tmp_str.startsWith(QLatin1String("0x"))) { - tmp_num_base = NB_HEX; - tmp_str.remove(0, 2); - } else if (tmp_str.startsWith(QLatin1String("0b"))) { - tmp_num_base = NB_BINARY; - tmp_str.remove(0, 2); - } else if (tmp_str.startsWith(QLatin1String("0"))) { - // we don't want this to trigger on "0.xxxxxx" cases - if(tmp_str.length() < 2 || QString(tmp_str[1]) != KNumber::decimalSeparator()) { - tmp_num_base = NB_OCTAL; - tmp_str.remove(0, 1); - } - } - - if (tmp_num_base != NB_DECIMAL) { - bool was_ok; - const qint64 tmp_result = tmp_str.toULongLong(&was_ok, tmp_num_base); - - if (!was_ok) { - setAmount(KNumber::NaN); - if (beep_) { - KNotification::beep(); - } - return; - } - setAmount(KNumber(tmp_result)); - } else { - setAmount(KNumber(tmp_str)); - if (beep_ && display_amount_ == KNumber::NaN) { - KNotification::beep(); - } - } -} - -//------------------------------------------------------------------------------ -// Name: slotDisplaySelected -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotDisplaySelected() { - - if (button_ == Qt::LeftButton) { - if (lit_) { - slotCopy(); - selection_timer_->start(100); - } else { - selection_timer_->stop(); - } - - invertColors(); - } else { - slotPaste(false); // Selection - } -} - -//------------------------------------------------------------------------------ -// Name: slotSelectionTimedOut -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::slotSelectionTimedOut() { - - lit_ = false; - invertColors(); - selection_timer_->stop(); -} - -//------------------------------------------------------------------------------ -// Name: invertColors -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::invertColors() { - - QPalette tmp_palette = palette(); - tmp_palette.setColor(QPalette::Base, palette().color(QPalette::Text)); - tmp_palette.setColor(QPalette::Text, palette().color(QPalette::Base)); - setPalette(tmp_palette); -} - -//------------------------------------------------------------------------------ -// Name: mousePressEvent -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::mousePressEvent(QMouseEvent *e) { - - if (e->button() == Qt::LeftButton) { - lit_ = !lit_; - button_ = Qt::LeftButton; - } else { - button_ = Qt::MiddleButton; - } - - emit clicked(); -} - -//------------------------------------------------------------------------------ -// Name: setPrecision -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setPrecision(int precision) { - - precision_ = precision; -} - -//------------------------------------------------------------------------------ -// Name: setFixedPrecision -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setFixedPrecision(int precision) { - - if (fixed_precision_ > precision_) { - fixed_precision_ = -1; - } else { - fixed_precision_ = precision; - } -} - -//------------------------------------------------------------------------------ -// Name: setBeep -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setBeep(bool flag) { - beep_ = flag; -} - -//------------------------------------------------------------------------------ -// Name: setGroupDigits -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setGroupDigits(bool flag) { - groupdigits_ = flag; -} - -//------------------------------------------------------------------------------ -// Name: setTwosComplement -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setTwosComplement(bool flag) { - twoscomplement_ = flag; -} - -//------------------------------------------------------------------------------ -// Name: setBinaryGrouping -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setBinaryGrouping(int digits) { - binaryGrouping_ = digits; -} - -//------------------------------------------------------------------------------ -// Name: setOctalGrouping -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setOctalGrouping(int digits) { - octalGrouping_ = digits; -} - -//------------------------------------------------------------------------------ -// Name: setHexadecimalGrouping -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setHexadecimalGrouping(int digits) { - hexadecimalGrouping_ = digits; -} - -//------------------------------------------------------------------------------ -// Name: getAmount -// Desc: -//------------------------------------------------------------------------------ -const KNumber &KCalcDisplay::getAmount() const { - return display_amount_; -} - -//------------------------------------------------------------------------------ -// Name: setAmount -// Desc: -//------------------------------------------------------------------------------ -bool KCalcDisplay::setAmount(const KNumber &new_amount) { - - QString display_str; - - str_int_ = QLatin1String("0"); - str_int_exp_.clear(); - period_ = false; - neg_sign_ = false; - eestate_ = false; - - if ((num_base_ != NB_DECIMAL) && (new_amount.type() != KNumber::TYPE_ERROR)) { - display_amount_ = new_amount.integerPart(); - - if (twoscomplement_) { - // treat number as 64-bit unsigned - const quint64 tmp_workaround = display_amount_.toUint64(); - display_str = QString::number(tmp_workaround, num_base_).toUpper(); - } else { - // QString::number treats non-decimal as unsigned - qint64 tmp_workaround = display_amount_.toInt64(); - const bool neg = tmp_workaround < 0; - if (neg) { - tmp_workaround = qAbs(tmp_workaround); - } - - display_str = QString::number(tmp_workaround, num_base_).toUpper(); - if (neg) { - display_str.prepend(KGlobal::locale()->toLocale().negativeSign()); - } - } - } else { - // num_base_ == NB_DECIMAL || new_amount.type() == KNumber::TYPE_ERROR - display_amount_ = new_amount; - display_str = display_amount_.toQString(KCalcSettings::precision(), fixed_precision_); - } - - setText(display_str); - emit changedAmount(display_amount_); - return true; -} - -//------------------------------------------------------------------------------ -// Name: setText -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setText(const QString &string) -{ - // note that "C" locale is being used internally - text_ = string; - - // don't mess with special numbers - const bool special = (string.contains(QLatin1String("nan")) || string.contains(QLatin1String("inf"))); - - // The decimal mode needs special treatment for two reasons, because: a) it uses KGlobal::locale() to get a localized - // format and b) it has possible numbers after the decimal place. Neither applies to Binary, Hexadecimal or Octal. - - if (groupdigits_ && !special){ - switch (num_base_) { - case NB_DECIMAL: - if (string.endsWith(QLatin1Char('.'))) { - text_.chop(1); - // Note: rounding happened already above! - text_ = KGlobal::locale()->formatNumber(text_, false, 0); - text_.append(KGlobal::locale()->toLocale().decimalPoint()); - } else { - // Note: rounding happened already above! - text_ = KGlobal::locale()->formatNumber(text_, false, 0); - } - break; - - case NB_BINARY: - text_ = groupDigits(text_, binaryGrouping_); - break; - - case NB_OCTAL: - text_ = groupDigits(text_, octalGrouping_); - break; - - case NB_HEX: - text_ = groupDigits(text_, hexadecimalGrouping_); - break; - } - } else if(special) { -#if 0 - // TODO: enable this code, it replaces the "inf" with an actual infinity - // symbol, but what should be put into the clip board when they copy? - if(string.contains(QLatin1String("inf"))) { - text_.replace("inf", QChar(0x221e)); - } -#endif - } - - update(); - emit changedText(text_); -} - -//------------------------------------------------------------------------------ -// Name: groupDigits -// Desc: -//------------------------------------------------------------------------------ -QString KCalcDisplay::groupDigits(const QString &displayString, int numDigits) { - - QString tmpDisplayString; - const int stringLength = displayString.length(); - - for (int i = stringLength; i > 0 ; i--){ - if(i % numDigits == 0 && i != stringLength) { - tmpDisplayString = tmpDisplayString + ' '; - } - - tmpDisplayString = tmpDisplayString + displayString[stringLength - i]; - } - - return tmpDisplayString; -} - -//------------------------------------------------------------------------------ -// Name: text -// Desc: -//------------------------------------------------------------------------------ -QString KCalcDisplay::text() const { - return text_; -} - -//------------------------------------------------------------------------------ -// Name: setBase -// Desc: change representation of display to new base (i.e. binary, decimal, -// octal, hexadecimal). The amount being displayed is changed to this -// base, but for now this amount can not be modified anymore (like -// being set with "setAmount"). Return value is the new base. -//------------------------------------------------------------------------------ -int KCalcDisplay::setBase(NumBase new_base) { - - switch (new_base) { - case NB_HEX: - num_base_ = NB_HEX; - period_ = false; - break; - case NB_DECIMAL: - num_base_ = NB_DECIMAL; - break; - case NB_OCTAL: - num_base_ = NB_OCTAL; - period_ = false; - break; - case NB_BINARY: - num_base_ = NB_BINARY; - period_ = false; - break; - default: - Q_ASSERT(0); - } - - // reset amount - setAmount(display_amount_); - return num_base_; -} - -//------------------------------------------------------------------------------ -// Name: setStatusText -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::setStatusText(int i, const QString &text) { - - if (i < NUM_STATUS_TEXT) { - str_status_[i] = text; - } - - update(); -} - -//------------------------------------------------------------------------------ -// Name: updateDisplay -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::updateDisplay() { - - // Put sign in front. - QString tmp_string; - if (neg_sign_) { - tmp_string = QLatin1Char('-') + str_int_; - } else { - tmp_string = str_int_; - } - - bool ok; - - switch (num_base_) { - case NB_BINARY: - Q_ASSERT(!period_ && !eestate_); - setText(tmp_string); - display_amount_ = KNumber(str_int_.toULongLong(&ok, 2)); - if (neg_sign_) { - display_amount_ = -display_amount_; - } - break; - - case NB_OCTAL: - Q_ASSERT(!period_ && !eestate_); - setText(tmp_string); - display_amount_ = KNumber(str_int_.toULongLong(&ok, 8)); - if (neg_sign_) { - display_amount_ = -display_amount_; - } - break; - - case NB_HEX: - Q_ASSERT(!period_ && !eestate_); - setText(tmp_string); - display_amount_ = KNumber(str_int_.toULongLong(&ok, 16)); - if (neg_sign_) { - display_amount_ = -display_amount_; - } - break; - - case NB_DECIMAL: - if (!eestate_) { - setText(tmp_string); - display_amount_ = KNumber(tmp_string); - } else { - if (str_int_exp_.isNull()) { - // add 'e0' to display but not to conversion - display_amount_ = KNumber(tmp_string); - setText(tmp_string + QLatin1String("e0")); - } else { - tmp_string += QLatin1Char('e') + str_int_exp_; - setText(tmp_string); - display_amount_ = KNumber(tmp_string); - } - } - break; - - default: - Q_ASSERT(0); - } - - emit changedAmount(display_amount_); -} - -//------------------------------------------------------------------------------ -// Name: newCharacter -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::newCharacter(const QChar new_char) { - const QChar decimalPoint = KGlobal::locale()->toLocale().decimalPoint(); - // test if character is valid - switch (new_char.toLatin1()) { - case 'e': - // EE can be set only once and in decimal mode - if (num_base_ != NB_DECIMAL || eestate_) { - if (beep_) { - KNotification::beep(); - } - return; - } - eestate_ = true; - break; - - case 'F': - case 'E': - case 'D': - case 'C': - case 'B': - case 'A': - if (num_base_ == NB_DECIMAL) { - if (beep_) { - KNotification::beep(); - } - return; - } - // no break - case '9': - case '8': - if (num_base_ == NB_OCTAL) { - if (beep_) { - KNotification::beep(); - } - return; - } - // no break - case '7': - case '6': - case '5': - case '4': - case '3': - case '2': - if (num_base_ == NB_BINARY) { - if (beep_) { - KNotification::beep(); - } - return; - } - // no break - case '1': - case '0': - break; - - default: - if(new_char == decimalPoint) { - // Period can be set only once and only in decimal - // mode, also not in EE-mode - if (num_base_ != NB_DECIMAL || period_ || eestate_) { - if (beep_) { - KNotification::beep(); - } - return; - } - period_ = true; - } else { - if (beep_) { - KNotification::beep(); - } - return; - } - } - - // change exponent or mantissa - if (eestate_) { - // ignore '.' before 'e'. turn e.g. '123.e' into '123e' - if (new_char == QLatin1Char('e') && str_int_.endsWith(decimalPoint)) { - str_int_.chop(1); - period_ = false; - } - - // 'e' only starts ee_mode, leaves strings unchanged - // do not add '0' if at start of exp - if (new_char != QLatin1Char('e') && !(str_int_exp_.isNull() && new_char == QLatin1Char('0'))) { - str_int_exp_.append(new_char); - } - } else { - // handle first character - if (str_int_ == QLatin1String("0")) { - switch (new_char.toLatin1()) { - case 'e': - // display "0e" not just "e" - // "0e" does not make sense either, but... - str_int_.append(new_char); - break; - default: - if(new_char == decimalPoint) { - // display "0." not just "." - str_int_.append(new_char); - } else { - // no leading '0's - str_int_[0] = new_char; - } - } - } else { - str_int_.append(new_char); - } - } - - updateDisplay(); -} - -//------------------------------------------------------------------------------ -// Name: deleteLastDigit -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::deleteLastDigit() { - - // Only partially implemented !! - if (eestate_) { - if (str_int_exp_.isNull()) { - eestate_ = false; - } else { - const int length = str_int_exp_.length(); - if (length > 1) { - str_int_exp_.chop(1); - } else { - str_int_exp_ = QLatin1String((const char *)0); - } - } - } else { - const int length = str_int_.length(); - if (length > 1) { - if (str_int_[length-1] == KGlobal::locale()->toLocale().decimalPoint()) { - period_ = false; - } - str_int_.chop(1); - } else { - Q_ASSERT(!period_); - str_int_[0] = QLatin1Char('0'); - } - } - - updateDisplay(); -} - -//------------------------------------------------------------------------------ -// Name: changeSign -// Desc: change Sign of display. Problem: Only possible here, when in input -// mode. Otherwise return 'false' so that the kcalc_core can handle -// things. -//------------------------------------------------------------------------------ -bool KCalcDisplay::changeSign() { - - //stupid way, to see if in input_mode or display_mode - if (str_int_ == QLatin1String("0")) { - return false; - } - - if (eestate_) { - if (!str_int_exp_.isNull()) { - if (str_int_exp_[0] != QLatin1Char('-')) { - str_int_exp_.prepend(QLatin1Char('-')); - } else { - str_int_exp_.remove(QLatin1Char('-')); - } - } - } else { - neg_sign_ = !neg_sign_; - } - - updateDisplay(); - return true; -} - -//------------------------------------------------------------------------------ -// Name: initStyleOption -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::initStyleOption(QStyleOptionFrame *option) const { - - if (!option) { - return; - } - - option->initFrom(this); - option->state &= ~QStyle::State_HasFocus; // don't draw focus highlight - - if (frameShadow() == QFrame::Sunken) { - option->state |= QStyle::State_Sunken; - } else if (frameShadow() == QFrame::Raised) { - option->state |= QStyle::State_Raised; - } - - option->lineWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, option, this); - option->midLineWidth = 0; -} - -//------------------------------------------------------------------------------ -// Name: paintEvent -// Desc: -//------------------------------------------------------------------------------ -void KCalcDisplay::paintEvent(QPaintEvent *) { - - QPainter painter(this); - - QStyleOptionFrame option; - initStyleOption(&option); - - style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, &painter, this); - - // draw display text - const int margin = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, 0); - QRect cr = contentsRect(); - cr.adjust(margin*2, 0, -margin*2, 0); // provide a margin - - const int align = QStyle::visualAlignment(layoutDirection(), Qt::AlignRight | Qt::AlignVCenter); - painter.drawText(cr, align | Qt::TextSingleLine, text_); - - // draw the status texts using half of the normal - // font size but not smaller than 7pt - QFont fnt(font()); - fnt.setPointSize(qMax((fnt.pointSize() / 2), 7)); - painter.setFont(fnt); - - QFontMetrics fm(fnt); - const uint w = fm.width(QLatin1String("________")); - const uint h = fm.height(); - - for (int n = 0; n < NUM_STATUS_TEXT; ++n) { - painter.drawText(5 + n * w, h, str_status_[n]); - } -} - -//------------------------------------------------------------------------------ -// Name: sizeHint -// Desc: -//------------------------------------------------------------------------------ -QSize KCalcDisplay::sizeHint() const { - - // basic size - QSize sz = fontMetrics().size(Qt::TextSingleLine, text_); - - // expanded by half font height to make room for the status texts - QFont fnt(font()); - fnt.setPointSize(qMax((fnt.pointSize() / 2), 7)); - - const QFontMetrics fm(fnt); - sz.setHeight(sz.height() + fm.height()); - - QStyleOptionFrame option; - initStyleOption(&option); - - return (style()->sizeFromContents(QStyle::CT_LineEdit, &option, sz.expandedTo(QApplication::globalStrut()), this)); -} diff --git a/kcalc/kcalcdisplay.h b/kcalc/kcalcdisplay.h deleted file mode 100644 index 3117b5dc..00000000 --- a/kcalc/kcalcdisplay.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#ifndef KCALCDISPLAY_H_ -#define KCALCDISPLAY_H_ - -#include -#include -#include "knumber.h" - -class CalcEngine; -class KAction; -#include -#include - -#define NUM_STATUS_TEXT 4 - -/* - This class provides a pocket calculator display. The display has - implicitely two major modes: One is for editing and one is purely - for displaying. - - When one uses "setAmount", the given amount is displayed, and the - amount which was possibly typed in before is lost. At the same time - this new value can not be modified. - - On the other hand, "addNewChar" adds a new digit to the amount that - is being typed in. If "setAmount" was used before, the display is - cleared and a new input starts. - - TODO: Check overflows, number of digits and such... -*/ - -enum NumBase { - NB_BINARY = 2, - NB_OCTAL = 8, - NB_DECIMAL = 10, - NB_HEX = 16 -}; - - -class KCalcDisplay : public QFrame { - Q_OBJECT - -public: - explicit KCalcDisplay(QWidget *parent = 0); - ~KCalcDisplay(); - - enum Event { - EventReset, // resets display - EventClear, // if no error reset display - EventError, - EventChangeSign - }; - - bool sendEvent(Event event); - void deleteLastDigit(); - const KNumber &getAmount() const; - void newCharacter(const QChar new_char); - bool setAmount(const KNumber &new_amount); - int setBase(NumBase new_base); - void setBeep(bool flag); - void setGroupDigits(bool flag); - void setTwosComplement(bool flag); - void setBinaryGrouping(int digits); - void setOctalGrouping(int digits); - void setHexadecimalGrouping(int digits); - void setFixedPrecision(int precision); - void setPrecision(int precision); - void setText(const QString &string); - QString groupDigits(const QString &displayString, int numDigits); - QString text() const; - void updateDisplay(); - void setStatusText(int i, const QString &text); - virtual QSize sizeHint() const; - - void changeSettings(); - void enterDigit(int data); - void updateFromCore(const CalcEngine &core, - bool store_result_in_history = false); - -public slots: - void slotCut(); - void slotCopy(); - void slotPaste(bool bClipboard = true); - -signals: - void clicked(); - void changedText(const QString &); - void changedAmount(const KNumber &); - -protected: - void mousePressEvent(QMouseEvent *); - virtual void paintEvent(QPaintEvent *p); - -private: - bool changeSign(); - void invertColors(); - void initStyleOption(QStyleOptionFrame *option) const; - -private slots: - void slotSelectionTimedOut(); - void slotDisplaySelected(); - void slotHistoryBack(); - void slotHistoryForward(); - -private: - QString text_; - bool beep_; - bool groupdigits_; - bool twoscomplement_; - int binaryGrouping_; - int octalGrouping_; - int hexadecimalGrouping_; - int button_; - bool lit_; - NumBase num_base_; - - int precision_; - int fixed_precision_; // "-1" = no fixed_precision - - KNumber display_amount_; - - QVector history_list_; - int history_index_; - - // only used for input of new numbers - bool eestate_; - bool period_; - bool neg_sign_; - QString str_int_; - QString str_int_exp_; - QString str_status_[NUM_STATUS_TEXT]; - - QTimer* selection_timer_; -}; - -#endif diff --git a/kcalc/kcalcui.rc b/kcalc/kcalcui.rc deleted file mode 100644 index 170ddf97..00000000 --- a/kcalc/kcalcui.rc +++ /dev/null @@ -1,17 +0,0 @@ - - - - &Settings - - - - - - - - - - - - - diff --git a/kcalc/knumber/CMakeLists.txt b/kcalc/knumber/CMakeLists.txt deleted file mode 100644 index a0f2314e..00000000 --- a/kcalc/knumber/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -if(ENABLE_TESTING) - add_subdirectory( tests ) -endif() diff --git a/kcalc/knumber/knumber.cpp b/kcalc/knumber/knumber.cpp deleted file mode 100644 index 5bbf11aa..00000000 --- a/kcalc/knumber/knumber.cpp +++ /dev/null @@ -1,937 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber.h" -#include "knumber_base.h" -#include "knumber_error.h" -#include "knumber_float.h" -#include "knumber_fraction.h" -#include "knumber_integer.h" -#include -#include -#include -#include - -QString KNumber::GroupSeparator = QLatin1String(","); -QString KNumber::DecimalSeparator = QLatin1String("."); - -const KNumber KNumber::Zero(QLatin1String("0")); -const KNumber KNumber::One(QLatin1String("1")); -const KNumber KNumber::NegOne(QLatin1String("-1")); -const KNumber KNumber::PosInfinity(QLatin1String("inf")); -const KNumber KNumber::NegInfinity(QLatin1String("-inf")); -const KNumber KNumber::NaN(QLatin1String("nan")); - -namespace { -namespace impl { - -//------------------------------------------------------------------------------ -// Name: increment -//------------------------------------------------------------------------------ -void increment(QString &str, int position) { - - for (int i = position; i >= 0; i--) { - const char last_char = str[i].toLatin1(); - switch (last_char) { - case '0': - str[i] = QLatin1Char('1'); - break; - case '1': - str[i] = QLatin1Char('2'); - break; - case '2': - str[i] = QLatin1Char('3'); - break; - case '3': - str[i] = QLatin1Char('4'); - break; - case '4': - str[i] = QLatin1Char('5'); - break; - case '5': - str[i] = QLatin1Char('6'); - break; - case '6': - str[i] = QLatin1Char('7'); - break; - case '7': - str[i] = QLatin1Char('8'); - break; - case '8': - str[i] = QLatin1Char('9'); - break; - case '9': - str[i] = QLatin1Char('0'); - if (i == 0) { - str.prepend(QLatin1Char('1')); - } - continue; - case '.': - continue; - } - break; - } -} - -//------------------------------------------------------------------------------ -// Name: round -//------------------------------------------------------------------------------ -void round(QString &str, int precision) { - - // Cut off if more digits in fractional part than 'precision' - - int decimalSymbolPos = str.indexOf(QLatin1Char('.')); - - if (decimalSymbolPos == -1) { - if (precision == 0) { - return; - } else if (precision > 0) { // add dot if missing (and needed) - str.append(QLatin1Char('.')); - decimalSymbolPos = str.length() - 1; - } - } - - // fill up with more than enough zeroes (in case fractional part too short) - str.append(QString().fill(QLatin1Char('0'), precision)); - - // Now decide whether to round up or down - const char last_char = str[decimalSymbolPos + precision + 1].toLatin1(); - switch (last_char) { - case '0': - case '1': - case '2': - case '3': - case '4': - // nothing to do, rounding down - break; - case '5': - case '6': - case '7': - case '8': - case '9': - // rounding up - increment(str, decimalSymbolPos + precision); - break; - default: - break; - } - - decimalSymbolPos = str.indexOf(QLatin1Char('.')); - str.truncate(decimalSymbolPos + precision + 1); - - // if precision == 0 delete also '.' - if (precision == 0) { - str = str.section(QLatin1Char('.'), 0, 0); - } -} -} - -//------------------------------------------------------------------------------ -// Name: round -//------------------------------------------------------------------------------ -QString round(const QString &s, int precision) { - - QString tmp = s; - if (precision < 0 || !QRegExp(QLatin1String("^[+-]?\\d+(\\.\\d+)*(e[+-]?\\d+)?$")).exactMatch(tmp)) { - return s; - } - - // Skip the sign (for now) - const bool neg = (tmp[0] == QLatin1Char('-')); - if (neg || tmp[0] == QLatin1Char('+')) { - tmp.remove(0, 1); - } - - // Split off exponential part (including 'e'-symbol) - QString mantString = tmp.section(QLatin1Char('e'), 0, 0, QString::SectionCaseInsensitiveSeps); - QString expString = tmp.section(QLatin1Char('e'), 1, 1, QString::SectionCaseInsensitiveSeps | QString::SectionIncludeLeadingSep); - - if (expString.length() == 1) { - expString.clear(); - } - - impl::round(mantString, precision); - - if (neg) { - mantString.prepend(QLatin1Char('-')); - } - - return mantString + expString; -} -} - -//------------------------------------------------------------------------------ -// Name: setGroupSeparator -//------------------------------------------------------------------------------ -void KNumber::setGroupSeparator(const QString &ch) { - GroupSeparator = ch; -} - -//------------------------------------------------------------------------------ -// Name: setDecimalSeparator -//------------------------------------------------------------------------------ -void KNumber::setDecimalSeparator(const QString &ch) { - DecimalSeparator = ch; -} - -//------------------------------------------------------------------------------ -// Name: groupSeparator -//------------------------------------------------------------------------------ -QString KNumber::groupSeparator() { - return GroupSeparator; -} - -//------------------------------------------------------------------------------ -// Name: decimalSeparator -//------------------------------------------------------------------------------ -QString KNumber::decimalSeparator() { - return DecimalSeparator; -} - -//------------------------------------------------------------------------------ -// Name: setDefaultFloatPrecision -//------------------------------------------------------------------------------ -void KNumber::setDefaultFloatPrecision(int precision) { - // Need to transform decimal digits into binary digits - const unsigned long int bin_prec = static_cast(double(precision) * M_LN10 / M_LN2 + 1); - mpf_set_default_prec(bin_prec); -} - -//------------------------------------------------------------------------------ -// Name: setSplitoffIntegerForFractionOutput -//------------------------------------------------------------------------------ -void KNumber::setSplitoffIntegerForFractionOutput(bool x) { - detail::knumber_fraction::set_split_off_integer_for_fraction_output(x); -} - -//------------------------------------------------------------------------------ -// Name: setDefaultFractionalInput -//------------------------------------------------------------------------------ -void KNumber::setDefaultFractionalInput(bool x) { - detail::knumber_fraction::set_default_fractional_input(x); -} - -//------------------------------------------------------------------------------ -// Name: setDefaultFloatOutput -//------------------------------------------------------------------------------ -void KNumber::setDefaultFloatOutput(bool x) { - detail::knumber_fraction::set_default_fractional_output(!x); -} - -//------------------------------------------------------------------------------ -// Name: Pi -//------------------------------------------------------------------------------ -KNumber KNumber::Pi() { - - // TODO: after 4.10 release: - // create a new constructor which works just like the normal QString - // accepting constructor, but allows us to specify separator - // characters, this will allow things to be done slightly more - // efficiently - QString s(QLatin1String("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068")); - s.replace('.', DecimalSeparator); - return KNumber(s); -} - -//------------------------------------------------------------------------------ -// Name: Euler -//------------------------------------------------------------------------------ -KNumber KNumber::Euler() { - - // TODO: after 4.10 release: - // create a new constructor which works just like the normal QString - // accepting constructor, but allows us to specify separator - // characters, this will allow things to be done slightly more - // efficiently - QString s(QLatin1String("2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274")); - s.replace('.', DecimalSeparator); - return KNumber(s); -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber() : value_(new detail::knumber_integer(0)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(const QString &s) : value_(0) { - - const QRegExp special_regex(QLatin1String("^(inf|-inf|nan)$")); - const QRegExp integer_regex(QLatin1String("^[+-]?\\d+$")); - const QRegExp fraction_regex(QLatin1String("^[+-]?\\d+/\\d+$")); - const QRegExp float_regex(QString(QLatin1String("^([+-]?\\d*)(%1\\d*)?(e([+-]?\\d+))?$")).arg(QRegExp::escape(DecimalSeparator))); - - if (special_regex.exactMatch(s)) { - value_ = new detail::knumber_error(s); - } else if (integer_regex.exactMatch(s)) { - value_ = new detail::knumber_integer(s); - } else if (fraction_regex.exactMatch(s)) { - value_ = new detail::knumber_fraction(s); - simplify(); - } else if (float_regex.exactMatch(s)) { - - if(detail::knumber_fraction::default_fractional_input) { - - const QStringList list = float_regex.capturedTexts(); - if(list.size() == 5) { - - const QString ipart = list[1]; - const QString fpart = list[2]; - const QString epart = list[3]; - const int e_val = list[4].toInt(); - - QString num = ipart + fpart.mid(1); - QString den = QLatin1String("1") + QString(fpart.size() - 1, QLatin1Char('0')); - - if(e_val < 0) { - den = den + QString(::abs(e_val), QLatin1Char('0')); - } else if(e_val > 0) { - num = num + QString(::abs(e_val), QLatin1Char('0')); - } - - value_ = new detail::knumber_fraction(QString(QLatin1String("%1/%2")).arg(num, den)); - simplify(); - return; - } - } - - // we need to normalize the decimal searator to US style because that's - // the only type that the GMP function accept - QString new_s = s; - new_s.replace(DecimalSeparator, QLatin1String(".")); - - value_ = new detail::knumber_float(new_s); - simplify(); - } else { - value_ = new detail::knumber_error(detail::knumber_error::ERROR_UNDEFINED); - } -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(qint32 value) : value_(new detail::knumber_integer(value)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(qint64 value) : value_(new detail::knumber_integer(value)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(quint32 value) : value_(new detail::knumber_integer(value)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(quint64 value) : value_(new detail::knumber_integer(value)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(qint64 num, quint64 den) : value_(new detail::knumber_fraction(num, den)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(quint64 num, quint64 den) : value_(new detail::knumber_fraction(num, den)) { -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(double value) : value_(new detail::knumber_float(value)) { - simplify(); -} - -//------------------------------------------------------------------------------ -// Name: KNumber -//------------------------------------------------------------------------------ -KNumber::KNumber(const KNumber &other) : value_(0) { - if(&other != this) { - value_ = other.value_->clone(); - } -} - -//------------------------------------------------------------------------------ -// Name: ~KNumber -//------------------------------------------------------------------------------ -KNumber::~KNumber() { - delete value_; -} - -//------------------------------------------------------------------------------ -// Name: type -//------------------------------------------------------------------------------ -KNumber::Type KNumber::type() const { - - if(dynamic_cast(value_)) { - return TYPE_INTEGER; - } else if(dynamic_cast(value_)) { - return TYPE_FLOAT; - } else if(dynamic_cast(value_)) { - return TYPE_FRACTION; - } else if(dynamic_cast(value_)) { - return TYPE_ERROR; - } else { - Q_ASSERT(0); - return TYPE_ERROR; - } -} - -//------------------------------------------------------------------------------ -// Name: operator= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator=(const KNumber &rhs) { - KNumber(rhs).swap(*this); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: swap -//------------------------------------------------------------------------------ -void KNumber::swap(KNumber &other) { - qSwap(value_, other.value_); -} - -//------------------------------------------------------------------------------ -// Name: integerPart -//------------------------------------------------------------------------------ -KNumber KNumber::integerPart() const { - - KNumber x(*this); - - if(detail::knumber_integer *const p = dynamic_cast(value_)) { - // NO-OP - Q_UNUSED(p); - } else if(detail::knumber_float *const p = dynamic_cast(value_)) { - detail::knumber_base *v = new detail::knumber_integer(p); - qSwap(v, x.value_); - delete v; - } else if(detail::knumber_fraction *const p = dynamic_cast(value_)) { - detail::knumber_base *v = new detail::knumber_integer(p); - qSwap(v, x.value_); - delete v; - } else if(detail::knumber_error *const p = dynamic_cast(value_)) { - // NO-OP - Q_UNUSED(p); - } else { - Q_ASSERT(0); - } - - return x; -} - -//------------------------------------------------------------------------------ -// Name: simplify -//------------------------------------------------------------------------------ -void KNumber::simplify() { - - if(value_->is_integer()) { - - if(detail::knumber_integer *const p = dynamic_cast(value_)) { - // NO-OP - Q_UNUSED(p); - } else if(detail::knumber_float *const p = dynamic_cast(value_)) { - detail::knumber_base *v = new detail::knumber_integer(p); - qSwap(v, value_); - delete v; - } else if(detail::knumber_fraction *const p = dynamic_cast(value_)) { - detail::knumber_base *v = new detail::knumber_integer(p); - qSwap(v, value_); - delete v; - } else if(detail::knumber_error *const p = dynamic_cast(value_)) { - // NO-OP - Q_UNUSED(p); - } else { - Q_ASSERT(0); - } - } -} - -//------------------------------------------------------------------------------ -// Name: operator+= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator+=(const KNumber &rhs) { - value_ = value_->add(rhs.value_); - simplify(); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator-= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator-=(const KNumber &rhs) { - value_ = value_->sub(rhs.value_); - simplify(); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator*= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator*=(const KNumber &rhs) { - value_ = value_->mul(rhs.value_); - simplify(); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator/= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator/=(const KNumber &rhs) { - - // Fix for bug #330577, x /0 is undefined, not infinity - // Also indirectly fixes bug #329897, tan(90) is undefined, not infinity - if(rhs == Zero) { - *this = NaN; - return *this; - } - - value_ = value_->div(rhs.value_); - simplify(); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator%= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator%=(const KNumber &rhs) { - value_ = value_->mod(rhs.value_); - simplify(); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator&= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator&=(const KNumber &rhs) { - value_ = value_->bitwise_and(rhs.value_); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator|= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator|=(const KNumber &rhs) { - value_ = value_->bitwise_or(rhs.value_); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator^= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator^=(const KNumber &rhs) { - value_ = value_->bitwise_xor(rhs.value_); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator<< -//------------------------------------------------------------------------------ -KNumber &KNumber::operator<<=(const KNumber &rhs) { - value_ = value_->bitwise_shift(rhs.value_); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator>>= -//------------------------------------------------------------------------------ -KNumber &KNumber::operator>>=(const KNumber &rhs) { - const KNumber rhs_neg(-rhs); - value_ = value_->bitwise_shift(rhs_neg.value_); - return *this; -} - -//------------------------------------------------------------------------------ -// Name: operator- -//------------------------------------------------------------------------------ -KNumber KNumber::operator-() const { - KNumber x(*this); - x.value_ = x.value_->neg(); - return x; -} - -//------------------------------------------------------------------------------ -// Name: operator~ -//------------------------------------------------------------------------------ -KNumber KNumber::operator~() const { - KNumber x(*this); - x.value_ = x.value_->cmp(); - return x; -} - -//------------------------------------------------------------------------------ -// Name: toQString -//------------------------------------------------------------------------------ -QString KNumber::toQString(int width, int precision) const { - - if(value_->is_zero()) { - return QLatin1String("0"); - } - - QString s; - - if(detail::knumber_integer *const p = dynamic_cast(value_)) { - if(width > 0) { - s = detail::knumber_float(p).toString(width); - } else { - s = value_->toString(width); - } - } else if(detail::knumber_float *const p = dynamic_cast(value_)) { - if(width > 0) { - s = value_->toString(width); - } else { - s = value_->toString(3 * mpf_get_default_prec() / 10); - } - } else if(detail::knumber_fraction *const p = dynamic_cast(value_)) { - s = value_->toString(width); - } else { - return value_->toString(width); - } - - // now do some rounding to make sure things are displayed reasonably - if (precision >= 0) { - return round(s, precision); - } else { - return s; - } -} - -//------------------------------------------------------------------------------ -// Name: toUint64 -//------------------------------------------------------------------------------ -quint64 KNumber::toUint64() const { - return value_->toUint64(); -} - -//------------------------------------------------------------------------------ -// Name: toInt64 -//------------------------------------------------------------------------------ -qint64 KNumber::toInt64() const { - return value_->toInt64(); -} - -//------------------------------------------------------------------------------ -// Name: abs -//------------------------------------------------------------------------------ -KNumber KNumber::abs() const { - KNumber z(*this); - z.value_ = z.value_->abs(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: cbrt -//------------------------------------------------------------------------------ -KNumber KNumber::cbrt() const { - KNumber z(*this); - z.value_ = z.value_->cbrt(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: sqrt -//------------------------------------------------------------------------------ -KNumber KNumber::sqrt() const { - KNumber z(*this); - z.value_ = z.value_->sqrt(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: pow -//------------------------------------------------------------------------------ -KNumber KNumber::pow(const KNumber &x) const { - - // Fix for bug #330711 (pow(0, -x) was causing crashes - // Fix for bug #330597 (pow(0,0) was 1 now it is NaN - // Thanks to Raushan Kumar for identifying the issue and submitting - // patches - if(*this == Zero && x <= Zero) { - return NaN; - } - - // if the LHS is a special then we can use this function - // no matter what, cause the result is a special too - if(!dynamic_cast(value_)) { - // number much bigger than this tend to crash GMP with - // an abort - if(x > KNumber(QLatin1String("1000000000"))) { - return PosInfinity; - } - } - - KNumber z(*this); - z.value_ = z.value_->pow(x.value_); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: sin -//------------------------------------------------------------------------------ -KNumber KNumber::sin() const { - KNumber z(*this); - z.value_ = z.value_->sin(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: cos -//------------------------------------------------------------------------------ -KNumber KNumber::cos() const { - KNumber z(*this); - z.value_ = z.value_->cos(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: tan -//------------------------------------------------------------------------------ -KNumber KNumber::tan() const { - KNumber z(*this); - z.value_ = z.value_->tan(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: tgamma -//------------------------------------------------------------------------------ -KNumber KNumber::tgamma() const { - KNumber z(*this); - if(z > KNumber(QLatin1String("10000000000"))) { - return PosInfinity; - } - z.value_ = z.value_->tgamma(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: asin -//------------------------------------------------------------------------------ -KNumber KNumber::asin() const { - KNumber z(*this); - z.value_ = z.value_->asin(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: acos -//------------------------------------------------------------------------------ -KNumber KNumber::acos() const { - KNumber z(*this); - z.value_ = z.value_->acos(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: atan -//------------------------------------------------------------------------------ -KNumber KNumber::atan() const { - KNumber z(*this); - z.value_ = z.value_->atan(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: sinh -//------------------------------------------------------------------------------ -KNumber KNumber::sinh() const { - KNumber z(*this); - z.value_ = z.value_->sinh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: cosh -//------------------------------------------------------------------------------ -KNumber KNumber::cosh() const { - KNumber z(*this); - z.value_ = z.value_->cosh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: tanh -//------------------------------------------------------------------------------ -KNumber KNumber::tanh() const { - KNumber z(*this); - z.value_ = z.value_->tanh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: asinh -//------------------------------------------------------------------------------ -KNumber KNumber::asinh() const { - KNumber z(*this); - z.value_ = z.value_->asinh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: acosh -//------------------------------------------------------------------------------ -KNumber KNumber::acosh() const { - KNumber z(*this); - z.value_ = z.value_->acosh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: atanh -//------------------------------------------------------------------------------ -KNumber KNumber::atanh() const { - KNumber z(*this); - z.value_ = z.value_->atanh(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: factorial -//------------------------------------------------------------------------------ -KNumber KNumber::factorial() const { - KNumber z(*this); - - // number much bigger than this tend to crash GMP with - // an abort - if(z > KNumber(QLatin1String("10000000000"))) { - return PosInfinity; - } - - z.value_ = z.value_->factorial(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: log2 -//------------------------------------------------------------------------------ -KNumber KNumber::log2() const { - KNumber z(*this); - z.value_ = z.value_->log2(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: log10 -//------------------------------------------------------------------------------ -KNumber KNumber::log10() const { - KNumber z(*this); - z.value_ = z.value_->log10(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: ln -//------------------------------------------------------------------------------ -KNumber KNumber::ln() const { - KNumber z(*this); - z.value_ = z.value_->ln(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: floor -//------------------------------------------------------------------------------ -KNumber KNumber::floor() const { - KNumber z(*this); - z.value_ = z.value_->floor(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: ceil -//------------------------------------------------------------------------------ -KNumber KNumber::ceil() const { - KNumber z(*this); - z.value_ = z.value_->ceil(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: exp2 -//------------------------------------------------------------------------------ -KNumber KNumber::exp2() const { - KNumber z(*this); - z.value_ = z.value_->exp2(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: exp10 -//------------------------------------------------------------------------------ -KNumber KNumber::exp10() const { - KNumber z(*this); - z.value_ = z.value_->exp10(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: exp -//------------------------------------------------------------------------------ -KNumber KNumber::exp() const { - KNumber z(*this); - z.value_ = z.value_->exp(); - z.simplify(); - return z; -} - -//------------------------------------------------------------------------------ -// Name: bin -//------------------------------------------------------------------------------ -KNumber KNumber::bin(const KNumber &x) const { - KNumber z(*this); - z.value_ = z.value_->bin(x.value_); - z.simplify(); - return z; -} diff --git a/kcalc/knumber/knumber.h b/kcalc/knumber/knumber.h deleted file mode 100644 index 79bc6fca..00000000 --- a/kcalc/knumber/knumber.h +++ /dev/null @@ -1,171 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_H_ -#define KNUMBER_H_ - -#include "knumber_operators.h" -#include - -namespace detail { -class knumber_base; -} - -class KNumber { -private: - friend bool operator==(const KNumber &lhs, const KNumber &rhs); - friend bool operator!=(const KNumber &lhs, const KNumber &rhs); - friend bool operator>=(const KNumber &lhs, const KNumber &rhs); - friend bool operator<=(const KNumber &lhs, const KNumber &rhs); - friend bool operator>(const KNumber &lhs, const KNumber &rhs); - friend bool operator<(const KNumber &lhs, const KNumber &rhs); - -public: - enum Type { - TYPE_ERROR, - TYPE_INTEGER, - TYPE_FLOAT, - TYPE_FRACTION - }; - -public: - // useful constants - static const KNumber Zero; - static const KNumber One; - static const KNumber NegOne; - static const KNumber PosInfinity; - static const KNumber NegInfinity; - static const KNumber NaN; - -public: - static KNumber Pi(); - static KNumber Euler(); - -public: - // construction/destruction - KNumber(); - explicit KNumber(const QString &s); - - explicit KNumber(qint32 value); - explicit KNumber(qint64 value); - explicit KNumber(quint32 value); - explicit KNumber(quint64 value); - - KNumber(qint64 num, quint64 den); - KNumber(quint64 num, quint64 den); - - explicit KNumber(double value); - - KNumber(const KNumber &other); - ~KNumber(); - -public: - Type type() const; - -public: - // assignment - KNumber &operator=(const KNumber &rhs); - -public: - // basic math operators - KNumber &operator+=(const KNumber &rhs); - KNumber &operator-=(const KNumber &rhs); - KNumber &operator*=(const KNumber &rhs); - KNumber &operator/=(const KNumber &rhs); - KNumber &operator%=(const KNumber &rhs); - -public: - // bitwise operators - KNumber &operator&=(const KNumber &rhs); - KNumber &operator|=(const KNumber &rhs); - KNumber &operator^=(const KNumber &rhs); - KNumber &operator<<=(const KNumber &rhs); - KNumber &operator>>=(const KNumber &rhs); - -public: - // neg/cmp - KNumber operator-() const; - KNumber operator~() const; - -public: - KNumber integerPart() const; - -public: - QString toQString(int width = -1, int precision = -1) const; - quint64 toUint64() const; - qint64 toInt64() const; - - -public: - KNumber abs() const; - KNumber cbrt() const; - KNumber sqrt() const; - KNumber pow(const KNumber &x) const; - - KNumber sin() const; - KNumber cos() const; - KNumber tan() const; - KNumber asin() const; - KNumber acos() const; - KNumber atan() const; - KNumber sinh() const; - KNumber cosh() const; - KNumber tanh() const; - KNumber asinh() const; - KNumber acosh() const; - KNumber atanh() const; - KNumber tgamma() const; - - KNumber factorial() const; - - KNumber log2() const; - KNumber log10() const; - KNumber ln() const; - KNumber floor() const; - KNumber ceil() const; - KNumber exp2() const; - KNumber exp10() const; - KNumber exp() const; - KNumber bin(const KNumber &x) const; - -public: - static void setDefaultFloatPrecision(int precision); - static void setSplitoffIntegerForFractionOutput(bool x); - static void setDefaultFractionalInput(bool x); - static void setDefaultFloatOutput(bool x); - static void setGroupSeparator(const QString &ch); - static void setDecimalSeparator(const QString &ch); - - static QString groupSeparator(); - static QString decimalSeparator(); - -public: - void swap(KNumber &other); - -private: - void simplify(); - -private: - detail::knumber_base *value_; - -private: - static QString GroupSeparator; - static QString DecimalSeparator; -}; - -#endif diff --git a/kcalc/knumber/knumber_base.h b/kcalc/knumber/knumber_base.h deleted file mode 100644 index 2f400d49..00000000 --- a/kcalc/knumber/knumber_base.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_BASE_H_ -#define KNUMBER_BASE_H_ - -#include - -#ifdef KNUMBER_USE_MPFR -#include -#endif - -#include - -#define KNUMBER_BUFFER(buffername, buffersize) \ - Q_ASSERT_X(buffersize >= 1, Q_FUNC_INFO, "buffer size is negative or zero"); \ - char buffername[buffersize]; \ - ::memset(buffername, 0, buffersize * sizeof(char)); - -namespace detail { - -class knumber_error; -class knumber_integer; -class knumber_fraction; -class knumber_float; - -class knumber_base { -public: - virtual ~knumber_base() { } - -public: - virtual knumber_base *clone() = 0; - -public: - virtual QString toString(int precision) const = 0; - virtual quint64 toUint64() const = 0; - virtual qint64 toInt64() const = 0; - -public: - virtual bool is_integer() const = 0; - virtual bool is_zero() const = 0; - virtual int sign() const = 0; - -public: - // basic math - virtual knumber_base *add(knumber_base *rhs) = 0; - virtual knumber_base *sub(knumber_base *rhs) = 0; - virtual knumber_base *mul(knumber_base *rhs) = 0; - virtual knumber_base *div(knumber_base *rhs) = 0; - virtual knumber_base *mod(knumber_base *rhs) = 0; - -public: - // logical operators - virtual knumber_base *bitwise_and(knumber_base *rhs) = 0; - virtual knumber_base *bitwise_xor(knumber_base *rhs) = 0; - virtual knumber_base *bitwise_or(knumber_base *rhs) = 0; - virtual knumber_base *bitwise_shift(knumber_base *rhs) = 0; - -public: - // algebraic functions - virtual knumber_base *pow(knumber_base *rhs) = 0; - virtual knumber_base *neg() = 0; - virtual knumber_base *cmp() = 0; - virtual knumber_base *abs() = 0; - virtual knumber_base *sqrt() = 0; - virtual knumber_base *cbrt() = 0; - virtual knumber_base *factorial() = 0; - virtual knumber_base *reciprocal() = 0; - -public: - // special functions - virtual knumber_base *log2() = 0; - virtual knumber_base *log10() = 0; - virtual knumber_base *ln() = 0; - virtual knumber_base *exp2() = 0; - virtual knumber_base *exp10() = 0; - virtual knumber_base *floor() = 0; - virtual knumber_base *ceil() = 0; - virtual knumber_base *exp() = 0; - virtual knumber_base *bin(knumber_base *rhs) = 0; - -public: - // trig functions - virtual knumber_base *sin() = 0; - virtual knumber_base *cos() = 0; - virtual knumber_base *tan() = 0; - virtual knumber_base *asin() = 0; - virtual knumber_base *acos() = 0; - virtual knumber_base *atan() = 0; - virtual knumber_base *sinh() = 0; - virtual knumber_base *cosh() = 0; - virtual knumber_base *tanh() = 0; - virtual knumber_base *asinh() = 0; - virtual knumber_base *acosh() = 0; - virtual knumber_base *atanh() = 0; - virtual knumber_base *tgamma() = 0; - -public: - // comparison - virtual int compare(knumber_base *rhs) = 0; -}; - -} - -#endif diff --git a/kcalc/knumber/knumber_error.cpp b/kcalc/knumber/knumber_error.cpp deleted file mode 100644 index 55903d41..00000000 --- a/kcalc/knumber/knumber_error.cpp +++ /dev/null @@ -1,714 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber_integer.h" -#include "knumber_float.h" -#include "knumber_fraction.h" -#include "knumber_error.h" -#include // for M_PI -#include - -namespace detail { - - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(Error e) : error_(e) { -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(const QString &s) { - - if (s == QLatin1String("nan")) error_ = ERROR_UNDEFINED; - else if (s == QLatin1String("inf")) error_ = ERROR_POS_INFINITY; - else if (s == QLatin1String("-inf")) error_ = ERROR_NEG_INFINITY; - else error_ = ERROR_UNDEFINED; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error() : error_(ERROR_UNDEFINED) { - -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::~knumber_error() { - -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(const knumber_integer *) : error_(ERROR_UNDEFINED) { -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(const knumber_fraction *) : error_(ERROR_UNDEFINED) { -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(const knumber_float *) : error_(ERROR_UNDEFINED) { -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_error::knumber_error(const knumber_error *value) : error_(value->error_) { -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -QString knumber_error::toString(int precision) const { - - Q_UNUSED(precision); - - switch(error_) { - case ERROR_POS_INFINITY: - return QLatin1String("inf"); - case ERROR_NEG_INFINITY: - return QLatin1String("-inf"); - case ERROR_UNDEFINED: - default: - return QLatin1String("nan"); - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::add(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(error_ == ERROR_POS_INFINITY && p->error_ == ERROR_NEG_INFINITY) { - error_ = ERROR_UNDEFINED; - } else if(error_ == ERROR_NEG_INFINITY && p->error_ == ERROR_POS_INFINITY) { - error_ = ERROR_UNDEFINED; - } else if(p->error_ == ERROR_UNDEFINED) { - error_ = ERROR_UNDEFINED; - } - return this; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::sub(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(error_ == ERROR_POS_INFINITY && p->error_ == ERROR_POS_INFINITY) { - error_ = ERROR_UNDEFINED; - } else if(error_ == ERROR_NEG_INFINITY && p->error_ == ERROR_NEG_INFINITY) { - error_ = ERROR_UNDEFINED; - } else if(p->error_ == ERROR_UNDEFINED) { - error_ = ERROR_UNDEFINED; - } - return this; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::mul(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - if(p->is_zero()) { - error_ = ERROR_UNDEFINED; - } - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - if(p->is_zero()) { - error_ = ERROR_UNDEFINED; - } - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - if(p->is_zero()) { - error_ = ERROR_UNDEFINED; - } - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(error_ == ERROR_POS_INFINITY && p->error_ == ERROR_NEG_INFINITY) { - error_ = ERROR_NEG_INFINITY; - } else if(error_ == ERROR_NEG_INFINITY && p->error_ == ERROR_POS_INFINITY) { - error_ = ERROR_NEG_INFINITY; - } else if(error_ == ERROR_NEG_INFINITY && p->error_ == ERROR_NEG_INFINITY) { - error_ = ERROR_POS_INFINITY; - } else if(p->error_ == ERROR_UNDEFINED) { - error_ = ERROR_UNDEFINED; - } - return this; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::div(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - error_ = ERROR_UNDEFINED; - return this; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::mod(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - error_ = ERROR_UNDEFINED; - return this; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::pow(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - - switch(error_) { - case ERROR_POS_INFINITY: - if(p->sign() > 0) { - return this; - } else if(p->sign() < 0) { - knumber_integer *n = new knumber_integer(0); - delete this; - return n; - } else { - error_ = ERROR_UNDEFINED; - return this; - } - break; - case ERROR_NEG_INFINITY: - if(p->sign() > 0) { - error_ = ERROR_POS_INFINITY; - return this; - } else if(p->sign() < 0) { - knumber_integer *n = new knumber_integer(0); - delete this; - return n; - } else { - error_ = ERROR_UNDEFINED; - return this; - } - break; - case ERROR_UNDEFINED: - return this; - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::neg() { - - switch(error_) { - case ERROR_POS_INFINITY: - error_ = ERROR_NEG_INFINITY; - break; - case ERROR_NEG_INFINITY: - error_ = ERROR_POS_INFINITY; - break; - case ERROR_UNDEFINED: - default: - break; - } - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::cmp() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::abs() { - - switch(error_) { - case ERROR_NEG_INFINITY: - error_ = ERROR_POS_INFINITY; - break; - case ERROR_POS_INFINITY: - case ERROR_UNDEFINED: - default: - break; - } - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::sqrt() { - - switch(error_) { - case ERROR_NEG_INFINITY: - error_ = ERROR_UNDEFINED; - break; - case ERROR_POS_INFINITY: - case ERROR_UNDEFINED: - default: - break; - } - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::cbrt() { - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::factorial() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::sin() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::cos() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base* knumber_error::tgamma() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::tan() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::asin() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::acos() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::atan() { - - switch(error_) { - case ERROR_POS_INFINITY: - delete this; - return new knumber_float(M_PI / 2.0); - case ERROR_NEG_INFINITY: - delete this; - return new knumber_float(-M_PI / 2.0); - case ERROR_UNDEFINED: - default: - return this; - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::sinh() { - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::cosh() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::tanh() { - - if(sign() > 0) { - delete this; - return new knumber_integer(1); - } else if(sign() < 0) { - delete this; - return new knumber_integer(-1); - } else { - return this; - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::asinh() { - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::acosh() { - - if(sign() < 0) { - error_ = ERROR_UNDEFINED; - } - - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::atanh() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_error::compare(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - if(sign() > 0) { - return 1; - } else { - return -1; - } - } else if(knumber_float *const p = dynamic_cast(rhs)) { - if(sign() > 0) { - return 1; - } else { - return -1; - } - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - if(sign() > 0) { - return 1; - } else { - return -1; - } - } else if(knumber_error *const p = dynamic_cast(rhs)) { - return sign() == p->sign(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::clone() { - return new knumber_error(this); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::bitwise_and(knumber_base *rhs) { - Q_UNUSED(rhs); - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::bitwise_xor(knumber_base *rhs) { - Q_UNUSED(rhs); - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::bitwise_or(knumber_base *rhs) { - Q_UNUSED(rhs); - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::bitwise_shift(knumber_base *rhs) { - Q_UNUSED(rhs); - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_error::is_integer() const { - - return false; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_error::is_zero() const { - - return false; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_error::sign() const { - - switch(error_) { - case ERROR_POS_INFINITY: - return +1; - case ERROR_NEG_INFINITY: - return -1; - case ERROR_UNDEFINED: - default: - return 0; - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::reciprocal() { - - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::log2() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::log10() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::ln() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::ceil() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::floor() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::exp2() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::exp10() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::exp() { - error_ = ERROR_UNDEFINED; - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -quint64 knumber_error::toUint64() const { - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -qint64 knumber_error::toInt64() const { - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_error::bin(knumber_base *rhs) { - Q_UNUSED(rhs); - error_ = ERROR_UNDEFINED; - return this; -} - -} diff --git a/kcalc/knumber/knumber_error.h b/kcalc/knumber/knumber_error.h deleted file mode 100644 index 38a34642..00000000 --- a/kcalc/knumber/knumber_error.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_ERROR_H_ -#define KNUMBER_ERROR_H_ - -#include "knumber_base.h" - -class KNumber; - -namespace detail { - -class knumber_error : public knumber_base { - friend class ::KNumber; - friend class knumber_integer; - friend class knumber_fraction; - friend class knumber_float; - -public: - enum Error { - ERROR_UNDEFINED, - ERROR_POS_INFINITY, - ERROR_NEG_INFINITY - }; - -public: - explicit knumber_error(const QString &s); - explicit knumber_error(Error e); - knumber_error(); - virtual ~knumber_error(); - -public: - virtual QString toString(int precision) const; - virtual quint64 toUint64() const; - virtual qint64 toInt64() const; - -public: - virtual bool is_integer() const; - virtual bool is_zero() const; - virtual int sign() const; - -public: - virtual knumber_base *add(knumber_base *rhs); - virtual knumber_base *sub(knumber_base *rhs); - virtual knumber_base *mul(knumber_base *rhs); - virtual knumber_base *div(knumber_base *rhs); - virtual knumber_base *mod(knumber_base *rhs); - -public: - virtual knumber_base *bitwise_and(knumber_base *rhs); - virtual knumber_base *bitwise_xor(knumber_base *rhs); - virtual knumber_base *bitwise_or(knumber_base *rhs); - virtual knumber_base *bitwise_shift(knumber_base *rhs); - -public: - virtual knumber_base *pow(knumber_base *rhs); - virtual knumber_base *neg(); - virtual knumber_base *cmp(); - virtual knumber_base *abs(); - virtual knumber_base *sqrt(); - virtual knumber_base *cbrt(); - virtual knumber_base *factorial(); - virtual knumber_base *reciprocal(); - virtual knumber_base *tgamma(); - -public: - virtual knumber_base *log2(); - virtual knumber_base *log10(); - virtual knumber_base *ln(); - virtual knumber_base *exp2(); - virtual knumber_base *exp10(); - virtual knumber_base *floor(); - virtual knumber_base *ceil(); - virtual knumber_base *exp(); - virtual knumber_base *bin(knumber_base *rhs); - -public: - virtual knumber_base *sin(); - virtual knumber_base *cos(); - virtual knumber_base *tan(); - virtual knumber_base *asin(); - virtual knumber_base *acos(); - virtual knumber_base *atan(); - virtual knumber_base *sinh(); - virtual knumber_base *cosh(); - virtual knumber_base *tanh(); - virtual knumber_base *asinh(); - virtual knumber_base *acosh(); - virtual knumber_base *atanh(); - -public: - virtual int compare(knumber_base *rhs); - -private: - // conversion constructors - explicit knumber_error(const knumber_integer *value); - explicit knumber_error(const knumber_fraction *value); - explicit knumber_error(const knumber_float *value); - explicit knumber_error(const knumber_error *value); - -public: - virtual knumber_base *clone(); - -private: - Error error_; -}; - -} - -#endif diff --git a/kcalc/knumber/knumber_float.cpp b/kcalc/knumber/knumber_float.cpp deleted file mode 100644 index 85abd865..00000000 --- a/kcalc/knumber/knumber_float.cpp +++ /dev/null @@ -1,999 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber_integer.h" -#include "knumber_float.h" -#include "knumber_fraction.h" -#include "knumber_error.h" -#include -#include - -namespace detail { - -#ifdef KNUMBER_USE_MPFR -const mpfr_rnd_t knumber_float::rounding_mode = MPFR_RNDN; -const mpfr_prec_t knumber_float::precision = 1024; -#endif - -template -knumber_base *knumber_float::execute_libc_func(double x) { - const double r = F(x); - if(isnan(r)) { - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } else if(isinf(r)) { - knumber_error *e = new knumber_error(knumber_error::ERROR_POS_INFINITY); - delete this; - return e; - } else { - mpf_set_d(mpf_, r); - return this; - } -} - -template -knumber_base *knumber_float::execute_libc_func(double x, double y) { - const double r = F(x, y); - if(isnan(r)) { - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } else if(isinf(r)) { - knumber_error *e = new knumber_error(knumber_error::ERROR_POS_INFINITY); - delete this; - return e; - } else { - mpf_set_d(mpf_, r); - return this; - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(const QString &s) { - - mpf_init(mpf_); - mpf_set_str(mpf_, s.toAscii(), 10); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(double value) { - - Q_ASSERT(!isinf(value)); - Q_ASSERT(!isnan(value)); - - mpf_init_set_d(mpf_, value); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(mpf_t mpf) { - - mpf_init(mpf_); - mpf_set(mpf_, mpf); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(const knumber_float *value) { - - mpf_init_set(mpf_, value->mpf_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(const knumber_integer *value) { - - mpf_init(mpf_); - mpf_set_z(mpf_, value->mpz_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::knumber_float(const knumber_fraction *value) { - - mpf_init(mpf_); - mpf_set_q(mpf_, value->mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::clone() { - - return new knumber_float(this); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_float::~knumber_float() { - - mpf_clear(mpf_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::add(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return add(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - mpf_add(mpf_, mpf_, p->mpf_); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return add(&f); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - knumber_error *e = new knumber_error(p); - delete this; - return e; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::sub(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return sub(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - mpf_sub(mpf_, mpf_, p->mpf_); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return sub(&f); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - knumber_error *e = new knumber_error(p); - delete this; - return e->neg(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::mul(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return mul(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - mpf_mul(mpf_, mpf_, p->mpf_); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return mul(&f); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(is_zero()) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - if(sign() < 0) { - delete this; - knumber_error *e = new knumber_error(p); - return e->neg(); - } else { - delete this; - return new knumber_error(p); - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::div(knumber_base *rhs) { - - if(rhs->is_zero()) { - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_NEG_INFINITY); - } else { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } - } - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return div(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - mpf_div(mpf_, mpf_, p->mpf_); - return this; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return div(&f); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(p->sign() > 0 || p->sign() < 0) { - delete this; - return new knumber_integer(0); - } - - delete this; - return new knumber_error(p); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::mod(knumber_base *rhs) { - - Q_UNUSED(rhs); - - if(rhs->is_zero()) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - delete this; - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::bitwise_and(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::bitwise_xor(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::bitwise_or(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::bitwise_shift(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - // NOTE: we don't support bitwise operations with non-integer operands - return new knumber_error(knumber_error::ERROR_UNDEFINED); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::neg() { - - mpf_neg(mpf_, mpf_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::cmp() { - - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::abs() { - - mpf_abs(mpf_, mpf_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::sqrt() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_sqrt(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); -#else - mpf_sqrt(mpf_, mpf_); -#endif - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::cbrt() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_cbrt(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { -#ifdef Q_CC_MSVC - return execute_libc_func< ::pow>(x, 1.0 / 3.0); -#else - return execute_libc_func< ::cbrt>(x); -#endif - } -#endif - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::factorial() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - knumber_integer *i = new knumber_integer(this); - delete this; - return i->factorial(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::sin() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_sin(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::sin>(x); - } -#endif - -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::floor() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_floor(mpfr, mpfr); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::floor>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::ceil() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_ceil(mpfr, mpfr); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::ceil>(x); - } -#endif -} -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::cos() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_cos(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::cos>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::tan() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_tan(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::tan>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::asin() { - if(mpf_cmp_d(mpf_, 1.0) > 0 || mpf_cmp_d(mpf_, -1.0) < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_asin(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::asin>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------s -knumber_base *knumber_float::acos() { - if(mpf_cmp_d(mpf_, 1.0) > 0 || mpf_cmp_d(mpf_, -1.0) < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_acos(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::acos>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::atan() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_atan(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::atan>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::sinh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_sinh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::sinh>(x); -#endif - -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::cosh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_cosh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::cosh>(x); -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::tanh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_tanh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::tanh>(x); -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::tgamma() { - -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_gamma(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - - } else { - return execute_libc_func< ::tgamma>(x); - } -#endif - -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::asinh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_asinh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::asinh>(x); -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::acosh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_acosh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::acosh>(x); -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::atanh() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_atanh(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - return execute_libc_func< ::atanh>(x); -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::pow(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpf_pow_ui(mpf_, mpf_, mpz_get_ui(p->mpz_)); - - if(p->sign() < 0) { - return reciprocal(); - } else { - return this; - } - } else if(knumber_float *const p = dynamic_cast(rhs)) { - return execute_libc_func< ::pow>(mpf_get_d(mpf_), mpf_get_d(p->mpf_)); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return execute_libc_func< ::pow>(mpf_get_d(mpf_), mpf_get_d(f.mpf_)); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(p->sign() > 0) { - knumber_error *e = new knumber_error(knumber_error::ERROR_POS_INFINITY); - delete this; - return e; - } else if(p->sign() < 0) { - knumber_integer *n = new knumber_integer(0); - delete this; - return n; - } else { - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_float::compare(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return compare(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - return mpf_cmp(mpf_, p->mpf_); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_float f(p); - return compare(&f); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - // NOTE: any number compared to NaN/Inf/-Inf always compares less - // at the moment - return -1; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -QString knumber_float::toString(int precision) const { - - size_t size; - if (precision > 0) { - size = gmp_snprintf(NULL, 0, "%.*Fg", precision, mpf_) + 1; - } else { - size = gmp_snprintf(NULL, 0, "%.Fg", mpf_) + 1; - } - - KNUMBER_BUFFER(buf, size); - - if (precision > 0) { - gmp_snprintf(&buf[0], size, "%.*Fg", precision, mpf_); - } else { - gmp_snprintf(&buf[0], size, "%.Fg", mpf_); - } - - return QLatin1String(&buf[0]); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_float::is_integer() const { - - return mpf_integer_p(mpf_) != 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_float::is_zero() const { - - return mpf_sgn(mpf_) == 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_float::sign() const { - - return mpf_sgn(mpf_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::reciprocal() { - - mpf_t mpf; - mpf_init_set_d(mpf, 1.0); - mpf_div(mpf_, mpf, mpf_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::log2() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_log2(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::log2>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::log10() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_log10(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::log10>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::ln() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_log(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::log>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::exp2() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_exp2(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::exp2>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::exp10() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_exp10(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::pow>(10, x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::exp() { -#ifdef KNUMBER_USE_MPFR - mpfr_t mpfr; - mpfr_init_set_f(mpfr, mpf_, rounding_mode); - mpfr_exp(mpfr, mpfr, rounding_mode); - mpfr_get_f(mpf_, mpfr, rounding_mode); - mpfr_clear(mpfr); - return this; -#else - const double x = mpf_get_d(mpf_); - if(isinf(x)) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } else { - return execute_libc_func< ::exp>(x); - } -#endif -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -quint64 knumber_float::toUint64() const { - return knumber_integer(this).toUint64(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -qint64 knumber_float::toInt64() const { - return knumber_integer(this).toInt64(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_float::bin(knumber_base *rhs) { - Q_UNUSED(rhs); - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); -} - -} diff --git a/kcalc/knumber/knumber_float.h b/kcalc/knumber/knumber_float.h deleted file mode 100644 index c0d6f3bd..00000000 --- a/kcalc/knumber/knumber_float.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_FLOAT_H_ -#define KNUMBER_FLOAT_H_ - -#include "knumber_base.h" - -class KNumber; - -namespace detail { - -class knumber_float : public knumber_base { - friend class ::KNumber; - friend class knumber_error; - friend class knumber_integer; - friend class knumber_fraction; - -private: -#ifdef KNUMBER_USE_MPFR - static const mpfr_rnd_t rounding_mode; - static const mpfr_prec_t precision; -#endif - -public: - explicit knumber_float(const QString &s); - explicit knumber_float(double value); - - explicit knumber_float(mpf_t mpf); - virtual ~knumber_float(); - -private: - // conversion constructors - explicit knumber_float(const knumber_integer *value); - explicit knumber_float(const knumber_fraction *value); - explicit knumber_float(const knumber_float *value); - explicit knumber_float(const knumber_error *value); - -public: - virtual QString toString(int precision) const; - virtual quint64 toUint64() const; - virtual qint64 toInt64() const; - -public: - virtual bool is_integer() const; - virtual bool is_zero() const; - virtual int sign() const; - -public: - virtual knumber_base *add(knumber_base *rhs); - virtual knumber_base *sub(knumber_base *rhs); - virtual knumber_base *mul(knumber_base *rhs); - virtual knumber_base *div(knumber_base *rhs); - virtual knumber_base *mod(knumber_base *rhs); - -public: - virtual knumber_base *pow(knumber_base *rhs); - virtual knumber_base *neg(); - virtual knumber_base *cmp(); - virtual knumber_base *abs(); - virtual knumber_base *sqrt(); - virtual knumber_base *cbrt(); - virtual knumber_base *factorial(); - virtual knumber_base *reciprocal(); - virtual knumber_base *tgamma(); - -public: - virtual knumber_base *log2(); - virtual knumber_base *log10(); - virtual knumber_base *ln(); - virtual knumber_base *floor(); - virtual knumber_base *ceil(); - virtual knumber_base *exp2(); - virtual knumber_base *exp10(); - virtual knumber_base *exp(); - virtual knumber_base *bin(knumber_base *rhs); - -public: - virtual knumber_base *sin(); - virtual knumber_base *cos(); - virtual knumber_base *tan(); - virtual knumber_base *asin(); - virtual knumber_base *acos(); - virtual knumber_base *atan(); - virtual knumber_base *sinh(); - virtual knumber_base *cosh(); - virtual knumber_base *tanh(); - virtual knumber_base *asinh(); - virtual knumber_base *acosh(); - virtual knumber_base *atanh(); - -public: - virtual int compare(knumber_base *rhs); - -public: - virtual knumber_base *bitwise_and(knumber_base *rhs); - virtual knumber_base *bitwise_xor(knumber_base *rhs); - virtual knumber_base *bitwise_or(knumber_base *rhs); - virtual knumber_base *bitwise_shift(knumber_base *rhs); - -public: - virtual knumber_base *clone(); - -private: - template - knumber_base *execute_libc_func(double x); - - template - knumber_base *execute_libc_func(double x, double y); - -private: - mpf_t mpf_; -}; - -} - -#endif diff --git a/kcalc/knumber/knumber_fraction.cpp b/kcalc/knumber/knumber_fraction.cpp deleted file mode 100644 index d5805edc..00000000 --- a/kcalc/knumber/knumber_fraction.cpp +++ /dev/null @@ -1,908 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber_integer.h" -#include "knumber_float.h" -#include "knumber_fraction.h" -#include "knumber_error.h" -#include - -namespace detail { - -bool knumber_fraction::default_fractional_input = false; -bool knumber_fraction::default_fractional_output = true; -bool knumber_fraction::split_off_integer_for_fraction_output = false; - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -void knumber_fraction::set_default_fractional_input(bool value) { - default_fractional_input = value; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -void knumber_fraction::set_default_fractional_output(bool value) { - default_fractional_output = value; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -void knumber_fraction::set_split_off_integer_for_fraction_output(bool value) { - split_off_integer_for_fraction_output = value; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(const QString &s) { - mpq_init(mpq_); - mpq_set_str(mpq_, s.toAscii(), 10); - mpq_canonicalize(mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(qint64 num, quint64 den) { - mpq_init(mpq_); - mpq_set_si(mpq_, num, den); - mpq_canonicalize(mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(quint64 num, quint64 den) { - mpq_init(mpq_); - mpq_set_ui(mpq_, num, den); - mpq_canonicalize(mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(mpq_t mpq) { - mpq_init(mpq_); - mpq_set(mpq_, mpq); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(const knumber_fraction *value) { - mpq_init(mpq_); - mpq_set(mpq_, value->mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(const knumber_integer *value) { - mpq_init(mpq_); - mpq_set_z(mpq_, value->mpz_); -} - -#if 0 -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::knumber_fraction(const knumber_float *value) { - mpq_init(mpq_); - mpq_set_f(mpq_, value->mpf_); -} -#endif - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::clone() { - return new knumber_fraction(this); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_fraction::~knumber_fraction() { - mpq_clear(mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_fraction::is_integer() const { - return (mpz_cmp_ui(mpq_denref(mpq_), 1) == 0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::add(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction q(p); - mpq_add(mpq_, mpq_, q.mpq_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->add(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - mpq_add(mpq_, mpq_, p->mpq_); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - knumber_error *e = new knumber_error(p); - delete this; - return e; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::sub(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction q(p); - mpq_sub(mpq_, mpq_, q.mpq_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->sub(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - mpq_sub(mpq_, mpq_, p->mpq_); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - knumber_error *e = new knumber_error(p); - delete this; - return e->neg(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::mul(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction q(p); - mpq_mul(mpq_, mpq_, q.mpq_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *q = new knumber_float(this); - delete this; - return q->mul(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - mpq_mul(mpq_, mpq_, p->mpq_); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(is_zero()) { - delete this; - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - return e; - } - - if(sign() < 0) { - delete this; - knumber_error *e = new knumber_error(p); - return e->neg(); - } else { - delete this; - knumber_error *e = new knumber_error(p); - return e; - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::div(knumber_base *rhs) { - - if(rhs->is_zero()) { - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_NEG_INFINITY); - } else { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } - } - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction f(p); - return div(&f); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->div(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - mpq_div(mpq_, mpq_, p->mpq_); - return this; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - - if(p->sign() > 0) { - delete this; - return new knumber_integer(0); - } else if(p->sign() < 0) { - delete this; - return new knumber_integer(0); - } - - knumber_error *e = new knumber_error(p); - delete this; - return e; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::mod(knumber_base *rhs) { - - if(rhs->is_zero()) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - // NOTE: we don't support modulus operations with non-integer operands - mpq_set_d(mpq_, 0); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::bitwise_and(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - // NOTE: we don't support bitwise operations with non-integer operands - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::bitwise_xor(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - // NOTE: we don't support bitwise operations with non-integer operands - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::bitwise_or(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - // NOTE: we don't support bitwise operations with non-integer operands - return new knumber_integer(0); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::bitwise_shift(knumber_base *rhs) { - - Q_UNUSED(rhs); - delete this; - // NOTE: we don't support bitwise operations with non-integer operands - return new knumber_error(knumber_error::ERROR_UNDEFINED); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::neg() { - mpq_neg(mpq_, mpq_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::abs() { - mpq_abs(mpq_, mpq_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::cmp() { - - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::sqrt() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - if(mpz_perfect_square_p(mpq_numref(mpq_)) && mpz_perfect_square_p(mpq_denref(mpq_))) { - mpz_t num; - mpz_t den; - mpz_init(num); - mpz_init(den); - mpq_get_num(num, mpq_); - mpq_get_den(den, mpq_); - mpz_sqrt(num, num); - mpz_sqrt(den, den); - mpq_set_num(mpq_, num); - mpq_set_den(mpq_, den); - mpq_canonicalize(mpq_); - mpz_clear(num); - mpz_clear(den); - return this; - } else { - knumber_float *f = new knumber_float(this); - delete this; - return f->sqrt(); - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::cbrt() { - - // TODO: figure out how to properly use mpq_numref/mpq_denref here - mpz_t num; - mpz_t den; - - mpz_init(num); - mpz_init(den); - - mpq_get_num(num, mpq_); - mpq_get_den(den, mpq_); - - if(mpz_root(num, num, 3) && mpz_root(den, den, 3)) { - mpq_set_num(mpq_, num); - mpq_set_den(mpq_, den); - mpq_canonicalize(mpq_); - mpz_clear(num); - mpz_clear(den); - return this; - } else { - mpz_clear(num); - mpz_clear(den); - knumber_float *f = new knumber_float(this); - delete this; - return f->cbrt(); - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::factorial() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - knumber_integer *i = new knumber_integer(this); - delete this; - return i->factorial(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::pow(knumber_base *rhs) { - - // TODO: figure out how to properly use mpq_numref/mpq_denref here - if(knumber_integer *const p = dynamic_cast(rhs)) { - - mpz_t num; - mpz_t den; - - mpz_init(num); - mpz_init(den); - - mpq_get_num(num, mpq_); - mpq_get_den(den, mpq_); - - mpz_pow_ui(num, num, mpz_get_ui(p->mpz_)); - mpz_pow_ui(den, den, mpz_get_ui(p->mpz_)); - mpq_set_num(mpq_, num); - mpq_set_den(mpq_, den); - mpq_canonicalize(mpq_); - mpz_clear(num); - mpz_clear(den); - - if(p->sign() < 0) { - return reciprocal(); - } else { - return this; - } - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - knumber_float *f = new knumber_float(this); - delete this; - return f->pow(rhs); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - - // ok, so if any part of the number is > 1,000,000, then we risk - // the pow function overflowing... so we'll just convert to float to be safe - // TODO: at some point, we should figure out exactly what the threashold is - // and if there is a better way to determine if the pow function will - // overflow. - if(mpz_cmpabs_ui(mpq_numref(mpq_), 1000000) > 0 || mpz_cmpabs_ui(mpq_denref(mpq_), 1000000) > 0 || mpz_cmpabs_ui(mpq_numref(p->mpq_), 1000000) > 0 || mpz_cmpabs_ui(mpq_denref(p->mpq_), 1000000) > 0) { - knumber_float *f = new knumber_float(this); - delete this; - return f->pow(rhs); - } - - mpz_t lhs_num; - mpz_t lhs_den; - mpz_t rhs_num; - mpz_t rhs_den; - - mpz_init(lhs_num); - mpz_init(lhs_den); - mpz_init(rhs_num); - mpz_init(rhs_den); - - mpq_get_num(lhs_num, mpq_); - mpq_get_den(lhs_den, mpq_); - mpq_get_num(rhs_num, p->mpq_); - mpq_get_den(rhs_den, p->mpq_); - - mpz_pow_ui(lhs_num, lhs_num, mpz_get_ui(rhs_num)); - mpz_pow_ui(lhs_den, lhs_den, mpz_get_ui(rhs_num)); - - if(mpz_sgn(lhs_num) < 0 && mpz_even_p(rhs_den)) { - mpz_clear(lhs_num); - mpz_clear(lhs_den); - mpz_clear(rhs_num); - mpz_clear(rhs_den); - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - if(mpz_sgn(lhs_den) < 0 && mpz_even_p(rhs_den)) { - mpz_clear(lhs_num); - mpz_clear(lhs_den); - mpz_clear(rhs_num); - mpz_clear(rhs_den); - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - const int n1 = mpz_root(lhs_num, lhs_num, mpz_get_ui(rhs_den)); - const int n2 = mpz_root(lhs_den, lhs_den, mpz_get_ui(rhs_den)); - - if(n1 && n2) { - - mpq_set_num(mpq_, lhs_num); - mpq_set_den(mpq_, lhs_den); - mpq_canonicalize(mpq_); - mpz_clear(lhs_num); - mpz_clear(lhs_den); - mpz_clear(rhs_num); - mpz_clear(rhs_den); - - if(p->sign() < 0) { - return reciprocal(); - } else { - return this; - } - } else { - mpz_clear(lhs_num); - mpz_clear(lhs_den); - mpz_clear(rhs_num); - mpz_clear(rhs_den); - knumber_float *f = new knumber_float(this); - delete this; - - return f->pow(rhs); - } - - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(p->sign() > 0) { - knumber_error *e = new knumber_error(knumber_error::ERROR_POS_INFINITY); - delete this; - return e; - } else if(p->sign() < 0) { - knumber_integer *n = new knumber_integer(0); - delete this; - return n; - } else { - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::sin() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->sin(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::floor() { - knumber_float *f = new knumber_float(this); - delete this; - return f->floor(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::ceil() { - knumber_float *f = new knumber_float(this); - delete this; - return f->ceil(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::cos() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->cos(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::tgamma() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->tgamma(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::tan() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->tan(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::asin() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->asin(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::acos() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->acos(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::atan() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->atan(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::sinh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->sinh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::cosh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->cosh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::tanh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->tanh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::asinh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->asinh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::acosh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->acosh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::atanh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->atanh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_fraction::compare(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction f(p); - return mpq_cmp(mpq_, f.mpq_); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float f(this); - return f.compare(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - return mpq_cmp(mpq_, p->mpq_); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - // NOTE: any number compared to NaN/Inf/-Inf always compares less - // at the moment - return -1; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -QString knumber_fraction::toString(int precision) const { - - - if(knumber_fraction::default_fractional_output) { - - // TODO: figure out how to properly use mpq_numref/mpq_denref here - - knumber_integer integer_part(this); - if(split_off_integer_for_fraction_output && !integer_part.is_zero()) { - - mpz_t num; - mpz_init(num); - mpq_get_num(num, mpq_); - - knumber_integer integer_part_1(this); - - mpz_mul(integer_part.mpz_, integer_part.mpz_, mpq_denref(mpq_)); - mpz_sub(num, num, integer_part.mpz_); - - if(mpz_sgn(num) < 0) { - mpz_neg(num, num); - } - - const size_t size = gmp_snprintf(NULL, 0, "%Zd %Zd/%Zd", integer_part_1.mpz_, num, mpq_denref(mpq_)) + 1; - KNUMBER_BUFFER(buf, size); - gmp_snprintf(&buf[0], size, "%Zd %Zd/%Zd", integer_part_1.mpz_, num, mpq_denref(mpq_)); - - mpz_clear(num); - - return QLatin1String(&buf[0]); - } else { - - mpz_t num; - mpz_init(num); - mpq_get_num(num, mpq_); - - const size_t size = gmp_snprintf(NULL, 0, "%Zd/%Zd", num, mpq_denref(mpq_)) + 1; - KNUMBER_BUFFER(buf, size); - gmp_snprintf(&buf[0], size, "%Zd/%Zd", num, mpq_denref(mpq_)); - - mpz_clear(num); - - return QLatin1String(&buf[0]); - } - } else { - return knumber_float(this).toString(precision); - } -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool knumber_fraction::is_zero() const { - return mpq_sgn(mpq_) == 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -int knumber_fraction::sign() const { - return mpq_sgn(mpq_); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::reciprocal() { - - mpq_inv(mpq_, mpq_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_integer *knumber_fraction::numerator() const { - - mpz_t num; - mpz_init(num); - mpq_get_num(num, mpq_); - knumber_integer *n = new knumber_integer(num); - mpz_clear(num); - return n; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_integer *knumber_fraction::denominator() const { - - mpz_t den; - mpz_init(den); - mpq_get_den(den, mpq_); - knumber_integer *n = new knumber_integer(den); - mpz_clear(den); - return n; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::log2() { - knumber_float *f = new knumber_float(this); - delete this; - return f->log2(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::log10() { - knumber_float *f = new knumber_float(this); - delete this; - return f->log10(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::ln() { - knumber_float *f = new knumber_float(this); - delete this; - return f->ln(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::exp2() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp2(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::exp10() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp10(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::exp() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -quint64 knumber_fraction::toUint64() const { - return knumber_integer(this).toUint64(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -qint64 knumber_fraction::toInt64() const { - return knumber_integer(this).toInt64(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_fraction::bin(knumber_base *rhs) { - Q_UNUSED(rhs); - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - -} - -} diff --git a/kcalc/knumber/knumber_fraction.h b/kcalc/knumber/knumber_fraction.h deleted file mode 100644 index fe6bd03f..00000000 --- a/kcalc/knumber/knumber_fraction.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_FRACTION_H_ -#define KNUMBER_FRACTION_H_ - -#include "knumber_base.h" - -class KNumber; - -namespace detail { - -class knumber_fraction : public knumber_base { - friend class ::KNumber; - friend class knumber_error; - friend class knumber_integer; - friend class knumber_float; - -public: - static bool default_fractional_input; - static bool default_fractional_output; - static bool split_off_integer_for_fraction_output; - -public: - static void set_default_fractional_input(bool value); - static void set_default_fractional_output(bool value); - static void set_split_off_integer_for_fraction_output(bool value); - -public: - explicit knumber_fraction(const QString &s); - knumber_fraction(qint64 num, quint64 den); - knumber_fraction(quint64 num, quint64 den); - explicit knumber_fraction(mpq_t mpq); - virtual ~knumber_fraction(); - -public: - virtual knumber_base *clone(); - -public: - virtual QString toString(int precision) const; - virtual quint64 toUint64() const; - virtual qint64 toInt64() const; - -public: - virtual bool is_integer() const; - virtual bool is_zero() const; - virtual int sign() const; - -public: - virtual knumber_base *add(knumber_base *rhs); - virtual knumber_base *sub(knumber_base *rhs); - virtual knumber_base *mul(knumber_base *rhs); - virtual knumber_base *div(knumber_base *rhs); - virtual knumber_base *mod(knumber_base *rhs); - -public: - virtual knumber_base *bitwise_and(knumber_base *rhs); - virtual knumber_base *bitwise_xor(knumber_base *rhs); - virtual knumber_base *bitwise_or(knumber_base *rhs); - virtual knumber_base *bitwise_shift(knumber_base *rhs); - -public: - virtual knumber_base *pow(knumber_base *rhs); - virtual knumber_base *neg(); - virtual knumber_base *cmp(); - virtual knumber_base *abs(); - virtual knumber_base *sqrt(); - virtual knumber_base *cbrt(); - virtual knumber_base *factorial(); - virtual knumber_base *reciprocal(); - virtual knumber_base *tgamma(); - -public: - virtual knumber_base *log2(); - virtual knumber_base *log10(); - virtual knumber_base *ln(); - virtual knumber_base *exp2(); - virtual knumber_base *floor(); - virtual knumber_base *ceil(); - virtual knumber_base *exp10(); - virtual knumber_base *exp(); - virtual knumber_base *bin(knumber_base *rhs); - -public: - virtual knumber_base *sin(); - virtual knumber_base *cos(); - virtual knumber_base *tan(); - virtual knumber_base *asin(); - virtual knumber_base *acos(); - virtual knumber_base *atan(); - virtual knumber_base *sinh(); - virtual knumber_base *cosh(); - virtual knumber_base *tanh(); - virtual knumber_base *asinh(); - virtual knumber_base *acosh(); - virtual knumber_base *atanh(); - -public: - virtual int compare(knumber_base *rhs); - -private: - knumber_integer *numerator() const; - knumber_integer *denominator() const; - -private: - // conversion constructors - explicit knumber_fraction(const knumber_integer *value); - explicit knumber_fraction(const knumber_fraction *value); -#if 0 - // TODO: this is omitted because there is no good way to - // implement it - knumber_fraction(const knumber_float *value); -#endif - explicit knumber_fraction(const knumber_error *value); - -private: - mpq_t mpq_; -}; - -} - -#endif diff --git a/kcalc/knumber/knumber_integer.cpp b/kcalc/knumber/knumber_integer.cpp deleted file mode 100644 index 8ce375b7..00000000 --- a/kcalc/knumber/knumber_integer.cpp +++ /dev/null @@ -1,887 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber_integer.h" -#include "knumber_float.h" -#include "knumber_fraction.h" -#include "knumber_error.h" -#include - -namespace detail { - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(const QString &s) { - mpz_init(mpz_); - mpz_set_str(mpz_, s.toAscii(), 10); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(qint32 value) { - mpz_init_set_si(mpz_, static_cast(value)); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(qint64 value) { - mpz_init(mpz_); -#if SIZEOF_SIGNED_LONG == 8 - mpz_set_si(mpz_, static_cast(value)); -#elif SIZEOF_SIGNED_LONG == 4 - mpz_set_si(mpz_, static_cast(value >> 32)); - mpz_mul_2exp(mpz_, mpz_, 32); - mpz_add_ui(mpz_, mpz_, static_cast(value)); -#else -#error "SIZEOF_SIGNED_LONG is a unhandled case" -#endif -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(quint32 value) { - mpz_init_set_ui(mpz_, static_cast(value)); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(quint64 value) { - mpz_init(mpz_); -#if SIZEOF_UNSIGNED_LONG == 8 - mpz_set_ui(mpz_, static_cast(value)); -#elif SIZEOF_UNSIGNED_LONG == 4 - mpz_set_ui(mpz_, static_cast(value >> 32)); - mpz_mul_2exp(mpz_, mpz_, 32); - mpz_add_ui(mpz_, mpz_, static_cast(value)); -#else -#error "SIZEOF_UNSIGNED_LONG is a unhandled case" -#endif -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(mpz_t mpz) { - mpz_init_set(mpz_, mpz); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(const knumber_integer *value) { - mpz_init_set(mpz_, value->mpz_); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(const knumber_float *value) { - mpz_init(mpz_); - mpz_set_f(mpz_, value->mpf_); -} - -//------------------------------------------------------------------------------ -// Name: knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::knumber_integer(const knumber_fraction *value) { - mpz_init(mpz_); - mpz_set_q(mpz_, value->mpq_); -} - -//------------------------------------------------------------------------------ -// Name: clone -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::clone() { - return new knumber_integer(this); -} - -//------------------------------------------------------------------------------ -// Name: ~knumber_integer -//------------------------------------------------------------------------------ -knumber_integer::~knumber_integer() { - mpz_clear(mpz_); -} - -//------------------------------------------------------------------------------ -// Name: add -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::add(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_add(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *const f = new knumber_float(this); - delete this; - return f->add(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *const q = new knumber_fraction(this); - delete this; - return q->add(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: sub -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::sub(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_sub(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->sub(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->sub(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - knumber_base *e = p->clone(); - delete this; - return e->neg(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: mul -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::mul(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_mul(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->mul(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->mul(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - - if(is_zero()) { - delete this; - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - return e->neg(); - } - - if(sign() < 0) { - delete this; - knumber_base *e = p->clone(); - return e->neg(); - } else { - delete this; - return p->clone(); - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: div -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::div(knumber_base *rhs) { - - if(rhs->is_zero()) { - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_NEG_INFINITY); - } else { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } - } - - if(knumber_integer *const p = dynamic_cast(rhs)) { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->div(p); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->div(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->div(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - - if(p->sign() > 0) { - delete this; - return new knumber_integer(0); - } else if(p->sign() < 0) { - delete this; - return new knumber_integer(0); - } - - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: mod -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::mod(knumber_base *rhs) { - - if(rhs->is_zero()) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_mod(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->mod(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->mod(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: bitwise_and -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::bitwise_and(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_and(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->bitwise_and(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *f = new knumber_fraction(this); - delete this; - return f->bitwise_and(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: bitwise_xor -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::bitwise_xor(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_xor(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->bitwise_xor(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *f = new knumber_fraction(this); - delete this; - return f->bitwise_xor(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: bitwise_or -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::bitwise_or(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_ior(mpz_, mpz_, p->mpz_); - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->bitwise_or(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *f = new knumber_fraction(this); - delete this; - return f->bitwise_or(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return p->clone(); - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: bitwise_shift -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::bitwise_shift(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - - const signed long int bit_count = mpz_get_si(p->mpz_); - - // TODO: left shift with high bit set is broken in - // non decimal modes :-/, always displays 0 - // interestingly, the bit is not "lost" - // we simply don't have a mechanism to display - // values in HEX/DEC/OCT mode which are greater than - // 64-bits - - if(bit_count > 0) { - // left shift - mpz_mul_2exp(mpz_, mpz_, bit_count); - } else if(bit_count < 0) { - // right shift - if(mpz_sgn(mpz_) < 0) { - mpz_fdiv_q_2exp(mpz_, mpz_, -bit_count); - } else { - mpz_tdiv_q_2exp(mpz_, mpz_, -bit_count); - } - } - return this; - } else if(knumber_float *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } else if(knumber_error *const p = dynamic_cast(rhs)) { - Q_UNUSED(p); - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: neg -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::neg() { - - mpz_neg(mpz_, mpz_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: cmp -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::cmp() { - -#if 0 - // unfortunately this breaks things pretty badly - // for non-decimal modes :-( - mpz_com(mpz_, mpz_); -#else - mpz_swap(mpz_, knumber_integer(~toUint64()).mpz_); -#endif - return this; -} - -//------------------------------------------------------------------------------ -// Name: abs -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::abs() { - - mpz_abs(mpz_, mpz_); - return this; -} - -//------------------------------------------------------------------------------ -// Name: sqrt -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::sqrt() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - if(mpz_perfect_square_p(mpz_)) { - mpz_sqrt(mpz_, mpz_); - return this; - } else { - knumber_float *f = new knumber_float(this); - delete this; - return f->sqrt(); - } -} - -//------------------------------------------------------------------------------ -// Name: cbrt -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::cbrt() { - - mpz_t x; - mpz_init_set(x, mpz_); - if(mpz_root(x, x, 3)) { - mpz_swap(mpz_, x); - mpz_clear(x); - return this; - } - - mpz_clear(x); - knumber_float *f = new knumber_float(this); - delete this; - return f->cbrt(); -} - -//------------------------------------------------------------------------------ -// Name: pow -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::pow(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - - if(is_zero() && p->is_even() && p->sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_POS_INFINITY); - } - - mpz_pow_ui(mpz_, mpz_, mpz_get_ui(p->mpz_)); - - if(p->sign() < 0) { - return reciprocal(); - } else { - return this; - } - } else if(knumber_float *const p = dynamic_cast(rhs)) { - knumber_float *f = new knumber_float(this); - delete this; - return f->pow(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - knumber_fraction *f = new knumber_fraction(this); - delete this; - return f->pow(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - if(p->sign() > 0) { - knumber_error *e = new knumber_error(knumber_error::ERROR_POS_INFINITY); - delete this; - return e; - } else if(p->sign() < 0) { - mpz_init_set_si(mpz_, 0); - return this; - } else { - knumber_error *e = new knumber_error(knumber_error::ERROR_UNDEFINED); - delete this; - return e; - } - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: sin -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::sin() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->sin(); -} - -//------------------------------------------------------------------------------ -// Name: cos -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::cos() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->cos(); -} - -//------------------------------------------------------------------------------ -// Name: tan -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::tan() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->tan(); -} - -//------------------------------------------------------------------------------ -// Name: asin -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::asin() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->asin(); -} - -//------------------------------------------------------------------------------ -// Name: acos -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::acos() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->acos(); -} - -//------------------------------------------------------------------------------ -// Name: atan -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::atan() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->atan(); -} - -//------------------------------------------------------------------------------ -// Name: tgamma -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::tgamma() { - - knumber_float *f = new knumber_float(this); - delete this; - return f->tgamma(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::sinh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->sinh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::cosh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->cosh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::tanh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->tanh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::asinh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->asinh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::acosh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->acosh(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::atanh() { - knumber_float *f = new knumber_float(this); - delete this; - return f->atanh(); -} - -//------------------------------------------------------------------------------ -// Name: factorial -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::factorial() { - - if(sign() < 0) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - mpz_fac_ui(mpz_, mpz_get_ui(mpz_)); - return this; -} - -//------------------------------------------------------------------------------ -// Name: compare -//------------------------------------------------------------------------------ -int knumber_integer::compare(knumber_base *rhs) { - - if(knumber_integer *const p = dynamic_cast(rhs)) { - return mpz_cmp(mpz_, p->mpz_); - } else if(knumber_float *const p = dynamic_cast(rhs)) { - return knumber_float(this).compare(p); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - return knumber_fraction(this).compare(p); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - // NOTE: any number compared to NaN/Inf/-Inf always compares less - // at the moment - return -1; - } - - Q_ASSERT(0); - return 0; -} - -//------------------------------------------------------------------------------ -// Name: toString -//------------------------------------------------------------------------------ -QString knumber_integer::toString(int precision) const { - - Q_UNUSED(precision); - - const size_t size = gmp_snprintf(NULL, 0, "%Zd", mpz_) + 1; - KNUMBER_BUFFER(buf, size); - gmp_snprintf(&buf[0], size, "%Zd", mpz_); - return QLatin1String(&buf[0]); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -quint64 knumber_integer::toUint64() const { - // libgmp doesn't have unsigned long long conversion - // so convert to string and then to unsigned long long - const QString tmpstring = toString(-1); - - bool ok; - quint64 value; - - if (sign() < 0) { - const qint64 signedvalue = tmpstring.toLongLong(&ok, 10); - value = static_cast(signedvalue); - } else { - value = tmpstring.toULongLong(&ok, 10); - } - - if (!ok) { - // TODO: what to do if error? - value = 0; - } - return value; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -qint64 knumber_integer::toInt64() const { - // libgmp doesn't have long long conversion - // so convert to string and then to long long - const QString tmpstring = toString(-1); - - bool ok; - qint64 value = tmpstring.toLongLong(&ok, 10); - - if (!ok) { - // TODO: what to do if error? - value = 0; - } - - return value; -} - -//------------------------------------------------------------------------------ -// Name: is_integer -//------------------------------------------------------------------------------ -bool knumber_integer::is_integer() const { - return true; -} - -//------------------------------------------------------------------------------ -// Name: is_zero -//------------------------------------------------------------------------------ -bool knumber_integer::is_zero() const { - return mpz_sgn(mpz_) == 0; -} - -//------------------------------------------------------------------------------ -// Name: sign -//------------------------------------------------------------------------------ -int knumber_integer::sign() const { - return mpz_sgn(mpz_); -} - -//------------------------------------------------------------------------------ -// Name: is_even -//------------------------------------------------------------------------------ -bool knumber_integer::is_even() const { - return mpz_even_p(mpz_); -} - -//------------------------------------------------------------------------------ -// Name: is_odd -//------------------------------------------------------------------------------ -bool knumber_integer::is_odd() const { - return mpz_odd_p(mpz_); -} - -//------------------------------------------------------------------------------ -// Name: reciprocal -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::reciprocal() { - knumber_fraction *q = new knumber_fraction(this); - delete this; - return q->reciprocal(); -} - -//------------------------------------------------------------------------------ -// Name: log2 -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::log2() { - knumber_float *f = new knumber_float(this); - delete this; - return f->log2(); -} - -//------------------------------------------------------------------------------ -// Name: floor -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::floor() { - // should have no effect on the value - return this; -} - -//------------------------------------------------------------------------------ -// Name: ceil -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::ceil() { - // should have no effect on the value - return this; -} - -//------------------------------------------------------------------------------ -// Name: log10 -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::log10() { - knumber_float *f = new knumber_float(this); - delete this; - return f->log10(); -} - -//------------------------------------------------------------------------------ -// Name: ln -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::ln() { - knumber_float *f = new knumber_float(this); - delete this; - return f->ln(); -} - -//------------------------------------------------------------------------------ -// Name: exp2 -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::exp2() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp2(); -} - -//------------------------------------------------------------------------------ -// Name: exp10 -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::exp10() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp10(); -} - -//------------------------------------------------------------------------------ -// Name: exp -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::exp() { - knumber_float *f = new knumber_float(this); - delete this; - return f->exp(); -} - -//------------------------------------------------------------------------------ -// Name: bin -//------------------------------------------------------------------------------ -knumber_base *knumber_integer::bin(knumber_base *rhs) { - - - if(knumber_integer *const p = dynamic_cast(rhs)) { - mpz_bin_ui(mpz_, mpz_, mpz_get_ui(p->mpz_)); - return this; - - } else if(knumber_float *const p = dynamic_cast(rhs)) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } else if(knumber_fraction *const p = dynamic_cast(rhs)) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } else if(knumber_error *const p = dynamic_cast(rhs)) { - delete this; - return new knumber_error(knumber_error::ERROR_UNDEFINED); - } - - Q_ASSERT(0); - return 0; -} - -} diff --git a/kcalc/knumber/knumber_integer.h b/kcalc/knumber/knumber_integer.h deleted file mode 100644 index 636af3d4..00000000 --- a/kcalc/knumber/knumber_integer.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_INTEGER_H_ -#define KNUMBER_INTEGER_H_ - -#include "knumber_base.h" - -class KNumber; - -namespace detail { - -class knumber_integer : public knumber_base { - friend class ::KNumber; - friend class knumber_error; - friend class knumber_fraction; - friend class knumber_float; - -public: - explicit knumber_integer(const QString &s); - explicit knumber_integer(qint32 value); - explicit knumber_integer(qint64 value); - explicit knumber_integer(quint32 value); - explicit knumber_integer(quint64 value); - explicit knumber_integer(mpz_t mpz); - virtual ~knumber_integer(); - -public: - virtual knumber_base *clone(); - -public: - virtual QString toString(int precision) const; - virtual quint64 toUint64() const; - virtual qint64 toInt64() const; - -public: - virtual bool is_even() const; - virtual bool is_odd() const; - virtual bool is_integer() const; - virtual bool is_zero() const; - virtual int sign() const; - -public: - virtual knumber_base *add(knumber_base *rhs); - virtual knumber_base *sub(knumber_base *rhs); - virtual knumber_base *mul(knumber_base *rhs); - virtual knumber_base *div(knumber_base *rhs); - virtual knumber_base *mod(knumber_base *rhs); - -public: - virtual knumber_base *bitwise_and(knumber_base *rhs); - virtual knumber_base *bitwise_xor(knumber_base *rhs); - virtual knumber_base *bitwise_or(knumber_base *rhs); - virtual knumber_base *bitwise_shift(knumber_base *rhs); - -public: - virtual knumber_base *pow(knumber_base *rhs); - virtual knumber_base *neg(); - virtual knumber_base *cmp(); - virtual knumber_base *abs(); - virtual knumber_base *sqrt(); - virtual knumber_base *cbrt(); - virtual knumber_base *factorial(); - virtual knumber_base *reciprocal(); - -public: - virtual knumber_base *log2(); - virtual knumber_base *log10(); - virtual knumber_base *ln(); - virtual knumber_base *exp2(); - virtual knumber_base *floor(); - virtual knumber_base *ceil(); - virtual knumber_base *exp10(); - virtual knumber_base *exp(); - virtual knumber_base *bin(knumber_base *rhs); - -public: - virtual knumber_base *sin(); - virtual knumber_base *cos(); - virtual knumber_base *tan(); - virtual knumber_base *asin(); - virtual knumber_base *acos(); - virtual knumber_base *atan(); - virtual knumber_base *sinh(); - virtual knumber_base *cosh(); - virtual knumber_base *tanh(); - virtual knumber_base *asinh(); - virtual knumber_base *acosh(); - virtual knumber_base *atanh(); - virtual knumber_base *tgamma(); - -public: - virtual int compare(knumber_base *rhs); - -private: - // conversion constructors - explicit knumber_integer(const knumber_integer *value); - explicit knumber_integer(const knumber_fraction *value); - explicit knumber_integer(const knumber_float *value); - explicit knumber_integer(const knumber_error *value); - -private: - mpz_t mpz_; -}; - -} - -#endif diff --git a/kcalc/knumber/knumber_operators.cpp b/kcalc/knumber/knumber_operators.cpp deleted file mode 100644 index a1383420..00000000 --- a/kcalc/knumber/knumber_operators.cpp +++ /dev/null @@ -1,296 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#include -#include "knumber_operators.h" -#include "knumber.h" -#include "knumber_base.h" -#include - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator+(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x += rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator-(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x -= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator*(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x *= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator/(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x /= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator%(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x %= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator&(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x &= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator|(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x |= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator^(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x ^= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator>>(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x >>= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber operator<<(const KNumber &lhs, const KNumber &rhs) { - KNumber x(lhs); - x <<= rhs; - return x; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber abs(const KNumber &x) { - return x.abs(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber cbrt(const KNumber &x) { - return x.cbrt(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber sqrt(const KNumber &x) { - return x.sqrt(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber sin(const KNumber &x) { - return x.sin(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber cos(const KNumber &x) { - return x.cos(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber tan(const KNumber &x) { - return x.tan(); -} - - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber asin(const KNumber &x) { - return x.asin(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber acos(const KNumber &x) { - return x.acos(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber tgamma(const KNumber &x) { - return x.tgamma(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber atan(const KNumber &x) { - return x.atan(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber pow(const KNumber &x, const KNumber &y) { - return x.pow(y); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber factorial(const KNumber &x) { - return x.factorial(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber log2(const KNumber &x) { - return x.log2(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber floor(const KNumber &x) { - return x.floor(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber ceil(const KNumber &x) { - return x.ceil(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber log10(const KNumber &x) { - return x.log10(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber ln(const KNumber &x) { - return x.ln(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber exp2(const KNumber &x) { - return x.exp2(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber exp10(const KNumber &x) { - return x.exp10(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -KNumber exp(const KNumber &x) { - return x.exp(); -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator==(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) == 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator!=(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) != 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator>=(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) >= 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator<=(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) <= 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator>(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) > 0; -} - -//------------------------------------------------------------------------------ -// Name: -//------------------------------------------------------------------------------ -bool operator<(const KNumber &lhs, const KNumber &rhs) { - return lhs.value_->compare(rhs.value_) < 0; -} diff --git a/kcalc/knumber/knumber_operators.h b/kcalc/knumber/knumber_operators.h deleted file mode 100644 index b6912ee4..00000000 --- a/kcalc/knumber/knumber_operators.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KNUMBER_OPERATORS_H_ -#define KNUMBER_OPERATORS_H_ - -class KNumber; - -bool operator==(const KNumber &lhs, const KNumber &rhs); -bool operator!=(const KNumber &lhs, const KNumber &rhs); -bool operator>=(const KNumber &lhs, const KNumber &rhs); -bool operator<=(const KNumber &lhs, const KNumber &rhs); -bool operator>(const KNumber &lhs, const KNumber &rhs); -bool operator<(const KNumber &lhs, const KNumber &rhs); - -KNumber operator+(const KNumber &lhs, const KNumber &rhs); -KNumber operator-(const KNumber &lhs, const KNumber &rhs); -KNumber operator*(const KNumber &lhs, const KNumber &rhs); -KNumber operator/(const KNumber &lhs, const KNumber &rhs); -KNumber operator%(const KNumber &lhs, const KNumber &rhs); - -KNumber operator&(const KNumber &lhs, const KNumber &rhs); -KNumber operator|(const KNumber &lhs, const KNumber &rhs); -KNumber operator^(const KNumber &lhs, const KNumber &rhs); -KNumber operator>>(const KNumber &lhs, const KNumber &rhs); -KNumber operator<<(const KNumber &lhs, const KNumber &rhs); - -KNumber abs(const KNumber &x); -KNumber cbrt(const KNumber &x); -KNumber sqrt(const KNumber &x); -KNumber pow(const KNumber &x, const KNumber &y); - -KNumber sin(const KNumber &x); -KNumber cos(const KNumber &x); -KNumber tan(const KNumber &x); -KNumber asin(const KNumber &x); -KNumber tgamma(const KNumber &x); -KNumber acos(const KNumber &x); -KNumber atan(const KNumber &x); - -KNumber factorial(const KNumber &x); - -KNumber log2(const KNumber &x); -KNumber log10(const KNumber &x); -KNumber ceil(const KNumber &x); -KNumber floor(const KNumber &x); -KNumber ln(const KNumber &x); -KNumber exp2(const KNumber &x); -KNumber exp10(const KNumber &x); -KNumber exp(const KNumber &x); - -#endif diff --git a/kcalc/knumber/tests/CMakeLists.txt b/kcalc/knumber/tests/CMakeLists.txt deleted file mode 100644 index 3f46f31c..00000000 --- a/kcalc/knumber/tests/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -include_directories( ${CMAKE_SOURCE_DIR}/knumber ) - -set(knumbertest_SRCS knumbertest.cpp ${libknumber_la_SRCS}) - -kde4_add_test(knumber-KNumber ${knumbertest_SRCS}) - -target_link_libraries(knumber-KNumber KDE4::kdecore ${GMP_LIBRARIES}) diff --git a/kcalc/knumber/tests/knumbertest.cpp b/kcalc/knumber/tests/knumbertest.cpp deleted file mode 100644 index 4ecacb8b..00000000 --- a/kcalc/knumber/tests/knumbertest.cpp +++ /dev/null @@ -1,851 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 2003 - 2005 Klaus Niederkrueger - kniederk@math.uni-koeln.de - -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, see . -*/ - -#include "knumber.h" -#include -#include -#include -#include - -namespace { -const int precision = 12; - -QString numtypeToString(int arg) { - switch (arg) { - case 0: - return QLatin1String("Special"); - case 1: - return QLatin1String("Integer"); - case 3: - return QLatin1String("Fraction"); - case 2: - return QLatin1String("Float"); - default: - return QLatin1String("Unknown:") + QString::number(arg); - } -} - -void checkResult(const QString &string, const KNumber &result, const QString &desired_string, int desired) { - - std::cout - << "Testing result of: " - << qPrintable(string) - << " should give " - << qPrintable(desired_string) - << " and gives " - << qPrintable(result.toQString(precision)) - << " ...\n"; - - std::cout - << "The type of the result should be " - << qPrintable(numtypeToString(desired)) - << " and gives " - << qPrintable(numtypeToString(result.type())) - << " ... "; - - if (result.type() == desired && result.toQString(precision) == desired_string) { - std::cout << "OK\n"; - return; - } - - std::cout << "Failed\n"; - exit(1); -} - -void checkTruth(const QString &string, bool computation, bool desired_result) { - - std::cout - << "Testing truth of: " - << qPrintable(string) - << " should be " - << desired_result - << " and is " - << computation - << " ... "; - - if (computation == desired_result) { - std::cout << "OK\n"; - return; - } - - std::cout << "Failed\n"; - exit(1); -} - -void checkType(const QString &string, int test_arg, int desired) { - - std::cout - << "Testing type of: " - << qPrintable(string) - << " should give " - << qPrintable(numtypeToString(desired)) - << " and gives " - << qPrintable(numtypeToString(test_arg)) - << " ..."; - - if (test_arg == desired) { - std::cout << "OK\n"; - return; - } - - std::cout << "Failed\n"; - exit(1); -} - -void testingCompare() { - - std::cout << "\n\n"; - std::cout << "Testing Compare:\n"; - std::cout << "----------------\n"; - - checkTruth("KNumber(5) == KNumber(2)", KNumber(5) == KNumber(2), false); - checkTruth("KNumber(5) > KNumber(2)", KNumber(5) > KNumber(2), true); - checkTruth("KNumber(5) < KNumber(2)", KNumber(5) < KNumber(2), false); - checkTruth("KNumber(5) < KNumber(0)", KNumber(5) < KNumber(0), false); - checkTruth("KNumber(-5) < KNumber(0)", KNumber(-5) < KNumber(0), true); - checkTruth("KNumber(5) >= KNumber(2)", KNumber(5) >= KNumber(2), true); - checkTruth("KNumber(5) <= KNumber(2)", KNumber(5) <= KNumber(2), false); - checkTruth("KNumber(5) != KNumber(2)", KNumber(5) != KNumber(2), true); - - checkTruth("KNumber(2) == KNumber(2)", KNumber(2) == KNumber(2), true); - checkTruth("KNumber(2) > KNumber(2)", KNumber(2) > KNumber(2), false); - checkTruth("KNumber(2) < KNumber(2)", KNumber(2) < KNumber(2), false); - checkTruth("KNumber(2) >= KNumber(2)", KNumber(2) >= KNumber(2), true); - checkTruth("KNumber(2) <= KNumber(2)", KNumber(2) <= KNumber(2), true); - checkTruth("KNumber(2) != KNumber(2)", KNumber(2) != KNumber(2), false); - - checkTruth("KNumber(5) == KNumber(\"1/2\")", KNumber(5) == KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(5) > KNumber(\"1/2\")", KNumber(5) > KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(5) < KNumber(\"1/2\")", KNumber(5) < KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(5) >= KNumber(\"1/2\")", KNumber(5) >= KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(5) <= KNumber(\"1/2\")", KNumber(5) <= KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(5) != KNumber(\"1/2\")", KNumber(5) != KNumber(QLatin1String("1/2")), true); - - checkTruth("KNumber(\"1/2\") == KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) == KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(\"1/2\") > KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) > KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(\"1/2\") < KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) < KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(\"1/2\") >= KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) >= KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(\"1/2\") <= KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) <= KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(\"1/2\") != KNumber(\"1/2\")", KNumber(QLatin1String("1/2")) != KNumber(QLatin1String("1/2")), false); - - checkTruth("KNumber(\"3/2\") == KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) == KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(\"3/2\") > KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) > KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(\"3/2\") < KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) < KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(\"3/2\") >= KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) >= KNumber(QLatin1String("1/2")), true); - checkTruth("KNumber(\"3/2\") <= KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) <= KNumber(QLatin1String("1/2")), false); - checkTruth("KNumber(\"3/2\") != KNumber(\"1/2\")", KNumber(QLatin1String("3/2")) != KNumber(QLatin1String("1/2")), true); - - checkTruth("KNumber(3.2) != KNumber(3)", KNumber(3.2) != KNumber(3), true); - checkTruth("KNumber(3.2) > KNumber(3)", KNumber(3.2) > KNumber(3), true); - checkTruth("KNumber(3.2) < KNumber(3)", KNumber(3.2) < KNumber(3), false); - - checkTruth("KNumber(3.2) < KNumber(\"3/5\")", KNumber(3.2) < KNumber(QLatin1String("3/5")), false); -} - - -void testingAdditions() { - - std::cout << "\n\n"; - std::cout << "Testing additions:\n"; - std::cout << "------------------\n"; - - checkResult("KNumber(5) + KNumber(2)", KNumber(5) + KNumber(2), QLatin1String("7"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) + KNumber(\"2/3\")", KNumber(5) + KNumber(QLatin1String("2/3")), QLatin1String("17/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(5) + KNumber(\"2.3\")", KNumber(5) + KNumber(QLatin1String("2.3")), QLatin1String("7.3"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(\"5/3\") + KNumber(2)", KNumber(QLatin1String("5/3")) + KNumber(2), QLatin1String("11/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") + KNumber(\"2/3\")", KNumber(QLatin1String("5/3")) + KNumber(QLatin1String("2/3")), QLatin1String("7/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") + KNumber(\"1/3\")", KNumber(QLatin1String("5/3")) + KNumber(QLatin1String("1/3")), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/3\") + KNumber(\"-26/3\")", KNumber(QLatin1String("5/3")) + KNumber(QLatin1String("-26/3")), QLatin1String("-7"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/2\") + KNumber(2.3)", KNumber(QLatin1String("5/2")) + KNumber(2.3), QLatin1String("4.8"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(5.3) + KNumber(2)", KNumber(5.3) + KNumber(2), QLatin1String("7.3"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) + KNumber(\"2/4\")", KNumber(5.3) + KNumber(QLatin1String("2/4")), QLatin1String("5.8"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) + KNumber(2.3)", KNumber(5.3) + KNumber(2.3), QLatin1String("7.6"), KNumber::TYPE_FLOAT); -} - -void testingSubtractions() { - - std::cout << "\n\n"; - std::cout << "Testing subtractions:\n"; - std::cout << "---------------------\n"; - - checkResult("KNumber(5) - KNumber(2)", KNumber(5) - KNumber(2), QLatin1String("3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) - KNumber(\"2/3\")", KNumber(5) - KNumber(QLatin1String("2/3")), QLatin1String("13/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(5) - KNumber(2.3)", KNumber(5) - KNumber(2.3), QLatin1String("2.7"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(\"5/3\") - KNumber(2)", KNumber(QLatin1String("5/3")) - KNumber(2), QLatin1String("-1/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") - KNumber(\"1/3\")", KNumber(QLatin1String("5/3")) - KNumber(QLatin1String("1/3")), QLatin1String("4/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") - KNumber(\"2/3\")", KNumber(QLatin1String("5/3")) - KNumber(QLatin1String("2/3")), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5/3\") - KNumber(\"4/3\")", KNumber(QLatin1String("-5/3")) - KNumber(QLatin1String("4/3")), QLatin1String("-3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/4\") - KNumber(2.2)", KNumber(QLatin1String("5/4")) - KNumber(2.2), QLatin1String("-0.95"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(5.3) - KNumber(2)", KNumber(5.3) - KNumber(2), QLatin1String("3.3"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) - KNumber(\"3/4\")", KNumber(5.3) - KNumber(QLatin1String("3/4")), QLatin1String("4.55"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) - KNumber(2.3)", KNumber(5.3) - KNumber(2.3), QLatin1String("3"), KNumber::TYPE_INTEGER); -} - -void testingSpecial() { - - std::cout << "\n\n"; - std::cout << "Testing special functions:\n"; - std::cout << "--------------------------\n"; - - checkResult("log10(KNumber(5))", log10(KNumber(5)), QLatin1String("0.698970004336"), KNumber::TYPE_FLOAT); - checkResult("log10(pow(KNumber(10), KNumber(308)))", log10(pow(KNumber(10), KNumber(308))), QLatin1String("308"), KNumber::TYPE_INTEGER); - - // TODO: enable this check once MPFR is commonly enabled - // checkResult("log10(pow(KNumber(10), KNumber(309)))", log10(pow(KNumber(10), KNumber(309))), QLatin1String("309"), KNumber::TYPE_INTEGER); - - checkResult("exp(KNumber(4.34))", exp(KNumber(4.34)), QLatin1String("76.7075393383"), KNumber::TYPE_FLOAT); -} - -void testingTrig() { - - std::cout << "\n\n"; - std::cout << "Testing trig functions:\n"; - std::cout << "-----------------------\n"; - - checkResult("sin(KNumber(5))", sin(KNumber(5)), QLatin1String("-0.958924274663"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(5))", cos(KNumber(5)), QLatin1String("0.283662185463"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(5))", tan(KNumber(5)), QLatin1String("-3.38051500625"), KNumber::TYPE_FLOAT); - checkResult("sin(KNumber(-5))", sin(KNumber(-5)), QLatin1String("0.958924274663"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(-5))", cos(KNumber(-5)), QLatin1String("0.283662185463"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(-5))", tan(KNumber(-5)), QLatin1String("3.38051500625"), KNumber::TYPE_FLOAT); - - checkResult("sin(KNumber(\"5/2\"))", sin(KNumber(QLatin1String("5/2"))), QLatin1String("0.598472144104"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(\"5/2\"))", cos(KNumber(QLatin1String("5/2"))), QLatin1String("-0.801143615547"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(\"5/2\"))", tan(KNumber(QLatin1String("5/2"))), QLatin1String("-0.747022297239"), KNumber::TYPE_FLOAT); - checkResult("sin(KNumber(\"-5/2\"))", sin(KNumber(QLatin1String("-5/2"))), QLatin1String("-0.598472144104"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(\"-5/2\"))", cos(KNumber(QLatin1String("-5/2"))), QLatin1String("-0.801143615547"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(\"-5/2\"))", tan(KNumber(QLatin1String("-5/2"))), QLatin1String("0.747022297239"), KNumber::TYPE_FLOAT); - - checkResult("sin(KNumber(5.3))", sin(KNumber(5.3)), QLatin1String("-0.832267442224"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(5.3))", cos(KNumber(5.3)), QLatin1String("0.554374336179"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(5.3))", tan(KNumber(5.3)), QLatin1String("-1.50127339581"), KNumber::TYPE_FLOAT); - checkResult("sin(KNumber(-5.3))", sin(KNumber(-5.3)), QLatin1String("0.832267442224"), KNumber::TYPE_FLOAT); - checkResult("cos(KNumber(-5.3))", cos(KNumber(-5.3)), QLatin1String("0.554374336179"), KNumber::TYPE_FLOAT); - checkResult("tan(KNumber(-5.3))", tan(KNumber(-5.3)), QLatin1String("1.50127339581"), KNumber::TYPE_FLOAT); - - checkResult("asin(KNumber(5))", asin(KNumber(5)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(5))", acos(KNumber(5)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(5))", atan(KNumber(5)), QLatin1String("1.37340076695"), KNumber::TYPE_FLOAT); - checkResult("asin(KNumber(-5))", asin(KNumber(-5)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(-5))", acos(KNumber(-5)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(-5))", atan(KNumber(-5)), QLatin1String("-1.37340076695"), KNumber::TYPE_FLOAT); - - checkResult("asin(KNumber(\"5/2\"))", asin(KNumber(QLatin1String("5/2"))), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(\"5/2\"))", acos(KNumber(QLatin1String("5/2"))), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(\"5/2\"))", atan(KNumber(QLatin1String("5/2"))), QLatin1String("1.19028994968"), KNumber::TYPE_FLOAT); - checkResult("asin(KNumber(\"-5/2\"))", asin(KNumber(QLatin1String("-5/2"))), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(\"-5/2\"))", acos(KNumber(QLatin1String("-5/2"))), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(\"-5/2\"))", atan(KNumber(QLatin1String("-5/2"))), QLatin1String("-1.19028994968"), KNumber::TYPE_FLOAT); - - checkResult("asin(KNumber(5.3))", asin(KNumber(5.3)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(5.3))", acos(KNumber(5.3)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(5.3))", atan(KNumber(5.3)), QLatin1String("1.38430942513"), KNumber::TYPE_FLOAT); - checkResult("asin(KNumber(-5.3))", asin(KNumber(-5.3)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("acos(KNumber(-5.3))", acos(KNumber(-5.3)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("atan(KNumber(-5.3))", atan(KNumber(-5.3)), QLatin1String("-1.38430942513"), KNumber::TYPE_FLOAT); - - - checkResult("asin(KNumber(\"2/5\"))", asin(KNumber(QLatin1String("2/5"))), QLatin1String("0.411516846067"), KNumber::TYPE_FLOAT); - checkResult("acos(KNumber(\"2/5\"))", acos(KNumber(QLatin1String("2/5"))), QLatin1String("1.15927948073"), KNumber::TYPE_FLOAT); - checkResult("atan(KNumber(\"2/5\"))", atan(KNumber(QLatin1String("2/5"))), QLatin1String("0.380506377112"), KNumber::TYPE_FLOAT); - checkResult("asin(KNumber(\"-2/5\"))", asin(KNumber(QLatin1String("-2/5"))), QLatin1String("-0.411516846067"), KNumber::TYPE_FLOAT); - checkResult("acos(KNumber(\"-2/5\"))", acos(KNumber(QLatin1String("-2/5"))), QLatin1String("1.98231317286"), KNumber::TYPE_FLOAT); - checkResult("atan(KNumber(\"-2/5\"))", atan(KNumber(QLatin1String("-2/5"))), QLatin1String("-0.380506377112"), KNumber::TYPE_FLOAT); - - checkResult("asin(KNumber(0.3))", asin(KNumber(0.3)), QLatin1String("0.304692654015"), KNumber::TYPE_FLOAT); - checkResult("acos(KNumber(0.3))", acos(KNumber(0.3)), QLatin1String("1.26610367278"), KNumber::TYPE_FLOAT); - checkResult("atan(KNumber(0.3))", atan(KNumber(0.3)), QLatin1String("0.291456794478"), KNumber::TYPE_FLOAT); - checkResult("asin(KNumber(-0.3))", asin(KNumber(-0.3)), QLatin1String("-0.304692654015"), KNumber::TYPE_FLOAT); - checkResult("acos(KNumber(-0.3))", acos(KNumber(-0.3)), QLatin1String("1.87548898081"), KNumber::TYPE_FLOAT); - checkResult("atan(KNumber(-0.3))", atan(KNumber(-0.3)), QLatin1String("-0.291456794478"), KNumber::TYPE_FLOAT); -} - - -void testingMultiplications() { - - std::cout << "\n\n"; - std::cout << "Testing multiplications:\n"; - std::cout << "------------------------\n"; - - checkResult("KNumber(5) * KNumber(2)", KNumber(5) * KNumber(2), QLatin1String("10"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) * KNumber(\"2/3\")", KNumber(5) * KNumber(QLatin1String("2/3")), QLatin1String("10/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(5) * KNumber(\"2/5\")", KNumber(5) * KNumber(QLatin1String("2/5")), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) * KNumber(2.3)", KNumber(5) * KNumber(2.3), QLatin1String("11.5"), KNumber::TYPE_FLOAT); - checkResult("KNumber(0) * KNumber(\"2/5\")", KNumber(0) * KNumber(QLatin1String("2/5")), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(0) * KNumber(2.3)", KNumber(0) * KNumber(2.3), QLatin1String("0"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(\"5/3\") * KNumber(2)", KNumber(QLatin1String("5/3")) * KNumber(2), QLatin1String("10/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") * KNumber(0)", KNumber(QLatin1String("5/3")) * KNumber(0), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/3\") * KNumber(\"2/3\")", KNumber(QLatin1String("5/3")) * KNumber(QLatin1String("2/3")), QLatin1String("10/9"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"25/6\") * KNumber(\"12/5\")", KNumber(QLatin1String("25/6")) * KNumber(QLatin1String("12/5")), QLatin1String("10"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/2\") * KNumber(2.3)", KNumber(QLatin1String("5/2")) * KNumber(2.3), QLatin1String("5.75"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(5.3) * KNumber(2)", KNumber(5.3) * KNumber(2), QLatin1String("10.6"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) * KNumber(0)", KNumber(5.3) * KNumber(0), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5.3) * KNumber(\"1/2\")", KNumber(5.3) * KNumber(QLatin1String("1/2")), QLatin1String("2.65"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) * KNumber(2.3)", KNumber(5.3) * KNumber(2.3), QLatin1String("12.19"), KNumber::TYPE_FLOAT); -} - -void testingDivisions() { - - std::cout << "\n\n"; - std::cout << "Testing divisions:\n"; - std::cout << "------------------\n"; - - checkResult("KNumber(5) / KNumber(2)", KNumber(5) / KNumber(2), QLatin1String("5/2"), KNumber::TYPE_FRACTION); - checkResult("KNumber(122) / KNumber(2)", KNumber(122) / KNumber(2), QLatin1String("61"), KNumber::TYPE_INTEGER); - checkResult("KNumber(12) / KNumber(0)", KNumber(12) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-12) / KNumber(0)", KNumber(-12) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(5) / KNumber(\"2/3\")", KNumber(5) / KNumber(QLatin1String("2/3")), QLatin1String("15/2"), KNumber::TYPE_FRACTION); - checkResult("KNumber(6) / KNumber(\"2/3\")", KNumber(6) / KNumber(QLatin1String("2/3")), QLatin1String("9"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) / KNumber(2.5)", KNumber(5) / KNumber(2.5), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) / KNumber(0.0)", KNumber(5) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) / KNumber(0.0)", KNumber(-5) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("KNumber(\"5/3\") / KNumber(2)", KNumber(QLatin1String("5/3")) / KNumber(2), QLatin1String("5/6"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") / KNumber(0)", KNumber(QLatin1String("5/3")) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") / KNumber(0)", KNumber(QLatin1String("-5/3")) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"5/3\") / KNumber(\"2/3\")", KNumber(QLatin1String("5/3")) / KNumber(QLatin1String("2/3")), QLatin1String("5/2"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"49/3\") / KNumber(\"7/9\")", KNumber(QLatin1String("49/3")) / KNumber(QLatin1String("7/9")), QLatin1String("21"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/2\") / KNumber(2.5)", KNumber(QLatin1String("5/2")) / KNumber(2.5), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/2\") / KNumber(0.0)", KNumber(QLatin1String("5/2")) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/2\") / KNumber(0.0)", KNumber(QLatin1String("-5/2")) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("KNumber(5.3) / KNumber(2)", KNumber(5.3) / KNumber(2), QLatin1String("2.65"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) / KNumber(0)", KNumber(5.3) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.3) / KNumber(0)", KNumber(-5.3) / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(5.3) / KNumber(\"2/3\")", KNumber(5.3) / KNumber(QLatin1String("2/3")), QLatin1String("7.95"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.5) / KNumber(2.5)", KNumber(5.5) / KNumber(2.5), QLatin1String("2.2"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.5) / KNumber(0.0)", KNumber(5.5) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.5) / KNumber(0.0)", KNumber(-5.5) / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); -} - -void testingModulus() { - - std::cout << "\n\n"; - std::cout << "Testing modulus:\n"; - std::cout << "----------------\n"; - - checkResult("KNumber(23) % KNumber(4)", KNumber(23) % KNumber(4), QLatin1String("3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(12) % KNumber(-5)", KNumber(12) % KNumber(-5), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-12) % KNumber(5)", KNumber(-12) % KNumber(5), QLatin1String("3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(12) % KNumber(0)", KNumber(-12) % KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-12) % KNumber(0)", KNumber(-12) % KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - - #warning test for other types -} - -void testingAndOr() { - - std::cout << "\n\n"; - std::cout << "Testing And/Or:\n"; - std::cout << "---------------\n"; - - checkResult("KNumber(17) & KNumber(9)", KNumber(17) & KNumber(9), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(17) | KNumber(9)", KNumber(17) | KNumber(9), QLatin1String("25"), KNumber::TYPE_INTEGER); - checkResult("KNumber(1023) & KNumber(255)", KNumber(1023) & KNumber(255), QLatin1String("255"), KNumber::TYPE_INTEGER); - checkResult("KNumber(1023) | KNumber(255)", KNumber(1023) | KNumber(255), QLatin1String("1023"), KNumber::TYPE_INTEGER); - - #warning test for other types -} - - -void testingAbs() { - - std::cout << "\n\n"; - std::cout << "Testing absolute value:\n"; - std::cout << "-----------------------\n"; - - checkResult("KNumber(5).abs()", KNumber(5).abs(), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"2/3\").abs()", KNumber(QLatin1String("2/3")).abs(), QLatin1String("2/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"2.3\").abs()", KNumber(QLatin1String("2.3")).abs(), QLatin1String("2.3"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(-5).abs()", KNumber(-5).abs(), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-2/3\").abs()", KNumber(QLatin1String("-2/3")).abs(), QLatin1String("2/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"-2.3\").abs()", KNumber(QLatin1String("-2.3")).abs(), QLatin1String("2.3"), KNumber::TYPE_FLOAT); -} - -void testingTruncateToInteger() { - - std::cout << "\n\n"; - std::cout << "Testing truncate to an integer:\n"; - std::cout << "-------------------------------\n"; - - checkResult("KNumber(16).integerPart()", KNumber(16).integerPart(), QLatin1String("16"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"43/9\").integerPart()", KNumber(QLatin1String("43/9")).integerPart(), QLatin1String("4"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-43/9\").integerPart()", KNumber(QLatin1String("-43/9")).integerPart(), QLatin1String("-4"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5.25\").integerPart()", KNumber(QLatin1String("5.25")).integerPart(), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5.25\").integerPart()", KNumber(QLatin1String("-5.25")).integerPart(), QLatin1String("-5"), KNumber::TYPE_INTEGER); -} - - -void testingSqrt() { - - std::cout << "\n\n"; - std::cout << "Testing square root, cubic root:\n"; - std::cout << "--------------------------------\n"; - - checkResult("KNumber(16).sqrt()", KNumber(16).sqrt(), QLatin1String("4"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-16).sqrt()", KNumber(-16).sqrt(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"16/9\").sqrt()", KNumber(QLatin1String("16/9")).sqrt(), QLatin1String("4/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"-16/9\").sqrt()", KNumber(QLatin1String("-16/9")).sqrt(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(2).sqrt()", KNumber(2).sqrt(), QLatin1String("1.41421356237"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"2/3\").sqrt()", KNumber(QLatin1String("2/3")).sqrt(), QLatin1String("0.816496580928"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"0.25\").sqrt()", KNumber(QLatin1String("0.25")).sqrt(), QLatin1String("0.5"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"-0.25\").sqrt()", KNumber(QLatin1String("-0.25")).sqrt(), QLatin1String("nan"), KNumber::TYPE_ERROR); - - - checkResult("KNumber(27).cbrt()", KNumber(27).cbrt(), QLatin1String("3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-27).cbrt()", KNumber(-27).cbrt(), QLatin1String("-3"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"27/8\").cbrt()", KNumber(QLatin1String("27/8")).cbrt(), QLatin1String("3/2"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"-8/27\").cbrt()", KNumber(QLatin1String("-8/27")).cbrt(), QLatin1String("-2/3"), KNumber::TYPE_FRACTION); -#warning need to check non-perfect cube roots - checkResult("KNumber(2).cbrt()", KNumber(2).cbrt(), QLatin1String("1.25992104989"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"2/3\").cbrt()", KNumber(QLatin1String("2/3")).cbrt(), QLatin1String("0.873580464736"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"0.25\").cbrt()", KNumber(QLatin1String("0.25")).cbrt(), QLatin1String("0.629960524947"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"-0.25\").cbrt()", KNumber(QLatin1String("-0.25")).cbrt(), QLatin1String("-0.629960524947"), KNumber::TYPE_FLOAT); - -} - -void testingFactorial() { - - std::cout << "\n\n"; - std::cout << "Testing factorial:\n"; - std::cout << "------------------\n"; - - checkResult("KNumber(-1).factorial()", KNumber(-1).factorial(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-2).factorial()", KNumber(-2).factorial(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-20).factorial()", KNumber(-20).factorial(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-1/2).factorial()", KNumber(QLatin1String("-1/2")).factorial(), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-0.5).factorial()", KNumber(QLatin1String("-0.5")).factorial(), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("KNumber(0).factorial()", KNumber(0).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(1).factorial()", KNumber(1).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(2).factorial()", KNumber(2).factorial(), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(3).factorial()", KNumber(3).factorial(), QLatin1String("6"), KNumber::TYPE_INTEGER); - checkResult("KNumber(4).factorial()", KNumber(4).factorial(), QLatin1String("24"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5).factorial()", KNumber(5).factorial(), QLatin1String("120"), KNumber::TYPE_INTEGER); - checkResult("KNumber(6).factorial()", KNumber(6).factorial(), QLatin1String("720"), KNumber::TYPE_INTEGER); - checkResult("KNumber(9).factorial()", KNumber(9).factorial(), QLatin1String("362880"), KNumber::TYPE_INTEGER); - checkResult("KNumber(12).factorial()", KNumber(12).factorial(), QLatin1String("479001600"), KNumber::TYPE_INTEGER); - checkResult("KNumber(13).factorial()", KNumber(13).factorial(), QLatin1String("6227020800"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(1/2).factorial()", KNumber(QLatin1String("1/2")).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(2/1).factorial()", KNumber(QLatin1String("2/1")).factorial(), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(3/2).factorial()", KNumber(QLatin1String("3/2")).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(0.1).factorial()", KNumber(0.1).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(0.5).factorial()", KNumber(0.5).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(1.5).factorial()", KNumber(1.5).factorial(), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(2.5).factorial()", KNumber(2.5).factorial(), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(3.5).factorial()", KNumber(3.5).factorial(), QLatin1String("6"), KNumber::TYPE_INTEGER); -} - -void testingComplement() { - std::cout << "\n\n"; - std::cout << "Testing complement:\n"; - std::cout << "-------------------\n"; - - // at first glance, these look like they should work - // but there is an annoyance. If we use the mpz_com function - // ~-2 == 1, but the HEX/OCT/BIN views are broken :-( - // specifically, if the value is negative, it goes badly pretty quick.. -#if 0 - checkResult("~KNumber(0)", ~KNumber(0), QLatin1String("-1"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(1)", ~KNumber(1), QLatin1String("-2"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(2)", ~KNumber(2), QLatin1String("-3"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(8)", ~KNumber(8), QLatin1String("-9"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(15)", ~KNumber(15), QLatin1String("-16"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(-1)", ~KNumber(-1), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(-2)", ~KNumber(-2), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(-3)", ~KNumber(-3), QLatin1String("2"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(-9)", ~KNumber(-9), QLatin1String("8"), KNumber::TYPE_INTEGER); - checkResult("~KNumber(-16)", ~KNumber(-16), QLatin1String("15"), KNumber::TYPE_INTEGER); -#endif - - checkResult("~KNumber(0.12345)", ~KNumber(0.12345), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("~KNumber(-0.12345)", ~KNumber(-0.12345), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("~KNumber(\"1/2\")", ~KNumber(QLatin1String("1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("~KNumber(\"-1/2\")", ~KNumber(QLatin1String("-1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); -} - -void testingShifts() { - - std::cout << "\n\n"; - std::cout << "Testing left/right shift:\n"; - std::cout << "-------------------------\n"; - - checkResult("KNumber(16) << KNumber(2)", KNumber(16) << KNumber(2), QLatin1String("64"), KNumber::TYPE_INTEGER); - checkResult("KNumber(16) >> KNumber(2)", KNumber(16) >> KNumber(2), QLatin1String("4"), KNumber::TYPE_INTEGER); -} - -void testingPower() { - - std::cout << "\n\n"; - std::cout << "Testing Power:\n"; - std::cout << "--------------\n"; - - checkResult("KNumber(0) ^ KNumber(0)", KNumber(0).pow(KNumber(0)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0) ^ KNumber(-4)", KNumber(0).pow(KNumber(-4)), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(5) ^ KNumber(4)", KNumber(5).pow(KNumber(4)), QLatin1String("625"), KNumber::TYPE_INTEGER); - checkResult("KNumber(122) ^ KNumber(0)", KNumber(122).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-5) ^ KNumber(0)", KNumber(-5).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-2) ^ KNumber(3)", KNumber(-2).pow(KNumber(3)), QLatin1String("-8"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-2) ^ KNumber(4)", KNumber(-2).pow(KNumber(4)), QLatin1String("16"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) ^ KNumber(-2)", KNumber(5).pow(KNumber(-2)), QLatin1String("1/25"), KNumber::TYPE_FRACTION); - checkResult("KNumber(8) ^ KNumber(\"2/3\")", KNumber(8).pow(KNumber(QLatin1String("2/3"))), QLatin1String("4"), KNumber::TYPE_INTEGER); - checkResult("KNumber(8) ^ KNumber(\"-2/3\")", KNumber(8).pow(KNumber(QLatin1String("-2/3"))), QLatin1String("1/4"), KNumber::TYPE_FRACTION); - - checkResult("KNumber(-16) ^ KNumber(\"1/4\")", KNumber(-16).pow(KNumber(QLatin1String("1/4"))), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-8) ^ KNumber(\"1/3\")", KNumber(-8).pow(KNumber(QLatin1String("1/3"))), QLatin1String("-2"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5) ^ KNumber(0.0)", KNumber(5).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-5) ^ KNumber(0.0)", KNumber(-5).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(\"5/3\") ^ KNumber(2)", KNumber(QLatin1String("5/3")).pow(KNumber(2)), QLatin1String("25/9"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/3\") ^ KNumber(0)", KNumber(QLatin1String("5/3")).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5/3\") ^ KNumber(0)", KNumber(QLatin1String("-5/3")).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"8/27\") ^ KNumber(\"2/3\")", KNumber(QLatin1String("8/27")).pow(KNumber(QLatin1String("2/3"))), QLatin1String("4/9"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"49/3\") ^ KNumber(\"7/9\")", KNumber(QLatin1String("49/3")).pow(KNumber(QLatin1String("7/9"))), QLatin1String("8.78016428243"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"5/2\") ^ KNumber(2.5)", KNumber(QLatin1String("5/2")).pow(KNumber(2.5)), QLatin1String("9.88211768803"), KNumber::TYPE_FLOAT); - checkResult("KNumber(\"5/2\") ^ KNumber(0.0)", KNumber(QLatin1String("5/2")).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5/2\") ^ KNumber(0.0)", KNumber(QLatin1String("-5/2")).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(5.3) ^ KNumber(2)", KNumber(5.3).pow(KNumber(2)), QLatin1String("28.09"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.3) ^ KNumber(0)", KNumber(5.3).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-5.3) ^ KNumber(0)", KNumber(-5.3).pow(KNumber(0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(5.3) ^ KNumber(\"2/3\")", KNumber(5.3).pow(KNumber(QLatin1String("2/3"))), QLatin1String("3.03983898039"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.5) ^ KNumber(2.5)", KNumber(5.5).pow(KNumber(2.5)), QLatin1String("70.9425383673"), KNumber::TYPE_FLOAT); - checkResult("KNumber(5.5) ^ KNumber(0.0)", KNumber(5.5).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-5.5) ^ KNumber(0.0)", KNumber(-5.5).pow(KNumber(0.0)), QLatin1String("1"), KNumber::TYPE_INTEGER); - - checkResult("KNumber::Pi() ^ KNumber::Pi()", KNumber::Pi().pow(KNumber::Pi()), QLatin1String("36.4621596072"), KNumber::TYPE_FLOAT); - checkResult("KNumber::Euler() ^ KNumber::Pi()", KNumber::Euler().pow(KNumber::Pi()), QLatin1String("23.1406926328"), KNumber::TYPE_FLOAT); - - - checkResult("KNumber(2.0) ^ KNumber(0.5)", KNumber(2.0).pow(KNumber(0.5)), QLatin1String("1.41421356237"), KNumber::TYPE_FLOAT); - checkResult("KNumber(2.0) ^ KNumber(-0.5)", KNumber(2.0).pow(KNumber(-0.5)), QLatin1String("0.707106781187"), KNumber::TYPE_FLOAT); - - - checkResult("KNumber(-2.0).exp()", KNumber(-2.0).exp(), QLatin1String("0.135335283237"), KNumber::TYPE_FLOAT); - checkResult("KNumber::Euler() ^ KNumber(-2.0)", KNumber::Euler().pow(KNumber(-2.0)), QLatin1String("0.135335283237"), KNumber::TYPE_FLOAT); - - - checkResult("KNumber(2.0).exp()", KNumber(2.0).exp(), QLatin1String("7.38905609893"), KNumber::TYPE_FLOAT); - checkResult("KNumber::Euler() ^ KNumber(2.0)", KNumber::Euler().pow(KNumber(2.0)), QLatin1String("7.38905609893"), KNumber::TYPE_FLOAT); - - // TODO: kinda odd that this ends up being an integer - // i guess since my euler constant is only 100 digits, we've exceeded the fractional part - checkResult("KNumber::Euler() ^ 1000", KNumber::Euler().pow(KNumber(1000)), QLatin1String("1.97007111402e+434"), KNumber::TYPE_INTEGER); - - // TODO: make this test pass - // the problem is that it is using the libc exp function which has limits that GMP does not - // we should basically make this equivalent to KNumber::Euler().pow(KNumber(1000)) - // which does work -#if 0 - checkResult("KNumber(1000).exp()", KNumber(1000).exp(), QLatin1String("23.1406926328"), KNumber::TYPE_FLOAT); -#endif - - KNumber::setDefaultFractionalInput(true); - checkResult("KNumber(\"3.1415926\") ^ KNumber(\"3.1415926\")", KNumber(QLatin1String("3.1415926")).pow(KNumber(QLatin1String("3.1415926"))), QLatin1String("36.4621554164"), KNumber::TYPE_FLOAT); - KNumber::setDefaultFractionalInput(false); -} - -void testingInfArithmetic() { - - std::cout << "\n\n"; - std::cout << "Testing inf/nan-arithmetics:\n"; - std::cout << "----------------------------\n"; - - checkResult("inf + KNumber(2)", KNumber::PosInfinity + KNumber(2), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) + inf", KNumber(-5) + KNumber::PosInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("inf + KNumber(\"1/2\")", KNumber::PosInfinity + KNumber(QLatin1String("1/2")), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") + inf", KNumber(QLatin1String("-5/3")) + KNumber::PosInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("inf + KNumber(2.01)", KNumber::PosInfinity + KNumber(2.01), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) + inf", KNumber(-5.4) + KNumber::PosInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf + KNumber(2)", KNumber::NegInfinity + KNumber(2), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) + -inf", KNumber(-5) + KNumber::NegInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf + KNumber(\"1/2\")", KNumber::NegInfinity + KNumber(QLatin1String("1/2")), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") + -inf", KNumber(QLatin1String("-5/3")) + KNumber::NegInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf + KNumber(2.01)", KNumber::NegInfinity + KNumber(2.01), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) + -inf", KNumber(-5.4) + KNumber::NegInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("nan + KNumber(2)", KNumber::NaN + KNumber(2), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) + nan", KNumber(-5) + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan + KNumber(\"1/2\")", KNumber::NaN + KNumber(QLatin1String("1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") + nan", KNumber(QLatin1String("-5/3")) + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan + KNumber(2.01)", KNumber::NaN + KNumber(2.01), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) + nan", KNumber(-5.4) + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf + inf", KNumber::PosInfinity + KNumber::PosInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("inf + -inf", KNumber::PosInfinity + KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf + inf", KNumber::NegInfinity + KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf + -inf", KNumber::NegInfinity + KNumber::NegInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("inf + nan", KNumber::PosInfinity + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf + nan", KNumber::NegInfinity + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan + inf", KNumber::NaN + KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf + nan", KNumber::NegInfinity + KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("inf - KNumber(2)", KNumber::PosInfinity - KNumber(2), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) - inf", KNumber(-5) - KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("inf - KNumber(\"1/2\")", KNumber::PosInfinity - KNumber(QLatin1String("1/2")), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") - inf", KNumber(QLatin1String("-5/3")) - KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("inf - KNumber(2.01)", KNumber::PosInfinity - KNumber(2.01), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) - inf", KNumber(-5.4) - KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf - KNumber(2)", KNumber::NegInfinity - KNumber(2), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) - -inf", KNumber(-5) - KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf - KNumber(\"1/2\")", KNumber::NegInfinity - KNumber(QLatin1String("1/2")), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") - -inf", KNumber(QLatin1String("-5/3")) - KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf - KNumber(2.01)", KNumber::NegInfinity - KNumber(2.01), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) - -inf", KNumber(-5.4) - KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("nan - KNumber(2)", KNumber::NaN - KNumber(2), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) - nan", KNumber(-5) - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan - KNumber(\"1/2\")", KNumber::NaN - KNumber(QLatin1String("1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") - nan", KNumber(QLatin1String("-5/3")) - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan - KNumber(2.01)", KNumber::NaN - KNumber(2.01), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) - nan", KNumber(-5.4) - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf - inf", KNumber::PosInfinity - KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf - -inf", KNumber::PosInfinity - KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf - inf", KNumber::NegInfinity - KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf - -inf", KNumber::NegInfinity - KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf - nan", KNumber::PosInfinity - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf - nan", KNumber::NegInfinity - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan - inf", KNumber::NaN - KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf - nan", KNumber::NegInfinity - KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("inf * KNumber(2)", KNumber::PosInfinity * KNumber(2), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) * inf", KNumber(-5) * KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("inf * KNumber(\"1/2\")", KNumber::PosInfinity * KNumber(QLatin1String("1/2")), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") * inf", KNumber(QLatin1String("-5/3")) * KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("inf * KNumber(2.01)", KNumber::PosInfinity * KNumber(2.01), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) * inf", KNumber(-5.4) * KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf * KNumber(2)", KNumber::NegInfinity * KNumber(2), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) * -inf", KNumber(-5) * KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf * KNumber(\"1/2\")", KNumber::NegInfinity * KNumber(QLatin1String("1/2")), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") * -inf", KNumber(QLatin1String("-5/3")) * KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("-inf * KNumber(2.01)", KNumber::NegInfinity * KNumber(2.01), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) * -inf", KNumber(-5.4) * KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("nan * KNumber(2)", KNumber::NaN * KNumber(2), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) * nan", KNumber(-5) * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan * KNumber(\"1/2\")", KNumber::NaN * KNumber(QLatin1String("1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") * nan", KNumber(QLatin1String("-5/3")) * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan * KNumber(2.01)", KNumber::NaN * KNumber(2.01), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) * nan", KNumber(-5.4) * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf * inf", KNumber::PosInfinity * KNumber::PosInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("inf * -inf", KNumber::PosInfinity * KNumber::NegInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf * inf", KNumber::NegInfinity * KNumber::PosInfinity, QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("-inf * -inf", KNumber::NegInfinity * KNumber::NegInfinity, QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("inf * nan", KNumber::PosInfinity * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf * nan", KNumber::NegInfinity * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan * inf", KNumber::NaN * KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf * nan", KNumber::NegInfinity * KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0) * inf", KNumber(0) * KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0) * -inf", KNumber(0) * KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf * KNumber(0)", KNumber::PosInfinity * KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf * KNumber(0)", KNumber::NegInfinity * KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0.0) * inf", KNumber(0.0) * KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0.0) * -inf", KNumber(0.0) * KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf * KNumber(0.0)", KNumber::PosInfinity * KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf * KNumber(0.0)", KNumber::NegInfinity * KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("inf / KNumber(2)", KNumber::PosInfinity / KNumber(2), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) / inf", KNumber(-5) / KNumber::PosInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("inf / KNumber(\"1/2\")", KNumber::PosInfinity / KNumber(QLatin1String("1/2")), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") / inf", KNumber(QLatin1String("-5/3")) / KNumber::PosInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("inf / KNumber(2.01)", KNumber::PosInfinity / KNumber(2.01), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) / inf", KNumber(-5.4) / KNumber::PosInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("-inf / KNumber(2)", KNumber::NegInfinity / KNumber(2), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) / -inf", KNumber(-5) / KNumber::NegInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("-inf / KNumber(\"1/2\")", KNumber::NegInfinity / KNumber(QLatin1String("1/2")), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") / -inf", KNumber(QLatin1String("-5/3")) / KNumber::NegInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("-inf / KNumber(2.01)", KNumber::NegInfinity / KNumber(2.01), QLatin1String("-inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) / -inf", KNumber(-5.4) / KNumber::NegInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("nan / KNumber(2)", KNumber::NaN / KNumber(2), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) / nan", KNumber(-5) / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan / KNumber(\"1/2\")", KNumber::NaN / KNumber(QLatin1String("1/2")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/3\") / nan", KNumber(QLatin1String("-5/3")) / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan / KNumber(2.01)", KNumber::NaN / KNumber(2.01), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5.4) / nan", KNumber(-5.4) / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf / inf", KNumber::PosInfinity / KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf / -inf", KNumber::PosInfinity / KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / inf", KNumber::NegInfinity / KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / -inf", KNumber::NegInfinity / KNumber::NegInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("inf / nan", KNumber::PosInfinity / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / nan", KNumber::NegInfinity / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("nan / inf", KNumber::NaN / KNumber::PosInfinity, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / nan", KNumber::NegInfinity / KNumber::NaN, QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0) / inf", KNumber(0) / KNumber::PosInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(0) / -inf", KNumber(0) / KNumber::NegInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("inf / KNumber(0)", KNumber::PosInfinity / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / KNumber(0)", KNumber::NegInfinity / KNumber(0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(0.0) / inf", KNumber(0.0) / KNumber::PosInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(0.0) / -inf", KNumber(0.0) / KNumber::NegInfinity, QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("inf / KNumber(0.0)", KNumber::PosInfinity / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("-inf / KNumber(0.0)", KNumber::NegInfinity / KNumber(0.0), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("KNumber(5) ^ KNumber(\"inf\")", KNumber(5).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) ^ KNumber(\"inf\")", KNumber(-5).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"5/2\") ^ KNumber(\"inf\")", KNumber(QLatin1String("5/2")).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/2\") ^ KNumber(\"inf\")", KNumber(QLatin1String("-5/2")).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"5.2\") ^ KNumber(\"inf\")", KNumber(QLatin1String("5.2")).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5.2\") ^ KNumber(\"inf\")", KNumber(QLatin1String("-5.2")).pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - - checkResult("KNumber(5) ^ KNumber(\"-inf\")", KNumber(5).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(-5) ^ KNumber(\"-inf\")", KNumber(-5).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/2\") ^ KNumber(\"-inf\")", KNumber(QLatin1String("5/2")).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5/2\") ^ KNumber(\"-inf\")", KNumber(QLatin1String("-5/2")).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5.2\") ^ KNumber(\"-inf\")", KNumber(QLatin1String("5.2")).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"-5.2\") ^ KNumber(\"-inf\")", KNumber(QLatin1String("-5.2")).pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(5) ^ KNumber(\"nan\")", KNumber(5).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(-5) ^ KNumber(\"nan\")", KNumber(-5).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"5/2\") ^ KNumber(\"nan\")", KNumber(QLatin1String("5/2")).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5/2\") ^ KNumber(\"nan\")", KNumber(QLatin1String("-5/2")).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"5.2\") ^ KNumber(\"nan\")", KNumber(QLatin1String("5.2")).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-5.2\") ^ KNumber(\"nan\")", KNumber(QLatin1String("-5.2")).pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - - - checkResult("KNumber(\"nan\") ^ KNumber(\"nan\")", KNumber::NaN.pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"nan\") ^ KNumber(\"inf\")", KNumber::NaN.pow(KNumber::PosInfinity), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"nan\") ^ KNumber(\"-inf\")", KNumber::NaN.pow(KNumber::NegInfinity), QLatin1String("nan"), KNumber::TYPE_ERROR); - - checkResult("KNumber(\"inf\") ^ KNumber(\"nan\")", KNumber::PosInfinity.pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"inf\") ^ KNumber(\"inf\")", KNumber::PosInfinity.pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"inf\") ^ KNumber(\"-inf\")", KNumber::PosInfinity.pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); - - checkResult("KNumber(\"-inf\") ^ KNumber(\"nan\")", KNumber::NegInfinity.pow(KNumber::NaN), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-inf\") ^ KNumber(\"inf\")", KNumber::NegInfinity.pow(KNumber::PosInfinity), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-inf\") ^ KNumber(\"-inf\")", KNumber::NegInfinity.pow(KNumber::NegInfinity), QLatin1String("0"), KNumber::TYPE_INTEGER); -} - -void testingFloatPrecision() { - - KNumber::setDefaultFloatPrecision(100); - checkResult("Precision >= 100: (KNumber(1) + KNumber(\"1e-80\")) - KNumber(1)", (KNumber(1) + KNumber(QLatin1String("1e-80"))) - KNumber(1), QLatin1String("1e-80"), KNumber::TYPE_FLOAT); - checkResult("Precision >= 100: (KNumber(1) + KNumber(\"1e-980\")) - KNumber(1)", (KNumber(1) + KNumber(QLatin1String("1e-980"))) - KNumber(1), QLatin1String("0"), KNumber::TYPE_INTEGER); - - KNumber::setDefaultFloatPrecision(1000); - checkResult("Precision >= 1000: (KNumber(1) + KNumber(\"1e-980\")) - KNumber(1)", (KNumber(1) + KNumber(QLatin1String("1e-980"))) - KNumber(1), QLatin1String("1e-980"), KNumber::TYPE_FLOAT); - - KNumber::setDefaultFloatPrecision(20); - checkResult("Precision >= 20: sin(KNumber(30))", sin(KNumber(30) * (KNumber::Pi() / KNumber(180))), QLatin1String("0.5"), KNumber::TYPE_FLOAT); - -} - -void testingOutput() { - - KNumber::setDefaultFloatOutput(false); - checkResult("Fractional output: KNumber(\"1/4\")", KNumber(QLatin1String("1/4")), QLatin1String("1/4"), KNumber::TYPE_FRACTION); - - KNumber::setDefaultFloatOutput(true); - checkResult("Float: KNumber(\"1/4\")", KNumber(QLatin1String("1/4")), QLatin1String("0.25"), KNumber::TYPE_FRACTION); - - KNumber::setDefaultFloatOutput(false); - KNumber::setSplitoffIntegerForFractionOutput(true); - checkResult("Fractional output: KNumber(\"1/4\")", KNumber(QLatin1String("1/4")), QLatin1String("1/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"-1/4\")", KNumber(QLatin1String("-1/4")), QLatin1String("-1/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"21/4\")", KNumber(QLatin1String("21/4")), QLatin1String("5 1/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"-21/4\")", KNumber(QLatin1String("-21/4")), QLatin1String("-5 1/4"), KNumber::TYPE_FRACTION); - - KNumber::setSplitoffIntegerForFractionOutput(false); - checkResult("Fractional output: KNumber(\"1/4\")", KNumber(QLatin1String("1/4")), QLatin1String("1/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"-1/4\")", KNumber(QLatin1String("-1/4")), QLatin1String("-1/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"21/4\")", KNumber(QLatin1String("21/4")), QLatin1String("21/4"), KNumber::TYPE_FRACTION); - checkResult("Fractional output: KNumber(\"-21/4\")", KNumber(QLatin1String("-21/4")), QLatin1String("-21/4"), KNumber::TYPE_FRACTION); -} - -void testingConstructors() { - std::cout << "Testing Constructors:\n"; - std::cout << "---------------------\n"; - - checkResult("KNumber(5)", KNumber(5), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkType(QLatin1String("KNumber(5.3)"), KNumber(5.3).type(), KNumber::TYPE_FLOAT); - checkType(QLatin1String("KNumber(0.0)"), KNumber(0.0).type(), KNumber::TYPE_INTEGER); - - checkResult("KNumber(\"5\")", KNumber(QLatin1String("5")), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"5/3\")", KNumber(QLatin1String("5/3")), QLatin1String("5/3"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5/1\")", KNumber(QLatin1String("5/1")), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"0/12\")", KNumber(QLatin1String("0/12")), QLatin1String("0"), KNumber::TYPE_INTEGER); - KNumber::setDefaultFractionalInput(true); - std::cout << "Read decimals as fractions:\n"; - checkResult("KNumber(\"5\")", KNumber(QLatin1String("5")), QLatin1String("5"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"1.2\")", KNumber(QLatin1String("1.2")), QLatin1String("6/5"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"-0.02\")", KNumber(QLatin1String("-0.02")), QLatin1String("-1/50"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"5e-2\")", KNumber(QLatin1String("5e-2")), QLatin1String("1/20"), KNumber::TYPE_FRACTION); - checkResult("KNumber(\"1.2e3\")", KNumber(QLatin1String("1.2e3")), QLatin1String("1200"), KNumber::TYPE_INTEGER); - checkResult("KNumber(\"0.02e+1\")", KNumber(QLatin1String("0.02e+1")), QLatin1String("1/5"), KNumber::TYPE_FRACTION); - - KNumber::setDefaultFractionalInput(false); - std::cout << "Read decimals as floats:\n"; - checkResult("KNumber(\"5.3\")", KNumber(QLatin1String("5.3")), QLatin1String("5.3"), KNumber::TYPE_FLOAT); - - checkResult("KNumber(\"nan\")", KNumber(QLatin1String("nan")), QLatin1String("nan"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"inf\")", KNumber(QLatin1String("inf")), QLatin1String("inf"), KNumber::TYPE_ERROR); - checkResult("KNumber(\"-inf\")", KNumber(QLatin1String("-inf")), QLatin1String("-inf"), KNumber::TYPE_ERROR); - - // test accepting of non-US number formatted strings - KNumber::setDecimalSeparator(","); - checkResult("KNumber(\"5,2\")", KNumber(QLatin1String("5,2")), QLatin1String("5.2"), KNumber::TYPE_FLOAT); - KNumber::setDecimalSeparator("."); -} - -void testingConstants() { - std::cout << "\n\n"; - std::cout << "Constants:\n"; - std::cout << "----------\n"; - - checkType(QLatin1String("KNumber::Zero"), KNumber::Zero.type(), KNumber::TYPE_INTEGER); - checkType(QLatin1String("KNumber::One"), KNumber::One.type(), KNumber::TYPE_INTEGER); - checkType(QLatin1String("KNumber::NegOne"), KNumber::NegOne.type(), KNumber::TYPE_INTEGER); - checkType(QLatin1String("KNumber::Pi"), KNumber::Pi().type(), KNumber::TYPE_FLOAT); - checkType(QLatin1String("KNumber::Euler"), KNumber::Euler().type(), KNumber::TYPE_FLOAT); -} - -} - - -int main() { - - testingConstants(); - testingConstructors(); - testingCompare(); - testingAdditions(); - testingSubtractions(); - testingMultiplications(); - testingDivisions(); - testingAndOr(); - testingModulus(); - testingAbs(); - testingSqrt(); - testingFactorial(); - testingComplement(); - testingPower(); - testingTruncateToInteger(); - testingShifts(); - testingInfArithmetic(); - testingFloatPrecision(); - testingTrig(); - testingSpecial(); - testingOutput(); - std::cout << "SUCCESS" << std::endl; -} - diff --git a/kcalc/scienceconstants.xml b/kcalc/scienceconstants.xml deleted file mode 100644 index ef6ce6df..00000000 --- a/kcalc/scienceconstants.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kcalc/stats.cpp b/kcalc/stats.cpp deleted file mode 100644 index 723ff29b..00000000 --- a/kcalc/stats.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#include "stats.h" - -//------------------------------------------------------------------------------ -// Name: KStats -// Desc: constructor -//------------------------------------------------------------------------------ -KStats::KStats() : error_flag_(false) { -} - -//------------------------------------------------------------------------------ -// Name: ~KStats -// Desc: destructor -//------------------------------------------------------------------------------ -KStats::~KStats() { -} - -//------------------------------------------------------------------------------ -// Name: clearAll -// Desc: empties the data set -//------------------------------------------------------------------------------ -void KStats::clearAll() { - data_.clear(); -} - -//------------------------------------------------------------------------------ -// Name: enterData -// Desc: adds an item to the data set -//------------------------------------------------------------------------------ -void KStats::enterData(const KNumber &data) { - data_.push_back(data); -} - -//------------------------------------------------------------------------------ -// Name: clearLast -// Desc: remoaves the last item from the data set -//------------------------------------------------------------------------------ -void KStats::clearLast() { - - if(!data_.isEmpty()) { - data_.pop_back(); - } -} - -//------------------------------------------------------------------------------ -// Name: sum -// Desc: calculates the SUM of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::sum() const { - - KNumber result = KNumber::Zero; - - Q_FOREACH(const KNumber &x, data_) { - result += x; - } - - return result; -} - -//------------------------------------------------------------------------------ -// Name: median -// Desc: calculates the MEDIAN of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::median() { - - KNumber result = KNumber::Zero; - size_t index; - - unsigned int bound = count(); - - if (bound == 0) { - error_flag_ = true; - return KNumber::Zero; - } - - if (bound == 1) - return data_.at(0); - - // need to copy data_-list, because sorting afterwards - QVector tmp_data(data_); - qSort(tmp_data); - - if (bound & 1) { // odd - index = (bound - 1) / 2 + 1; - result = tmp_data.at(index - 1); - } else { // even - index = bound / 2; - result = ((tmp_data.at(index - 1)) + (tmp_data.at(index))) / KNumber(2); - } - - return result; -} - -//------------------------------------------------------------------------------ -// Name: std_kernel -// Desc: calculates the STD Kernel of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::std_kernel() { - KNumber result = KNumber::Zero; - const KNumber mean_value = mean(); - - if(mean_value.type() != KNumber::TYPE_ERROR) { - Q_FOREACH(const KNumber &x, data_) { - result += (x - mean_value) * (x - mean_value); - } - } - - return result; -} - -//------------------------------------------------------------------------------ -// Name: sum_of_squares -// Desc: calculates the SUM of all values in the data set (each squared) -//------------------------------------------------------------------------------ -KNumber KStats::sum_of_squares() const { - - KNumber result = KNumber::Zero; - - Q_FOREACH(const KNumber &x, data_) { - result += (x * x); - } - - return result; -} - -//------------------------------------------------------------------------------ -// Name: mean -// Desc: calculates the MEAN of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::mean() { - - if (data_.isEmpty()) { - error_flag_ = true; - return KNumber::Zero; - } - - return (sum() / KNumber(count())); -} - -//------------------------------------------------------------------------------ -// Name: std -// Desc: calculates the STANDARD DEVIATION of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::std() { - - if (data_.isEmpty()) { - error_flag_ = true; - return KNumber::Zero; - } - - return (std_kernel() / KNumber(count())).sqrt(); -} - -//------------------------------------------------------------------------------ -// Name: sample_std -// Desc: calculates the SAMPLE STANDARD DEVIATION of all values in the data set -//------------------------------------------------------------------------------ -KNumber KStats::sample_std() { - - KNumber result = KNumber::Zero; - - if (count() < 2) { - error_flag_ = true; - return KNumber::Zero; - } - - result = (std_kernel() / KNumber(count() - 1)).sqrt(); - - return result; -} - -//------------------------------------------------------------------------------ -// Name: count -// Desc: returns the amount of values in the data set -//------------------------------------------------------------------------------ -int KStats::count() const { - - return data_.size(); -} - -//------------------------------------------------------------------------------ -// Name: error -// Desc: returns the error state AND clears it -//------------------------------------------------------------------------------ -bool KStats::error() { - - bool value = error_flag_; - error_flag_ = false; - return value; -} - - - diff --git a/kcalc/stats.h b/kcalc/stats.h deleted file mode 100644 index e4e32c9d..00000000 --- a/kcalc/stats.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -Copyright (C) 1996 - 2000 Bernd Johannes Wuebben - wuebben@kde.org - -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, see . -*/ - -#ifndef KSTATS_H_ -#define KSTATS_H_ - -#include -#include "knumber.h" - -class KStats { -public: - KStats(); - ~KStats(); - -public: - void clearAll(); - void enterData(const KNumber &data); - void clearLast(); - KNumber sum() const; - KNumber sum_of_squares() const; - KNumber mean(); - KNumber median(); - KNumber std_kernel(); - KNumber std(); - KNumber sample_std(); - int count() const; - bool error(); - -private: - QVector data_; - bool error_flag_; -}; - -#endif - diff --git a/kcalc/version.h b/kcalc/version.h deleted file mode 100644 index 054ea521..00000000 --- a/kcalc/version.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright (C) 2001 - 2013 Evan Teran - evan.teran@gmail.com - -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, see . -*/ - -#ifndef KCALCVERSION -#define KCALCVERSION "2.13" -#endif diff --git a/kdeplasma-addons/applets/bubblemon/plasma-applet-bubblemon.desktop b/kdeplasma-addons/applets/bubblemon/plasma-applet-bubblemon.desktop index 7f3ea710..99287ceb 100644 --- a/kdeplasma-addons/applets/bubblemon/plasma-applet-bubblemon.desktop +++ b/kdeplasma-addons/applets/bubblemon/plasma-applet-bubblemon.desktop @@ -107,5 +107,4 @@ X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true -X-Plasma-NotificationArea=true X-Plasma-DefaultSize=200,200 diff --git a/kdeplasma-addons/applets/konsoleprofiles/Messages.sh b/kdeplasma-addons/applets/konsoleprofiles/Messages.sh index f0347089..a031c463 100644 --- a/kdeplasma-addons/applets/konsoleprofiles/Messages.sh +++ b/kdeplasma-addons/applets/konsoleprofiles/Messages.sh @@ -1,4 +1,4 @@ #!/bin/bash $EXTRACTRC `find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` >> rc.cpp -$XGETTEXT `find . -name \*.js -o -name \*.qml -o -name \*.cpp` -o $podir/konsoleprofiles.pot +$XGETTEXT `find . -o -name \*.cpp` -o $podir/konsoleprofiles.pot rm -f rc.cpp diff --git a/kdeplasma-addons/applets/konsoleprofiles/plasma-applet-konsoleprofiles.desktop b/kdeplasma-addons/applets/konsoleprofiles/plasma-applet-konsoleprofiles.desktop index 8a3ff872..25547a40 100644 --- a/kdeplasma-addons/applets/konsoleprofiles/plasma-applet-konsoleprofiles.desktop +++ b/kdeplasma-addons/applets/konsoleprofiles/plasma-applet-konsoleprofiles.desktop @@ -126,5 +126,3 @@ X-KDE-PluginInfo-Category=Utilities X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true - -#X-Plasma-NotificationArea=true diff --git a/kdeplasma-addons/applets/paste/plasma-applet-paste.desktop b/kdeplasma-addons/applets/paste/plasma-applet-paste.desktop index bae39ad9..282bf4f5 100644 --- a/kdeplasma-addons/applets/paste/plasma-applet-paste.desktop +++ b/kdeplasma-addons/applets/paste/plasma-applet-paste.desktop @@ -128,5 +128,3 @@ X-KDE-PluginInfo-Category=Utilities X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true -X-Plasma-NotificationArea=true - diff --git a/kdeplasma-addons/wallpapers/CMakeLists.txt b/kdeplasma-addons/wallpapers/CMakeLists.txt index 6aecd514..f08a2070 100644 --- a/kdeplasma-addons/wallpapers/CMakeLists.txt +++ b/kdeplasma-addons/wallpapers/CMakeLists.txt @@ -1,4 +1,3 @@ add_subdirectory(potd) add_subdirectory(virus) -add_subdirectory(qmlwallpapers) add_subdirectory(pattern) diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/CMakeLists.txt b/kdeplasma-addons/wallpapers/qmlwallpapers/CMakeLists.txt deleted file mode 100644 index 52edb487..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -project(plasma-wallpaper-qml) - -kde4_add_plugin(plasma_wallpaper_qml wallpapersmodel.cpp wallpapersqml.cpp backgrounddelegate.cpp viewconfig.ui) -target_link_libraries(plasma_wallpaper_qml - ${QT_QTDECLARATIVE_LIBRARY} - KDE4::plasma KDE4::kdecore kdeclarative -) - -install(TARGETS plasma_wallpaper_qml DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) -install(FILES plasma-wallpaper-qml.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - -add_subdirectory(wallpapers) diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/Messages.sh b/kdeplasma-addons/wallpapers/qmlwallpapers/Messages.sh deleted file mode 100755 index d510dfee..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/Messages.sh +++ /dev/null @@ -1,2 +0,0 @@ -#! /usr/bin/env bash -$XGETTEXT *.cpp -o $podir/plasma_wallpaper_wallpaper-qml.pot diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.cpp b/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.cpp deleted file mode 100644 index d2647825..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - Copyright (c) 2007 Paolo Capriotti - Copyright (c) 2010 Dario Andres Rodriguez - - 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. -*/ - -#include "backgrounddelegate.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include - -static const int BLUR_PAD = 6; - -BackgroundDelegate::BackgroundDelegate(QObject *parent) - : QAbstractItemDelegate(parent) -{ - m_maxHeight = SCREENSHOT_SIZE/1.6 + BLUR_INCREMENT; - m_maxWidth = SCREENSHOT_SIZE + BLUR_INCREMENT; -} - -void BackgroundDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - const QString title = index.model()->data(index, Qt::DisplayRole).toString(); - const QString author = index.model()->data(index, AuthorRole).toString(); - const QString resolution = index.model()->data(index, ResolutionRole).toString(); - const QPixmap pix = index.model()->data(index, ScreenshotRole).value(); - - // Highlight selected item - QStyleOptionViewItemV4 opt(option); - opt.showDecorationSelected = true; - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); - - // Draw wallpaper thumbnail - if (pix.isNull()) { - painter->fillRect(option.rect, option.palette.brush(QPalette::Base)); - } else { - // blur calculation - QImage blur(pix.size() + QSize(BLUR_INCREMENT + BLUR_PAD, BLUR_INCREMENT + BLUR_PAD), QImage::Format_ARGB32); - QRect blurRect = QRect(QPoint((blur.width() - pix.width()) / 2, (blur.height() - pix.height()) / 2), pix.size()); - blur.fill(Qt::transparent); - QPainter p(&blur); - - QColor color = option.palette.color(QPalette::Base); - bool darkBaseColor = qGray(color.rgb()) < 192; - p.fillRect(blurRect, darkBaseColor ? Qt::white : Qt::black); - p.end(); - - // apply blur with a radius of 2 as thumbnail shadow - Plasma::PaintUtils::shadowBlur(blur, 2, darkBaseColor ? Qt::white : Qt::black); - - // calculate point - const int bx = (option.rect.width() - blur.width()) / 2; - const int by = MARGIN + qMax(0, m_maxHeight - blur.height()); - QRect shadowRect = QRect(option.rect.topLeft(), blur.size()).translated(bx, by); - // draw the blur - painter->drawImage(shadowRect.topLeft(), blur); - // draw the actual thumbnail - painter->drawPixmap(QRect(shadowRect.topLeft() + QPoint((shadowRect.width() - pix.width()) / 2, (shadowRect.height() - pix.height()) / 2), - pix.size()), pix); - } - - //Use a QTextDocument to layout the text - - // Borrowed from Dolphin for consistency and beauty. - // For the color of the additional info the inactive text color - // is not used as this might lead to unreadable text for some color schemes. Instead - // the text color is slightly mixed with the background color. - const QColor textColor = option.palette.text().color(); - const QColor baseColor = option.palette.base().color(); - const int p1 = 70; - const int p2 = 100 - p1; - const QColor detailsColor = QColor((textColor.red() * p1 + baseColor.red() * p2) / 100, - (textColor.green() * p1 + baseColor.green() * p2) / 100, - (textColor.blue() * p1 + baseColor.blue() * p2) / 100); - QTextDocument document; - QString html = title; - - if (!resolution.isEmpty()) { - html += QString("
%2") - .arg(detailsColor.name()) - .arg(resolution); - } - - if (!author.isEmpty()) { - html += QString("
%2") - .arg(detailsColor.name()) - .arg(author); - } - - //Set the text color according to the item state - QPalette::ColorGroup cg = QPalette::Active; - if (!(option.state & QStyle::State_Enabled)) { - cg = QPalette::Disabled; - } else if (!(option.state & QStyle::State_Active)) { - cg = QPalette::Inactive; - } - - QColor color; - if (option.state & QStyle::State_Selected) { - color = QApplication::palette().brush(cg, QPalette::HighlightedText).color(); - } else { - color = QApplication::palette().brush(cg, QPalette::Text).color(); - } - - html = QString("
%2
").arg(color.name()).arg(html); - - document.setHtml(html); - - //Calculate positioning - int x = option.rect.left() + MARGIN; - - //Enable word-wrap - document.setTextWidth(m_maxWidth); - - //Center text on the row - int y = option.rect.top() + m_maxHeight + MARGIN * 2; //qMax(0 ,(int)((option.rect.height() - document.size().height()) / 2)); - - //Draw text - painter->save(); - painter->translate(x, y); - document.drawContents(painter, QRect(QPoint(0, 0), option.rect.size() - QSize(0, m_maxHeight + MARGIN * 2))); - painter->restore(); -} - -QSize BackgroundDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - Q_UNUSED(option) - const QString title = index.model()->data(index, Qt::DisplayRole).toString(); - const QString author = index.model()->data(index, AuthorRole).toString(); - - //Generate a sample complete entry (with the real title) to calculate sizes - QTextDocument document; - QString html = title + "
"; - if (!author.isEmpty()) { - html += author + "
"; - } - html += QString("1600x1200"); - - document.setHtml(html); - document.setTextWidth(m_maxWidth); - - QSize s(m_maxWidth + MARGIN * 2, - m_maxHeight + MARGIN * 3 + (int)(document.size().height())); - return s; -} - diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.h b/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.h deleted file mode 100644 index 9e38b501..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/backgrounddelegate.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (c) 2007 Paolo Capriotti - - 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. -*/ - -#ifndef BACKGROUNDDELEGATE_H -#define BACKGROUNDDELEGATE_H - -#include - -class BackgroundDelegate : public QAbstractItemDelegate -{ -public: - enum { - AuthorRole = Qt::UserRole, - ScreenshotRole, - ResolutionRole - }; - - BackgroundDelegate(QObject *parent = 0); - - virtual void paint(QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const; - virtual QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const; - - static const int SCREENSHOT_SIZE = 128; - static const int BLUR_INCREMENT = 9; - static const int MARGIN = 6; - - void resetMaxHeight() { m_maxHeight = 0; } - int m_maxHeight; -private: - int m_maxWidth; -}; - -#endif // BACKGROUNDDELEGATEL_H diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/plasma-wallpaper-qml.desktop b/kdeplasma-addons/wallpapers/qmlwallpapers/plasma-wallpaper-qml.desktop deleted file mode 100644 index b7d01be9..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/plasma-wallpaper-qml.desktop +++ /dev/null @@ -1,92 +0,0 @@ -[Desktop Entry] -Name=Animations -Name[bs]=Animacije -Name[ca]=Animacions -Name[ca@valencia]=Animacions -Name[cs]=Animace -Name[da]=Animationer -Name[de]=Animationen -Name[el]=Κινούμενα -Name[en_GB]=Animations -Name[es]=Animaciones -Name[et]=Animatsioonid -Name[fi]=Animaatiot -Name[fr]=Animations -Name[gl]=Animacións -Name[hu]=Animációk -Name[it]=Animazioni -Name[kk]=Анимациялар -Name[ko]=애니메이션 -Name[nb]=Animasjoner -Name[nds]=Animatschonen -Name[nl]=Animaties -Name[pl]=Animacje -Name[pt]=Animações -Name[pt_BR]=Animações -Name[ro]=Animații -Name[ru]=Анимации -Name[sk]=Animácie -Name[sl]=Animacije -Name[sr]=анимације -Name[sr@ijekavian]=анимације -Name[sr@ijekavianlatin]=animacije -Name[sr@latin]=animacije -Name[sv]=Animeringar -Name[tr]=Animasyonlar -Name[ug]=جانلاندۇرۇملار -Name[uk]=Анімації -Name[x-test]=xxAnimationsxx -Name[zh_CN]=动画 -Name[zh_TW]=動畫 -Comment=Interactive, animated wallpapers -Comment[ar]=خلفيات متحركة غير فعالة -Comment[bs]=Interaktivne, animirane pozadinske slike -Comment[ca]=Fons d'escriptori interactius, animats -Comment[ca@valencia]=Fons d'escriptori interactius, animats -Comment[cs]=Interaktivní animované tapety -Comment[da]=Interaktive, animerede baggrundsbilleder -Comment[de]=Interaktive, animierte Hintergrundbilder -Comment[el]=Διαδραστικές, κινούμενες ταπετσαρίες -Comment[en_GB]=Interactive, animated wallpapers -Comment[es]=Fondos de pantalla interactivos animados -Comment[et]=Interaktiivsed animeeritud taustapildid -Comment[fi]=Vuorovaikutteiset, animoidut taustat -Comment[fr]=Fonds d'écran interactifs et animés -Comment[gl]=Fondos de escritorio animados e interactivos. -Comment[hu]=Interaktív, animált háttérképek -Comment[it]=Sfondi animati, interattivi -Comment[kk]=Интерактивті, анимацияланған тұсқағаздар -Comment[ko]=인터랙티브 애니메이션 배경 그림 -Comment[nb]=Interaktive, animerte tapeter -Comment[nds]=Brukerstüert, animeert Achtergrundbiller -Comment[nl]=Interactieve geanimeerde bureaubladachtergronden -Comment[pl]=Interaktywne, animowane tapety -Comment[pt]=Papéis de parede animados e interactivos -Comment[pt_BR]=Papéis de parede animados e interativos -Comment[ro]=Fundaluri animate, interactive -Comment[ru]=Интерактивные анимированные фоны -Comment[sk]=Interaktívne, animované tapety -Comment[sl]=Interaktivne, animirane slike ozadja -Comment[sr]=Интерактивни анимирани тапети -Comment[sr@ijekavian]=Интерактивни анимирани тапети -Comment[sr@ijekavianlatin]=Interaktivni animirani tapeti -Comment[sr@latin]=Interaktivni animirani tapeti -Comment[sv]=Interaktiva, animerade skrivbordsunderlägg -Comment[tr]=Etkileşimli, hareketli Duvar Kağıtları -Comment[uk]=Інтерактивні анімовані шпалери -Comment[x-test]=xxInteractive, animated wallpapersxx -Comment[zh_CN]=交互,动画壁纸 -Comment[zh_TW]=互動式動畫桌布 -Type=Service -Icon=preferences-desktop-wallpaper -ServiceTypes=Plasma/Wallpaper - -X-KDE-Library=plasma_wallpaper_qml -X-KDE-PluginInfo-Author=Aleix Pol Gonzalez -X-KDE-PluginInfo-Email=aleixpol@kde.org -X-KDE-PluginInfo-Name=org.kde.wallpaper-qml -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true - diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/viewconfig.ui b/kdeplasma-addons/wallpapers/qmlwallpapers/viewconfig.ui deleted file mode 100644 index 1a9dcd9c..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/viewconfig.ui +++ /dev/null @@ -1,115 +0,0 @@ - - - ViewConfig - - - - 0 - 0 - 568 - 379 - - - - - - - &Color: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - m_color - - - - - - - - - - 0 - 0 - - - - Change wallpaper frame color - - - Change the color of the frame that it may be visible when the wallpaper is centered or scaled with the same proportions. - - - - 70 - 90 - 130 - - - - - 70 - 90 - 130 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 300 - 220 - - - - QListView::Static - - - QListView::Adjust - - - QListView::Batched - - - 2 - - - QListView::IconMode - - - true - - - true - - - - - - - - KColorButton - QPushButton -
kcolorbutton.h
-
-
- -
diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/CMakeLists.txt b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/CMakeLists.txt deleted file mode 100644 index f20fc30c..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -install(DIRECTORY hunyango/ DESTINATION ${KDE4_DATA_INSTALL_DIR}/plasma/wallpapers/org.kde.hunyango) diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/main.qml b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/main.qml deleted file mode 100644 index bad62894..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/main.qml +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2012 Marco Martin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2 or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -import QtQuick 1.1 -import org.kde.plasma.core 0.1 as PlasmaCore - -Rectangle { - id: root - width: 800 - height: 480 - - function randomColor() { - root.color = Qt.hsva(Math.random(), 1,0.5,1) - } - - Component.onCompleted: randomColor() - MouseArea { - anchors.fill: parent - onClicked: randomColor() - } - - PlasmaCore.SvgItem { - anchors.fill: parent - smooth: true - svg: PlasmaCore.Svg { - id: wallpaperSvg - //FIXME: Svg doesn't support relative paths - imagePath: Qt.resolvedUrl("wallpaper.svgz").substring(7) - } - } - - Timer { - running: true - repeat: true - interval: 30000 - onTriggered: randomColor() - } - Behavior on color { ColorAnimation { duration: 1000; easing.type: Easing.InQuad } } -} \ No newline at end of file diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/wallpaper.svgz b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/wallpaper.svgz deleted file mode 100644 index 0c5d200d..00000000 Binary files a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/contents/ui/wallpaper.svgz and /dev/null differ diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/metadata.desktop b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/metadata.desktop deleted file mode 100644 index 8a7c8e2c..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapers/hunyango/metadata.desktop +++ /dev/null @@ -1,55 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Name=Hunyango -Name[bs]=Hunjango -Name[ca]=Hunyango -Name[ca@valencia]=Hunyango -Name[cs]=Hunyango -Name[da]=Hunyango -Name[de]=Hunyango -Name[el]=Hunyango -Name[en_GB]=Hunyango -Name[es]=Hunyango -Name[et]=Hunyango -Name[fi]=Hunyango -Name[fr]=Hunyango -Name[gl]=Hunyango -Name[hu]=Hunyango -Name[it]=Hunyango -Name[kk]=Хаянго -Name[ko]=Hunyango -Name[mr]=हुन्यान्गो -Name[nb]=Hunyango -Name[nds]=Hunyango -Name[nl]=Hunyango -Name[pl]=Hunyango -Name[pt]=Hunyango -Name[pt_BR]=Hunyango -Name[ro]=Hunyango -Name[ru]=Hunyango -Name[sk]=Hunyango -Name[sl]=Hunyango -Name[sr]=Хунјанго -Name[sr@ijekavian]=Хунјанго -Name[sr@ijekavianlatin]=Hunjango -Name[sr@latin]=Hunjango -Name[sv]=Hunyango -Name[tr]=Hunyango -Name[uk]=Уньянго -Name[wa]=Hunyango -Name[x-test]=xxHunyangoxx -Name[zh_CN]=变色龙 -Name[zh_TW]=Hunyango - - -Type=Service -ServiceTypes=Plasma/DeclarativeWallpaper -Icon=preferences-desktop-wallpaper -X-Plasma-MainScript=ui/main.qml -X-KDE-PluginInfo-Author=Marco Martin -X-KDE-PluginInfo-Email=mart@kde.org -X-KDE-PluginInfo-Name=org.kde.hunyango -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-License=LGPL -X-KDE-PluginInfo-EnabledByDefault=true diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.cpp b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.cpp deleted file mode 100644 index 4a1d1589..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2012 by Aleix Pol Gonzalez - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "wallpapersmodel.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -Q_DECLARE_METATYPE(Plasma::Package*); - -WallpapersModel::WallpapersModel(QObject* parent) - : QAbstractListModel(parent) -{ - m_scene = new QGraphicsScene(this); - m_engine = new QDeclarativeEngine(this); - KDeclarative kdeclarative; - kdeclarative.setDeclarativeEngine(m_engine); - kdeclarative.initialize(); - kdeclarative.setupBindings(); -} - -WallpapersModel::~WallpapersModel() -{ - clearCache(); -} - -void WallpapersModel::clearCache() -{ - qDeleteAll(m_packagesItems); -} - -void WallpapersModel::addPackage(const QString& packageRoot, const QString& packageName) -{ - beginInsertRows(QModelIndex(), m_packages.count(), m_packages.count()); - Plasma::PackageStructure::Ptr str = Plasma::PackageStructure::load("Plasma/Generic"); - Plasma::Package* p = new Plasma::Package(packageRoot, packageName, str); - - if (p->isValid() && p->metadata().serviceType()=="Plasma/DeclarativeWallpaper") { - m_packages += p; - QDeclarativeComponent* component = new QDeclarativeComponent(m_engine); - component->loadUrl(QUrl(p->filePath("mainscript"))); - if (component->isReady()) { - QDeclarativeItem* item = qobject_cast(component->create()); - Q_ASSERT(item); - m_packagesItems[p] = item; - item->setWidth(m_scene->width()); - item->setHeight(m_scene->height()); - item->setVisible(false); - m_scene->addItem(item); - } - delete component; - } else { - delete p; - } - endInsertRows(); -} - -QVariant WallpapersModel::data(const QModelIndex& index, int role) const -{ - Plasma::Package* p = m_packages[index.row()]; - switch (role) { - case PackageNameRole: - return p->metadata().pluginName(); - case Qt::DisplayRole: - return p->metadata().name(); - case Qt::ToolTipRole: - return p->metadata().description(); - case Qt::DecorationRole: - return KIcon(p->metadata().icon()); - case BackgroundDelegate::AuthorRole: - return p->metadata().author(); - case BackgroundDelegate::ScreenshotRole: - QDeclarativeItem* it = m_packagesItems.value(p); - if(it) { - QPixmap pix(m_scene->sceneRect().size().toSize()); - pix.fill(Qt::transparent); - QPainter painter(&pix); - it->setVisible(true); - m_scene->render(&painter, QRectF(), QRectF(), Qt::KeepAspectRatio); - it->setVisible(false); - return pix; - } - break; - } - return QVariant(); -} - -int WallpapersModel::rowCount(const QModelIndex& parent) const -{ - return parent.isValid()? 0 : m_packages.count(); -} - -QModelIndex WallpapersModel::indexForPackagePath(const QString& path) -{ - for (int i = 0; ipath()==path) { - return index(i,0); - } - } - return QModelIndex(); -} - -void WallpapersModel::setWallpaperSize(const QSize& size) -{ - float newHeight = ((float)size.height() / (float)size.width()) * BackgroundDelegate::SCREENSHOT_SIZE; - - m_size = QSize(BackgroundDelegate::SCREENSHOT_SIZE, newHeight); - - m_size.scale(BackgroundDelegate::SCREENSHOT_SIZE, BackgroundDelegate::SCREENSHOT_SIZE/1.6, Qt::KeepAspectRatio); - - reload(); -} - -void WallpapersModel::reload(){ - m_scene->setSceneRect(0,0, m_size.width(), m_size.height()); - QStringList dirs(KGlobal::dirs()->findDirs("data", "plasma/wallpapers")); - foreach (const QString &dir, dirs) { - foreach (const QString &package, Plasma::Package::listInstalled(dir)) { - addPackage(dir, package); - } - } -} diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.h b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.h deleted file mode 100644 index 1c449e0b..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersmodel.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012 by Aleix Pol Gonzalez - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef WALLPAPERSMODEL_H -#define WALLPAPERSMODEL_H - -#include -#include -#include -#include -#include "backgrounddelegate.h" - -namespace Plasma { class Package; } - -class WallpapersModel : public QAbstractListModel -{ - Q_OBJECT - public: - enum Roles { - PackageNameRole = BackgroundDelegate::ResolutionRole+1 - }; - - explicit WallpapersModel(QObject* parent = 0); - ~WallpapersModel(); - - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; - QModelIndex indexForPackagePath(const QString& path); - void clearCache(); - void reload(); - void setWallpaperSize(const QSize& size); - - private: - void addPackage(const QString& root, const QString& name); - - QList m_packages; - QMap m_packagesItems; - QDeclarativeEngine* m_engine; - QGraphicsScene* m_scene; - QSize m_size; -}; - -#endif // WALLPAPERSMODEL_H diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.cpp b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.cpp deleted file mode 100644 index 989e898f..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright 2012 by Aleix Pol Gonzalez - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "wallpapersqml.h" -#include "wallpapersmodel.h" -#include "backgrounddelegate.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ui_viewconfig.h" - -K_EXPORT_PLASMA_WALLPAPER(org.kde.wallpaper-qml, WallpaperQml) - -WallpaperQml::WallpaperQml(QObject *parent, const QVariantList &args) - : Plasma::Wallpaper(parent, args) - , m_scene(new QGraphicsScene(this)) - , m_item(0) - , m_package(0) -{ - m_engine = new QDeclarativeEngine(this); - KDeclarative kdeclarative; - kdeclarative.setDeclarativeEngine(m_engine); - kdeclarative.initialize(); - kdeclarative.setupBindings(); - - m_component = new QDeclarativeComponent(m_engine); - connect( - m_component, SIGNAL(statusChanged(QDeclarativeComponent::ComponentStatus)), - this, SLOT(componentStatusChanged(QDeclarativeComponent::ComponentStatus)) - ); - connect(this, SIGNAL(renderHintsChanged()), SLOT(resizeWallpaper())); - connect(m_scene, SIGNAL(changed(QList)), SLOT(shouldRepaint(QList))); -} - -void WallpaperQml::setPackageName(const QString& packageName) -{ - delete m_package; - - kDebug() << "loading package..." << packageName; - m_structure = Plasma::PackageStructure::load("Plasma/Generic"); - QStringList dirs(KGlobal::dirs()->findDirs("data", "plasma/wallpapers")); - foreach (const QString &dir, dirs) { - m_package = new Plasma::Package(dir, packageName, m_structure); - if (m_package->isValid() && !m_package->filePath("mainscript").isEmpty()) { - break; - } else { - delete m_package; - m_package = 0; - } - } - if(m_package) { - QUrl scriptUrl(m_package->filePath("mainscript")); - if (scriptUrl.isValid()) { - m_component->loadUrl(scriptUrl); - m_packageName = packageName; - } else { - m_component->setData("import QtQuick 1.1\n Text { text: 'wrong wallpaper'}", QDir::tempPath()); - } - } else - kWarning() << "couldn't load the package named" << packageName; -} - -void WallpaperQml::componentStatusChanged(QDeclarativeComponent::ComponentStatus s) -{ - if (s==QDeclarativeComponent::Ready) { - if (m_item) { - m_scene->removeItem(m_item); - delete m_item; - } - - m_item = qobject_cast(m_component->create()); - m_item->setSize(targetSizeHint()); - Q_ASSERT(m_item); - m_scene->addItem(m_item); - - resizeWallpaper(); - } else if (s==QDeclarativeComponent::Error) { - delete m_component; - m_component = new QDeclarativeComponent(m_engine); - connect( - m_component, SIGNAL(statusChanged(QDeclarativeComponent::ComponentStatus)), - this, SLOT(componentStatusChanged(QDeclarativeComponent::ComponentStatus)) - ); - } - if (!m_component->errors().isEmpty()) - kDebug() << "wallpaper errors:" << m_component->errors(); -} - -void WallpaperQml::paint(QPainter *painter, const QRectF& exposedRect) -{ - painter->drawPixmap(exposedRect, m_pixmap, exposedRect.translated(-boundingRect().topLeft())); -} - -void WallpaperQml::resizeWallpaper() -{ - m_scene->setSceneRect(QRectF(QPointF(0,0), targetSizeHint())); - if (m_item) { - m_item->setSize(targetSizeHint()); - } - m_pixmap = QPixmap(targetSizeHint().toSize()); - m_pixmap.fill(m_scene->backgroundBrush().color()); - QPainter p(&m_pixmap); - m_scene->render(&p, QRectF(), QRectF(), Qt::IgnoreAspectRatio); - p.end(); - emit update(QRectF()); -} - -void WallpaperQml::shouldRepaint(const QList &rects) -{ - QRectF repaintRect(0,0,0,0); - foreach (const QRectF& rect, rects) { - repaintRect = repaintRect.united(rect); - } - - if (!repaintRect.isEmpty()) { - QPainter p(&m_pixmap); - m_scene->render(&p, repaintRect, repaintRect, Qt::IgnoreAspectRatio); - p.end(); - emit update(repaintRect); - } -} - -QWidget* WallpaperQml::createConfigurationInterface(QWidget* parent) -{ - QWidget* w = new QWidget; - Ui::ViewConfig v; - v.setupUi(w); - - WallpapersModel* m = new WallpapersModel(w); - m->setWallpaperSize(targetSizeHint().toSize()); - - v.m_view->setModel(m); - v.m_view->setItemDelegate(new BackgroundDelegate(v.m_view)); - if (m_package) { - v.m_view->setCurrentIndex(m->indexForPackagePath(m_package->path())); - m_packageName = m_package->metadata().pluginName(); - } - v.m_color->setColor(m_scene->backgroundBrush().color()); - - connect(v.m_view->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), SLOT(changeWallpaper(QModelIndex))); - connect(v.m_color, SIGNAL(changed(QColor)), this, SLOT(setBackgroundColor(QColor))); - connect(this, SIGNAL(changed(bool)), parent, SLOT(settingsChanged(bool))); - return w; -} - -void WallpaperQml::changeWallpaper(const QModelIndex& idx) -{ - m_packageName = idx.data(WallpapersModel::PackageNameRole).toString(); - emit changed(true); -} - -void WallpaperQml::init(const KConfigGroup& config) -{ - setPackageName(config.readEntry("packageName", "org.kde.hunyango")); - setBackgroundColor(config.readEntry("color", QColor(Qt::transparent))); - emit changed(false); -} - -void WallpaperQml::save(KConfigGroup& config) -{ - config.writeEntry("packageName", m_packageName); - config.writeEntry("color", m_scene->backgroundBrush().color()); - config.sync(); - emit changed(false); -} - -void WallpaperQml::setBackgroundColor(const QColor& color) -{ - m_scene->setBackgroundBrush(color); - emit changed(false); -} - -void WallpaperQml::mouseMoveEvent(QGraphicsSceneMouseEvent* event) -{ - QApplication::sendEvent(m_scene, event); -} - -void WallpaperQml::mousePressEvent(QGraphicsSceneMouseEvent* event) -{ - QApplication::sendEvent(m_scene, event); -} - -void WallpaperQml::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) -{ - QApplication::sendEvent(m_scene, event); -} - -void WallpaperQml::wheelEvent(QGraphicsSceneWheelEvent* event) -{ - QApplication::sendEvent(m_scene, event); -} diff --git a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.h b/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.h deleted file mode 100644 index e5914750..00000000 --- a/kdeplasma-addons/wallpapers/qmlwallpapers/wallpapersqml.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2012 by Aleix Pol Gonzalez - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef WALLPAPERQML_H -#define WALLPAPERQML_H - -#include -#include - -#include -#include - -class WallpaperQml : public Plasma::Wallpaper -{ - Q_OBJECT - public: - WallpaperQml(QObject* parent, const QVariantList& args); - - virtual void paint(QPainter* painter, const QRectF& exposedRect); - virtual QWidget* createConfigurationInterface(QWidget* parent); - virtual void save(KConfigGroup& config); - virtual void init(const KConfigGroup& config); - - private slots: - void resizeWallpaper(); - void shouldRepaint(const QList< QRectF >& rects); - void componentStatusChanged(QDeclarativeComponent::ComponentStatus s); - void setPackageName(const QString& name); - void changeWallpaper(const QModelIndex& idx); - void setBackgroundColor(const QColor& color); - - signals: - void changed(bool hasChanged=true); - - private: - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event); - virtual void mousePressEvent(QGraphicsSceneMouseEvent* event); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); - virtual void wheelEvent(QGraphicsSceneWheelEvent* event); - - QGraphicsScene* m_scene; - QDeclarativeItem* m_item; - QDeclarativeComponent* m_component; - Plasma::Package* m_package; - Plasma::PackageStructure::Ptr m_structure; - QPixmap m_pixmap; - QDeclarativeEngine* m_engine; - QString m_packageName; -}; - -#endif diff --git a/kemu/kemu.desktop b/kemu/kemu.desktop index ede843e4..7ff1b739 100644 --- a/kemu/kemu.desktop +++ b/kemu/kemu.desktop @@ -8,4 +8,3 @@ Terminal=false Type=Application Categories=Qt;KDE;System; StartupNotify=true -X-KDE-HasTrayOption=true diff --git a/kget/CMakeLists.txt b/kget/CMakeLists.txt deleted file mode 100644 index 2f61a9e7..00000000 --- a/kget/CMakeLists.txt +++ /dev/null @@ -1,235 +0,0 @@ -project(kget) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - include(FeatureSummary) - - find_package(KDELibs4 4.23.0 REQUIRED) - - include_directories(${KDE4_INCLUDES}) - add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -endif() - -include(CheckIncludeFile) -include(CheckIncludeFiles) -include(CheckSymbolExists) -include(CheckFunctionExists) -include(CheckLibraryExists) -include(CheckTypeSize) - -include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}) - -kde4_optional_find_package(LibTorrent) -set_package_properties(LibTorrent PROPERTIES - DESCRIPTION "Feature complete C++ bittorrent implementation focusing on efficiency and scalability" - URL "https://libtorrent.org/" - PURPOSE "Needed to build KGet torrent support" -) - -kde4_optional_find_package(KDE4Workspace) -set_package_properties(KDE4Workspace PROPERTIES - DESCRIPTION "KDE base workspace libraries" - URL "https://osdn.net/projects/kde/" - PURPOSE "Allows 'shutdown after downloads completed' in KGet" -) - -set(kget_adaptor_SRCS - dbus/dbuskgetwrapper.cpp -) -# set(kget_transfer_adaptor_SRCS -# core/transferhandler.cpp -# core/transfertreemodel.cpp -# ) - -add_definitions(-DKDE_DEFAULT_DEBUG_AREA=5001) - -# TODO: utterly broken -set(KGET_TESTING FALSE) - -set(SUPPORTED_KGET_MIMETYPES "application/x-kgetlist;") - -if(KGET_TESTING) - add_definitions(-DDO_KGET_TEST) -endif() - -add_subdirectory(core) -add_subdirectory(ui) -add_subdirectory(transfer-plugins) -add_subdirectory(extensions) -add_subdirectory(desktop) -add_subdirectory(plasma) -if(KGET_TESTING) - add_subdirectory(tests) -endif() - -if(KDE4WORKSPACE_FOUND) - add_definitions(-DHAVE_KWORKSPACE) -endif() - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/core/ - ${CMAKE_CURRENT_BINARY_DIR}/core/ - ${CMAKE_CURRENT_BINARY_DIR} -) - -# kgetcore - -set(kgetcore_SRCS - core/job.cpp - core/jobqueue.cpp - core/kget.cpp - core/scheduler.cpp - core/transfertreemodel.cpp - core/transfertreeselectionmodel.cpp - core/transfer.cpp - core/transfergroup.cpp - core/transfergrouphandler.cpp - core/transferhandler.cpp - core/handler.cpp - core/transfergroupscheduler.cpp - core/plugin/plugin.cpp - core/plugin/transferfactory.cpp - core/transferdatasource.cpp - core/kgetkjobadapter.cpp - core/kuiserverjobs.cpp - core/kgetglobaljob.cpp - core/download.cpp - core/transferhistorystore.cpp - core/transferhistorystore_xml.cpp - core/transferhistorystore_json.cpp - core/linkimporter.cpp - dbus/dbustransferwrapper.cpp - dbus/dbusverifierwrapper.cpp - core/filemodel.cpp - core/verifier.cpp - core/verificationthread.cpp - core/verificationmodel.cpp - core/verificationdelegate.cpp - core/urlchecker.cpp - core/basedialog.cpp - core/mostlocalurl.cpp - core/filedeleter.cpp -) - -kde4_add_kcfg_files(kgetcore_SRCS conf/settings.kcfgc) - -qt4_add_dbus_adaptor(kgetcore_SRCS dbus/org.kde.kget.transfer.xml dbus/dbustransferwrapper.h DBusTransferWrapper) -qt4_add_dbus_adaptor(kgetcore_SRCS dbus/org.kde.kget.verifier.xml dbus/dbusverifierwrapper.h DBusVerifierWrapper) - -add_library(kgetcore SHARED ${kgetcore_SRCS}) - -target_link_libraries(kgetcore - KDE4::kio - KDE4::knetworkmanager - KDE4::solid -) - -if (KDE4WORKSPACE_FOUND) - target_link_libraries(kgetcore KDE4Workspace::kworkspace) -endif (KDE4WORKSPACE_FOUND) - -set_target_properties(kgetcore PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -install( - TARGETS kgetcore - DESTINATION ${KDE4_LIB_INSTALL_DIR} -) - -# kget - -set(kget_SRCS ${kget_adaptor_SRCS} ${kget_transfer_adaptor_SRCS} - conf/autopastemodel.cpp - conf/integrationpreferences.cpp - conf/dlgwebinterface.cpp - conf/preferencesdialog.cpp - conf/transfersgrouptree.cpp - conf/transfersgroupwidget.cpp - conf/pluginselector.cpp - conf/verificationpreferences.cpp - ui/droptarget.cpp - ui/transfersview.cpp - ui/transfersviewdelegate.cpp - ui/transferdetails.cpp - ui/viewscontainer.cpp - ui/newtransferdialog.cpp - ui/groupsettingsdialog.cpp - ui/transfersettingsdialog.cpp - ui/contextmenu.cpp - ui/tray.cpp - ui/history/rangetreewidget.cpp - ui/history/transferhistory.cpp - ui/history/transferhistoryitemdelegate.cpp - ui/history/transferhistorycategorizeddelegate.cpp - ui/history/transferhistorycategorizedview.cpp - ui/linkview/kget_linkview.cpp - ui/linkview/kget_sortfilterproxymodel.cpp - ui/mirror/mirrorsettings.cpp - ui/mirror/mirrormodel.cpp - ui/renamefile.cpp - ui/verificationdialog.cpp - mainwindow.cpp - main.cpp - - extensions/webinterface/httpserver.cpp - - conf/dlgadvanced.ui - conf/dlgappearance.ui - conf/dlggroups.ui - conf/dlgintegration.ui - conf/dlgwebinterface.ui - conf/dlgnetwork.ui - conf/verificationpreferences.ui - ui/transferdetailsfrm.ui - ui/newtransferwidget.ui - ui/history/transferhistory.ui - ui/groupsettingsdialog.ui - ui/transfersettingsdialog.ui - ui/linkview/importlinkdialog.ui - ui/mirror/mirrorsettings.ui - ui/mirror/mirroradddlg.ui - ui/renamefile.ui - ui/verificationdialog.ui - ui/verificationadddlg.ui -) - -if(KGET_TESTING) - set(kget_SRCS - ${kget_SRCS} - tests/testkget.cpp - ) -endif() - -qt4_add_dbus_adaptor(kget_SRCS dbus/org.kde.kget.main.xml dbus/dbuskgetwrapper.h DBusKGetWrapper) - -add_executable(kget ${kget_SRCS}) - -target_link_libraries(kget - KDE4::kdeui - KDE4::kio - KDE4::kcmutils - KDE4::kpasswdstore - kgetcore -) - -if (KGET_TESTING) - target_link_libraries(kget - ${QT_QTTEST_LIBRARY} - ) -endif() - -install( - TARGETS kget - DESTINATION ${KDE4_BIN_INSTALL_DIR} -) - -install( - FILES kget.notifyrc - DESTINATION ${KDE4_CONFIG_INSTALL_DIR}/notifications -) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) -endif() diff --git a/kget/COPYING b/kget/COPYING deleted file mode 100644 index 8900e10b..00000000 --- a/kget/COPYING +++ /dev/null @@ -1,347 +0,0 @@ -NOTE! The GPL below is copyrighted by the Free Software Foundation, but -the instance of code that it refers to (the kde programs) are copyrighted -by the authors who actually wrote it. - ---------------------------------------------------------------------------- - - 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 Library 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) 19yy - - 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) 19yy 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 Library General -Public License instead of this License. diff --git a/kget/COPYING.LIB b/kget/COPYING.LIB deleted file mode 100644 index 2d2d780e..00000000 --- a/kget/COPYING.LIB +++ /dev/null @@ -1,510 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations -below. - - When we speak of free software, we are referring to freedom of use, -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 and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it -becomes a de-facto standard. To achieve this, non-free programs must -be allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control -compilation and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least - three years, to give the same user the materials specified in - Subsection 6a, above, for a charge no more than the cost of - performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply, and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License -may add an explicit geographical distribution limitation excluding those -countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms -of the ordinary General Public License). - - To apply these terms, attach the following notices to the library. -It is safest to attach them to the start of each source file to most -effectively convey the exclusion of warranty; and each file should -have at least the "copyright" line and a pointer to where the full -notice is found. - - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the library, -if necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James - Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/kget/HACKING b/kget/HACKING deleted file mode 100644 index 33153f44..00000000 --- a/kget/HACKING +++ /dev/null @@ -1,150 +0,0 @@ -This file has been copied from the kicker HACKING file from Aaron Seigo. - -While you may notice that there are many discrepencies between -the code and this document, all new development should -follow the coding style as described below amd one day the codebase will -actually be consistent! - -Naming Conventions ------------------- -Class names start with a capital letter, member variables begin with m_. -Methods and functions start with a lower case letter. - - -Indenting ---------- -Tabstop is 4 spaces. No tabs, only spaces. - -Try to keep lines under 80 characters in width. When wrapping a single -logical line of code across multiple lines, new lines should be indented -at least once and should preferably line up with parentheses, if any, on -the line above. e.g.: - - someMethod(parameterOne, parameterTwo, - parameterThree, parameterFour); - -If a boolean expression is spread out over several lines, the boolean -operator is always the last item on the line, e.g.: - - if ((condition1 || condition2) && - condition3 && - (condition4 || condition5)) - { - -Switch statements should have the case line indented and the case block -itsel further indented, e.g.: - - switch (condition) - { - case 1: - ... - break; - case 2: - ... - break; - default: - ...; - } - -Spaces ------- -A single space should appear between keywords and parentheses, eg: - - if ( - while ( - for ( - -No spaces appear between function/method names and parentheses: - - function( - someObject->method( - -No spaces appear between opening closing parens and the arguments: - - for (int i = 0; i < count; ++i) - -Spaces appear between operators, e.g.: - - int i = i + 3; - someObject.setValue(someObject.currentValue() + 1) - - -Braces ------- -Braces always appear on a line by themself, indented to align with the -above keyword: - - if (foo) - { - ... - } - else - { - ... - } - -Unless it uglifies the code, use braces even for one-liner conditionals: - - if (foo) - { - return 1; - } - -Always use braces if the conditional expression wraps across multiple -physical lines. - -Braces around case blocks in switch statements are optional. - - -Constructors ------------- -Constructors are written as: - - MyClass::MyClass(...) - : SuperClass(...), - m_member1(...), - m_member2(...), - ... - { - - -Class Definitions ------------------ -Class definitions will follow the following order: - - class : - { - public: - - - - - - - - public slots: - - - signals: - - - protected: - - - - - - - protected slots: - - - private: - - - - - - - private slots: - - }; diff --git a/kget/Messages.sh b/kget/Messages.sh deleted file mode 100755 index 4e3f1e47..00000000 --- a/kget/Messages.sh +++ /dev/null @@ -1,7 +0,0 @@ -#! /bin/sh -kget_subdirs="conf core dbus transfer-plugins ui extensions/webinterface" -$EXTRACTRC `find $kget_subdirs -name \*.ui` >> rc.cpp || exit 11 -$EXTRACTRC `find $kget_subdirs -name \*.rc` >> rc.cpp || exit 12 -$EXTRACTRC `find $kget_subdirs -name \*.kcfg` >> rc.cpp || exit 13 -$XGETTEXT `find $kget_subdirs -name \*.cpp -o -name \*.h` *.cpp *.h -o $podir/kget.pot -rm -f rc.cpp diff --git a/kget/conf/autopastemodel.cpp b/kget/conf/autopastemodel.cpp deleted file mode 100644 index 267fecba..00000000 --- a/kget/conf/autopastemodel.cpp +++ /dev/null @@ -1,353 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 "autopastemodel.h" -#include "settings.h" - -#include -#include -#include -#include - -AutoPasteDelegate::AutoPasteDelegate(QAbstractItemModel *types, QAbstractItemModel *syntaxes, QObject *parent) - : QStyledItemDelegate(parent), - m_types(types), - m_syntaxes(syntaxes) -{ -} - -QWidget *AutoPasteDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - - if (!index.isValid()) { - return 0; - } - - switch(index.column()) { - case AutoPasteModel::Type: { - KComboBox *types = new KComboBox(parent); - types->setModel(m_types); - return types; - } - case AutoPasteModel::Pattern: { - KLineEdit *pattern = new KLineEdit(parent); - return pattern; - } - case AutoPasteModel::PatternSyntax: { - KComboBox *syntaxes = new KComboBox(parent); - syntaxes->setModel(m_syntaxes); - return syntaxes; - } - default: - return 0; - } -} - -void AutoPasteDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (!index.isValid() || !editor) { - return; - } - - switch (index.column()) { - case AutoPasteModel::Type: { - KComboBox *type = static_cast(editor); - const int row = type->findData(index.data(Qt::EditRole)); - type->setCurrentIndex(row); - break; - } - case AutoPasteModel::Pattern: { - KLineEdit *line = static_cast(editor); - line->setText(index.data(Qt::EditRole).toString()); - break; - } - case AutoPasteModel::PatternSyntax: { - KComboBox *syntax = static_cast(editor); - const int row = syntax->findData(index.data(Qt::EditRole)); - syntax->setCurrentIndex(row); - break; - } - default: - break; - } -} - -void AutoPasteDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (!index.isValid() || !editor || !model) { - return; - } - - switch (index.column()) { - case AutoPasteModel::Type: { - KComboBox *typeBox = static_cast(editor); - const int type = typeBox->itemData(typeBox->currentIndex()).toInt(); - model->setData(index, type); - break; - } - case AutoPasteModel::Pattern: { - KLineEdit *line = static_cast(editor); - const QString text = line->text(); - if (!text.isEmpty()) { - model->setData(index, text); - } - break; - } - case AutoPasteModel::PatternSyntax: { - KComboBox *syntaxBox = static_cast(editor); - const int syntax = syntaxBox->itemData(syntaxBox->currentIndex()).toInt(); - model->setData(index, syntax); - break; - } - default: - break; - } -} - -void AutoPasteDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(index) - editor->setGeometry(option.rect); -} - -QSize AutoPasteDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - //make the sizeHint a little bit nicer to have more beautiful editors - QSize hint; - hint.setWidth(QStyledItemDelegate::sizeHint(option, index).width()); - hint.setHeight(option.fontMetrics.height() + 7); - return hint; -} - -AutoPasteModel::AutoPasteModel(QObject *parent) - : QAbstractTableModel(parent) -{ -} - -AutoPasteModel::~AutoPasteModel() -{ -} - -int AutoPasteModel::rowCount(const QModelIndex &index) const -{ - if (!index.isValid()) { - return m_data.count(); - } - - return 0; -} - -int AutoPasteModel::columnCount(const QModelIndex &index) const -{ - if (!index.isValid()) { - return 3; - } - - return 0; -} - -QVariant AutoPasteModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Vertical) { - return QVariant(); - } - - if (role == Qt::DisplayRole) { - if (section == Pattern) { - return i18n("Pattern"); - } else if (section == PatternSyntax) { - return i18n("Syntax"); - } - } - - return QVariant(); -} - -QVariant AutoPasteModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) { - return QVariant(); - } - - const int column = index.column(); - const int row = index.row(); - - switch (column) { - case Type: { - if (role == Qt::DecorationRole) { - return (m_data[row].type == Include ? KIcon("list-add") : KIcon("list-remove")); - } else if ((role == Qt::UserRole) || (role == Qt::EditRole)) { - return m_data[row].type; - } - break; - } - case Pattern: { - if ((role == Qt::DisplayRole) || (role == Qt::EditRole) || (role == Qt::UserRole)) { - return m_data[row].pattern; - } - break; - } - case PatternSyntax: { - if (role == Qt::DisplayRole) { - return (m_data[row].syntax == Wildcard ? i18n("Escape sequences") : i18n("Regular expression")); - } else if ((role == Qt::UserRole) || (role == Qt::EditRole)) { - return m_data[row].syntax; - } - break; - } - default: - return QVariant(); - } - - return QVariant(); -} - -Qt::ItemFlags AutoPasteModel::flags(const QModelIndex &index) const -{ - Q_UNUSED(index) - - return (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); -} - -bool AutoPasteModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (role != Qt::EditRole) { - return false; - } - - const int row = index.row(); - const int column = index.column(); - - switch (column) { - case Type: { - m_data[row].type = static_cast(value.toInt()); - break; - } - case Pattern: { - m_data[row].pattern = value.toString(); - break; - } - case PatternSyntax: { - m_data[row].syntax = static_cast(value.toInt()); - break; - } - default: - return false; - } - - emit dataChanged(index, index); - return true; -} - -bool AutoPasteModel::removeRows(int row, int count, const QModelIndex &parent) -{ - if (parent.isValid() || (row < 0) || (count < 1) || (row + count > rowCount())) { - return false; - } - - beginRemoveRows(parent, row, row + count - 1); - while (count) { - m_data.removeAt(row); - --count; - } - endRemoveRows(); - - return true; -} - -void AutoPasteModel::addItem(TypeData dataType, PatternSyntaxData patternSyntax, const QString &pattern) -{ - addItems(QList() << dataType, QList() << patternSyntax, QStringList() << pattern); -} - -void AutoPasteModel::addItems(const QList &dataTypes, const QList patternSyntaxes, const QStringList &patterns) -{ - const int row = rowCount(); - const int numItems = patterns.count(); - beginInsertRows(QModelIndex(), row, row + numItems - 1); - - for (int i = 0; i < numItems; ++i) { - Data data; - data.type = static_cast(dataTypes[i]); - data.pattern = patterns[i]; - data.syntax = static_cast(patternSyntaxes[i]); - m_data.append(data); - } - - endInsertRows(); -} - -bool AutoPasteModel::moveItem(int sourceRow, int destinationRow) -{ - if (!beginMoveRows(QModelIndex(), sourceRow, sourceRow, QModelIndex(), destinationRow)) { - return false; - } - - //beginMoveRows asks for different data, than QList::move does, see the 4.7 docs - if (sourceRow + 2 == destinationRow) { - --destinationRow; - } - m_data.move(sourceRow, destinationRow); - endMoveRows(); - - return true; -} - -void AutoPasteModel::load() -{ - //remove all old items if there are any - if (rowCount()) { - beginRemoveRows(QModelIndex(), 0, rowCount() - 1); - m_data.clear(); - endRemoveRows(); - } - addItems(Settings::autoPasteTypes(), Settings::autoPastePatternSyntaxes(), Settings::autoPastePatterns()); -} - -void AutoPasteModel::save() -{ - QList types; - QList syntaxes; - QStringList patterns; - foreach (const Data &data, m_data) { - types << data.type; - syntaxes << data.syntax; - patterns << data.pattern; - } - - Settings::self()->setAutoPasteTypes(types); - Settings::self()->setAutoPastePatternSyntaxes(syntaxes); - Settings::self()->setAutoPastePatterns(patterns); - Settings::self()->writeConfig(); -} - -void AutoPasteModel::resetDefaults() -{ - QStringList names = QStringList() << "AutoPastePatterns" << "AutoPasteTypes" << "AutoPastePatternSyntaxes"; - foreach (const QString &name, names) { - KConfigSkeletonItem *item = Settings::self()->findItem(name); - if (item) { - item->readDefault(Settings::self()->config()); - } - } - - load(); -} - diff --git a/kget/conf/autopastemodel.h b/kget/conf/autopastemodel.h deleted file mode 100644 index d2c8dcb3..00000000 --- a/kget/conf/autopastemodel.h +++ /dev/null @@ -1,123 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 AUTOPASTEMODEL -#define AUTOPASTEMODEL - -#include -#include - -class AutoPasteDelegate : public QStyledItemDelegate -{ - Q_OBJECT - - public: - AutoPasteDelegate(QAbstractItemModel *types, QAbstractItemModel *syntaxes, QObject *parent = 0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - - private: - QAbstractItemModel *m_types; - QAbstractItemModel *m_syntaxes; -}; - -class AutoPasteModel : public QAbstractTableModel -{ - Q_OBJECT - - public: - enum DataType { - Type = 0, - Pattern, - PatternSyntax - }; - enum TypeData { - Include = 0, - Exclude - }; - enum PatternSyntaxData { - Wildcard = 0, - RegExp - }; - - explicit AutoPasteModel(QObject *parent = 0); - ~AutoPasteModel(); - - int rowCount(const QModelIndex &index = QModelIndex()) const; - int columnCount(const QModelIndex &index = QModelIndex()) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - - /** - * Adds an an item - * @note do not use this for loading data - * @see load() - */ - void addItem(TypeData dataType, PatternSyntaxData patternSyntax, const QString &pattern); - - /** - * Moves an item to a new position - * @param sourceRow the current row of the selected item - * @param destinationRow is the new row before the move, - * i.e. if sourceRow was not removed from the model - * @see QAbstractItemModel::beginMoveRows() - */ - bool moveItem(int sourceRow, int destinationRow); - - public slots: - /** - * Loads the stored data - * @see save() - */ - void load(); - - /** - * Saves the current data - * @see load() - */ - void save(); - - /** - * Resets the model to the default data - */ - void resetDefaults(); - - private: - void addItems(const QList &dataTypes, const QList patternSyntaxes, const QStringList &patterns); - - private: - struct Data - { - TypeData type; - QString pattern; - PatternSyntaxData syntax; - }; - - QList m_data; -}; - -#endif - diff --git a/kget/conf/dlgadvanced.ui b/kget/conf/dlgadvanced.ui deleted file mode 100644 index 992ff103..00000000 --- a/kget/conf/dlgadvanced.ui +++ /dev/null @@ -1,162 +0,0 @@ - - - DlgAdvanced - - - - 0 - 0 - 585 - 443 - - - - - - - Enable system tray icon - - - - - - - - - Execute action after all downloads have been finished: - - - - - - - - Quit KGet - - - - - - - - At startup: - - - - - - - - Restore Download State - - - - - Start All Downloads - - - - - Stop All Downloads - - - - - - - - - - - History backend: - - - - - - - - - Enable KDE Global Progress Tracking - - - true - - - false - - - - - - Show every single download - - - - - - - Show overall progress - - - - - - - - - - Handle existing Files/Transfers - - - - - - Always ask - - - - - - - Automatic rename - - - - - - - Overwrite - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 200 - 20 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
-
- -
diff --git a/kget/conf/dlgappearance.ui b/kget/conf/dlgappearance.ui deleted file mode 100644 index da94d9ac..00000000 --- a/kget/conf/dlgappearance.ui +++ /dev/null @@ -1,55 +0,0 @@ - - - DlgAppearance - - - - 0 - 0 - 507 - 381 - - - - - - - Use Drop Target - - - true - - - false - - - - - - Enable animations - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 349 - 70 - - - - - - - - diff --git a/kget/conf/dlggroups.ui b/kget/conf/dlggroups.ui deleted file mode 100644 index 4225f5b4..00000000 --- a/kget/conf/dlggroups.ui +++ /dev/null @@ -1,94 +0,0 @@ - - - DlgGroups - - - - 0 - 0 - 531 - 322 - - - - - - - Use default folders for groups as suggestion - - - - - - - Ask for destination if there are no default folders - - - - - - - true - - - QAbstractItemView::ExtendedSelection - - - false - - - false - - - - - - - - - - - - Rename - - - - - - - - - - Select Icon... - - - 16 - - - - - - - - - - - - - KIconButton - QPushButton -
kicondialog.h
-
- - KPushButton - QPushButton -
kpushbutton.h
-
- - TransfersGroupTree - QTreeView -
conf/transfersgrouptree.h
-
-
- -
diff --git a/kget/conf/dlgintegration.ui b/kget/conf/dlgintegration.ui deleted file mode 100644 index b8c6ab6e..00000000 --- a/kget/conf/dlgintegration.ui +++ /dev/null @@ -1,137 +0,0 @@ - - - DlgIntegration - - - - 0 - 0 - 558 - 293 - - - - - - - Monitor Clipboard for Files to Download - - - true - - - false - - - - - - Case sensitive: - - - - - - - - - - - - - - - - - - - - - - true - - - true - - - - - - - - - - - QAbstractItemView::ExtendedSelection - - - false - - - true - - - - - - - - - - - - - - - &Increase Priority - - - - - - - &Decrease Priority - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KPushButton - QPushButton -
kpushbutton.h
-
-
- -
diff --git a/kget/conf/dlgnetwork.ui b/kget/conf/dlgnetwork.ui deleted file mode 100644 index 25905d46..00000000 --- a/kget/conf/dlgnetwork.ui +++ /dev/null @@ -1,184 +0,0 @@ - - - DlgNetwork - - - - 0 - 0 - 349 - 437 - - - - - - - - - Maximum downloads per group: - - - - - - - No limit - - - - - - - - - Speed Limit - - - true - - - - - - Global &download limit: - - - kcfg_GlobalDownloadLimit - - - - - - - KiB/s - - - 1000000 - - - 5 - - - 10 - - - - - - - Global &upload limit: - - - kcfg_GlobalUploadLimit - - - - - - - KiB/s - - - 1000000 - - - 5 - - - 10 - - - - - - - Per transfer: - - - - - - - KiB/s - - - 1000000 - - - 5 - - - - - - - - - - Reconnect on Broken Connection - - - true - - - - - - Number of retries: - - - - - - - true - - - - - - - Retry after: - - - - - - - sec - - - 10 - - - 86400 - - - 5 - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Expanding - - - - 200 - 16 - - - - - - - - diff --git a/kget/conf/dlgwebinterface.cpp b/kget/conf/dlgwebinterface.cpp deleted file mode 100644 index f60ff9ff..00000000 --- a/kget/conf/dlgwebinterface.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Urs Wolfer - - 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. -*/ - -#include "dlgwebinterface.h" - -#include "core/kget.h" -#include "mainwindow.h" -#include "extensions/webinterface/httpserver.h" -#include "settings.h" - -#include -#include - -DlgWebinterface::DlgWebinterface(KDialog *parent) - : QWidget(parent), - m_passwdstore(nullptr) -{ - setupUi(this); - - readConfig(); - - connect(parent, SIGNAL(accepted()), SLOT(saveSettings())); - connect(webinterfacePwd, SIGNAL(textChanged(QString)), SIGNAL(changed())); -} - -DlgWebinterface::~DlgWebinterface() -{ -} - -void DlgWebinterface::readConfig() -{ - if (Settings::webinterfaceEnabled()) { - if (!m_passwdstore) { - m_passwdstore = new KPasswdStore(this); - m_passwdstore->setStoreID("KGet"); - } - - if (m_passwdstore->openStore(winId())) { - webinterfacePwd->setText(m_passwdstore->getPasswd("Webinterface", winId())); - } else { - KMessageBox::error(nullptr, i18n("Could not open KPasswdStore")); - } - } - - QString webaddress; - if (KGet::m_mainWindow && KGet::m_mainWindow->m_webinterface) { - webaddress = KGet::m_mainWindow->m_webinterface->address(); - } - if (!webaddress.isEmpty()) { - serverLabel->setText(i18n("The server can be accessed at %1.", webaddress)); - } else { - serverLabel->setText(QString()); - } -} - -void DlgWebinterface::saveSettings() -{ - if (kcfg_WebinterfaceEnabled->isChecked()) { - if (!m_passwdstore) { - m_passwdstore = new KPasswdStore(this); - m_passwdstore->setStoreID("KGet"); - } - - if (m_passwdstore->openStore(winId())) { - m_passwdstore->storePasswd("Webinterface", webinterfacePwd->text(), winId()); - } - } - emit saved(); -} - -#include "moc_dlgwebinterface.cpp" diff --git a/kget/conf/dlgwebinterface.h b/kget/conf/dlgwebinterface.h deleted file mode 100644 index f1b54f69..00000000 --- a/kget/conf/dlgwebinterface.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Urs Wolfer - - 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. -*/ - -#ifndef DLGWEBINTERFACE_H -#define DLGWEBINTERFACE_H - -#include -#include -#include - -#include "ui_dlgwebinterface.h" - -class DlgWebinterface : public QWidget, public Ui::DlgWebinterface -{ - Q_OBJECT - -public: - DlgWebinterface(KDialog *parent = 0); - ~DlgWebinterface(); - -signals: - void changed(); - void saved(); - -private Q_SLOTS: - void readConfig(); - void saveSettings(); - -private: - KPasswdStore *m_passwdstore; -}; - -#endif diff --git a/kget/conf/dlgwebinterface.ui b/kget/conf/dlgwebinterface.ui deleted file mode 100644 index 11920eb0..00000000 --- a/kget/conf/dlgwebinterface.ui +++ /dev/null @@ -1,113 +0,0 @@ - - - DlgWebinterface - - - - 0 - 0 - 400 - 389 - - - - - 0 - - - - - Enable Web Interface - - - true - - - false - - - - - - Port: - - - - - - - 100000 - - - - - - - User: - - - - - - - true - - - - - - - Password: - - - - - - - true - - - true - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - Qt::AlignHCenter|Qt::AlignVCenter - - - true - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
-
- -
diff --git a/kget/conf/integrationpreferences.cpp b/kget/conf/integrationpreferences.cpp deleted file mode 100644 index cd6bf82d..00000000 --- a/kget/conf/integrationpreferences.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 "integrationpreferences.h" -#include "autopastemodel.h" -#include "settings.h" - -#include -#include - -IntegrationPreferences::IntegrationPreferences(KConfigDialog *parent, Qt::WindowFlags f) - : QWidget(parent, f) -{ - ui.setupUi(this); - - //AutoPaste stuff - ui.type->addItem(KIcon("list-add"), i18n("Include"), AutoPasteModel::Include); - ui.type->addItem(KIcon("list-remove"), i18n("Exclude"), AutoPasteModel::Exclude); - - ui.patternSyntax->addItem(i18n("Escape sequences"), AutoPasteModel::Wildcard); - ui.patternSyntax->addItem(i18n("Regular expression"), AutoPasteModel::RegExp); - - ui.add->setGuiItem(KStandardGuiItem::add()); - ui.remove->setGuiItem(KStandardGuiItem::remove()); - ui.increase->setIcon(KIcon("arrow-up")); - ui.decrease->setIcon(KIcon("arrow-down")); - - m_model = new AutoPasteModel(this); - m_model->load(); - ui.list->setModel(m_model); - AutoPasteDelegate *delegate = new AutoPasteDelegate(ui.type->model(), ui.patternSyntax->model(), this); - ui.list->setItemDelegate(delegate); - - QByteArray loadedState = QByteArray::fromBase64(Settings::autoPasteHeaderState().toAscii()); - if (Settings::autoPasteHeaderState().isEmpty()) { - ui.list->resizeColumnToContents(AutoPasteModel::Type); - } else if (!loadedState.isNull()) { - ui.list->header()->restoreState(loadedState); - } - - connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SIGNAL(changed())); - connect(ui.list->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(slotUpdateButtons())); - connect(ui.pattern, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons())); - connect(ui.pattern, SIGNAL(returnPressed(QString)), this, SLOT(slotAddItem())); - connect(ui.add, SIGNAL(clicked()), this, SLOT(slotAddItem())); - connect(ui.remove, SIGNAL(clicked()), this, SLOT(slotRemoveItem())); - connect(ui.increase, SIGNAL(clicked()), this, SLOT(slotIncreasePriority())); - connect(ui.decrease, SIGNAL(clicked()), this, SLOT(slotDecreasePriority())); - connect(parent, SIGNAL(rejected()), m_model, SLOT(load())); - connect(parent, SIGNAL(applyClicked()), m_model, SLOT(save())); - connect(parent, SIGNAL(okClicked()), m_model, SLOT(save())); - connect(parent, SIGNAL(defaultClicked()), m_model, SLOT(resetDefaults())); - - slotUpdateButtons(); -} - -IntegrationPreferences::~IntegrationPreferences() -{ -} - -void IntegrationPreferences::slotUpdateButtons() -{ - ui.add->setEnabled(!ui.pattern->text().isEmpty()); - ui.remove->setEnabled(ui.list->selectionModel()->hasSelection()); - - const QModelIndex index = ui.list->currentIndex(); - const bool indexValid = index.isValid() && (ui.list->selectionModel()->selectedRows().count() == 1); - ui.increase->setEnabled(indexValid && (index.row() > 0)); - ui.decrease->setEnabled(indexValid && (m_model->rowCount() > (index.row() + 1))); -} - -void IntegrationPreferences::slotAddItem() -{ - const QString pattern = ui.pattern->text(); - if (pattern.isEmpty()) { - return; - } - - AutoPasteModel::TypeData type = static_cast(ui.type->itemData(ui.type->currentIndex()).toInt()); - AutoPasteModel::PatternSyntaxData syntax = static_cast(ui.patternSyntax->itemData(ui.patternSyntax->currentIndex()).toInt()); - m_model->addItem(type, syntax, pattern); - - ui.pattern->clear(); - ui.pattern->setFocus(); - emit changed(); -} - -void IntegrationPreferences::slotRemoveItem() -{ - QItemSelectionModel *selection = ui.list->selectionModel(); - if (selection->hasSelection()) { - while (selection->selectedRows().count()) { - const QModelIndex index = selection->selectedRows().first(); - m_model->removeRow(index.row()); - } - emit changed(); - } -} - -void IntegrationPreferences::slotIncreasePriority() -{ - const int row = ui.list->currentIndex().row(); - m_model->moveItem(row, row - 1); - slotUpdateButtons(); - emit changed(); -} - -void IntegrationPreferences::slotDecreasePriority() -{ - const int row = ui.list->currentIndex().row(); - m_model->moveItem(row, row + 2); - slotUpdateButtons(); - emit changed(); -} - diff --git a/kget/conf/integrationpreferences.h b/kget/conf/integrationpreferences.h deleted file mode 100644 index 5cd4e022..00000000 --- a/kget/conf/integrationpreferences.h +++ /dev/null @@ -1,57 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 INTEGRATIONPREFERENCES -#define INTEGRATIONPREFERENCES - -#include - -#include "ui_dlgintegration.h" - -class AutoPasteModel; -class KConfigDialog; - -class IntegrationPreferences : public QWidget -{ - Q_OBJECT - - public: - explicit IntegrationPreferences(KConfigDialog *parent, Qt::WindowFlags f = 0); - ~IntegrationPreferences(); - - private slots: - void slotUpdateButtons(); - void slotAddItem(); - void slotRemoveItem(); - void slotIncreasePriority(); - void slotDecreasePriority(); - - signals: - /** - * Emitted whenever something changes - */ - void changed(); - - private: - Ui::DlgIntegration ui; - AutoPasteModel *m_model; -}; - -#endif - diff --git a/kget/conf/kget.kcfg b/kget/conf/kget.kcfg deleted file mode 100644 index 1c70a803..00000000 --- a/kget/conf/kget.kcfg +++ /dev/null @@ -1,185 +0,0 @@ - - - - kdemacros.h - KGlobalSettings - - - - - - - - - - - - - - true - - - false - - - false - - - false - - - true - - - - - - false - - - false - - - * - - - 0 - - - 0 - - - false - - - QDateTime::currentDateTime() - - - false - - - QDateTime::currentDateTime() - - - true - - - false - - - 0 - - - false - - - true - - - false - - - 1 - - - 0 - - - true - - - false - - - false - - - - - - 2 - - - false - - - 20 - - - 0 - - - 0 - - - true - - - 5 - - - 60 - - - - - - false - - - 8080 - - - admin - - - - - - false - - - true - - - - - - - QPoint(-1, -1) - - - 0 - - - true - - - KGlobalSettings::downloadPath() - - - - - 0 - - - - - - - - - - - - 1 - - - 1 - - - - diff --git a/kget/conf/pluginselector.cpp b/kget/conf/pluginselector.cpp deleted file mode 100644 index d6127d5f..00000000 --- a/kget/conf/pluginselector.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ -#include "pluginselector.h" - -#include "core/kget.h" - -#include -#include -#include -#include -#include -#include - -PluginSelector::PluginSelector(KDialog * parent) - : KPluginSelector(parent) -{ - KService::List offers = KServiceTypeTrader::self()->query("KGet/Plugin"); - - addPlugins(KPluginInfo::fromServices(offers), KPluginSelector::ReadConfigFile, i18n("Plugins"), "Service", KGlobal::config()); - - load(); - - connect(parent, SIGNAL(accepted()), SLOT(saveState())); - connect(parent, SIGNAL(rejected()), SLOT(loadDefaults())); -} - -PluginSelector::~PluginSelector() -{ -} - -void PluginSelector::saveState() -{ - save(); - KGet::loadPlugins(); -} - -void PluginSelector::loadDefaults() -{ - defaults(); -} - -#include "moc_pluginselector.cpp" diff --git a/kget/conf/pluginselector.h b/kget/conf/pluginselector.h deleted file mode 100644 index 888a027e..00000000 --- a/kget/conf/pluginselector.h +++ /dev/null @@ -1,29 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ -#ifndef PLUGINSELECTOR_H -#define PLUGINSELECTOR_H - -#include - -class KDialog; - -class PluginSelector : public KPluginSelector -{ - Q_OBJECT - public: - PluginSelector(KDialog * parent); - ~PluginSelector(); - - private slots: - void saveState(); - void loadDefaults(); -}; - -#endif diff --git a/kget/conf/preferencesdialog.cpp b/kget/conf/preferencesdialog.cpp deleted file mode 100644 index ab042da1..00000000 --- a/kget/conf/preferencesdialog.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2004 - 2007 KGet Developers - - 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. -*/ - -#include "preferencesdialog.h" -#include "core/kget.h" -#include "core/transferhistorystore.h" - -#include "ui_dlgappearance.h" -#include "ui_dlgnetwork.h" -#include "dlgwebinterface.h" - -#include "integrationpreferences.h" -#include "transfersgroupwidget.h" -#include "pluginselector.h" -#include "verificationpreferences.h" - -#include -#include - -PreferencesDialog::PreferencesDialog(QWidget * parent, KConfigSkeleton * skeleton) - : KConfigDialog(parent, "preferences", skeleton) -{ - QWidget *appearance = new QWidget(this); - TransfersGroupWidget *groups = new TransfersGroupWidget(this); - DlgWebinterface *webinterface = new DlgWebinterface(this); - connect(webinterface, SIGNAL(changed()), SLOT(enableApplyButton())); - connect(webinterface, SIGNAL(saved()), SLOT(settingsChangedSlot())); - QWidget *network = new QWidget(this); - QWidget *advanced = new QWidget(this); - IntegrationPreferences *integration = new IntegrationPreferences(this); - connect(integration, SIGNAL(changed()), SLOT(enableApplyButton())); - VerificationPreferences *verification = new VerificationPreferences(this); - connect(verification, SIGNAL(changed()), SLOT(enableApplyButton())); - PluginSelector * pluginSelector = new PluginSelector(this); - connect(pluginSelector, SIGNAL(changed(bool)), SLOT(enableApplyButton())); - - Ui::DlgAppearance dlgApp; - Ui::DlgNetwork dlgNet; - - dlgApp.setupUi(appearance); - dlgNet.setupUi(network); - dlgAdv.setupUi(advanced); - - // history backend entries - dlgAdv.kcfg_HistoryBackend->addItem(i18n("Json"), QVariant(TransferHistoryStore::Json)); - dlgAdv.kcfg_HistoryBackend->addItem(i18n("Xml"), QVariant(TransferHistoryStore::Xml)); - -#ifdef HAVE_KWORKSPACE - dlgAdv.kcfg_AfterFinishAction->addItem(i18n("Turn Off Computer"), QVariant(KGet::Shutdown)); - dlgAdv.kcfg_AfterFinishAction->addItem(i18n("Hibernate Computer"), QVariant(KGet::Hibernate)); - dlgAdv.kcfg_AfterFinishAction->addItem(i18n("Suspend Computer"), QVariant(KGet::Suspend)); -#endif - - // enable or disable the AfterFinishAction depends on the AfterFinishActionEnabled checkbox state - dlgAdv.kcfg_AfterFinishAction->setEnabled(dlgAdv.kcfg_AfterFinishActionEnabled->checkState () == Qt::Checked); - connect(dlgAdv.kcfg_AfterFinishActionEnabled, SIGNAL(stateChanged(int)), - SLOT(slotToggleAfterFinishAction(int))); - - // TODO: remove the following lines as soon as these features are ready - dlgNet.lb_per_transfer->setVisible(false); - dlgNet.kcfg_TransferSpeedLimit->setVisible(false); - - addPage(appearance, i18n("Appearance"), "preferences-desktop-theme", i18n("Change appearance settings")); - addPage(groups, i18n("Groups"), "bookmarks", i18n("Manage the groups")); - addPage(network, i18n("Network"), "network-workgroup", i18n("Network and Downloads")); - addPage(webinterface, i18n("Web Interface"), "network-workgroup", i18n("Control KGet over a Network or the Internet")); - addPage(verification, i18n("Verification"), "document-encrypt", i18n("Verification")); - addPage(integration, i18n("Integration"), "applications-other", i18n("Integration of KGet with other applications")); - addPage(advanced, i18n("Advanced Options"), "preferences-other", i18n("Advanced Options")); - addPage(pluginSelector, i18n("Plugins"), "preferences-plugin", i18n("Transfer Plugins")); - - connect(this, SIGNAL(accepted()), SLOT(disableApplyButton())); - connect(this, SIGNAL(rejected()), SLOT(disableApplyButton())); -} - -void PreferencesDialog::disableApplyButton() -{ - enableButtonApply(false); -} - -void PreferencesDialog::enableApplyButton() -{ - enableButtonApply(true); -} - -void PreferencesDialog::slotToggleAfterFinishAction(int state) -{ - dlgAdv.kcfg_AfterFinishAction->setEnabled(state == Qt::Checked); -} diff --git a/kget/conf/preferencesdialog.h b/kget/conf/preferencesdialog.h deleted file mode 100644 index 48c34bcf..00000000 --- a/kget/conf/preferencesdialog.h +++ /dev/null @@ -1,36 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2004 - 2007 KGet Developers - - 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. -*/ - -#ifndef PREFERENCESDIALOG_H -#define PREFERENCESDIALOG_H - -#include "ui_dlgadvanced.h" - -#include - -#include -class KConfigSkeleton; -class KTabWidget; - -class PreferencesDialog : public KConfigDialog -{ - Q_OBJECT - public: - PreferencesDialog( QWidget * parent, KConfigSkeleton * config ); - - private slots: - void slotToggleAfterFinishAction(int state); - void disableApplyButton(); - void enableApplyButton(); - - private: - Ui::DlgAdvanced dlgAdv; -}; - -#endif diff --git a/kget/conf/settings.kcfgc b/kget/conf/settings.kcfgc deleted file mode 100644 index 026ecf56..00000000 --- a/kget/conf/settings.kcfgc +++ /dev/null @@ -1,5 +0,0 @@ -ClassName=Settings -File=kget.kcfg -Mutators=true -Singleton=true -Visibility=KDE_EXPORT diff --git a/kget/conf/transfersgrouptree.cpp b/kget/conf/transfersgrouptree.cpp deleted file mode 100644 index 47d74de1..00000000 --- a/kget/conf/transfersgrouptree.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2007 Javier Goday - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "transfersgrouptree.h" - -#include "core/kget.h" -#include "core/transfertreemodel.h" -#include "core/transfertreeselectionmodel.h" - -#include - -#include - -TransfersGroupDelegate::TransfersGroupDelegate(QAbstractItemView *parent) - : BasicTransfersViewDelegate(parent) -{ -} - -QWidget *TransfersGroupDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Name) { - return new KLineEdit(parent); - } else { - return BasicTransfersViewDelegate::createEditor(parent, option, index); - } -} - -void TransfersGroupDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Name) { - KLineEdit *groupEditor = static_cast(editor); - groupEditor->setText(index.data().toString()); - } else { - BasicTransfersViewDelegate::setEditorData(editor, index); - } -} - -void TransfersGroupDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Name) { - KLineEdit *groupEditor = static_cast(editor); - const QString newName = groupEditor->text(); - const QString oldName = index.data().toString(); - - if (!newName.isEmpty()) { - foreach (const QString &groupName, KGet::transferGroupNames()) { - if (groupName == newName && groupName != oldName) { - groupEditor->setText(oldName); - return; - } - } - - KGet::renameGroup(oldName, newName); - } - } else { - BasicTransfersViewDelegate::setModelData(editor, model, index); - } -} - - -TransfersGroupTree::TransfersGroupTree(QWidget *parent) - : QTreeView(parent) -{ - setItemDelegate(new TransfersGroupDelegate(this)); -} - -void TransfersGroupTree::setModel(QAbstractItemModel *model) -{ - QTreeView::setModel(model); - - int nGroups = model->rowCount(QModelIndex()); - for (int i = 0; i < nGroups; i++) { - kDebug() << "openEditor for row " << i; - openPersistentEditor(model->index(i, TransferTreeModel::Status, QModelIndex())); - } - - setColumnWidth(0 , 250); -} - -void TransfersGroupTree::rowsInserted(const QModelIndex &parent, int start, int end) -{ - if (!parent.isValid()) { - for (int i = start; i <= end; ++i) { - kDebug() << "openEditor for row " << i; - openPersistentEditor(model()->index(i, TransferTreeModel::Status, parent)); - } - } - - QTreeView::rowsInserted(parent, start, end); -} - -void TransfersGroupTree::editCurrent() -{ - QTreeView::edit(currentIndex()); -} - -void TransfersGroupTree::addGroup() -{ - QString groupName(i18n("New Group")); - int i=0; - - while(KGet::transferGroupNames().contains(groupName)) - { - groupName = i18n("New Group") + QString::number(++i); - } - - if (KGet::addGroup(groupName)) { - QModelIndex index = model()->index(model()->rowCount() - 1, 0); - setCurrentIndex(index); - editCurrent(); - } -} - -void TransfersGroupTree::deleteSelectedGroup() -{ - KGet::delGroups(KGet::selectedTransferGroups()); -} - -void TransfersGroupTree::renameSelectedGroup() -{ - if(currentIndex().isValid()) - editCurrent(); -} - -void TransfersGroupTree::changeIcon(const QString &icon) -{ - TransferTreeSelectionModel *selModel = KGet::selectionModel(); - - QModelIndexList indexList = selModel->selectedRows(); - - if (!icon.isEmpty()) - { - foreach (TransferGroupHandler *group, KGet::selectedTransferGroups()) - { - group->setIconName(icon); - } - } - emit dataChanged(indexList.first(),indexList.last()); -} diff --git a/kget/conf/transfersgrouptree.h b/kget/conf/transfersgrouptree.h deleted file mode 100644 index 5d6a710f..00000000 --- a/kget/conf/transfersgrouptree.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2007 Javier Goday - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef TRANSFERSGROUPTREE_H -#define TRANSFERSGROUPTREE_H - -#include "ui/transfersviewdelegate.h" - -#include -#include - -class GroupStatusEditor; - -class TransfersGroupDelegate : public BasicTransfersViewDelegate -{ - Q_OBJECT - - public: - TransfersGroupDelegate(QAbstractItemView *parent); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; -}; - -class TransfersGroupTree : public QTreeView -{ - Q_OBJECT - public: - TransfersGroupTree(QWidget *parent=0); - void setModel(QAbstractItemModel *model); - - public slots: - void editCurrent(); - void addGroup(); - void deleteSelectedGroup(); - void renameSelectedGroup(); - void changeIcon(const QString &icon); - - private: - void rowsInserted(const QModelIndex &index, int start, int end); -}; - -#endif diff --git a/kget/conf/transfersgroupwidget.cpp b/kget/conf/transfersgroupwidget.cpp deleted file mode 100644 index 84d618e5..00000000 --- a/kget/conf/transfersgroupwidget.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2007 Javier Goday - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "transfersgroupwidget.h" -#include "transfersgrouptree.h" - -#include "core/kget.h" -#include "core/transfertreemodel.h" -#include "core/transfertreeselectionmodel.h" - - -TransfersGroupWidget::TransfersGroupWidget(QWidget *parent) - : QWidget(parent) -{ - ui.setupUi(this); - - ui.treeView->setModel(KGet::model()); - ui.treeView->setSelectionModel(KGet::selectionModel()); - - ui.treeView->header()->hideSection(TransferTreeModel::Progress); - ui.treeView->header()->hideSection(TransferTreeModel::RemainingTime); - ui.treeView->header()->hideSection(TransferTreeModel::Size); - ui.treeView->header()->hideSection(TransferTreeModel::Speed); - - ui.add->setGuiItem(KStandardGuiItem::add()); - ui.remove->setGuiItem(KStandardGuiItem::remove()); - ui.configure->setGuiItem(KStandardGuiItem::Configure); - ui.rename->setIcon(KIcon("edit-rename")); - ui.selectIcon->setIcon(KIcon("preferences-desktop-icons")); - - connect(ui.add, SIGNAL(clicked()), ui.treeView, SLOT(addGroup())); - connect(ui.remove, SIGNAL(clicked()), ui.treeView, SLOT(deleteSelectedGroup())); - connect(ui.rename, SIGNAL(clicked()), ui.treeView, SLOT(renameSelectedGroup())); - connect(ui.selectIcon, SIGNAL(iconChanged(QString)), ui.treeView, SLOT(changeIcon(QString))); - connect(ui.configure, SIGNAL(clicked()), KGet::actionCollection()->action("transfer_group_settings"), SLOT(trigger())); - connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(slotSelectionChanged())); - - slotSelectionChanged(); -} - -void TransfersGroupWidget::slotSelectionChanged() -{ - const QModelIndexList selectedGroups = ui.treeView->selectionModel()->selectedRows(); - const bool somethingSelected = !selectedGroups.isEmpty(); - bool canDelete = somethingSelected && KGet::selectedTransferGroups().count() != KGet::allTransferGroups().count(); - - ui.rename->setEnabled(canDelete); - ui.remove->setEnabled(canDelete); - ui.configure->setEnabled(somethingSelected); - ui.selectIcon->setEnabled(somethingSelected); - - if (somethingSelected && !KGet::selectedTransferGroups().isEmpty()) { - ui.selectIcon->setIcon(KIcon(KGet::selectedTransferGroups().first()->iconName())); - } else { - ui.selectIcon->setIcon(KIcon("preferences-desktop-icons")); - } -} diff --git a/kget/conf/transfersgroupwidget.h b/kget/conf/transfersgroupwidget.h deleted file mode 100644 index 5f03e885..00000000 --- a/kget/conf/transfersgroupwidget.h +++ /dev/null @@ -1,32 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2007 Javier Goday - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef TRANSFERS_GROUP_WIDGET_H -#define TRANSFERS_GROUP_WIDGET_H - -#include "ui_dlggroups.h" - -class TransfersGroupWidget : public QWidget -{ - Q_OBJECT - public: - TransfersGroupWidget(QWidget *parent = 0); - - private slots: - void slotSelectionChanged(); - - private: - Ui::DlgGroups ui; -}; - -#endif diff --git a/kget/conf/verificationpreferences.cpp b/kget/conf/verificationpreferences.cpp deleted file mode 100644 index c25df19a..00000000 --- a/kget/conf/verificationpreferences.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "verificationpreferences.h" -#include "settings.h" - -#include -#include -#include -#include -#include - -VerificationPreferences::VerificationPreferences(KConfigDialog *parent, Qt::WindowFlags f) - : QWidget(parent, f) -{ - ui.setupUi(this); - - connect(parent, SIGNAL(accepted()), SLOT(slotAccpeted())); -} - -void VerificationPreferences::slotAccpeted() -{ - Settings::self()->writeConfig(); -} - -#include "moc_verificationpreferences.cpp" diff --git a/kget/conf/verificationpreferences.h b/kget/conf/verificationpreferences.h deleted file mode 100644 index 45c1652c..00000000 --- a/kget/conf/verificationpreferences.h +++ /dev/null @@ -1,49 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 VERIFICATIONPREFERENCES_H -#define VERIFICATIONPREFERENCES_H - -#include - -#include "ui_verificationpreferences.h" - -class KConfigDialog; - -class VerificationPreferences : public QWidget -{ - Q_OBJECT - - public: - explicit VerificationPreferences(KConfigDialog *parent, Qt::WindowFlags f = 0); - - signals: - /** - * Emitted when the mirrors change - */ - void changed(); - - private slots: - void slotAccpeted(); - - private: - Ui::VerificationPreferences ui; -}; - -#endif diff --git a/kget/conf/verificationpreferences.ui b/kget/conf/verificationpreferences.ui deleted file mode 100644 index f022f930..00000000 --- a/kget/conf/verificationpreferences.ui +++ /dev/null @@ -1,86 +0,0 @@ - - - VerificationPreferences - - - - 0 - 0 - 411 - 174 - - - - - - - Automatic checksums verification - - - false - - - true - - - - QFormLayout::ExpandingFieldsGrow - - - - - Used checksum: - - - - - - - - - - true - - - - 0 - - - - - Weak (fastest) - - - - - - - Strong (recommended) - - - - - - - Strongest (slowest) - - - - - - - - - - - - - - KButtonGroup - QGroupBox -
kbuttongroup.h
- 1 -
-
- -
diff --git a/kget/core/CMakeLists.txt b/kget/core/CMakeLists.txt deleted file mode 100644 index 7d5453f6..00000000 --- a/kget/core/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(plugin) diff --git a/kget/core/basedialog.cpp b/kget/core/basedialog.cpp deleted file mode 100644 index c021f451..00000000 --- a/kget/core/basedialog.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 "basedialog.h" -#include "settings.h" - -KGetSaveSizeDialog::KGetSaveSizeDialog(const QByteArray &name, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_name("Size" + name) -{ - const QSize size = KGlobal::config()->group("Geometry").readEntry(m_name.constData(), QSize()); - if (size.isValid()) { - resize(size); - } -} - -KGetSaveSizeDialog::~KGetSaveSizeDialog() -{ - const QString name = QString("Size_") + metaObject()->className(); - KGlobal::config()->group("Geometry").writeEntry(m_name.constData(), size()); -} - diff --git a/kget/core/basedialog.h b/kget/core/basedialog.h deleted file mode 100644 index 8157ccc4..00000000 --- a/kget/core/basedialog.h +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 KGET_BASE_DIALOG -#define KGET_BASE_DIALOG - -#include "../kget_export.h" -#include - -#include - -/** - * Subclass to make sure that the size of the dialog is - * automatically stored and restored - */ -class KGET_EXPORT KGetSaveSizeDialog : public KDialog -{ - Q_OBJECT - - public: - /** - * Restores the dialog to the size saved for name - */ - explicit KGetSaveSizeDialog(const QByteArray &name, QWidget *parent = 0, Qt::WFlags flags = 0); - virtual ~KGetSaveSizeDialog(); - - private: - QByteArray m_name; -}; - -#endif diff --git a/kget/core/download.cpp b/kget/core/download.cpp deleted file mode 100644 index c3efae82..00000000 --- a/kget/core/download.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 Lukas Appelhans - - 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. -*/ -#include "download.h" - -#include -#include - -#include - -Download::Download(const KUrl &srcUrl, const KUrl &destUrl) - : m_srcUrl(srcUrl), - m_destUrl(destUrl) -{ - kDebug() << "DownloadFile: " << m_srcUrl.url() << " to dest: " << m_destUrl.url(); - m_copyJob = KIO::get(m_srcUrl, KIO::NoReload, KIO::HideProgressInfo); - connect(m_copyJob, SIGNAL(data(KIO::Job*,QByteArray)), SLOT(slotData(KIO::Job*,QByteArray))); - connect(m_copyJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*))); -} - -Download::~Download() -{ -} - -void Download::slotData(KIO::Job *job, const QByteArray& data) -{ - Q_UNUSED(job) - /**if (data.size() == 0) - { - slotResult(job); - return; - }**/ - m_data.append(data); -} - -void Download::slotResult(KJob * job) -{ - switch (job->error()) - { - case 0://The download has finished - { - kDebug() << "Downloading successfully finished" << m_destUrl.url(); - QFile torrentFile(m_destUrl.toLocalFile()); - if (!torrentFile.open(QIODevice::WriteOnly | QIODevice::Text)) {} - //TODO: Do a Message box here - torrentFile.write(m_data); - torrentFile.close(); - emit finishedSuccessfully(m_destUrl, m_data); - m_data = 0; - break; - } - case KIO::ERR_FILE_ALREADY_EXIST: - { - kDebug() << "ERROR - File already exists"; - QFile file(m_destUrl.toLocalFile()); - emit finishedSuccessfully(m_destUrl, file.readAll()); - m_data = 0; - break; - } - default: - kDebug() << "We are sorry to say you, that there were errors while downloading :("; - m_data = 0; - emit finishedWithError(); - break; - } -} - diff --git a/kget/core/download.h b/kget/core/download.h deleted file mode 100644 index 63145154..00000000 --- a/kget/core/download.h +++ /dev/null @@ -1,46 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 Lukas Appelhans - - 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. -*/ - -#ifndef DOWNLOAD_H -#define DOWNLOAD_H - -#include "kget_export.h" - -#include -#include - -#include - -#include - -class KGET_EXPORT Download : public QObject -{ - Q_OBJECT - public: - Download(const KUrl &srcUrl, const KUrl &destUrl); - ~Download(); - - Q_SIGNALS: - void finishedSuccessfully(KUrl dest, QByteArray data); - void finishedWithError(); - - private slots: - void slotResult(KJob * job); - void slotData(KIO::Job *job, const QByteArray& data); - - private: - KIO::TransferJob *m_copyJob; - KUrl m_srcUrl; - KUrl m_destUrl; - KUrl m_destFile; - QByteArray m_data; -}; - -#endif diff --git a/kget/core/filedeleter.cpp b/kget/core/filedeleter.cpp deleted file mode 100644 index e4bab48a..00000000 --- a/kget/core/filedeleter.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 "filedeleter.h" -#include "filedeleter_p.h" - -K_GLOBAL_STATIC(FileDeleter, fileDeleter) - -FileDeleter::Private::Private() - : QObject(0) -{ -} - -FileDeleter::Private::~Private() -{ -} - -bool FileDeleter::Private::isFileBeingDeleted(const KUrl &dest) const -{ - return m_jobs.contains(dest); -} - -KJob *FileDeleter::Private::deleteFile(const KUrl &dest, QObject *receiver, const char *method) -{ - QHash::iterator it = m_jobs.find(dest); - if (it == m_jobs.end()) { - KJob *job = KIO::del(dest, KIO::HideProgressInfo); - it = m_jobs.insert(dest, job); - connect(*it, SIGNAL(result(KJob*)), this, SLOT(slotResult(KJob*))); - } - - if (receiver && method) { - //make sure that there is just one connection - disconnect(*it, SIGNAL(result(KJob*)), receiver, method); - connect(*it, SIGNAL(result(KJob*)), receiver, method); - } - - return *it; -} - -void FileDeleter::Private::slotResult(KJob *job) -{ - KIO::DeleteJob *deleteJob = static_cast(job); - m_jobs.remove(deleteJob->urls().first()); -} - -FileDeleter::FileDeleter() - : d(new Private) -{ -} - -FileDeleter::~FileDeleter() -{ - delete d; -} - -KJob *FileDeleter::deleteFile(const KUrl &dest, QObject *receiver, const char *method) -{ - return fileDeleter->d->deleteFile(dest, receiver, method); -} - -bool FileDeleter::isFileBeingDeleted(const KUrl &dest) -{ - return fileDeleter->d->isFileBeingDeleted(dest); -} - -#include "moc_filedeleter_p.cpp" diff --git a/kget/core/filedeleter.h b/kget/core/filedeleter.h deleted file mode 100644 index b5af2fcf..00000000 --- a/kget/core/filedeleter.h +++ /dev/null @@ -1,63 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 KGET_FILE_DELETER_H -#define KGET_FILE_DELETER_H - -#include "kget_export.h" - -class KJob; -class KUrl; -#include - -/** - * The FileDeleter is a wrapper around KIO ensuring that always - * just one job is started for deleting a file. - * Thus deleteFile can be called mutliple times safely and all callees - * are informed once the file is actually deleted. - */ -class KGET_EXPORT FileDeleter -{ - public: - FileDeleter(); - ~FileDeleter(); - - /** - * Starts the deletion of dest and emits KJob::finished once done. - * You can safely call this method multiple times for the same destination. - * @param dest destination to delete - * @param receiver receiver of the finished signal - * @param method method the finished signal should be connected to, thus - * informing you of the result - * @return the KJob that has been created - * @note only use the returned job to create connections yourself, not to modify it! - */ - static KJob *deleteFile(const KUrl &dest, QObject *receiver = 0, const char *method = 0); - - /** - * @return true if dest is being deleted - */ - static bool isFileBeingDeleted(const KUrl &dest); - - private: - class Private; - Private *d; -}; - -#endif diff --git a/kget/core/filedeleter_p.h b/kget/core/filedeleter_p.h deleted file mode 100644 index 6faa3c3a..00000000 --- a/kget/core/filedeleter_p.h +++ /dev/null @@ -1,47 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 FILEDELETER_P_H -#define FILEDELETER_P_H - -#include -#include - -#include -#include - -class FileDeleter::Private : QObject -{ - Q_OBJECT - public: - Private(); - ~Private(); - - KJob *deleteFile(const KUrl &dest, QObject *receiver, const char *method); - - bool isFileBeingDeleted(const KUrl &dest) const; - - public Q_SLOTS: - void slotResult(KJob *job); - - private: - QHash m_jobs; -}; - -#endif // FILEDELETER_P_H diff --git a/kget/core/filemodel.cpp b/kget/core/filemodel.cpp deleted file mode 100644 index 68a5ff21..00000000 --- a/kget/core/filemodel.cpp +++ /dev/null @@ -1,676 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "filemodel.h" - -#include "verifier.h" - -#include -#include -#include - -FileItem::FileItem(const QString &name, FileItem *parent) - : m_name(name), - m_state(Qt::Checked), - m_status(Job::Stopped), - m_totalSize(0), - m_checkusmVerified(0), - m_parent(parent) -{ -} - -FileItem::~FileItem() -{ - qDeleteAll(m_childItems); -} - -void FileItem::appendChild(FileItem *child) -{ - m_childItems.append(child); -} - -FileItem *FileItem::child(int row) -{ - return m_childItems.value(row); -} - -int FileItem::childCount() const -{ - return m_childItems.count(); -} - -bool FileItem::isFile() const -{ - return m_childItems.isEmpty(); -} - -int FileItem::columnCount() const -{ - return 5; -} - -QVariant FileItem::data(int column, int role) const -{ - if (column == FileItem::File) - { - if (role == Qt::CheckStateRole) - { - return m_state; - } - else if (role == Qt::DisplayRole) - { - return m_name; - } - else if (role == Qt::DecorationRole) - { - if (m_mimeType.isNull()) { - if (isFile()) { - m_mimeType = KIcon(KMimeType::iconNameForUrl(KUrl(m_name))); - } else { - m_mimeType = KIcon("folder"); - } - } - - return m_mimeType; - } - } - else if (column == FileItem::Status) - { - if ((role == Qt::DisplayRole) || (role == Qt::DecorationRole)) - { - if (isFile()) { - return m_status; - } - } - } - else if (column == FileItem::Size) - { - if (role == Qt::DisplayRole) - { - return KIO::convertSize(m_totalSize); - } - } else if (column == FileItem::ChecksumVerified) { - if (role == Qt::DecorationRole) { - switch (m_checkusmVerified) { - case Verifier::Verified: - return KIcon("dialog-ok"); - case Verifier::NotVerified: - return KIcon("dialog-error"); - case Verifier::NoResult: - default: - return KIcon(); - } - } - } - - return QVariant(); -} - -bool FileItem::setData(int column, const QVariant &value, FileModel *model, int role) -{ - if (value.isNull()) - { - return false; - } - - if (column == FileItem::File) - { - if (role == Qt::CheckStateRole) - { - m_state = static_cast(value.toInt()); - model->changeData(this->row(), column, this); - checkParents(m_state, model); - checkChildren(m_state, model); - return true; - } - else if (role == Qt::EditRole) - { - m_name = value.toString(); - model->changeData(this->row(), column, this); - return true; - } - } - else if (column == FileItem::Status) - { - if (role == Qt::EditRole) - { - if (isFile()) { - m_status = static_cast(value.toInt()); - bool finished = (m_status == Job::Finished); - model->changeData(this->row(), column, this, finished); - - return true; - } - } - } - else if (column == FileItem::Size) - { - if (role == Qt::EditRole) - { - KIO::fileoffset_t newSize = value.toLongLong(); - if (m_parent) - { - m_parent->addSize(newSize - m_totalSize, model); - } - m_totalSize = newSize; - model->changeData(this->row(), column, this); - return true; - } - } else if (column == FileItem::ChecksumVerified) { - m_checkusmVerified = value.toInt(); - model->changeData(this->row(), column, this); - return true; - } - - return false; -} - -void FileItem::checkParents(Qt::CheckState state, FileModel *model) -{ - if (!model) - { - return; - } - - if (!m_parent) - { - return; - } - - foreach (FileItem *child, m_parent->m_childItems) - { - if (child->m_state != state) - { - state = Qt::Unchecked; - break; - } - } - - m_parent->m_state = state; - model->changeData(m_parent->row(), FileItem::File, m_parent); - m_parent->checkParents(state, model); -} - -void FileItem::checkChildren(Qt::CheckState state, FileModel *model) -{ - if (!model) - { - return; - } - - m_state = state; - model->changeData(row(), FileItem::File, this); - - foreach (FileItem *child, m_childItems) - { - child->checkChildren(state, model); - } -} - -FileItem *FileItem::parent() -{ - return m_parent; -} - -int FileItem::row() const -{ - if (m_parent) - { - return m_parent->m_childItems.indexOf(const_cast(this)); - } - - return 0; -} - -void FileItem::addSize(KIO::fileoffset_t size, FileModel *model) -{ - if (!isFile()) - { - m_totalSize += size; - model->changeData(this->row(), FileItem::Size, this); - if (m_parent) - { - m_parent->addSize(size, model); - } - } -} - - -FileModel::FileModel(const QList &files, const KUrl &destDirectory, QObject *parent) - : QAbstractItemModel(parent), - m_destDirectory(destDirectory), - m_checkStateChanged(false) -{ - m_rootItem = new FileItem("root"); - m_header << i18nc("file in a filesystem", "File") << i18nc("status of the download", "Status") << i18nc("size of the download", "Size") << i18nc("checksum of a file", "Checksum"); - - setupModelData(files); -} - -FileModel::~FileModel() -{ - delete m_rootItem; -} - -void FileModel::setupModelData(const QList &files) -{ - QString destDirectory = m_destDirectory.pathOrUrl(); - - foreach (const KUrl &file, files) - { - FileItem *parent = m_rootItem; - QStringList directories = file.pathOrUrl().remove(destDirectory).split('/', QString::SkipEmptyParts); - FileItem *child = 0; - while (directories.count()) - { - QString part = directories.takeFirst(); - for (int i = 0; i < parent->childCount(); ++i) - { - //folder already exists - if (parent->child(i)->data(0, Qt::DisplayRole).toString() == part) - { - parent = parent->child(i); - //file already exists - if (!directories.count()) - { - break; - } - part = directories.takeFirst(); - i = -1; - continue; - } - } - child = new FileItem(part, parent); - parent->appendChild(child); - parent = parent->child(parent->childCount() - 1); - } - if (child) - { - m_files.append(child); - } - } -} - -int FileModel::columnCount(const QModelIndex &parent) const -{ - if (parent.isValid()) - { - return static_cast(parent.internalPointer())->columnCount(); - } - else - { - return m_rootItem->columnCount(); - } -} - -QVariant FileModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - { - return QVariant(); - } - - - FileItem *item = static_cast(index.internalPointer()); - const QVariant data = item->data(index.column(), role); - - //get the status icon as well as status text - if (index.column() == FileItem::Status) - { - const Job::Status status = static_cast(data.toInt()); - if (item->isFile()) { - if (role == Qt::DisplayRole) - { - if (m_customStatusTexts.contains(status)) - { - return m_customStatusTexts[status]; - } - else - { - return Transfer::statusText(status); - } - } - else if (role == Qt::DecorationRole) - { - if (m_customStatusIcons.contains(status)) - { - return m_customStatusIcons[status]; - } - else - { - return Transfer::statusPixmap(status); - } - } - } else { - return QVariant(); - } - } - - return data; -} - -bool FileModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (!index.isValid()) - { - return false; - } - - FileItem *item = static_cast(index.internalPointer()); - - if ((index.column() == FileItem::File) && (role == Qt::CheckStateRole)) { - const bool worked = item->setData(index.column(), value, this, role); - if (worked) { - m_checkStateChanged = true; - } - - return worked; - } - - return item->setData(index.column(), value, this, role); -} - -Qt::ItemFlags FileModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - { - return 0; - } - - if (index.column() == FileItem::File) - { - return QAbstractItemModel::flags(index) | Qt::ItemIsUserCheckable; - } - - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; -} - -QVariant FileModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if ((orientation == Qt::Horizontal) && (role == Qt::DisplayRole)) - { - return m_header.value(section); - } - - return QVariant(); -} - -QModelIndex FileModel::index(int row, int column, const QModelIndex &parent) const -{ - if (!hasIndex(row, column, parent)) - { - return QModelIndex(); - } - - FileItem *parentItem; - if (parent.isValid()) - { - parentItem = static_cast(parent.internalPointer()); - } - else - { - parentItem = m_rootItem; - } - - FileItem *childItem = parentItem->child(row); - if (childItem) - { - return createIndex(row, column, childItem); - } - else - { - return QModelIndex(); - } -} - -QModelIndex FileModel::index(const KUrl &file, int column) -{ - FileItem *item = getItem(file); - if (!item) - { - return QModelIndex(); - } - - return createIndex(item->row(), column, item); -} - -QModelIndexList FileModel::fileIndexes(int column) const -{ - QModelIndexList indexList; - foreach (FileItem *item, m_files) - { - int row = item->row(); - indexList.append(createIndex(row, column, item)); - } - - return indexList; -} - -QModelIndex FileModel::parent(const QModelIndex &index) const -{ - if (!index.isValid()) - { - return QModelIndex(); - } - - FileItem *childItem = static_cast(index.internalPointer()); - FileItem *parentItem = childItem->parent(); - if ((parentItem == m_rootItem) || (!parentItem)) - { - return QModelIndex(); - } - else - { - return createIndex(parentItem->row(), 0, parentItem); - } -} - -int FileModel::rowCount(const QModelIndex &parent) const -{ - if (parent.column() > 0) - { - return 0; - } - - FileItem *parentItem; - if (parent.isValid()) - { - parentItem = static_cast(parent.internalPointer()); - } - else - { - parentItem = m_rootItem; - } - - return parentItem->childCount(); -} - -void FileModel::changeData(int row, int column, FileItem *item, bool finished) -{ - QModelIndex index = createIndex(row, column, item); - emit dataChanged(index, index); - - if (finished) { - const KUrl file = getUrl(index); - emit fileFinished(file); - } -} - - -void FileModel::setDirectory(const KUrl &newDirectory) -{ - m_destDirectory = newDirectory; - m_itemCache.clear(); -} - -KUrl FileModel::getUrl(const QModelIndex &index) -{ - if (!index.isValid()) { - return KUrl(); - } - - const QModelIndex file = index.sibling(index.row(), FileItem::File); - - return getUrl(static_cast(file.internalPointer())); -} - -KUrl FileModel::getUrl(FileItem *item) -{ - const QString path = getPath(item); - const QString name = item->data(FileItem::File, Qt::DisplayRole).toString(); - KUrl url = m_destDirectory; - url.addPath(path + name); - - return url; -} - -QString FileModel::getPath(FileItem *item) -{ - FileItem *parent = item->parent(); - QString path; - while (parent && parent->parent()) - { - path = parent->data(FileItem::File, Qt::DisplayRole).toString() + '/' + path; - parent = parent->parent(); - } - - return path; -} - -FileItem *FileModel::getItem(const KUrl &file) -{ - if (m_itemCache.contains(file)) - { - return m_itemCache[file]; - } - - QString destDirectory = m_destDirectory.pathOrUrl(); - - FileItem *item = m_rootItem; - QStringList directories = file.pathOrUrl().remove(destDirectory).split('/', QString::SkipEmptyParts); - while (directories.count()) - { - QString part = directories.takeFirst(); - for (int i = 0; i < item->childCount(); ++i) - { - //folder already exists - if (item->child(i)->data(FileItem::File, Qt::DisplayRole).toString() == part) - { - item = item->child(i); - //file already exists - if (!directories.count()) - { - break; - } - part = directories.takeFirst(); - i = -1; - continue; - } - } - } - - if (item == m_rootItem) - { - item = 0; - } - else - { - m_itemCache[file] = item; - } - - return item; -} - -bool FileModel::downloadFinished(const KUrl &file) -{ - FileItem *item = getItem(file); - if (item) - { - const Job::Status status = static_cast(item->data(FileItem::Status, Qt::DisplayRole).toInt()); - if (status == Job::Finished) - { - return true; - } - } - - return false; -} - -bool FileModel::isFile(const QModelIndex &index) const -{ - if (!index.isValid()) { - return false; - } - - FileItem *item = static_cast(index.internalPointer()); - - //only files can be renamed, no folders - return item->isFile(); -} - -void FileModel::rename(const QModelIndex &file, const QString &newName) -{ - if (!file.isValid() || (file.column() != FileItem::File)) - { - return; - } - - FileItem *item = static_cast(file.internalPointer()); - //only files can be renamed, no folders - if (!item->isFile()) { - return; - } - - //Find out the old and the new KUrl - QString oldName = file.data(Qt::DisplayRole).toString(); - QString path = getPath(item); - - KUrl oldUrl = m_destDirectory; - oldUrl.addPath(path + oldName); - KUrl newUrl = m_destDirectory; - newUrl.addPath(path + newName); - - m_itemCache.remove(oldUrl); - - setData(file, newName); - - emit rename(oldUrl, newUrl); -} - -void FileModel::renameFailed(const KUrl &beforeRename, const KUrl &afterRename) -{ - Q_UNUSED(beforeRename) - Q_UNUSED(afterRename) -} - -void FileModel::watchCheckState() -{ - m_checkStateChanged = false; -} - -void FileModel::stopWatchCheckState() -{ - if (m_checkStateChanged) - { - emit checkStateChanged(); - } - - m_checkStateChanged = false; -} - diff --git a/kget/core/filemodel.h b/kget/core/filemodel.h deleted file mode 100644 index 5b791aad..00000000 --- a/kget/core/filemodel.h +++ /dev/null @@ -1,226 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 FILEMODEL_H -#define FILEMODEL_H - -#include "kget_export.h" -#include "transfer.h" - -#include - -#include -#include -#include - -#include -#include - -class FileModel; - -class KGET_EXPORT FileItem -{ - public: - explicit FileItem(const QString &name, FileItem *parent = 0); - ~FileItem(); - - enum DataType - { - File = 0, - Status, - Size, - ChecksumVerified - }; - - void appendChild(FileItem *child); - - FileItem *child(int row); - int childCount() const; - /** - * Returns true if the index represents a file - */ - bool isFile() const; - int columnCount() const; - QVariant data(int column, int role) const; - bool setData(int column, const QVariant &value, FileModel *model, int role = Qt::EditRole); - int row() const; - FileItem *parent(); - - private: - /** - * Add the totalsize to the parent - */ - void addSize(KIO::fileoffset_t size, FileModel *model); - - /** - * If all siblings of this have the same state the parent of item will also be set - * to that state - */ - void checkParents(Qt::CheckState state, FileModel *model); - - /** - * All children of item will be set to state - */ - void checkChildren(Qt::CheckState state, FileModel *model); - - private: - QList m_childItems; - mutable KIcon m_mimeType; - QString m_name; - Qt::CheckState m_state; - Job::Status m_status; - KIO::fileoffset_t m_totalSize; - int m_checkusmVerified; - FileItem *m_parent; - - friend class TorrentFileModel; -}; - -/** - * This model represents the files that are being downloaded - * @note whenever a method takes a url as argument use the url to the file - * destination on your hard disk, the file does not need to exist though - */ - -class KGET_EXPORT FileModel : public QAbstractItemModel -{ - Q_OBJECT - - friend class FileItem; - - public: - FileModel(const QList &files, const KUrl &destDirectory, QObject *parent = 0); - ~FileModel(); - - QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - virtual Qt::ItemFlags flags(const QModelIndex &index) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex index(const KUrl &file, int column); - QModelIndex parent(const QModelIndex &index) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - - void rename(const QModelIndex &file, const QString &newName); - - /** - * Returns a list of pointers to all files of this model - * @note it would be possible to directly interact with the model data that way, - * though that is discouraged - */ - QModelIndexList fileIndexes(int column) const; - - /** - * The url on the filesystem (no check if the file exists yet!) of index, - * it can be a folder or file - */ - KUrl getUrl(const QModelIndex &index); - - /** - * Set the url to the directory the files are stored in, the filemodel stores - * its entries as relative path to the base directory - * @param newDirectory the base directory for the model - */ - void setDirectory(const KUrl &newDirectory); - - /** - * Set a custom status text for status - * @note QString() removes the custom text for status - */ - void setCustomStatusText(Job::Status status, const QString &text); - - /** - * Set a custom status icon for status - * @note KIcon() removes the custom icon for status - */ - void setCustomStatusIcon(Job::Status status, const KIcon &icon); - - /** - * Checks if the download for file has been finished - */ - bool downloadFinished(const KUrl &file); - - /** - * Returns true if the index represents a file - */ - bool isFile(const QModelIndex &index) const; - - public slots: - /** - * Watches if the check state changes, the result of that will be emitted - * when stopWatchCheckState() is being called() - */ - void watchCheckState(); - - /** - * Emits checkStateChanged if a CheckState of an entry changend - */ - void stopWatchCheckState(); - - Q_SIGNALS: - void rename(const KUrl &oldUrl, const KUrl &newUrl); - void checkStateChanged(); - void fileFinished(const KUrl &file); - - private: - void setupModelData(const QList &files); - - /** - * The url on the filesystem (no check if the file exists yet!) of item, - * it can be a folder or file - */ - KUrl getUrl(FileItem *item); - - /** - * Get the path of item - * @note path means here the part between m_destDirectory and the filename - * e.g. m_destDirectory = "file:///home/user/Downloads", path = "Great Album/", - * filename = "Song 1.ogg" - */ - QString getPath(FileItem *item); - - /** - * Get the item of the corresponding url - */ - FileItem *getItem(const KUrl &file); - - void changeData(int row, int column, FileItem *item, bool fileFinished = false); - - private slots: - void renameFailed(const KUrl &beforeRename, const KUrl &afterRename); - - private: - FileItem *m_rootItem; - KUrl m_destDirectory; - QList m_header; - bool m_checkStateChanged; - - QHash m_itemCache; //used to make getItem faster - - /** - * Stores links to all files - */ - QList m_files; - - QHash m_customStatusTexts; - QHash m_customStatusIcons; -}; - -#endif diff --git a/kget/core/handler.cpp b/kget/core/handler.cpp deleted file mode 100644 index 5813ff8b..00000000 --- a/kget/core/handler.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 - 2009 Lukas Appelhans - - 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. -*/ -#include "handler.h" - -#include "scheduler.h" - -Handler::Handler(Scheduler * scheduler, QObject * parent) - : QObject(parent), - m_scheduler(scheduler) -{ -} - -Handler::~Handler() -{ -} diff --git a/kget/core/handler.h b/kget/core/handler.h deleted file mode 100644 index b6003bfa..00000000 --- a/kget/core/handler.h +++ /dev/null @@ -1,33 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 - 2009 Lukas Appelhans - - 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. -*/ -#ifndef HANDLER_H -#define HANDLER_H - -#include - -class Scheduler; - -class Handler : public QObject -{ - Q_OBJECT - public: - Handler(Scheduler * scheduler, QObject * parent); - virtual ~Handler(); - - virtual void start() = 0; - virtual void stop() = 0; - - virtual QVariant data(int column) = 0; - - protected: - Scheduler * m_scheduler; -}; - -#endif diff --git a/kget/core/job.cpp b/kget/core/job.cpp deleted file mode 100644 index bce1aa09..00000000 --- a/kget/core/job.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - - 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. -*/ - -#include "core/job.h" - -#include "core/jobqueue.h" -#include "core/scheduler.h" - -#include - -Job::Job(Scheduler * scheduler, JobQueue * parent) - : QObject(parent), - m_jobQueue(parent), - m_scheduler(scheduler), - m_status(Stopped), - m_policy(None) -{ - m_error.id = -1; - m_error.type = AutomaticRetry; -} - -Job::~Job() -{ -} - -void Job::setStatus(Status jobStatus) -{ - if(jobStatus == m_status) - return; - if (m_status == Aborted) { - m_error.id = -1; - m_error.text.clear(); - m_error.pixmap = QPixmap(); - m_error.type = AutomaticRetry; - } - m_status = jobStatus; - m_scheduler->jobChangedEvent(this, m_status); -} - -void Job::setStartStatus(Status jobStatus) -{ - kDebug() << "Setting start status to " << jobStatus; - m_startStatus = jobStatus; -} - -void Job::setPolicy(Policy jobPolicy) -{ - if(jobPolicy == m_policy) - return; - - kDebug() << "Job::setPolicy(" << jobPolicy << ")"; - - m_policy = jobPolicy; - m_scheduler->jobChangedEvent(this, m_policy); -} - -void Job::setError(const QString &text, const QPixmap &pixmap, ErrorType type, int errorId) -{ - setStatus(Job::Aborted); - m_error.id = errorId; - m_error.text = text; - m_error.pixmap = pixmap; - m_error.type = type; -} - -void Job::resolveError(int errorId) -{ - Q_UNUSED(errorId) -} diff --git a/kget/core/job.h b/kget/core/job.h deleted file mode 100644 index f45766e4..00000000 --- a/kget/core/job.h +++ /dev/null @@ -1,129 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - - 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. -*/ - -#ifndef JOB_H -#define JOB_H - -/** - * @brief Job class - * - * We want to abstract this common interface in order to simplify the - * Scheduler code. A Job can be either a Transfer or a search through the net. - * It is basically something you execute in background and that the scheduler - * can decide to start, stop or cancel. In this way we don't expose the complex - * API of a Transfer (or a Search), to the scheduler. - * By definition a job must always belong to a JobQueue (see jobqueue.h). - **/ - -#include "../kget_export.h" - -#include - -#include - -class Scheduler; -class JobQueue; - -class KGET_EXPORT Job : public QObject -{ - Q_OBJECT - public: - /** - * The status property describes the current job status - */ - enum Status { - Running = 0, /// The job is being executed - Stopped = 2, /// The job is stopped - Aborted = 3, /// The job is stopped, but this also indicates that it - /// stopped because an error occurred - Finished = 4, /// The job exited from its Running state successfully - FinishedKeepAlive = 5, /// The job exited from its Running state successfully - /// but wants to be restarted by the scheduler - Moving = 6 /// The associated files to that job (e.g. Download) are - /// moved to a different location - }; - - /** - * The policy property describes how the scheduler should manage this job. - */ - enum Policy { - Start, /// The scheduler should start this job even if its queue - /// isn't in a Running status - Stop, /// The scheduler shouldn't never start this job, even if - /// if its queue is in a Running status - None /// The scheduler should start this job depending on its - /// queue status - }; - /** - * Describes different types of errors and how the scheduler should manage them. - */ - enum ErrorType { - AutomaticRetry, - ManualSolve, - NotSolveable - }; - struct Error { - int id; - QString text; - QPixmap pixmap; - ErrorType type; - }; - Job(Scheduler * scheduler, JobQueue * parent); - virtual ~Job(); - - //Job commands - virtual void start()=0; - virtual void stop()=0; - - JobQueue * jobQueue() {return m_jobQueue;} - - //Job properties - void setStatus(Status jobStatus); - void setPolicy(Policy jobPolicy); - void setError(const QString &text, const QPixmap &pixmap, ErrorType type = AutomaticRetry, int errorId = -1); - - Status status() const {return m_status;} - Status startStatus() const { return m_startStatus;} - Policy policy() const {return m_policy;} - Error error() const {return m_error;} - - virtual int elapsedTime() const =0; - virtual int remainingTime() const =0; - virtual bool isStalled() const =0; - virtual bool isWorking() const =0; - - virtual void resolveError(int errorId); - - protected: - Scheduler * scheduler() const {return m_scheduler;} - - void read(QDomNode * n); - void write(QDomNode * n); - - void setStartStatus(Status jobStatus); - - /** - * This one posts a job event to the scheduler - */ - void postJobEvent(Status); //do we need a JobEvent instead of JobStatus? - - JobQueue * m_jobQueue; - Scheduler * m_scheduler; - - private: - Status m_status; - // our status when KGet is started - Status m_startStatus; - Policy m_policy; - Error m_error; -}; - -#endif diff --git a/kget/core/jobqueue.cpp b/kget/core/jobqueue.cpp deleted file mode 100644 index 3c002e6d..00000000 --- a/kget/core/jobqueue.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - - 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. -*/ -#include "core/jobqueue.h" - -#include "core/scheduler.h" -#include "settings.h" - -#include - -JobQueue::JobQueue(Scheduler * parent) - : QObject(parent), - m_maxSimultaneousJobs(2), - m_scheduler(parent), - m_status(Running) -{ -} - -JobQueue::~JobQueue() -{ -} - -const QList JobQueue::runningJobs() -{ - QList jobs; - - iterator it = begin(); - iterator itEnd = end(); - - for( ; it!=itEnd ; ++it ) - { - if( (*it)->status() == Job::Running ) - jobs.append(*it); - } - return jobs; -} - -void JobQueue::setStatus(Status queueStatus) -{ - m_status = queueStatus; - - // Now make sure to reset all the job policy that shouldn't - // be applied anymore. - iterator it = begin(); - iterator itEnd = end(); - - for( ; it!=itEnd ; ++it ) - { - if( ( m_status == JobQueue::Running ) && - ( (*it)->status() == Job::Running ) ) - { - (*it)->setPolicy(Job::None); - } - - if( ( m_status == JobQueue::Stopped ) && - ( (*it)->status() == Job::Stopped ) ) - { - (*it)->setPolicy(Job::None); - } - } - - m_scheduler->jobQueueChangedEvent(this, m_status); -} - -int JobQueue::maxSimultaneousJobs() const -{ - const int maxConnections = Settings::maxConnections(); - return (maxConnections ? maxConnections : 1000);// High value just to indicate no limit -} - -void JobQueue::append(Job * job) -{ - m_jobs.append(job); - - m_scheduler->jobQueueAddedJobEvent(this, job); -} - -void JobQueue::append(const QList &jobs) -{ - m_jobs.append(jobs); - - m_scheduler->jobQueueAddedJobsEvent(this, jobs); -} - -void JobQueue::prepend(Job * job) -{ - m_jobs.prepend(job); - - m_scheduler->jobQueueAddedJobEvent(this, job); -} - -void JobQueue::insert(Job * job, Job * after) -{ - if((job->jobQueue() == this) || ((after) && (after->jobQueue() != this))) - return; - - m_jobs.insert(m_jobs.indexOf(after) +1, job); - m_scheduler->jobQueueAddedJobEvent(this, job); -} - -void JobQueue::remove(Job * job) -{ - m_jobs.removeAll(job); - - m_scheduler->jobQueueRemovedJobEvent(this, job); -} - -void JobQueue::remove(const QList jobs) -{ - foreach (Job *job, jobs) { - m_jobs.removeAll(job); - } - - m_scheduler->jobQueueRemovedJobsEvent(this, jobs); -} - -void JobQueue::move(Job * job, Job * after) -{ - kDebug() << "JobQueue::move"; - - if( (m_jobs.removeAll(job) == 0) || (job == after) || - ((after) && (after->jobQueue() != this)) ) - { - //The job doesn't belong to this JobQueue or the requested - //operations doesn't make any sense since job==after - return; - } - - if(!after) - { - //The job must be inserted in front of the list - m_jobs.prepend(job); - } - else - { - m_jobs.insert(m_jobs.indexOf(after) + 1, job); - } - - m_scheduler->jobQueueMovedJobEvent(this, job); -} - - diff --git a/kget/core/jobqueue.h b/kget/core/jobqueue.h deleted file mode 100644 index 51b9442d..00000000 --- a/kget/core/jobqueue.h +++ /dev/null @@ -1,170 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - - 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. -*/ - - -#ifndef JOBQUEUE_H -#define JOBQUEUE_H - -/** - * @brief JobQueue class - * - * This class abstracts the concept of queue. A queue is, basically, a - * group of jobs that should be executed by the scheduler (if the queue - * is marked as active). The scheduler will execute a maximum of n jobs - * belonging to this queue at a time, where n can be set calling the - * setMaxSimultaneousJobs(int n) - * - */ - -#include -#include "../kget_export.h" - -class Job; -class Scheduler; - -class KGET_EXPORT JobQueue : public QObject -{ - Q_OBJECT - public: - enum Status {Running, Stopped}; - typedef QList::iterator iterator; - - JobQueue(Scheduler * parent); - virtual ~JobQueue(); - - /** - * Sets the JobQueue status - * - * @param queueStatus the new JobQueue status - */ - virtual void setStatus(Status queueStatus); - - /** - * @return the jobQueue status - */ - Status status() const {return m_status;} - - /** - * @return the begin of the job's list - */ - iterator begin() {return m_jobs.begin();} - - /** - * @return the end of the job's list - */ - iterator end() {return m_jobs.end();} - - /** - * @return the last job in the job's list - */ - Job * last() {return m_jobs.last();} - - /** - * @return the number of jobs in the queue - */ - int size() const {return m_jobs.size();} - - /** - * @param job The job for which we want to find the index - * - * @return the job index for the given job. If the given - * job can't be found, it returns -1 - */ - int indexOf(Job * job) const {return m_jobs.indexOf(job);} - - /** - * @returns the Job in the queue at the given index i - */ - Job * operator[] (int i) const {return m_jobs[i];} - - /** - * @return a list with the running Jobs - */ - const QList runningJobs(); - - /** - * FIXME not implemented - * Sets the maximum number of jobs belonging to this queue that - * should executed simultaneously by the scheduler - * - * @param n The maximum number of jobs - */ - void setMaxSimultaneousJobs(int n); - - /** - * @return the maximum number of jobs the scheduler should ever - * execute simultaneously (in this queue). - */ - int maxSimultaneousJobs() const; - - protected: - /** - * appends a job to the current queue - * - * @param job The job to append to the current queue - */ - void append(Job * job); - - /** - * appends jobs to the current queue - * - * @param jobs to append to the current queue - */ - void append(const QList &jobs); - - /** - * prepends a job to the current queue - * - * @param job The job to prepend to the current queue - */ - void prepend(Job * job); - - /** - * inserts a job to the current queue after the given job - * - * @param job The job to add in the current queue - * @param after The job after which to add the job - */ - void insert(Job * job, Job * after); - - /** - * removes a job from the current queue - * - * @param job The job to remove from the current queue - */ - void remove(Job * job); - - /** - * removes jobs from the current queue - * - * @param jobs The jobs to remove from the current queue - */ - void remove(const QList jobs); - - /** - * Moves a job in the queue. Both the given jobs must belong to this queue - * - * @param job The job to move - * @param position The job after which we have to move the given job - */ - void move(Job * job, Job * after); - - Scheduler * scheduler() {return m_scheduler;} - - private: - QList m_jobs; - - int m_maxSimultaneousJobs; - - Scheduler * m_scheduler; - Status m_status; -}; - -#endif diff --git a/kget/core/kget.cpp b/kget/core/kget.cpp deleted file mode 100644 index b4cc2def..00000000 --- a/kget/core/kget.cpp +++ /dev/null @@ -1,1658 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007-2009 Lukas Appelhans - Copyright (C) 2008 Urs Wolfer - Copyright (C) 2008 Dario Freddi - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ - -#include "core/kget.h" - -#include "mainwindow.h" -#include "core/mostlocalurl.h" -#include "core/transfer.h" -#include "core/transferdatasource.h" -#include "core/transfergroup.h" -#include "core/transfergrouphandler.h" -#include "core/transfertreemodel.h" -#include "core/transfertreeselectionmodel.h" -#include "core/plugin/plugin.h" -#include "core/plugin/transferfactory.h" -#include "core/kuiserverjobs.h" -#include "core/transfergroupscheduler.h" -#include "settings.h" -#include "core/transferhistorystore.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - - -#ifdef HAVE_KWORKSPACE -# include -#endif - - -KGet::TransferData::TransferData(const KUrl &source, const KUrl &destination, const QString& group, bool doStart, const QDomElement *element) - : src(source), - dest(destination), - groupName(group), - start(doStart), - e(element) -{ -} - -/** - * This is our KGet class. This is where the user's transfers and searches are - * stored and organized. - * Use this class from the views to add or remove transfers or searches - * In order to organize the transfers inside categories we have a TransferGroup - * class. By definition, a transfer must always belong to a TransferGroup. If we - * don't want it to be displayed by the gui inside a specific group, we will put - * it in the group named "Not grouped" (better name?). - **/ - -KGet* KGet::self( MainWindow * mainWindow ) -{ - if(mainWindow) - { - m_mainWindow = mainWindow; - m_jobManager = new KUiServerJobs(m_mainWindow); - } - - static KGet *m = new KGet(); - - return m; -} - -bool KGet::addGroup(const QString& groupName) -{ - // Check if a group with that name already exists - if (m_transferTreeModel->findGroup(groupName)) - return false; - - TransferGroup * group = new TransferGroup(m_transferTreeModel, m_scheduler, groupName); - m_transferTreeModel->addGroup(group); - - return true; -} - -void KGet::delGroup(TransferGroupHandler *group, bool askUser) -{ - TransferGroup *g = group->m_group; - - if (askUser) { - QWidget *configDialog = KConfigDialog::exists("preferences"); - if (KMessageBox::warningYesNo(configDialog ? configDialog : m_mainWindow, - i18n("Are you sure that you want to remove the group named %1?", g->name()), - i18n("Remove Group"), - KStandardGuiItem::remove(), KStandardGuiItem::cancel()) != KMessageBox::Yes) - return; - } - - m_transferTreeModel->delGroup(g); - g->deleteLater(); -} - -void KGet::delGroups(QList groups, bool askUser) -{ - if (groups.isEmpty()) - return; - if (groups.count() == 1) { - KGet::delGroup(groups.first(), askUser); - return; - } - bool del = !askUser; - if (askUser) { - QStringList names; - foreach (TransferGroupHandler * handler, groups) - names << handler->name(); - QWidget * configDialog = KConfigDialog::exists("preferences"); - del = KMessageBox::warningYesNoList(configDialog ? configDialog : m_mainWindow, - i18n("Are you sure that you want to remove the following groups?"), - names, - i18n("Remove groups"), - KStandardGuiItem::remove(), KStandardGuiItem::cancel()) == KMessageBox::Yes; - } - if (del) { - foreach (TransferGroupHandler * handler, groups) - KGet::delGroup(handler, false); - } -} - -void KGet::renameGroup(const QString& oldName, const QString& newName) -{ - TransferGroup *group = m_transferTreeModel->findGroup(oldName); - - if(group) - { - group->handler()->setName(newName); - } -} - -QStringList KGet::transferGroupNames() -{ - QStringList names; - - foreach(TransferGroup *group, m_transferTreeModel->transferGroups()) { - names << group->name(); - } - - return names; -} - -TransferHandler * KGet::addTransfer(KUrl srcUrl, QString destDir, QString suggestedFileName, // krazy:exclude=passbyvalue - QString groupName, bool start) -{ - srcUrl = mostLocalUrl(srcUrl); - // Note: destDir may actually be a full path to a file :-( - kDebug() << "Source:" << srcUrl.url() << ", dest: " << destDir << ", sugg file: " << suggestedFileName; - - KUrl destUrl; // the final destination, including filename - - if ( srcUrl.isEmpty() ) - { - //No src location: we let the user insert it manually - srcUrl = urlInputDialog(); - if( srcUrl.isEmpty() ) - return 0; - } - - if ( !isValidSource( srcUrl ) ) - return 0; - - // when we get a destination directory and suggested filename, we don't - // need to ask for it again - bool confirmDestination = false; - if (destDir.isEmpty()) - { - confirmDestination = true; - QList list = groupsFromExceptions(srcUrl); - if (!list.isEmpty()) { - destDir = list.first()->defaultFolder(); - groupName = list.first()->name(); - } - - } else { - // check whether destDir is actually already the path to a file - KUrl targetUrl = KUrl(destDir); - QString directory = targetUrl.directory(KUrl::LeaveTrailingSlash); - QString fileName = targetUrl.fileName(KUrl::LeaveTrailingSlash); - if (QFileInfo(directory).isDir() && !fileName.isEmpty()) { - destDir = directory; - suggestedFileName = fileName; - } - } - - if (suggestedFileName.isEmpty()) - { - confirmDestination = true; - suggestedFileName = srcUrl.fileName(KUrl::LeaveTrailingSlash); - if (suggestedFileName.isEmpty()) - { - // simply use the full url as filename - suggestedFileName = KUrl::toPercentEncoding( srcUrl.prettyUrl(), "/" ); - } - } - - // now ask for confirmation of the entire destination url (dir + filename) - if (confirmDestination || !isValidDestDirectory(destDir)) - { - do - { - destUrl = destFileInputDialog(destDir, suggestedFileName); - if (destUrl.isEmpty()) - return 0; - - destDir = destUrl.directory(KUrl::LeaveTrailingSlash); - } while (!isValidDestDirectory(destDir)); - } else { - destUrl = KUrl(); - destUrl.setDirectory(destDir); - destUrl.addPath(suggestedFileName); - } - destUrl = getValidDestUrl(destUrl, srcUrl); - - if (destUrl == KUrl()) - return 0; - - TransferHandler *transfer = createTransfer(srcUrl, destUrl, groupName, start); - if (transfer) { - KNotification *notification = KGet::showNotification( - m_mainWindow, - "kget/added", - i18n("

The following transfer has been added to the download list:

%1

", transfer->source().pathOrUrl()), - "kget", - i18n("Download added") - ); - notification->send(); - } - - return transfer; -} - -QList KGet::addTransfers(const QList &elements, const QString &groupName) -{ - QList data; - - foreach(const QDomElement &e, elements) { - //We need to read these attributes now in order to know which transfer - //plugin to use. - KUrl srcUrl = KUrl(e.attribute("Source")); - KUrl destUrl = KUrl(e.attribute("Dest")); - data << TransferData(srcUrl, destUrl, groupName, false, &e); - - kDebug() << "src=" << srcUrl << " dest=" << destUrl << " group=" << groupName; - } - - return createTransfers(data); -} - -const QList KGet::addTransfer(KUrl::List srcUrls, QString destDir, QString groupName, bool start) -{ - KUrl::List urlsToDownload; - - KUrl::List::Iterator it = srcUrls.begin(); - KUrl::List::Iterator itEnd = srcUrls.end(); - - QList addedTransfers; - - for(; it!=itEnd ; ++it) - { - *it = mostLocalUrl(*it); - if ( isValidSource( *it ) ) - urlsToDownload.append( *it ); - } - - if ( urlsToDownload.count() == 0 ) - return addedTransfers; - - if ( urlsToDownload.count() == 1 ) - { - // just one file -> ask for filename - TransferHandler * newTransfer = addTransfer(srcUrls.first(), destDir, srcUrls.first().fileName(), groupName, start); - - if (newTransfer) { - addedTransfers.append(newTransfer); - } - - return addedTransfers; - } - - KUrl destUrl; - - // multiple files -> ask for directory, not for every single filename - if (!isValidDestDirectory(destDir))//TODO: Move that after the for-loop - destDir = destDirInputDialog(); - - it = urlsToDownload.begin(); - itEnd = urlsToDownload.end(); - - QList data; - for ( ; it != itEnd; ++it ) - { - if (destDir.isEmpty()) - { - //TODO only use groupsFromExceptions if that is allowed in the settings - QList list = groupsFromExceptions(*it); - if (!list.isEmpty()) { - destDir = list.first()->defaultFolder(); - groupName = list.first()->name(); - } - } - destUrl = getValidDestUrl(KUrl(destDir), *it); - - if (destUrl == KUrl()) - continue; - - data << TransferData(*it, destUrl, groupName, start); - } - - QList transfers = createTransfers(data); - if (!transfers.isEmpty()) { - QString urls = transfers[0]->source().pathOrUrl(); - for (int i = 1; i < transfers.count(); ++i) { - urls += '\n' + transfers[i]->source().pathOrUrl(); - } - - QString message; - if (transfers.count() == 1) { - message = i18n("

The following transfer has been added to the download list:

"); - } else { - message = i18n("

The following transfers have been added to the download list:

"); - } - const QString content = QString("

%1

").arg(urls); - KNotification *notification = KGet::showNotification( - m_mainWindow, - "kget/added", - message + content, - "kget", - i18n("Download added") - ); - notification->send(); - } - - return transfers; -} - - -bool KGet::delTransfer(TransferHandler * transfer, DeleteMode mode) -{ - return delTransfers(QList() << transfer, mode); -} - -bool KGet::delTransfers(const QList &handlers, DeleteMode mode) -{ - if (!m_store) { - m_store = TransferHistoryStore::getStore(); - } - QList transfers; - QList historyItems; - foreach (TransferHandler *handler, handlers) { - Transfer *transfer = handler->m_transfer; - transfers << transfer; - historyItems << TransferHistoryItem(*transfer); - - // TransferHandler deinitializations - handler->destroy(); - // Transfer deinitializations (the deinit function is called by the destroy() function) - if (mode == AutoDelete) { - Transfer::DeleteOptions o = Transfer::DeleteTemporaryFiles; - if (transfer->status() != Job::Finished && transfer->status() != Job::FinishedKeepAlive) - o |= Transfer::DeleteFiles; - transfer->destroy(o); - } else { - transfer->destroy((Transfer::DeleteTemporaryFiles | Transfer::DeleteFiles)); - } - } - m_store->saveItems(historyItems); - - m_transferTreeModel->delTransfers(transfers); - qDeleteAll(transfers); - return true; -} - - -void KGet::moveTransfer(TransferHandler * transfer, const QString& groupName) -{ - Q_UNUSED(transfer) - Q_UNUSED(groupName) -} - -void KGet::redownloadTransfer(TransferHandler * transfer) -{ - QString group = transfer->group()->name(); - QString src = transfer->source().url(); - QString dest = transfer->dest().url(); - QString destFile = transfer->dest().fileName(); - - KGet::delTransfer(transfer); - KGet::addTransfer(src, dest, destFile, group, true); -} - -QList KGet::selectedTransfers() -{ - // kDebug() << "KGet::selectedTransfers"; - - QList selectedTransfers; - - QModelIndexList selectedIndexes = m_selectionModel->selectedRows(); - //sort the indexes as this can speed up operations like deleting etc. - qSort(selectedIndexes.begin(), selectedIndexes.end()); - - foreach(const QModelIndex ¤tIndex, selectedIndexes) - { - ModelItem * item = m_transferTreeModel->itemFromIndex(currentIndex); - if (!item->isGroup()) - selectedTransfers.append(item->asTransfer()->transferHandler()); - } - - return selectedTransfers; - - -// This is the code that was used in the old selectedTransfers function -/* QList::const_iterator it = m_transferTreeModel->transferGroups().begin(); - QList::const_iterator itEnd = m_transferTreeModel->transferGroups().end(); - - for( ; it!=itEnd ; ++it ) - { - TransferGroup::iterator it2 = (*it)->begin(); - TransferGroup::iterator it2End = (*it)->end(); - - for( ; it2!=it2End ; ++it2 ) - { - Transfer * transfer = (Transfer*) *it2; - - if( transfer->isSelected() ) - selectedTransfers.append( transfer->handler() ); - } - } - return selectedTransfers;*/ -} - -QList KGet::finishedTransfers() -{ - QList finishedTransfers; - - foreach(TransferHandler *transfer, allTransfers()) - { - if (transfer->status() == Job::Finished) { - finishedTransfers << transfer; - } - } - return finishedTransfers; -} - -QList KGet::selectedTransferGroups() -{ - QList selectedTransferGroups; - - QModelIndexList selectedIndexes = m_selectionModel->selectedRows(); - - foreach(const QModelIndex ¤tIndex, selectedIndexes) - { - ModelItem * item = m_transferTreeModel->itemFromIndex(currentIndex); - if (item->isGroup()) { - TransferGroupHandler *group = item->asGroup()->groupHandler(); - selectedTransferGroups.append(group); - } - } - - return selectedTransferGroups; -} - -TransferTreeModel * KGet::model() -{ - return m_transferTreeModel; -} - -TransferTreeSelectionModel * KGet::selectionModel() -{ - return m_selectionModel; -} - - -void KGet::load( QString filename ) // krazy:exclude=passbyvalue -{ - kDebug() << "(" << filename << ")"; - - if(filename.isEmpty()) - filename = KStandardDirs::locateLocal("appdata", "transfers.kgt"); - - QString tmpFile; - - //Try to save the transferlist to a temporary location - if(!KIO::NetAccess::download(KUrl(filename), tmpFile, 0)) { - if (m_transferTreeModel->transferGroups().isEmpty()) //Create the default group - addGroup(i18n("My Downloads")); - return; - } - - QFile file(tmpFile); - QDomDocument doc; - - kDebug() << "file:" << filename; - - if(doc.setContent(&file)) - { - QDomElement root = doc.documentElement(); - - QDomNodeList nodeList = root.elementsByTagName("TransferGroup"); - int nItems = nodeList.length(); - - for( int i = 0 ; i < nItems ; i++ ) - { - TransferGroup * foundGroup = m_transferTreeModel->findGroup( nodeList.item(i).toElement().attribute("Name") ); - - kDebug() << "KGet::load -> group = " << nodeList.item(i).toElement().attribute("Name"); - - if( !foundGroup ) - { - kDebug() << "KGet::load -> group not found"; - - TransferGroup * newGroup = new TransferGroup(m_transferTreeModel, m_scheduler); - - m_transferTreeModel->addGroup(newGroup); - - newGroup->load(nodeList.item(i).toElement()); - } - else - { - kDebug() << "KGet::load -> group found"; - - //A group with this name already exists. - //Integrate the group's transfers with the ones read from file - foundGroup->load(nodeList.item(i).toElement()); - } - } - } - else - { - kWarning() << "Error reading the transfers file"; - } - - if (m_transferTreeModel->transferGroups().isEmpty()) //Create the default group - addGroup(i18n("My Downloads")); - - new GenericObserver(m_mainWindow); -} - -void KGet::save( QString filename, bool plain ) // krazy:exclude=passbyvalue -{ - if ( !filename.isEmpty() - && QFile::exists( filename ) - && (KMessageBox::questionYesNoCancel(0, - i18n("The file %1 already exists.\nOverwrite?", filename), - i18n("Overwrite existing file?"), KStandardGuiItem::yes(), - KStandardGuiItem::no(), KStandardGuiItem::cancel(), "QuestionFilenameExists" ) - != KMessageBox::Yes) ) - return; - - if(filename.isEmpty()) - filename = KStandardDirs::locateLocal("appdata", "transfers.kgt"); - - KSaveFile file(filename); - if ( !file.open( QIODevice::WriteOnly ) ) - { - // kWarning() << "Unable to open output file when saving"; - KNotification *notification = KGet::showNotification( - m_mainWindow, "kget/error", - i18n("Unable to save to: %1", filename) - ); - notification->send(); - return; - } - - if (plain) { - QTextStream out(&file); - foreach(TransferHandler *handler, allTransfers()) { - out << handler->source().prettyUrl() << endl; - } - } - else { - QDomDocument doc(QString("KGetTransfers")); - QDomElement root = doc.createElement("Transfers"); - doc.appendChild(root); - - foreach (TransferGroup * group, m_transferTreeModel->transferGroups()) - { - QDomElement e = doc.createElement("TransferGroup"); - root.appendChild(e); - group->save(e); - //KGet::delGroup((*it)->name()); - } - - QTextStream stream( &file ); - doc.save( stream, 2 ); - } - file.finalize(); -} - -QList KGet::factories() -{ - return m_transferFactories; -} - -TransferFactory * KGet::factory(TransferHandler * transfer) -{ - return transfer->m_transfer->factory(); -} - -KActionCollection * KGet::actionCollection() -{ - return m_mainWindow->actionCollection(); -} - -void KGet::setSchedulerRunning(bool running) -{ - if(running) - { - m_scheduler->stop(); //stopall first, to have a clean startingpoint - m_scheduler->start(); - } - else - m_scheduler->stop(); -} - -bool KGet::schedulerRunning() -{ - return (m_scheduler->hasRunningJobs()); -} - -void KGet::setSuspendScheduler(bool isSuspended) -{ - m_scheduler->setIsSuspended(isSuspended); -} - -QList KGet::allTransfers() -{ - QList transfers; - - foreach (TransferGroup *group, KGet::m_transferTreeModel->transferGroups()) - { - transfers << group->handler()->transfers(); - } - return transfers; -} - -QList KGet::allTransferGroups() -{ - QList transfergroups; - - foreach (TransferGroup *group, KGet::m_transferTreeModel->transferGroups()) - { - kDebug() << group->name(); - transfergroups << group->handler(); - } - return transfergroups; -} - -TransferHandler * KGet::findTransfer(const KUrl &src) -{ - Transfer *transfer = KGet::m_transferTreeModel->findTransfer(src); - if (transfer) - { - return transfer->handler(); - } - return 0; -} - -TransferGroupHandler * KGet::findGroup(const QString &name) -{ - TransferGroup *group = KGet::m_transferTreeModel->findGroup(name); - if (group) - { - return group->handler(); - } - return 0; -} - -void KGet::checkSystemTray() -{ - bool running = false; - - foreach (TransferHandler *handler, KGet::allTransfers()) - { - if (handler->status() == Job::Running) - { - running = true; - break; - } - } - - m_mainWindow->setSystemTrayDownloading(running); -} - -void KGet::settingsChanged() -{ - foreach (TransferFactory *factory, m_transferFactories) - { - factory->settingsChanged(); - } - - m_jobManager->settingsChanged(); - m_scheduler->settingsChanged(); -} - -QList KGet::groupsFromExceptions(const KUrl &filename) -{ - QList handlers; - foreach (TransferGroupHandler * handler, allTransferGroups()) { - const QStringList patterns = handler->regExp().pattern().split(',');//FIXME 4.5 add a tooltip: "Enter a list of foo separated by ," and then do split(i18nc("used as separator in a list, translate to the same thing you translated \"Enter a list of foo separated by ,\"", ",")) - if (matchesExceptions(filename, patterns)) { - handlers.append(handler); - } - } - - return handlers; -} - -bool KGet::matchesExceptions(const KUrl &sourceUrl, const QStringList &patterns) -{ - foreach (const QString &pattern, patterns) { - const QString trimmedPattern = pattern.trimmed(); - if (trimmedPattern.isEmpty()) { - continue; - } - QRegExp regExp = QRegExp(trimmedPattern); - - //try with Regular Expression first - regExp.setPatternSyntax(QRegExp::RegExp2); - regExp.setCaseSensitivity(Qt::CaseInsensitive); - if (regExp.exactMatch(sourceUrl.url())) { - return true; - } - - //now try with wildcards - if (!regExp.pattern().isEmpty() && !regExp.pattern().contains('*')) { - regExp.setPattern('*' + regExp.pattern()); - } - - regExp.setPatternSyntax(QRegExp::Wildcard); - regExp.setCaseSensitivity(Qt::CaseInsensitive); - - if (regExp.exactMatch(sourceUrl.url())) { - return true; - } - } - - return false; -} - -void KGet::setGlobalDownloadLimit(int limit) -{ - m_scheduler->setDownloadLimit(limit); -} - -void KGet::setGlobalUploadLimit(int limit) -{ - m_scheduler->setUploadLimit(limit); -} - -void KGet::calculateGlobalSpeedLimits() -{ - //if (m_scheduler->downloadLimit())//TODO: Remove this and the both other hacks in the 2 upper functions with a better replacement - m_scheduler->calculateDownloadLimit(); - //if (m_scheduler->uploadLimit()) - m_scheduler->calculateUploadLimit(); -} - -void KGet::calculateGlobalDownloadLimit() -{ - m_scheduler->calculateDownloadLimit(); -} - -void KGet::calculateGlobalUploadLimit() -{ - m_scheduler->calculateUploadLimit(); -} - -// ------ STATIC MEMBERS INITIALIZATION ------ -TransferTreeModel * KGet::m_transferTreeModel; -TransferTreeSelectionModel * KGet::m_selectionModel; -QList KGet::m_transferFactories; -TransferGroupScheduler * KGet::m_scheduler = 0; -MainWindow * KGet::m_mainWindow = 0; -KUiServerJobs * KGet::m_jobManager = 0; -TransferHistoryStore * KGet::m_store = 0; -KNetworkManager * KGet::m_networkManager = 0; -bool KGet::m_hasConnection = true; - -// ------ PRIVATE FUNCTIONS ------ -KGet::KGet() -{ - m_networkManager = new KNetworkManager(); - m_scheduler = new TransferGroupScheduler(); - m_transferTreeModel = new TransferTreeModel(m_scheduler); - m_selectionModel = new TransferTreeSelectionModel(m_transferTreeModel); - - QObject::connect(m_transferTreeModel, SIGNAL(transfersAddedEvent(QList)), - m_jobManager, SLOT(slotTransfersAdded(QList))); - QObject::connect(m_transferTreeModel, SIGNAL(transfersAboutToBeRemovedEvent(QList)), - m_jobManager, SLOT(slotTransfersAboutToBeRemoved(QList))); - QObject::connect(m_transferTreeModel, SIGNAL(transfersChangedEvent(QMap)), - m_jobManager, SLOT(slotTransfersChanged(QMap))); - - //check if there is a connection - const KNetworkManager::KNetworkStatus status = m_networkManager->status(); - KGet::setHasNetworkConnection(status == KNetworkManager::ConnectedStatus); - - //Load all the available plugins - loadPlugins(); -} - -KGet::~KGet() -{ - kDebug(); - delete m_networkManager; - delete m_transferTreeModel; - delete m_jobManager; //This one must always be before the scheduler otherwise the job manager can't remove the notifications when deleting. - delete m_scheduler; - delete m_store; - -} - -TransferHandler * KGet::createTransfer(const KUrl &src, const KUrl &dest, const QString& groupName, - bool start, const QDomElement * e) -{ - QList transfer = createTransfers(QList() << TransferData(src, dest, groupName, start, e)); - return (transfer.isEmpty() ? 0 : transfer.first()); -} - -QList KGet::createTransfers(const QList &dataItems) -{ - QList handlers; - if (dataItems.isEmpty()) { - return handlers; - } - - QList start; - QHash > groups; - - QStringList urlsFailed; - foreach (const TransferData &data, dataItems) { - kDebug() << "srcUrl=" << data.src << " destUrl=" << data.dest << " group=" << data.groupName; - - TransferGroup *group = m_transferTreeModel->findGroup(data.groupName); - if (!group) { - kDebug() << "KGet::createTransfer -> group not found"; - group = m_transferTreeModel->transferGroups().first(); - } - - Transfer *newTransfer = 0; - foreach (TransferFactory *factory, m_transferFactories) { - kDebug() << "Trying plugin n.plugins=" << m_transferFactories.size(); - if ((newTransfer = factory->createTransfer(data.src, data.dest, group, m_scheduler))) { - // kDebug() << "KGet::createTransfer -> CREATING NEW TRANSFER ON GROUP: _" << group->name() << "_"; - newTransfer->create(); - newTransfer->load(data.e); - handlers << newTransfer->handler(); - groups[group] << newTransfer; - start << data.start; - break; - } - } - if (!newTransfer) { - urlsFailed << data.src.url(); - kWarning() << "Warning! No plugin found to handle" << data.src; - } - } - - //show urls that failed - if (!urlsFailed.isEmpty()) { - QString message = i18np("

The following URL cannot be downloaded, its protocol is not supported by KGet:

", - "

The following URLs cannot be downloaded, their protocols are not supported by KGet:

", - urlsFailed.count()); - - QString content = urlsFailed.takeFirst(); - foreach (const QString &url, urlsFailed) { - content += '\n' + url; - } - content = QString("

%1

").arg(content); - - KNotification *notification = KGet::showNotification( - m_mainWindow, - "kget/error", - message + content, - "dialog-error", - i18n("Protocol unsupported") - ); - notification->send(); - } - - //add the created transfers to the model and start them if specified - QHash >::const_iterator it; - QHash >::const_iterator itEnd = groups.constEnd(); - for (it = groups.constBegin(); it != itEnd; ++it) { - KGet::model()->addTransfers(it.value(), it.key()); - } - for (int i = 0; i < handlers.count(); ++i) { - if (start[i]) { - handlers[i]->start(); - } - } - - return handlers;//TODO implement error message if it is 0, or should the addTransfers stuff do that, in case if the numer of returned items does not match the number of sent data? -} - -TransferDataSource * KGet::createTransferDataSource(const KUrl &src, const QDomElement &type, QObject *parent) -{ - TransferDataSource *dataSource; - foreach (TransferFactory *factory, m_transferFactories) - { - dataSource = factory->createTransferDataSource(src, type, parent); - if(dataSource) - return dataSource; - } - return 0; -} - -QString KGet::generalDestDir(bool preferXDGDownloadDir) -{ - QString dir = Settings::lastDirectory(); - - if (preferXDGDownloadDir) { - dir = KGlobalSettings::downloadPath(); - } - - return dir; -} - -KUrl KGet::urlInputDialog() -{ - QString newtransfer; - bool ok = false; - - KUrl clipboardUrl = KUrl(QApplication::clipboard()->text(QClipboard::Clipboard).trimmed()); - if (clipboardUrl.isValid()) - newtransfer = clipboardUrl.url(); - - while (!ok) - { - newtransfer = KInputDialog::getText(i18n("New Download"), i18n("Enter URL:"), newtransfer, &ok, 0); - newtransfer = newtransfer.trimmed(); //Remove any unnecessary space at the beginning and/or end - - if (!ok) - { - //user pressed cancel - return KUrl(); - } - - KUrl src = KUrl(newtransfer); - if(src.isValid()) - return src; - else - ok = false; - } - return KUrl(); -} - -QString KGet::destDirInputDialog() -{ - QString destDir = KFileDialog::getExistingDirectory(generalDestDir()); - Settings::setLastDirectory(destDir); - - return destDir; -} - -KUrl KGet::destFileInputDialog(QString destDir, const QString& suggestedFileName) // krazy:exclude=passbyvalue -{ - if (destDir.isEmpty()) - destDir = generalDestDir(); - - // Use the destination name if not empty... - KUrl startLocation(destDir); - if (!suggestedFileName.isEmpty()) { - startLocation.addPath(suggestedFileName); - } - - KUrl destUrl = KFileDialog::getSaveUrl(startLocation, QString(), m_mainWindow, i18n("Save As")); - if (!destUrl.isEmpty()) { - Settings::setLastDirectory(destUrl.directory(KUrl::LeaveTrailingSlash)); - } - - return destUrl; -} - -bool KGet::isValidSource(const KUrl &source) -{ - // Check if the URL is well formed - if (!source.isValid()) { - KNotification *notification = KGet::showNotification( - m_mainWindow, "kget/error", - i18n("Malformed URL:\n%1", source.prettyUrl()) - ); - notification->send(); - return false; - } - // Check if the URL contains the protocol - if (source.protocol().isEmpty()){ - KNotification *notification = KGet::showNotification( - m_mainWindow, "kget/error", - i18n("Malformed URL, protocol missing:\n%1", source.prettyUrl()) - ); - notification->send(); - return false; - } - // Check if a transfer with the same url already exists - Transfer * transfer = m_transferTreeModel->findTransfer( source ); - if (transfer) - { - if (transfer->status() == Job::Finished) { - // transfer is finished, ask if we want to download again - if (KMessageBox::questionYesNoCancel(0, - i18n("You have already completed a download from the location: \n\n%1\n\nDownload it again?", source.prettyUrl()), - i18n("Download it again?"), KStandardGuiItem::yes(), - KStandardGuiItem::no(), KStandardGuiItem::cancel()) - == KMessageBox::Yes) { - transfer->stop(); - KGet::delTransfer(transfer->handler()); - return true; - } - else - return false; - } - else { - if (KMessageBox::warningYesNoCancel(0, - i18n("You have a download in progress from the location: \n\n%1\n\nDelete it and download again?", source.prettyUrl()), - i18n("Delete it and download again?"), KStandardGuiItem::yes(), - KStandardGuiItem::no(), KStandardGuiItem::cancel()) - == KMessageBox::Yes) { - transfer->stop(); - KGet::delTransfer(transfer->handler()); - return true; - } - else - return false; - } - return false; - } - return true; -} - -bool KGet::isValidDestDirectory(const QString & destDir) -{ - kDebug() << destDir; - if (!QFileInfo(destDir).isDir()) - { - if (QFileInfo(KUrl(destDir).directory()).isWritable()) - return (!destDir.isEmpty()); - if (!QFileInfo(KUrl(destDir).directory()).isWritable() && !destDir.isEmpty()) - KMessageBox::error(0, i18n("Directory is not writable")); - } - else - { - if (QFileInfo(destDir).isWritable()) - return (!destDir.isEmpty()); - if (!QFileInfo(destDir).isWritable() && !destDir.isEmpty()) - KMessageBox::error(0, i18n("Directory is not writable")); - } - return false; -} - -KUrl KGet::getValidDestUrl(const KUrl& destDir, const KUrl &srcUrl) -{ - kDebug() << "Source Url" << srcUrl << "Destination" << destDir; - if ( !isValidDestDirectory(destDir.toLocalFile()) ) - return KUrl(); - - KUrl destUrl = destDir; - - if (QFileInfo(destUrl.toLocalFile()).isDir()) - { - QString filename = srcUrl.fileName(); - if (filename.isEmpty()) - filename = KUrl::toPercentEncoding( srcUrl.prettyUrl(), "/" ); - destUrl.adjustPath( KUrl::AddTrailingSlash ); - destUrl.setFileName( filename ); - } - - Transfer * existingTransferDest = m_transferTreeModel->findTransferByDestination(destUrl); - QPointer dlg = 0; - - if (existingTransferDest) { - if (existingTransferDest->status() == Job::Finished) { - if (KMessageBox::questionYesNoCancel(0, - i18n("You have already downloaded that file from another location.\n\nDownload and delete the previous one?"), - i18n("File already downloaded. Download anyway?"), KStandardGuiItem::yes(), - KStandardGuiItem::no(), KStandardGuiItem::cancel()) - == KMessageBox::Yes) { - existingTransferDest->stop(); - KGet::delTransfer(existingTransferDest->handler()); - //start = true; - } else - return KUrl(); - } else { - dlg = new KIO::RenameDialog( m_mainWindow, i18n("You are already downloading the same file"/*, destUrl.prettyUrl()*/), srcUrl, - destUrl, KIO::M_MULTI ); - } - } else if (srcUrl == destUrl) { - dlg = new KIO::RenameDialog(m_mainWindow, i18n("File already exists"), srcUrl, - destUrl, KIO::M_MULTI); - } else if (destUrl.isLocalFile() && QFile::exists(destUrl.toLocalFile())) { - dlg = new KIO::RenameDialog( m_mainWindow, i18n("File already exists"), srcUrl, - destUrl, KIO::M_OVERWRITE ); - } - - if (dlg) { - int result = dlg->exec(); - - if (result == KIO::R_RENAME || result == KIO::R_OVERWRITE) - destUrl = dlg->newDestUrl(); - else { - delete(dlg); - return KUrl(); - } - - delete(dlg); - } - - return destUrl; -} - -void KGet::loadPlugins() -{ - m_transferFactories.clear(); - // Add versioning constraint - QString - str = "[X-KDE-KGet-framework-version] == "; - str += QString::number( FrameworkVersion ); - str += " and "; - str += "[X-KDE-KGet-rank] > 0"; - str += " and "; - str += "[X-KDE-KGet-plugintype] == "; - - - //TransferFactory plugins - KService::List offers = KServiceTypeTrader::self()->query( "KGet/Plugin", str + "'TransferFactory'" ); - - //Here we use a QMap only to easily sort the plugins by rank - QMap services; - QMap::ConstIterator it; - - for ( int i = 0; i < offers.count(); ++i ) - { - services[ offers[i]->property( "X-KDE-KGet-rank" ).toInt() ] = offers[i]; - kDebug() << " TransferFactory plugin found:\n" << - " rank = " << offers[i]->property( "X-KDE-KGet-rank" ).toInt() << '\n' << - " plugintype = " << offers[i]->property( "X-KDE-KGet-plugintype" ); - } - - //I must fill this pluginList before and my m_transferFactories list after. - //This because calling the KLibLoader::globalLibrary() erases the static - //members of this class (why?), such as the m_transferFactories list. - QList pluginList; - - const KConfigGroup plugins = KConfigGroup(KGlobal::config(), "Plugins"); - - foreach (KService::Ptr service, services) - { - KPluginInfo info(service); - info.load(plugins); - - if( !info.isPluginEnabled() ) { - kDebug() << "TransferFactory plugin (" << service->library() - << ") found, but not enabled"; - continue; - } - - KGetPlugin * plugin; - if( (plugin = createPluginFromService(service)) != 0 ) - { - const QString pluginName = info.name(); - - pluginList.prepend(plugin); - kDebug() << "TransferFactory plugin (" << (service)->library() - << ") found and added to the list of available plugins"; - } - else - { - kDebug() << "Error loading TransferFactory plugin (" - << service->library() << ")"; - } - } - - foreach (KGetPlugin *plugin, pluginList) - { - m_transferFactories.append(qobject_cast(plugin)); - } - - kDebug() << "Number of factories = " << m_transferFactories.size(); -} - - -void KGet::setHasNetworkConnection(bool hasConnection) -{ - kDebug() << "Existing internet connection:" << hasConnection << "old:" << m_hasConnection; - if (hasConnection == m_hasConnection) { - return; - } - m_hasConnection = hasConnection; - const bool initialState = m_scheduler->hasRunningJobs(); - m_scheduler->setHasNetworkConnection(hasConnection); - const bool finalState = m_scheduler->hasRunningJobs(); - - if (initialState != finalState) { - KNotification *notification = nullptr; - if (hasConnection) { - notification = KGet::showNotification( - m_mainWindow, "kget/notification", - i18n("Internet connection established, resuming transfers."), - "dialog-info" - ); - - } else { - notification = KGet::showNotification( - m_mainWindow, - "kget/notification", - i18n("No internet connection, stopping transfers."), - "dialog-info" - ); - } - notification->send(); - } -} - -KGetPlugin * KGet::createPluginFromService( const KService::Ptr &service ) -{ - //try to load the specified library - KPluginLoader loader(service->library()); - KPluginFactory *factory = loader.factory(); - - if (!factory) - { - KNotification *notification = KGet::showNotification( - m_mainWindow, - "kget/error", - i18n("Plugin loader could not load the plugin: %1.", service->library()), - "dialog-info" - ); - notification->send(); - kError() << "KPluginFactory could not load the plugin:" << service->library() << loader.errorString(); - return 0; - } - KGetPlugin * plugin = factory->create< TransferFactory >(KGet::m_mainWindow); - - return plugin; -} - -bool KGet::safeDeleteFile( const KUrl& url ) -{ - if ( url.isLocalFile() ) { - QFileInfo info( url.toLocalFile() ); - if (info.isDir()) { - KNotification *notification = KGet::showNotification( - m_mainWindow, "kget/notification", - i18n("Not deleting\n%1\nas it is a directory.", url.prettyUrl()), - "dialog-info" - ); - notification->send(); - return false; - } - KIO::NetAccess::del( url, 0L ); - return true; - } - KNotification *notification = KGet::showNotification( - m_mainWindow, - "kget/notification", - i18n("Not deleting\n%1\nas it is not a local file.", url.prettyUrl()), - "dialog-info" - ); - notification->send(); - return false; -} - -KNotification *KGet::showNotification(QWidget *parent, const QString &eventType, - const QString &text, const QString &icon, const QString &title, const KNotification::NotificationFlags &flags) -{ - KNotification *notification = new KNotification(parent); - notification->setEventID(eventType); - notification->setText(text); - notification->setIcon(icon); - notification->setTitle(title); - notification->setWidget(parent); - notification->setFlags(flags); - return notification; -} - -GenericObserver::GenericObserver(QObject *parent) - : QObject(parent), - m_save(0), - m_finishAction(0), - m_allFinished(false) -{ - connect(KGet::model(), SIGNAL(groupRemovedEvent(TransferGroupHandler*)), SLOT(groupRemovedEvent(TransferGroupHandler*))); - connect(KGet::model(), SIGNAL(transfersAddedEvent(QList)), - SLOT(transfersAddedEvent(QList))); - connect(KGet::model(), SIGNAL(groupAddedEvent(TransferGroupHandler*)), SLOT(groupAddedEvent(TransferGroupHandler*))); - connect(KGet::model(), SIGNAL(transfersRemovedEvent(QList)), - SLOT(transfersRemovedEvent(QList))); - connect(KGet::model(), SIGNAL(transfersChangedEvent(QMap)), - SLOT(transfersChangedEvent(QMap))); - connect(KGet::model(), SIGNAL(groupsChangedEvent(QMap)), - SLOT(groupsChangedEvent(QMap))); - connect(KGet::model(), SIGNAL(transferMovedEvent(TransferHandler*,TransferGroupHandler*)), - SLOT(transferMovedEvent(TransferHandler*,TransferGroupHandler*))); - connect(KGet::m_networkManager, SIGNAL(statusChanged(KNetworkManager::KNetworkStatus)), - this, SLOT(slotNetworkStatusChanged(KNetworkManager::KNetworkStatus))); - -} - -GenericObserver::~GenericObserver() -{ -} - -void GenericObserver::groupAddedEvent(TransferGroupHandler *handler) -{ - Q_UNUSED(handler) - KGet::save(); -} - -void GenericObserver::groupRemovedEvent(TransferGroupHandler *handler) -{ - Q_UNUSED(handler) - KGet::save(); -} - -void GenericObserver::transfersAddedEvent(const QList &handlers) -{ - Q_UNUSED(handlers) - requestSave(); - KGet::calculateGlobalSpeedLimits(); - KGet::checkSystemTray(); - m_allFinished = false; -} - -void GenericObserver::transfersRemovedEvent(const QList &handlers) -{ - Q_UNUSED(handlers) - requestSave(); - KGet::calculateGlobalSpeedLimits(); - KGet::checkSystemTray(); - m_allFinished = false; -} - -void GenericObserver::transferMovedEvent(TransferHandler *transfer, TransferGroupHandler *group) -{ - Q_UNUSED(transfer) - Q_UNUSED(group) - requestSave(); - KGet::calculateGlobalSpeedLimits(); -} - -void GenericObserver::requestSave() -{ - if (!m_save) { - m_save = new QTimer(this); - m_save->setInterval(5000); - connect(m_save, SIGNAL(timeout()), this, SLOT(slotSave())); - } - - //save regularly if there are running jobs - m_save->setSingleShot(!KGet::m_scheduler->hasRunningJobs()); - - if (!m_save->isActive()) { - m_save->start(); - } -} - -void GenericObserver::slotSave() -{ - KGet::save(); -} - -void GenericObserver::transfersChangedEvent(QMap transfers) -{ - bool checkSysTray = false; - bool allFinished = true; - QMap::const_iterator it; - QMap::const_iterator itEnd = transfers.constEnd(); - for (it = transfers.constBegin(); it != itEnd; ++it) - { - TransferHandler::ChangesFlags transferFlags = *it; - TransferHandler *transfer = it.key(); - - if (transferFlags & Transfer::Tc_Status) { - if ((transfer->status() == Job::Finished) && (transfer->startStatus() != Job::Finished)) { - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, "kget/finished", - i18n("

The following file has finished downloading:

%1

", transfer->dest().fileName()), - "kget", i18n("Download completed") - ); - notification->send(); - } else if (transfer->status() == Job::Running) { - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, "kget/started", - i18n("

The following transfer has been started:

%1

", transfer->source().pathOrUrl()), - "kget", i18n("Download started") - ); - notification->send(); - } else if (transfer->status() == Job::Aborted && transfer->error().type != Job::AutomaticRetry) { - KNotification* notification = new KNotification(this); - notification->setEventID("kget/error"); - notification->setTitle(i18n("Error")); - notification->setText( - i18n( - "

There has been an error in the following transfer:

%1

" - "

The error message is:

%2

", transfer->source().pathOrUrl(), transfer->error().text - ) - ); - notification->setIcon("kget"); - notification->setWidget(KGet::m_mainWindow); - if (transfer->error().type == Job::ManualSolve) { - m_notifications.insert(notification, transfer); - notification->setActions(QStringList() << i18n("Resolve")); - connect(notification, SIGNAL(action1Activated()), SLOT(slotResolveTransferError())); - connect(notification, SIGNAL(closed()), SLOT(slotNotificationClosed())); - } - notification->send(); - } - } - - if (transferFlags & Transfer::Tc_Status) { - checkSysTray = true; - requestSave(); - } - - if (transferFlags & Transfer::Tc_Percent) { - transfer->group()->setGroupChange(TransferGroup::Gc_Percent, true); - transfer->checkShareRatio(); - } - - if (transferFlags & Transfer::Tc_DownloadSpeed) { - transfer->group()->setGroupChange(TransferGroup::Gc_DownloadSpeed, true); - } - - if (transferFlags & Transfer::Tc_UploadSpeed) { - transfer->group()->setGroupChange(TransferGroup::Gc_UploadSpeed, true); - } - - if ((transfer->status() == Job::Finished) || (transfer->status() == Job::FinishedKeepAlive)) { - requestSave(); - } else { - allFinished = false; - } - } - allFinished = allFinished && allTransfersFinished(); - - if (checkSysTray) - KGet::checkSystemTray(); - - //only perform after finished actions if actually the status changed (that is the - //case if checkSysTray is set to true) - if (checkSysTray && Settings::afterFinishActionEnabled() && allFinished) - { - kDebug() << "All finished"; - KNotification *notification = nullptr; - - if (!m_finishAction) { - m_finishAction = new QTimer(this); - m_finishAction->setSingleShot(true); - m_finishAction->setInterval(10000); - connect(m_finishAction, SIGNAL(timeout()), this, SLOT(slotAfterFinishAction())); - } - - switch (Settings::afterFinishAction()) { - case KGet::Quit: - notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/notification", - i18n("KGet is now closing, as all downloads have completed."), - "kget", - "KGet", - KNotification::Persistent | KNotification::CloseWhenWidgetActivated - ); - break; -#ifdef HAVE_KWORKSPACE - case KGet::Shutdown: - notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/notification", - i18n("The computer will now turn off, as all downloads have completed."), - "system-shutdown", - i18nc("Shutting down computer", "Shutdown"), - KNotification::Persistent | KNotification::CloseWhenWidgetActivated - ); - break; -#endif - case KGet::Hibernate: - notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/notification", - i18n("The computer will now suspend to disk, as all downloads have completed."), - "system-suspend-hibernate", - i18nc("Hibernating computer", "Hibernating"), - KNotification::Persistent | KNotification::CloseWhenWidgetActivated - ); - break; - case KGet::Suspend: - notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/notification", - i18n("The computer will now suspend to RAM, as all downloads have completed."), - "system-suspend", - i18nc("Suspending computer", "Suspending"), - KNotification::Persistent | KNotification::CloseWhenWidgetActivated - ); - break; - default: - break; - } - - if (notification) { - notification->setActions(QStringList() << i18nc("abort the proposed action", "Abort")); - connect(notification, SIGNAL(action1Activated()), this, SLOT(slotAbortAfterFinishAction())); - connect(m_finishAction, SIGNAL(timeout()), notification, SLOT(close())); - - if (!m_finishAction->isActive()) { - m_finishAction->start(); - } - } - } else if (allFinished && !m_allFinished) { - m_allFinished = true; - KNotification *notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/finishedall", - i18n("

All transfers have been finished.

"), - "kget", - i18n("Downloads completed") - ); - notification->send(); - } -} - -void GenericObserver::slotResolveTransferError() -{ - KNotification * notification = static_cast(QObject::sender()); - if (notification) { - TransferHandler * handler = m_notifications[notification]; - kDebug() << "Resolve error for" << handler->source().pathOrUrl() << "with id" << handler->error().id; - handler->resolveError(handler->error().id); - m_notifications.remove(notification); - } -} - -void GenericObserver::slotNotificationClosed() -{ - kDebug() << "Remove notification"; - KNotification * notification = static_cast(QObject::sender()); - if (notification) - m_notifications.remove(notification); -} - -void GenericObserver::slotNetworkStatusChanged(const KNetworkManager::KNetworkStatus status) -{ - KGet::setHasNetworkConnection(status == KNetworkManager::ConnectedStatus); -} - -void GenericObserver::groupsChangedEvent(QMap groups) -{ - bool recalculate = false; - foreach (const TransferGroup::ChangesFlags &flags, groups) - { - if (flags & TransferGroup::Gc_Percent || flags & TransferGroup::Gc_Status) { - recalculate = true; - break; - } - } - kDebug() << "Recalculate limits?" << recalculate; - if (recalculate) - KGet::calculateGlobalSpeedLimits(); -} - -bool GenericObserver::allTransfersFinished() -{ - bool quitFlag = true; - - // if all the downloads had state finished from - // the beginning - bool allWereFinished = true; - - foreach(TransferGroup *transferGroup, KGet::model()->transferGroups()) { - foreach(TransferHandler *transfer, transferGroup->handler()->transfers()) { - if ((transfer->status() != Job::Finished) && (transfer->status() != Job::FinishedKeepAlive)) { - quitFlag = false; - } - if ((transfer->status() == Job::Finished || transfer->status() == Job::FinishedKeepAlive) && - (transfer->startStatus() != Job::Finished && transfer->startStatus() != Job::FinishedKeepAlive)) { - allWereFinished = false; - } - } - } - - // if the only downloads in the queue - // are those that are already finished - // before the current KGet instance - // we don't want to quit - if (allWereFinished) - { - return false; - } - - // otherwise, we did some downloads right now, let quitFlag decide - return quitFlag; -} - -void GenericObserver::slotAfterFinishAction() -{ - switch (Settings::afterFinishAction()) { - case KGet::Quit: { - kDebug() << "Quit Kget."; - QTimer::singleShot(0, KGet::m_mainWindow, SLOT(slotQuit())); - break; - } -#ifdef HAVE_KWORKSPACE - case KGet::Shutdown: { - QTimer::singleShot(0, KGet::m_mainWindow, SLOT(slotQuit())); - KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmNo, - KWorkSpace::ShutdownTypeHalt, - KWorkSpace::ShutdownModeForceNow); - break; - } -#endif - case KGet::Hibernate: { - Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState); - break; - } - case KGet::Suspend: { - Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState); - break; - } - default: { - break; - } - } -} - -void GenericObserver::slotAbortAfterFinishAction() -{ - m_finishAction->stop(); -} - -#include "moc_kget.cpp" diff --git a/kget/core/kget.h b/kget/core/kget.h deleted file mode 100644 index ad01fadb..00000000 --- a/kget/core/kget.h +++ /dev/null @@ -1,496 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - Based on: - kmainwidget.{h,cpp} - Copyright (C) 2002 by Patrick Charbonnier - that was based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - - 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. -*/ - -#ifndef KGET_H -#define KGET_H - -#include -#include -#include -#include -#include -#include - -#include - -#include "kuiserverjobs.h" -#include "scheduler.h" -#include "../kget_export.h" -#include "transfer.h" -#include "transfergrouphandler.h" - -#include -#include -#include - -class KComboBox; - -class TransferDataSource; -class TransferGroup; -class TransferHandler; -class TransferFactory; -class TransferTreeModel; -class TransferTreeSelectionModel; -class KGetPlugin; -class MainWindow; -class NewTransferDialog; -class TransferGroupScheduler; -class TransferHistoryStore; - - -/** - * This is our KGet class. This is where the user's transfers and searches are - * stored and organized. - * Use this class from the views to add or remove transfers or searches - * In order to organize the transfers inside categories we have a TransferGroup - * class. By definition, a transfer must always belong to a TransferGroup. If we - * don't want it to be displayed by the gui inside a specific group, we will put - * it in the group named "Not grouped" (better name?). - **/ - -class KGET_EXPORT KGet -{ - friend class NewTransferDialog; - friend class NewTransferDialogHandler; - friend class GenericObserver; - friend class TransferTreeModel; - friend class UrlChecker; - friend class DlgWebinterface; - - public: - enum AfterFinishAction { - Quit = 0, - Shutdown = 1, - Hibernate = 2, - Suspend = 3 - }; - enum DeleteMode { - AutoDelete, - DeleteFiles - }; - ~KGet(); - - static KGet* self( MainWindow * mainWindow=0 ); - - /** - * Adds a new group to the KGet. - * - * @param groupName The name of the new group - * - * @returns true if the group has been successully added, otherwise - * it returns false, probably because a group with that named - * already exists - */ - static bool addGroup(const QString& groupName); - - /** - * Removes a group from the KGet. - * - * @param groupName The name of the group to be deleted - */ - static void delGroup(TransferGroupHandler * group, bool askUser = true); - - /** - * Removes specific groups from the KGet. - * - * @param groups The names of the groups to be deleted. - */ - static void delGroups(QList groups, bool askUser = true); - - /** - * Changes the name of the group - * - * @param oldName the name of the group to be changed - * @param newName the new name of the group - */ - static void renameGroup(const QString& oldName, const QString& newName); - - /** - * @returns the name of the available transfers groups - */ - static QStringList transferGroupNames(); - - /** - * Adds a new transfer to the KGet - * - * @param srcUrl The url to be downloaded - * @param destDir The destination directory. If empty we show a dialog - * where the user can choose it. - * @param suggestedFileName a suggestion of a simple filename to be saved in destDir - * @param groupName The name of the group the new transfer will belong to - * @param start Specifies if the newly added transfers should be started. - * If the group queue is already in a running state, this flag does nothing - */ - static TransferHandler * addTransfer(KUrl srcUrl, QString destDir = QString(), QString suggestedFileName = QString(), - QString groupName = QString(), bool start = false); - - /** - * Adds new transfers to the KGet, it is assumed that this takes place because of loading - * that results in less checks for loaction etc. - * - * @param elements The dom elements of the transfers to add - * @param groupName The name of the group the new transfer will belong to - */ - static QList addTransfers(const QList &elements, const QString &groupName = QString()); - - /** - * Adds new transfers to the KGet - * - * @param srcUrls The urls to be downloaded - * @param destDir The destination directory. If empty we show a dialog - * where the user can choose it. - * @param groupName The name of the group the new transfer will belong to - * @param start Specifies if the newly added transfers should be started. - * If the group queue is already in a running state, this flag does nothing - */ - static const QList addTransfer(KUrl::List srcUrls, QString destDir = QString(), - QString groupName = QString(), bool start=false); - - /** - * Removes a transfer from the KGet - * - * @param transfer The transfer to be removed - */ - static bool delTransfer(TransferHandler * transfer, DeleteMode mode = AutoDelete); - - /** - * Removes multiple transfers from the KGet - * - * @param transfers The transfers to be removed - */ - static bool delTransfers(const QList &transfers, DeleteMode mode = AutoDelete); - - /** - * Moves a transfer to a new group - * - * @param transfer The transfer to be moved - * @param groupName The name of the new transfer's group - */ - static void moveTransfer(TransferHandler * transfer, const QString& groupName); - - /** - * Redownload a transfer - * @param transfer the transfer to redownload - */ - static void redownloadTransfer(TransferHandler * transfer); - - /** - * @returns the list of selected transfers - */ - static QList selectedTransfers(); - - /** - * @returns the list of the finished transfers - */ - static QList finishedTransfers(); - - /** - * @returns the list of selected groups - */ - static QList - selectedTransferGroups(); - - /** - * @returns a pointer to the TransferTreeModel object - */ - static TransferTreeModel * model(); - - /** - * @returns a pointer to the QItemSelectionModel object - */ - static TransferTreeSelectionModel * selectionModel(); - - /** - * Imports the transfers and groups included in the provided xml file - * - * @param filename the file name to - */ - static void load( QString filename=QString() ); - - /** - * Exports all the transfers and groups to the given file - * - * @param filename the file name - * @param plain should list be in plain mode or kget mode - */ - static void save( QString filename=QString(), bool plain=false ); - - /** - * @returns a list of all transferfactories - */ - static QList factories(); - - /** - * @returns The factory of a given transfer - * - * @param transfer the transfer about which we want to have the factory - */ - static TransferFactory * factory(TransferHandler * transfer); - - /** - * @return a pointer to the KActionCollection objects - */ - static KActionCollection * actionCollection(); - - /** - * if running == true starts the scheduler - * if running == false stops the scheduler - */ - static void setSchedulerRunning(bool running=true); - - /** - * Returns true if the scheduler has running jobs. - */ - static bool schedulerRunning(); - - /** - * true suspends the scheduler, any events that would result in a reschedule are ignored - * false wakes up the scheduler, events result in reschedule again - * NOTE this is a HACK for cases where the scheduler is the bottleneck, e.g. when stopping - * a lot of running transfers, or starting a lot transfers - */ - static void setSuspendScheduler(bool isSuspended); - - /** - * Gets all transfers - */ - static QList allTransfers(); - - /** - * Gets all transfer-groups - */ - static QList allTransferGroups(); - - /** - * Get the transfer with the given url - * @param src the url - */ - static TransferHandler * findTransfer(const KUrl &src); - - /** - * Get the group with the given name - * @param name the name - */ - static TransferGroupHandler * findGroup(const QString &name); - - /** - * Run this function for enabling the systemTray - * (will be automatically done, if there is download running) - */ - static void checkSystemTray(); - - /** - * This will be called when the settings have been changed - */ - static void settingsChanged(); - - /** - * @return a list of the groups assigned to the filename of a transfer - */ - static QList groupsFromExceptions(const KUrl &filename); - - /** - * Returns true if sourceUrl matches any of the patterns - */ - static bool matchesExceptions(const KUrl &sourceUrl, const QStringList &patterns); - - /** - * Scans for all the available plugins and creates the proper - * transfer DataSource object for transfers Containers - * - * @param src Source Url - * @param type the type of the DataSource that should be created e.g. - * this is only needed when creating a "special" TransferDataSource like the search for Urls - * you can set additional information and the TransferDataSource will use it if it can - */ - static TransferDataSource * createTransferDataSource(const KUrl &src, const QDomElement &type = QDomElement(), QObject *parent = 0); - - /** - * Sets the global download limit - * @param limit the new global download limit - */ - static void setGlobalDownloadLimit(int limit); - - /** - * Sets the global upload limit - * @param limit the new global upload limit - */ - static void setGlobalUploadLimit(int limit); - - /** - * Recalculates the global speedlimits - */ - static void calculateGlobalSpeedLimits(); - - /** - * Recalculates the global download-limit - */ - static void calculateGlobalDownloadLimit(); - - /** - * Recalculates the global upload-limit - */ - static void calculateGlobalUploadLimit(); - - - /** - * Shows a knotification - * @param parent QWidget parent of the notification - * @param eventId Notification type - * @param text Description of the information showed by the notification - * @param icon Pixmap showed in the notification, by default 'dialog-error' - */ - static KNotification *showNotification(QWidget *parent, const QString &eventType, - const QString &text, - const QString &icon = QString("dialog-error"), - const QString &title = i18n("KGet"), - const KNotification::NotificationFlags &flags = KNotification::CloseOnTimeout); - - static void loadPlugins(); - - /** - * Returns a download directory - * @param preferXDGDownloadDir if true the XDG_DOWNLOAD_DIR will be taken if it is not empty - * @note depending if the directories exist it will return them in the following order: - * (preferXDGDownloadDirectory >) lastDirectory > XDG_DOWNLOAD_DIR - */ - static QString generalDestDir(bool preferXDGDownloadDir = false); - - - private: - KGet(); - - class TransferData; - - /** - * Scans for all the available plugins and creates the proper - * transfer object for the given src url - * - * @param src the source url - * @param dest the destination url - * @param groupName the group name - * @param start Specifies if the newly added transfers should be started. - */ - static TransferHandler * createTransfer(const KUrl &src, const KUrl &dest, const QString& groupName = QString(), bool start = false, const QDomElement * e = 0); - - /** - * Creates multiple transfers with transferData - */ - static QList createTransfers(const QList &transferData); - - static KUrl urlInputDialog(); - static QString destDirInputDialog(); - static KUrl destFileInputDialog(QString destDir = QString(), const QString& suggestedFileName = QString()); - - static bool isValidSource(const KUrl &source); - static bool isValidDestDirectory(const QString& destDir); - - static KUrl getValidDestUrl(const KUrl& destDir, const KUrl &srcUrl); - - //Plugin-related functions - static KGetPlugin * createPluginFromService( const KService::Ptr &service ); - - /** - * Stops all downloads if there is no connection and also displays - * a message. - * If there is a connection, then the downloads will be started again - */ - static void setHasNetworkConnection(bool hasConnection); - - /** - * Deletes the given file, if possible. - * - * @param url The file to delete - * - * @return true if the file was successully deleted: if the given url - * is a directory or if it is not local it returns false and shows a - * warning message. - */ - static bool safeDeleteFile( const KUrl& url ); - - //Interview models - static TransferTreeModel * m_transferTreeModel; - static TransferTreeSelectionModel * m_selectionModel; - - //Lists of available plugins - static QList m_transferFactories; - - //pointer to the Main window - static MainWindow * m_mainWindow; - - //Scheduler object - static TransferGroupScheduler * m_scheduler; - - //pointer to the kget uiserver jobs manager - static KUiServerJobs *m_jobManager; - - //pointer to the used TransferHistoryStore - static TransferHistoryStore *m_store; - - static KNetworkManager *m_networkManager; - static bool m_hasConnection; - -}; - -class KGET_EXPORT KGet::TransferData -{ - public: - TransferData(const KUrl &src, const KUrl &dest, const QString &groupName = QString(), bool start = false, const QDomElement *e = 0); - - KUrl src; - KUrl dest; - QString groupName; - bool start; - const QDomElement *e; -}; - -class GenericObserver : public QObject -{ - Q_OBJECT - public: - GenericObserver(QObject *parent = 0); - virtual ~GenericObserver (); - - public slots: - void groupAddedEvent(TransferGroupHandler *handler); - void groupRemovedEvent(TransferGroupHandler *handler); - void transfersAddedEvent(const QList &handlers); - void transfersRemovedEvent(const QList &handlers); - void transfersChangedEvent(QMap transfers); - void groupsChangedEvent(QMap groups); - void transferMovedEvent(TransferHandler *, TransferGroupHandler *); - - private slots: - void slotSave(); - void slotAfterFinishAction(); - void slotAbortAfterFinishAction(); - void slotResolveTransferError(); - void slotNotificationClosed(); - void slotNetworkStatusChanged(const KNetworkManager::KNetworkStatus status); - - private: - bool allTransfersFinished(); - - void requestSave(); - - private: - QTimer *m_save; - QTimer *m_finishAction; - bool m_allFinished; - QHash m_notifications; -}; -#endif diff --git a/kget/core/kgetglobaljob.cpp b/kget/core/kgetglobaljob.cpp deleted file mode 100644 index 03ae5986..00000000 --- a/kget/core/kgetglobaljob.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Javier Goday - Copyright (C) 2009 by Dario Massarin - - 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. -*/ -#include "kgetglobaljob.h" -#include "transferhandler.h" -#include "kget.h" - -#include -#include - -#include - -KGetGlobalJob::KGetGlobalJob(QObject *parent) - : KJob(parent) -{ - setCapabilities(Killable); -} - -KGetGlobalJob::~KGetGlobalJob() -{ -} - - -void KGetGlobalJob::update() -{ - int runningTransfers = 0; - qulonglong processedAmount = 0; - qulonglong totalAmount = 0; - unsigned long speed = 0; - unsigned long percent = 0; - - foreach(const TransferHandler * transfer, KGet::allTransfers()) { - if(transfer->status() == Job::Running) { - runningTransfers++; - processedAmount += transfer->downloadedSize(); - speed += transfer->downloadSpeed(); - totalAmount += transfer->totalSize(); - } - } - - // kDebug() << totalAmount; - - if (totalAmount > 0) - percent = 100 * processedAmount / totalAmount; - else - percent = 0; - - emit description(this, "KGet global information", - qMakePair(QString("source"), i18np("KGet is downloading %1 file", "KGet is downloading %1 files", runningTransfers))); - - emitSpeed(speed); - setTotalAmount(KJob::Bytes, totalAmount); - setProcessedAmount(KJob::Bytes, processedAmount); - - setPercent(percent); -} - -bool KGetGlobalJob::doKill() -{ - kDebug() << "Kill of global job called:" << this; - emit requestStop(this, 0); - return KJob::doKill(); -} diff --git a/kget/core/kgetglobaljob.h b/kget/core/kgetglobaljob.h deleted file mode 100644 index 1c5e4aa5..00000000 --- a/kget/core/kgetglobaljob.h +++ /dev/null @@ -1,43 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Javier Goday - Copyright (C) 2009 by Dario Massarin - - 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. -*/ -#ifndef KGETGLOBALJOB_H -#define KGETGLOBALJOB_H - -#include - -class TransferHandler; - -class KGetGlobalJob : public KJob -{ - Q_OBJECT -public: - KGetGlobalJob(QObject *parent=0); - ~KGetGlobalJob(); - - void update(); - - void start() {}; - -signals: - /** - * Emitted when doKill is called, e.g. when the gui is closed. - * Not handling this signal might lead to a crash if something tries to - * access the then non-existing gui. - * @param job is this - * @param handler is always 0 suggesting that all TransferHandlers should be stopped - */ - void requestStop(KJob *job, TransferHandler *handler); - -protected: - virtual bool doKill(); -}; - -#endif diff --git a/kget/core/kgetkjobadapter.cpp b/kget/core/kgetkjobadapter.cpp deleted file mode 100644 index 5a746881..00000000 --- a/kget/core/kgetkjobadapter.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - Idea by Copyright (C) 2008 Lukas Appelhans - - 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. -*/ -#include "kgetkjobadapter.h" - -#include - -KGetKJobAdapter::KGetKJobAdapter(QObject *parent, TransferHandler *transfer) - : KJob(parent), - m_transferHandler(transfer) -{ - setCapabilities(Killable | Suspendable); -} - -KGetKJobAdapter::~KGetKJobAdapter() -{ -} - -qulonglong KGetKJobAdapter::processedAmount(Unit unit) const -{ - Q_UNUSED(unit) - return m_transferHandler->downloadedSize(); -} - -qulonglong KGetKJobAdapter::totalAmount(Unit unit) const -{ - Q_UNUSED(unit) - return m_transferHandler->totalSize(); -} - -unsigned long KGetKJobAdapter::percent() const -{ - return m_transferHandler->percent(); -} - -void KGetKJobAdapter::slotUpdateDescription() -{ - emit description(this, i18n("KGet Transfer"), - qMakePair(QString("source"), m_transferHandler->source().prettyUrl()), - qMakePair(QString("destination"), m_transferHandler->dest().prettyUrl())); - - emitSpeed(m_transferHandler->downloadSpeed()); - setProcessedAmount(KJob::Bytes, processedAmount(KJob::Bytes)); - setTotalAmount(KJob::Bytes, totalAmount(KJob::Bytes)); - setPercent(percent()); -} - -bool KGetKJobAdapter::doKill() -{ - kDebug() << "Kill of job adapter called:" << this << m_transferHandler->dest(); - emit requestStop(this, m_transferHandler); - return KJob::doKill(); -} - -bool KGetKJobAdapter::doSuspend() -{ - if (m_transferHandler->capabilities() & Transfer::Cap_Resuming) { - emit requestSuspend(this, m_transferHandler); - return true; - } - - return false; -} - -bool KGetKJobAdapter::doResume() -{ - emit requestResume(this, m_transferHandler); - return true; -} diff --git a/kget/core/kgetkjobadapter.h b/kget/core/kgetkjobadapter.h deleted file mode 100644 index 5941ff06..00000000 --- a/kget/core/kgetkjobadapter.h +++ /dev/null @@ -1,57 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - Idea by Copyright (C) 2008 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef KGETKJOBADAPTER_H -#define KGETKJOBADAPTER_H - -#include "transferhandler.h" - -#include - -/** -* Allows kget to register all transfers in kuiserver as kjobs -*/ -class KGetKJobAdapter : public KJob -{ - Q_OBJECT -public: - KGetKJobAdapter(QObject *parent, TransferHandler *transfer); - ~KGetKJobAdapter(); - - void start() {}; - - qulonglong processedAmount(Unit unit) const; - qulonglong totalAmount(Unit unit) const; - unsigned long percent() const; - -public slots: - void slotUpdateDescription(); - -signals: - /** - * Emitted when doKill is called, e.g. when the gui is closed. - * Not handling this signal might lead to a crash if something tries to - * access the then non-existing gui. - */ - void requestStop(KJob *job, TransferHandler *handler); - void requestSuspend(KJob *job, TransferHandler *handler); - void requestResume(KJob *job, TransferHandler *handler); - -protected: - virtual bool doKill(); - virtual bool doSuspend(); - virtual bool doResume(); - -private: - TransferHandler *m_transferHandler; -}; -#endif diff --git a/kget/core/kuiserverjobs.cpp b/kget/core/kuiserverjobs.cpp deleted file mode 100644 index 7095e779..00000000 --- a/kget/core/kuiserverjobs.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Javier Goday - Copyright (C) 2009 by Dario Massarin - Copyright (C) 2010 by Matthias Fuchs - - 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. -*/ - -#include "kuiserverjobs.h" - -#include "kgetglobaljob.h" -#include "kgetkjobadapter.h" -#include "transferhandler.h" -#include "settings.h" -#include "kget.h" - -#include -#include - -KUiServerJobs::KUiServerJobs(QObject *parent) - : QObject(parent), m_globalJob(0) -{ -} - -KUiServerJobs::~KUiServerJobs() -{ - while(m_registeredJobs.size()) { - unregisterJob(m_registeredJobs.begin().value(), m_registeredJobs.begin().key()); - } - - delete m_globalJob; -} - -void KUiServerJobs::settingsChanged() -{ - QList transfers = KGet::allTransfers(); - - foreach(TransferHandler * transfer, transfers) { - if(shouldBeShown(transfer)) - registerJob(transfer->kJobAdapter(), transfer); - else - unregisterJob(transfer->kJobAdapter(), transfer); - } - - // GlobalJob is associated to a virtual transfer pointer of value == 0 - if(shouldBeShown(0)) - registerJob(globalJob(), 0); - else - unregisterJob(globalJob(), 0); -} - -void KUiServerJobs::slotTransfersAdded(QList transfers) -{ - foreach (TransferHandler *transfer, transfers) { - if(shouldBeShown(transfer)) - registerJob(transfer->kJobAdapter(), transfer); - - if(shouldBeShown(0)) { - globalJob()->update(); - registerJob(globalJob(), 0); - } - else - unregisterJob(globalJob(), 0); - } -} - -void KUiServerJobs::slotTransfersAboutToBeRemoved(const QList &transfers) -{ - m_invalidTransfers << transfers; - foreach (TransferHandler *transfer, transfers) { - unregisterJob(transfer->kJobAdapter(), transfer); - - if (shouldBeShown(0)) { - globalJob()->update(); - registerJob(globalJob(), 0); - } else { - unregisterJob(globalJob(), 0); - } - } -} - -void KUiServerJobs::slotTransfersChanged(QMap transfers) -{ - if(!Settings::enableKUIServerIntegration()) - return; - - QMapIterator i(transfers); - while (i.hasNext()) { - i.next(); - // if(!m_invalidTransfers.contains(i.key())) - { - TransferHandler * transfer = i.key(); - if (shouldBeShown(transfer)) { - registerJob(transfer->kJobAdapter(), transfer); - } else { - unregisterJob(transfer->kJobAdapter(), transfer); - } - } - } - - if(shouldBeShown(0)) { - globalJob()->update(); - registerJob(globalJob(), 0); - } - else - unregisterJob(globalJob(), 0); -} - -void KUiServerJobs::registerJob(KGetKJobAdapter *job, TransferHandler *transfer) -{ - if (m_registeredJobs.contains(transfer) || !job) { - return; - } - connect(job, SIGNAL(requestStop(KJob*,TransferHandler*)), this, SLOT(slotRequestStop(KJob*,TransferHandler*))); - connect(job, SIGNAL(requestSuspend(KJob*,TransferHandler*)), this, SLOT(slotRequestSuspend(KJob*,TransferHandler*))); - connect(job, SIGNAL(requestResume(KJob*,TransferHandler*)), this, SLOT(slotRequestResume(KJob*,TransferHandler*))); - - KJob *j = job; - registerJob(j, transfer); -} - -void KUiServerJobs::registerJob(KJob * job, TransferHandler * transfer) -{ - if(m_registeredJobs.contains(transfer) || !job) - return; - - KIO::getJobTracker()->registerJob(job); - m_registeredJobs[transfer] = job; -} - -bool KUiServerJobs::unregisterJob(KJob * job, TransferHandler * transfer) -{ - if (!m_registeredJobs.contains(transfer) || !job) - return false; - - //Transfer should only be suspended, thus still show the job tracker - if (m_suspendRequested.contains(transfer)) { - m_suspendRequested.removeAll(transfer); - return false; - } - - //unregister the job if it was a single adaptor - if (job != m_globalJob) { - disconnect(job); - } - KIO::getJobTracker()->unregisterJob(m_registeredJobs[transfer]); - m_registeredJobs.remove(transfer); - - return true; -} - -void KUiServerJobs::slotRequestStop(KJob *job, TransferHandler *transfer) -{ - if (unregisterJob(job, transfer)) { - if (transfer) { - transfer->stop(); - } else { - foreach (TransferHandler *t, KGet::allTransfers()) { - t->stop(); - } - } - } -} - -bool KUiServerJobs::shouldBeShown(TransferHandler * transfer) -{ - if(!Settings::enableKUIServerIntegration()) - return false; - - if(Settings::exportGlobalJob() && (transfer == 0) && existRunningTransfers()) - return true; - - if(!Settings::exportGlobalJob() && (transfer) && (transfer->status() == Job::Running)) - return true; - - return false; -} - -bool KUiServerJobs::existRunningTransfers() -{ - foreach(TransferHandler * transfer, KGet::allTransfers()) { - //if added to m_invalidTransfers it means that the job is about to be removed - if ((transfer->status() == Job::Running) && !m_invalidTransfers.contains(transfer)) { - return true; - } - } - - return false; -} - -KGetGlobalJob * KUiServerJobs::globalJob() -{ - if (!m_globalJob) { - m_globalJob = new KGetGlobalJob(); - connect(m_globalJob, SIGNAL(requestStop(KJob*,TransferHandler*)), this, SLOT(slotRequestStop(KJob*,TransferHandler*))); - } - return m_globalJob; -} - -void KUiServerJobs::slotRequestSuspend(KJob *job, TransferHandler *transfer) -{ - Q_UNUSED(job) - if (transfer) { - m_suspendRequested << transfer; - transfer->stop(); - } -} - -void KUiServerJobs::slotRequestResume(KJob *job, TransferHandler *transfer) -{ - Q_UNUSED(job) - if (transfer) { - transfer->start(); - } -} diff --git a/kget/core/kuiserverjobs.h b/kget/core/kuiserverjobs.h deleted file mode 100644 index e7a61be7..00000000 --- a/kget/core/kuiserverjobs.h +++ /dev/null @@ -1,65 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Javier Goday - Copyright (C) 2009 by Dario Massarin - Copyright (C) 2010 by Matthias Fuchs - - 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. -*/ - -#ifndef KUISERVERJOBS_H -#define KUISERVERJOBS_H - -#include "kgetglobaljob.h" -#include "transfer.h" - -#include - -#include -#include - -class KGetKJobAdapter; -class TransferHandler; -class TransferGroupHandler; - -class KUiServerJobs : public QObject -{ - Q_OBJECT -public: - KUiServerJobs(QObject *parent=0); - ~KUiServerJobs(); - - void settingsChanged(); - -public slots: - void slotTransfersAdded(QList transfers); - void slotTransfersAboutToBeRemoved(const QList &transfer); - void slotTransfersChanged(QMap transfers); - -private slots: - void slotRequestStop(KJob *job, TransferHandler *transfer); - void slotRequestSuspend(KJob *job, TransferHandler *transfer); - void slotRequestResume(KJob *job, TransferHandler *transfer); - -private: - void registerJob(KJob * job, TransferHandler * transfer); - void registerJob(KGetKJobAdapter *job, TransferHandler *transfer); - /** - * Unregisters job and returns true if it worked - */ - bool unregisterJob(KJob * job, TransferHandler * transfer); - bool shouldBeShown(TransferHandler * transfer); - bool existRunningTransfers(); - KGetGlobalJob * globalJob(); - -private: - QMap m_registeredJobs; - QList m_invalidTransfers; - QList m_suspendRequested; - KGetGlobalJob *m_globalJob; -}; - -#endif diff --git a/kget/core/linkimporter.cpp b/kget/core/linkimporter.cpp deleted file mode 100644 index 216bc2b0..00000000 --- a/kget/core/linkimporter.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - First Url regular expression taken from urlview tool by Michael Elkins . - Regular expression improved by FiNex. - Improvements to regular expression and slotReadFile by Frantisek Ziacik - - 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. -*/ -#include "linkimporter.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -//static QString REGULAR_EXPRESSION = "(((https?|ftp|gopher)://|(mailto|file|news):)[^’ <>\"]+|(www|web|w3).[-a-z0-9.]+)[^’ .,;<>\":]"; -// static QString REGULAR_EXPRESSION = "((http|https|ftp|ftps)+([\\:\\w\\d:#@%/;$()~_?\\+-=\\\\.&])*)"; -static QString REGULAR_EXPRESSION = "(\\w+[:]//)?(((([\\w-]+[.]){1,}(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|int|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|sv|st|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|aero|biz|coop|info|museum|name|pro|travel))|([0-9]+[.][0-9]+[.][0-9]+[.][0-9]+)))([:][0-9]*)?([?/][\\w~#\\-;%?@&=/.+]*)?(?!\\w)"; - -LinkImporter::LinkImporter(const KUrl &url, QObject *parent) : QThread(parent), - m_url(url), - m_transfers(), - m_tempFile() -{ -} - -LinkImporter::LinkImporter(QObject *parent) : QThread(parent), - m_url(), - m_transfers(), - m_tempFile() -{ -} - -LinkImporter::~LinkImporter() -{ -} - -void LinkImporter::checkClipboard(const QString &clipboardContent) -{ - QRegExp rx(REGULAR_EXPRESSION); - - int regexPos = 0; - - while ((regexPos = rx.indexIn(clipboardContent, regexPos)) > -1) { - QString link = rx.capturedTexts()[0]; - - addTransfer(link); - - regexPos += rx.matchedLength(); - } - - emit finished(); -} - -void LinkImporter::run() -{ - if(!m_url.isLocalFile() && !m_tempFile.isEmpty()) { - slotReadFile(KUrl(m_tempFile)); - } - else { - slotReadFile(m_url); - } - - emit finished(); -} - -void LinkImporter::copyRemoteFile() -{ - m_tempFile = QString("%1/%2.tmp").arg(QDir::tempPath()).arg("importer_aux"); - - KUrl aux(m_tempFile); - KIO::CopyJob *job = KIO::copy(m_url, aux, KIO::HideProgressInfo); - - KIO::MetaData metaData; - bool ok = KIO::NetAccess::synchronousRun(job, 0, 0, 0, &metaData); - if(!ok) { - emit error(ki18n("Error trying to get %1").subs(m_url.url())); - } -} - -void LinkImporter::slotReadFile(const QUrl &url) -{ - QRegExp rx(REGULAR_EXPRESSION); - QFile file(url.toLocalFile()); - - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QTextStream in(&file); - quint64 size = file.size(); - quint64 position = 0; - - while (!in.atEnd()) { - QString line = in.readLine(); - int regexPos = 0; - quint64 lastPosition = position; - - while ((regexPos = rx.indexIn(line, regexPos)) > -1) { - QString link = rx.capturedTexts()[0]; - - addTransfer(link); - - regexPos += rx.matchedLength(); - position = lastPosition + regexPos; - - emit progress(position * 100 / size); - } - - position += line.size(); - - emit progress(position * 100 / size); - } - - if(!m_url.isLocalFile()) { - file.remove(); - } -} - -void LinkImporter::addTransfer(QString &link) -{ - KUrl auxUrl; - - if (link.contains("://")) { - auxUrl = KUrl(link); - } else { - auxUrl = KUrl(QString("http://") + link); - } - - if(!link.isEmpty() && auxUrl.isValid() && m_transfers.indexOf(link) < 0 && - !auxUrl.scheme().isEmpty() && !auxUrl.host().isEmpty()) { - m_transfers << link; - } -} - -#include "moc_linkimporter.cpp" diff --git a/kget/core/linkimporter.h b/kget/core/linkimporter.h deleted file mode 100644 index 6109b615..00000000 --- a/kget/core/linkimporter.h +++ /dev/null @@ -1,74 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ -#ifndef LINKIMPORTER_H -#define LINKIMPORTER_H - -#include "kget_export.h" - -#include -#include - -#include - -class KLocalizedString; - -/** -* Import a list of urls from a file (local or remote) -*/ -class KGET_EXPORT LinkImporter : public QThread -{ -Q_OBJECT -public: - LinkImporter(const KUrl &source, QObject *parent); - LinkImporter(QObject *parent); - ~LinkImporter(); - - /** - * Check for urls in clipboard - */ - void checkClipboard(const QString &clipboardContent); - - /** - * Start reading the url contents - */ - void run(); - - /** - * copy the remote file out of the thread - */ - void copyRemoteFile(); - - /** - * Returns a list with the links of the selected url m_url - */ - QList links() - { - return m_transfers; - }; - -signals: - void error(const KLocalizedString &); - void progress(int progress); - -private slots: - void slotReadFile(const QUrl &url); - -private: - /** - * Checks if an url is valid and adds it to the transfers lists - */ - void addTransfer(QString &link); - -private: - KUrl m_url; - QList m_transfers; - QString m_tempFile; -}; -#endif diff --git a/kget/core/mostlocalurl.cpp b/kget/core/mostlocalurl.cpp deleted file mode 100644 index 543dcf3c..00000000 --- a/kget/core/mostlocalurl.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 "mostlocalurl.h" -#include "kget.h" -#include "plugin/transferfactory.h" - -#include -#include - -KUrl mostLocalUrl(const KUrl &url) -{ - const QString protocol = url.protocol(); - foreach (TransferFactory *factory, KGet::factories()) { - if (factory->addsProtocols().contains(protocol)) { - return url; - } - } - - kDebug() << "Starting KIO::NetAccess::mostLocalUrl for:" << url; - return KIO::NetAccess::mostLocalUrl(url, 0); -} - -MostLocalUrlJob *mostLocalUrlJob(const KUrl &url) -{ - return new MostLocalUrlJob(url); -} - -MostLocalUrlJob::MostLocalUrlJob(const KUrl& url) - : KIO::Job(), - m_url(url) -{ -} - -KUrl MostLocalUrlJob::url() -{ - return m_url; -} - -KUrl MostLocalUrlJob::mostLocalUrl() const -{ - return m_mostLocalUrl; -} - -void MostLocalUrlJob::start() -{ - bool startJob = true; - const QString protocol = m_url.protocol(); - foreach (TransferFactory *factory, KGet::factories()) { - if (factory->addsProtocols().contains(protocol)) { - startJob = false; - break; - } - } - - if (startJob) { - kDebug() << "Starting KIO::mostLocalUrl for:" << m_url; - KIO::Job *job = KIO::mostLocalUrl(m_url, KIO::HideProgressInfo); - addSubjob(job); - } else { - m_mostLocalUrl = m_url; - emitResult(); - } -} - -void MostLocalUrlJob::slotResult(KJob* job) -{ - if (job->error()) { - kWarning() << "Error" << job->error() << "happened for:" << m_url; - m_mostLocalUrl = m_url; - } else { - m_mostLocalUrl = static_cast(job)->mostLocalUrl(); - } - kDebug() << "Setting mostLocalUrl to" << m_mostLocalUrl; - emitResult(); -} diff --git a/kget/core/mostlocalurl.h b/kget/core/mostlocalurl.h deleted file mode 100644 index dc5eadb7..00000000 --- a/kget/core/mostlocalurl.h +++ /dev/null @@ -1,76 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 KGET_MOSTLOCALURL_H -#define KGET_MOSTLOCALURL_H - -#include "kget_export.h" -#include -#include - -/** - * NOTE this implementation does KIO::mostLocalUrl on any url whose protocol - * is not supported by a TransferFactory. - * I.e. it is assumed that an e.g. ftp url does _not_ point to a local file. - * - * The reason for that is to avoid connecting to external urls, which could - * cause problems with websites that only allow one connection, or with - * servers you connected already, reaching their maximum connections. - * See #264452 - */ - -class MostLocalUrlJob; - -/** - * Synchronous - */ -KGET_EXPORT KUrl mostLocalUrl(const KUrl &url); - -/** - * Asynchronous - */ -KGET_EXPORT MostLocalUrlJob *mostLocalUrlJob(const KUrl &url); - -/** - * Job for asynchronously getting the most local url, do not use directly, but use - * mostLocalUrlJob instead - */ -class KGET_EXPORT MostLocalUrlJob : public KIO::Job -{ - Q_OBJECT - public: - MostLocalUrlJob(const KUrl &url); - - virtual void start(); - KUrl url(); - - /** - * Call this in the slot connected to result. - */ - KUrl mostLocalUrl() const; - - protected: - virtual void slotResult(KJob *job); - - private: - KUrl m_url; - KUrl m_mostLocalUrl; -}; - -#endif diff --git a/kget/core/plugin/CMakeLists.txt b/kget/core/plugin/CMakeLists.txt deleted file mode 100644 index 057fa848..00000000 --- a/kget/core/plugin/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -install(FILES kget_plugin.desktop DESTINATION ${KDE4_SERVICETYPES_INSTALL_DIR}) diff --git a/kget/core/plugin/kget_plugin.desktop b/kget/core/plugin/kget_plugin.desktop deleted file mode 100644 index 520dc8f9..00000000 --- a/kget/core/plugin/kget_plugin.desktop +++ /dev/null @@ -1,140 +0,0 @@ -[Desktop Entry] -Type=ServiceType -X-KDE-ServiceType=KGet/Plugin -Name=KGet Plugin -Name[ar]=KGet ملحق -Name[ast]=Complementu de Kopete -Name[bg]=Приставка KGet -Name[bs]=KGet priključak -Name[ca]=Connector del KGet -Name[ca@valencia]=Connector del KGet -Name[cs]=Modul aplikace KGet -Name[da]=KGet-plugin -Name[de]=KGet-Modul -Name[el]=Πρόσθετο KGet -Name[en_GB]=KGet Plugin -Name[es]=Complemento de Kopete -Name[et]=KGeti plugin -Name[eu]=Kget plugina -Name[fi]=KGet-liitännäinen -Name[fr]=Module externe pour KGet -Name[ga]=Breiseán KGet -Name[gl]=Engadido para KGet -Name[hne]=के-गेट प्लगइन -Name[hr]=Priključak za KGet -Name[hu]=KGet-bővítőmodul -Name[ia]=Plug-in de KGet -Name[is]=KGet íforrit -Name[it]=Estensione per KGet -Name[ja]=KGet プラグイン -Name[kk]=KGet плагині -Name[km]=កម្មវិធី​ជំនួយ KGet -Name[ko]=KGet 플러그인 -Name[lt]=KGet įskiepis -Name[lv]=KGet spraudnis -Name[ml]=കെഗെറ്റ് സംയോജകം -Name[mr]=के-गेट प्लगइन -Name[nb]=Programtillegg for KGet -Name[nds]=KGet-Moduul -Name[nl]=KGet-plugin -Name[nn]=KGet-programtillegg -Name[pa]=ਕੇਗਿੱਟ ਪਲੱਗਇਨ -Name[pl]=Wtyczka KGet -Name[pt]='Plugin' do KGet -Name[pt_BR]=Plugin do KGet -Name[ro]=Modul KGet -Name[ru]=Модуль KGet -Name[si]=KGet ප්ලගිනය -Name[sk]=Modul KGet -Name[sl]=Vstavek za KGet -Name[sq]=KGet Plugin -Name[sr]=Прикључак К‑гета -Name[sr@ijekavian]=Прикључак К‑гета -Name[sr@ijekavianlatin]=Priključak KGeta -Name[sr@latin]=Priključak KGeta -Name[sv]=Insticksprogram för Kget -Name[th]=ส่วนเสริมของ KGet -Name[tr]=KGet Eklentisi -Name[ug]=KGet قىستۇرما -Name[uk]=Додаток KGet -Name[wa]=Tchôke-divins po KGet -Name[x-test]=xxKGet Pluginxx -Name[zh_CN]=KGet 插件 -Name[zh_TW]=KGet 外掛程式 -Comment=Plugin for KGet -Comment[ar]=ملحق لـ KGet -Comment[ast]=Complementu pa KGet -Comment[bg]=Приставка за KGet -Comment[bs]=Priključak za KGet -Comment[ca]=Connector pel KGet -Comment[ca@valencia]=Connector pel KGet -Comment[cs]=Modul pro KGet -Comment[da]=Plugin til KGet -Comment[de]=Modul für KGet -Comment[el]=Πρόσθετο για το KGet -Comment[en_GB]=Plugin for KGet -Comment[eo]=Kromaĵo por KGet -Comment[es]=Complemento para KGet -Comment[et]=KGeti plugin -Comment[eu]=KGet-en plugina -Comment[fi]=KGet-liitännäinen -Comment[fr]=Module externe pour KGet -Comment[ga]=Breiseán KGet -Comment[gl]=Engadido para KGet -Comment[hi]=केगेट के लिए प्लगइन -Comment[hne]=केगेट बर प्लगइन -Comment[hr]=Priključak za KGet -Comment[hu]=KGet-modul -Comment[ia]=Plug-in per KGet -Comment[is]=Íforrit fyrir KGet -Comment[it]=Estensione per KGet -Comment[ja]=KGet のプラグイン -Comment[kk]=KGet-тің плагині -Comment[km]=កម្មវិធី​ជំនួយ​សម្រាប់ KGet -Comment[ko]=KGet 플러그인 -Comment[lt]=KGet įskiepis -Comment[lv]=KGet spraudnis -Comment[ml]=കെഗെറ്റിനുള്ള സംയോജകം -Comment[mr]=के-गेट करिता प्लगइन -Comment[nb]=Programtillegg for KGet -Comment[nds]=Moduul för KGet -Comment[ne]=केडीई गेटका लागि प्लगइन -Comment[nl]=Plugin voor KGet -Comment[nn]=Programtillegg til KGet -Comment[pa]=ਕੇ-ਗੈੱਟ ਲਈ ਪਲੱਗਇਨ -Comment[pl]=Wtyczka dla KGet -Comment[pt]=Plugin do KGet -Comment[pt_BR]=Plugin para o KGet -Comment[ro]=Modul pentru KGet -Comment[ru]=Подключаемый модуль для KGet -Comment[si]=KGet සඳහා ප්ලගිනය -Comment[sk]=Modul pre KGet -Comment[sl]=Vstavek za KGet -Comment[sq]=Plugin për KGet -Comment[sr]=Прикључак за К‑гет -Comment[sr@ijekavian]=Прикључак за К‑гет -Comment[sr@ijekavianlatin]=Priključak za KGet -Comment[sr@latin]=Priključak za KGet -Comment[sv]=Insticksprogram för Kget -Comment[th]=ส่วนเสริมของ KGet -Comment[tr]=KGet için eklenti -Comment[ug]=KGet قىستۇرمىسى -Comment[uk]=Додаток для KGet -Comment[vi]=Phần bổ sung cho KGet -Comment[x-test]=xxPlugin for KGetxx -Comment[zh_CN]=KGet 插件 -Comment[zh_TW]=KGet 外掛程式 - -# Type of plugin, e.g. "TransferFactory". -[PropertyDef::X-KDE-KGet-plugintype] -Type=QString - -# Priority of the plugin. When KTrader returns multiple offers, the one with the highest rank is chosen. -# Range: 0 (disabled) - 255 (highest) -[PropertyDef::X-KDE-KGet-rank] -Type=int - -# Version of the framework this plugin is compatible with. -# Current version: 1 -[PropertyDef::X-KDE-KGet-framework-version] -Type=int diff --git a/kget/core/plugin/plugin.cpp b/kget/core/plugin/plugin.cpp deleted file mode 100644 index 2d6562c8..00000000 --- a/kget/core/plugin/plugin.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 by Enrico Ros - based on amarok code Copyright (C) 2004 by Mark Kretschmann - - 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. -*/ - -#include "plugin.h" - -#include - -KGetPlugin::KGetPlugin(QObject *parent, const QVariantList &args) - : QObject(parent) -{ - Q_UNUSED(args) -} - -KGetPlugin::~KGetPlugin() -{ -} - -/* -void Plugin::addPluginProperty( const QString& key, const QString& value ) -{ - m_properties[key.toLower()] = value; -} - -QString Plugin::pluginProperty( const QString& key ) -{ - if ( m_properties.find( key.toLower() ) == m_properties.end() ) - return "false"; - - return m_properties[key.toLower()]; -} - -bool Plugin::hasPluginProperty( const QString& key ) -{ - return m_properties.find( key.toLower() ) != m_properties.end(); -} -*/ - diff --git a/kget/core/plugin/plugin.h b/kget/core/plugin/plugin.h deleted file mode 100644 index 37d078cc..00000000 --- a/kget/core/plugin/plugin.h +++ /dev/null @@ -1,85 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 by Enrico Ros - based on amarok code Copyright (C) 2004 by Mark Kretschmann - - 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. -*/ - -#ifndef KGET_PLUGIN_H -#define KGET_PLUGIN_H - -/* KGet plugins -How they work- [enrico: 0.6] - * - * Here is a generic framework for plugins usage. Since the purpose of a - * plugin is providing some type of well known functionality, there are - * some requirements that must be satisfied. In fact a plugin must: - * - inherit KGetPlugin interface or a subclass of that - * - declare that the class IS a kget plugin (using a macro) - * - declare its 'type' to the loader (using a .desktop file) - * - * Plugins providing the same functionality (TransferFactory for example) - * must inherit the same interface and be declared as plugins of the same - * type. In that case all the plugins will inherit and implement the - * TransferFactory class and provide a .desktop file that identify them - * as belonging to the same type (X-KDE-KGet-pluginType=TransferFactory). - * - * Loading. This operation is done by using KDE framework. So we define a - * new ServiceType in the kget_plugin.desktop file. KGet plugins service - * is called "KGet/Plugin". In the Desktop file that describes a plugin - * the "X-KDE-ServiceType" is set to to "KGet/Plugin" and other fields - * are set as described in the service type definition. - * As an example say that we need "InputFilter" plugins. In that case we - * can use KTrader to enumerate the plugins of that type installed in the - * system and after getting the name of the libraries they're in, load - * them. In that case the Input object that loaded the plugins must know - * how to treat them (and that is easy, since they all reimplemented an - * 'input plugin class' providing necessary information). - * - * @see: kget_plugin.desktop - for servicetype definition. - * @see: other headers in the dir - for plugin types definition. - */ - -#include "kget_export.h" - -#include -#include - -/** - * Bump this number whenever the plugin framework gets - * incompatible with older versions - */ - const int FrameworkVersion = 1; - -/** - * @short Base class for kget plugins. - * ... - */ -class KGET_EXPORT KGetPlugin : public QObject -{ - Q_OBJECT - public: - KGetPlugin(QObject *parent, const QVariantList &args); - virtual ~KGetPlugin(); - - /* - // set and retrieve properties - void addPluginProperty( const QString & key, const QString & value ); - bool hasPluginProperty( const QString & key ); - QString pluginProperty( const QString & key ); - - reimplement this to set the type of the plugin - enum PluginType { PreProcessing, Factory, PostProcessing } - virtual PluginType pluginType() = 0; - */ - - private: - //QMap< QString, QString > m_properties; - - -}; - -#endif diff --git a/kget/core/plugin/transferfactory.cpp b/kget/core/plugin/transferfactory.cpp deleted file mode 100644 index 061f74a9..00000000 --- a/kget/core/plugin/transferfactory.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - - 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. -*/ - -#include "transferfactory.h" - -#include "kget.h" - -#include -#include -#include - -TransferFactory::TransferFactory(QObject *parent, const QVariantList &args) - : KGetPlugin(parent, args) -{ - -} - -Transfer * TransferFactory::createTransfer(const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup * parent, - Scheduler * scheduler) -{ - Q_UNUSED(srcUrl) - Q_UNUSED(destUrl) - Q_UNUSED(parent) - Q_UNUSED(scheduler) - return 0; -} - -TransferHandler * TransferFactory::createTransferHandler(Transfer * transfer, Scheduler * scheduler) -{ - return new TransferHandler(transfer, scheduler); -} - -QWidget * TransferFactory::createDetailsWidget(TransferHandler * transfer) -{ - Q_UNUSED(transfer) - return 0; -} - -KDialog * TransferFactory::createNewTransferDialog(const KUrl &srcUrl, const QString &suggestedFileName, TransferGroupHandler * defaultGroup) -{ - Q_UNUSED(srcUrl) - Q_UNUSED(suggestedFileName) - Q_UNUSED(defaultGroup) - return 0; -} - -const QList TransferFactory::actions(TransferHandler *handler) -{ - Q_UNUSED(handler) - return QList(); -} - -TransferDataSource * TransferFactory::createTransferDataSource(const KUrl &srcUrl, const QDomElement &type, QObject *parent) -{ - Q_UNUSED(srcUrl) - Q_UNUSED(type) - Q_UNUSED(parent) - return 0; -} - -bool TransferFactory::isSupported(const KUrl &url) const -{ - Q_UNUSED(url) - return false; -} - -QStringList TransferFactory::addsProtocols() const -{ - return QStringList(); -} diff --git a/kget/core/plugin/transferfactory.h b/kget/core/plugin/transferfactory.h deleted file mode 100644 index 83f5efb1..00000000 --- a/kget/core/plugin/transferfactory.h +++ /dev/null @@ -1,89 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 by Enrico Ros - Copyright (C) 2009 by Lukas Appelhans - - 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. -*/ - -#ifndef KGET_TRANSFERFACTORY_H -#define KGET_TRANSFERFACTORY_H - -/* TransferFactory [KGet/Plugin] - * - * Defines a ...XXX... - * - * Common fields in the [Desktop Entry]: - * Type=Service - * ServiceTypes=KGet/Plugin - * X-KDE-KGet-plugintype=TransferFactory - * X-KDE-KGet-framework-version=1 - * Custom fields in the [Desktop Entry]: - * Name=%YOURTRANSFERFACTORY% - * X-KDE-Library=lib%YOURLIBRARY% - * X-KDE-KGet-rank=%PLUGINRANK% - * - * @see kget_plugin.desktop - for "KGet/Plugin" definition - * @see transfers/kio/kget_kiotransfer.desktop - desktop entry example - */ - -#include -#include - -#include "core/plugin/plugin.h" -#include "core/kget.h" -#include "core/transfer.h" -#include "core/transferhandler.h" -#include "core/transferdatasource.h" -#include "kget_export.h" - -class TransferGroup; -class Scheduler; -class KDialog; - -/** - * @short TransferFactory - * - * desc to come... - */ -class KGET_EXPORT TransferFactory : public KGetPlugin -{ - Q_OBJECT - public: - TransferFactory(QObject *parent, const QVariantList &args); - - virtual Transfer * createTransfer( const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup * parent, - Scheduler * scheduler); - - virtual TransferHandler * createTransferHandler(Transfer * transfer, - Scheduler * scheduler); - - virtual QWidget * createDetailsWidget(TransferHandler * transfer); - - virtual KDialog * createNewTransferDialog(const KUrl &srcUrl, const QString &suggestedFileName = QString(), TransferGroupHandler * defaultGroup = 0); - - virtual const QList actions(TransferHandler *handler = 0); - - virtual void settingsChanged() {} - - virtual bool isSupported(const KUrl &url) const; - - /** - * Returns a list of protocols for which the TransferFactory adds support. - * An empty list simply means that the TransferFactory does not add support - * for the urls and might internally resort on other TransferFactories - */ - virtual QStringList addsProtocols() const; - - /** - * Returns a Data Source. needed for Transfers Containers if any. - * default implementation returns 0 - */ - virtual TransferDataSource * createTransferDataSource(const KUrl &srcUrl, const QDomElement &type, QObject *parent); -}; - -#endif diff --git a/kget/core/scheduler.cpp b/kget/core/scheduler.cpp deleted file mode 100644 index 2a7afa5f..00000000 --- a/kget/core/scheduler.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Coypright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "core/scheduler.h" - -#include "core/transferhandler.h" -#include "settings.h" - -#include -#include - -#include - -Scheduler::Scheduler(QObject * parent) - : QObject(parent), - m_failureCheckTimer(0), - m_stallTime(5), - m_stallTimeout(Settings::reconnectDelay()), - m_abortTimeout(Settings::reconnectDelay()), - m_isSuspended(false), - m_hasConnection(true) -{ - -} - -Scheduler::~Scheduler() -{ - -} - -void Scheduler::setIsSuspended(bool isSuspended) -{ - const bool changed = (isSuspended != m_isSuspended); - m_isSuspended = isSuspended; - - //update all the queues - if (changed && shouldUpdate()) { - updateAllQueues(); - } -} - -void Scheduler::setHasNetworkConnection(bool hasConnection) -{ - const bool changed = (hasConnection != m_hasConnection); - m_hasConnection = hasConnection; - - if (changed) { - if (hasConnection) { - if (!m_failureCheckTimer) { - m_failureCheckTimer = startTimer(1000); - } - updateAllQueues(); - } else { - if (m_failureCheckTimer) { - killTimer(m_failureCheckTimer); - m_failureCheckTimer = 0; - } - foreach (JobQueue *queue, m_queues) { - std::for_each(queue->begin(), queue->end(), std::bind(&Job::stop, std::placeholders::_1)); - } - } - } -} - -void Scheduler::addQueue(JobQueue * queue) -{ - if(!m_queues.contains(queue)) - m_queues.append(queue); -} - -void Scheduler::delQueue(JobQueue * queue) -{ - m_queues.removeAll(queue); -} - -struct IsRunningJob -{ - bool operator()(Job *job) const {return (job->status() == Job::Running);} -}; - -bool Scheduler::hasRunningJobs() const -{ - foreach (JobQueue *queue, m_queues) { - if (std::find_if(queue->begin(), queue->end(), IsRunningJob()) != queue->end()) { - return true; - } - } - return false; -} - -int Scheduler::countRunningJobs() const -{ - int count = 0; - foreach(JobQueue * queue, m_queues) { - count += std::count_if(queue->begin(), queue->end(), IsRunningJob()); - } - - return count; -} - -void Scheduler::settingsChanged() -{ - m_stallTimeout = Settings::reconnectDelay(); - m_abortTimeout = Settings::reconnectDelay(); - - updateAllQueues(); -} - -void Scheduler::jobQueueChangedEvent(JobQueue * queue, JobQueue::Status status) -{ - if( status == JobQueue::Stopped ) - { - JobQueue::iterator it = queue->begin(); - JobQueue::iterator itEnd = queue->end(); - - for ( ; it!=itEnd ; ++it) - { - if ((*it)->status() != Job::Stopped) - (*it)->stop(); - } - } - else - updateQueue(queue); -} - -void Scheduler::jobQueueMovedJobEvent(JobQueue * queue, Job * job) -{ - Q_UNUSED(job) - - updateQueue(queue); -} - -void Scheduler::jobQueueAddedJobEvent(JobQueue * queue, Job * job) -{ - Q_UNUSED(job) - - updateQueue(queue); -} - -void Scheduler::jobQueueAddedJobsEvent(JobQueue *queue, const QList jobs) -{ - Q_UNUSED(jobs) - - updateQueue(queue); -} - - -void Scheduler::jobQueueRemovedJobEvent(JobQueue * queue, Job * job) -{ - Q_UNUSED(job) - - updateQueue(queue); -} - -void Scheduler::jobQueueRemovedJobsEvent(JobQueue *queue, const QList jobs) -{ - Q_UNUSED(jobs) - - updateQueue(queue); -} - -void Scheduler::jobChangedEvent(Job * job, Job::Status status) -{ - kDebug() << "Scheduler::jobChangedEvent (job=" << job << " status=" << status << ")"; - - if (!m_failureCheckTimer) - m_failureCheckTimer = startTimer(1000); - - if (status != Job::Running) - updateQueue( job->jobQueue() ); -} - -void Scheduler::jobChangedEvent(Job * job, Job::Policy policy) -{ - Q_UNUSED(policy) - - updateQueue( job->jobQueue() ); -} - -void Scheduler::jobChangedEvent(Job * job, JobFailure failure) -{ - switch(failure.status) - { - case None: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = None "; - break; - case AboutToStall: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = AboutToStall "; - break; - case Stall: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = Stall "; - break; - case StallTimeout: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = StallTimeout "; - break; - case Abort: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = Abort "; - break; - case AbortTimeout: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = AbortTimeout "; - break; - case Error: - kDebug() << "job = " << job << " failure (#" << failure.count << ") = Error "; - break; - } - - if (failure.status == Error) { - static_cast(job)->handler()->stop(); - } else if (//If this happens the job just gets stopped - // Second condition: if count > reconnectRetries and Timeout happened trigger a stop/start BUT only if - // 10 timeouts have happened (9 of them without taking any action). This means every 10*Settings::reconnectDelay() (ex. 15s -> 150s) - (failure.count > Settings::reconnectRetries() && (failure.status == StallTimeout || failure.status == AbortTimeout) - && !((failure.count - Settings::reconnectRetries()) % 10)) ) - { - //FIXME reenable once a connection limit per mirror is in place BUG:262098 - //static_cast(job)->handler()->stop();// This will trigger the changedEvent which will trigger an updateQueue call - job->stop();//FIXME remove once a connection limit per mirror is in place - } else if (failure.count <= Settings::reconnectRetries() && (failure.status == StallTimeout || failure.status == AbortTimeout)){ - // First condition: if count <= reconnectRetries and Timeout happened trigger a stop/start - job->stop();//stops the job, it will be later restarted by updateQueue - } - else - updateQueue( job->jobQueue() ); -} - -void Scheduler::start() -{ - std::for_each(m_queues.begin(), m_queues.end(), std::bind(&JobQueue::setStatus, std::placeholders::_1, JobQueue::Running)); -} - -void Scheduler::stop() -{ - std::for_each(m_queues.begin(), m_queues.end(), std::bind(&JobQueue::setStatus, std::placeholders::_1, JobQueue::Stopped)); -} - -void Scheduler::updateQueue( JobQueue * queue ) -{ - static bool updatingQueue = false; - - if (!shouldUpdate() || updatingQueue) - return; - - updatingQueue = true; - - int runningJobs = 0; //Jobs that are running (and not in the stallTimeout) - int waitingJobs = 0; //Jobs that we leave running but are in stallTimeout. We wait for them to start downloading, while we start other ones - - /** - * Implemented behaviour - * - * The scheduler allows a maximum number of runningJobs equal to the queue->maxSimultaneousJobs() setting. - * If that number is not reached because of stallTimeout transfers, the scheduler allows that: - * (runningJobs + waitingJobs) < 2 * queue->maxSimultaneousJobs() - * Examples (with maxSimultaneousJobs = 2): - * These are if the running jobs come first in the queue - * 1) 2 runningJobs - 0 waitingJobs - * 2) 1 runningJobs - up to 3 waitingJobs - * 3) 0 runningJobs - up to 4 waitingJobs - * These are if the waiting jobs come first in the queue - * 1) 1 waitingJobs - 2 runningJobs - * 2) 2 waitingJobs - 2 runningJobs - * 3) 3 waitingJobs - 1 runningJobs - * 4) 4 waitingJobs - 0 runningJobs - **/ - - JobQueue::iterator it = queue->begin(); - JobQueue::iterator itEnd = queue->end(); - - for( int job=0 ; it!=itEnd ; ++it, ++job) - { - // kDebug() << "MaxSimJobs " << queue->maxSimultaneousJobs(); - kDebug() << "Scheduler: Evaluating job " << job; - - JobFailure failure = m_failedJobs.value(*it); - - if( runningJobs < queue->maxSimultaneousJobs() && ((runningJobs + waitingJobs) < 2 * queue->maxSimultaneousJobs()) ) - { - if( (*it)->status() == Job::Running || (*it)->status() == Job::FinishedKeepAlive ) - { - if( !shouldBeRunning(*it) ) - { - kDebug() << "Scheduler: stopping job"; - (*it)->stop(); - } - else if(failure.status == None || failure.status == AboutToStall) - runningJobs++; - else - waitingJobs++; - } - else // != Job::Running - { - if( shouldBeRunning(*it) ) - { - kDebug() << "Scheduler: starting job"; - (*it)->start(); - if((failure.status == None || failure.status == AboutToStall) && (*it)->status() != Job::FinishedKeepAlive) - runningJobs++; - else - waitingJobs++; - } - } - } - else - { - // Stop all the other running downloads - kDebug() << "Scheduler: stopping job over maxSimJobs limit"; - (*it)->stop(); - } - } - - updatingQueue = false; -} - -void Scheduler::updateAllQueues() -{ - foreach (JobQueue *queue, m_queues) { - updateQueue(queue); - } -} - -bool Scheduler::shouldBeRunning( Job * job ) -{ - Job::Policy policy = job->policy(); - Job::Status status = job->status(); - - if( job->jobQueue()->status() == JobQueue::Stopped ) - { - return ( (policy == Job::Start) && - ((status != Job::Finished) && - (status != Job::Aborted || job->error().type == Job::AutomaticRetry))); - } - else //JobQueue::Running - { - return ( (policy != Job::Stop) && - ((status != Job::Finished) && - (status != Job::Aborted || job->error().type == Job::AutomaticRetry))); - } -} - -void Scheduler::timerEvent( QTimerEvent * event ) -{ - Q_UNUSED(event) - if (!shouldUpdate()) { - return; - } - - foreach(JobQueue * queue, m_queues) - { - JobQueue::iterator it = queue->begin(); - JobQueue::iterator itEnd = queue->end(); - - for( int job=0 ; it!=itEnd ; ++it, ++job) - { - JobFailure failure = m_failedJobs[*it]; - JobFailure prevFailure = failure; - - if((*it)->isStalled()) // Stall status initialization - { - if(failure.status!=AboutToStall && failure.status!=Stall && failure.status!=StallTimeout) - { - failure.status = AboutToStall; - failure.time = 0; - failure.count = 0; - } - else - { - failure.time++; - - if(failure.time >= m_stallTime + m_stallTimeout) - { - failure.status = StallTimeout; - failure.count++; - - } - else if(failure.time >= m_stallTime) - failure.status = Stall; - else - failure.status = AboutToStall; - - if(failure.status == StallTimeout) - failure.time = m_stallTime; - } - } - else if((*it)->status() == Job::Aborted) // Abort status initialization - { - if ((*it)->error().type != Job::AutomaticRetry) { - failure.status = Error; - } else { - if(failure.status!=Abort) - { - failure.status = Abort; - failure.time = 0; - failure.count = 0; - } - else - { - failure.time++; - failure.count++; - - if(failure.time >= m_abortTimeout) - { - failure.status = AbortTimeout; - failure.count++; - } - - if(failure.status == AbortTimeout) - failure.time = 0; - } - } - } - else if ((*it)->isWorking()) - { - failure = JobFailure(); - } - - if(failure.isValid()) // A failure has been detected - m_failedJobs[*it] = failure; - else // No failure detected, remove it - m_failedJobs.remove(*it); - - // if(failure.isValid() || prevFailure.isValid()) - // kDebug() << "failure = " << failure.status << " T=" << failure.time << " prevFailure = " << prevFailure.status; - - if(failure.status != prevFailure.status) - jobChangedEvent(*it, failure); // Notify the scheduler - } - } -} - -#include "moc_scheduler.cpp" diff --git a/kget/core/scheduler.h b/kget/core/scheduler.h deleted file mode 100644 index 45fa1a6d..00000000 --- a/kget/core/scheduler.h +++ /dev/null @@ -1,192 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Coypright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef SCHEDULER_H -#define SCHEDULER_H - -#include -#include -#include - -#include "core/job.h" -#include "core/jobqueue.h" -#include "../kget_export.h" - -/** - * @brief Scheduler class: what handle all the jobs in kget. - * - * This class handles all the jobs in kget. See job.h for further details. - * When we want a job to be executed in kget, we have to add the queue - * that owns the job in the scheduler calling the addQueue(JobQueue *) function. - * - */ - -class KGET_EXPORT Scheduler : public QObject -{ - Q_OBJECT - - friend class SchedulerTest; - - public: - - enum FailureStatus { - None = 0, - AboutToStall = 1, - Stall = 2, - StallTimeout = 3, - Abort = 4, - AbortTimeout = 5, - Error = 6 - }; - - class JobFailure { - public: - JobFailure() - : status(None), time(-1), count(0) - {} - - bool isValid() {return ((status != None) && (time != -1));} - - FailureStatus status; - int time; - int count; - - bool operator==(JobFailure f) const {return ((status == f.status) && (time == f.time));} - bool operator!=(JobFailure f) const {return ((status != f.status) || (time != f.time));} - }; - - Scheduler(QObject * parent = 0); - ~Scheduler(); - - /** - * Starts globally the execution of the jobs - * - * @see stop() - */ - void start(); - - /** - * Stops globally the execution of the jobs - * - * @see start() - */ - void stop(); - - /** - * Can be used to suspend the scheduler before doing lenghty operations - * and activating it later again - * - * NOTE does not stop running jobs, just prevents changes to jobs - * HACK this is needed since the scheduler would constantly update the queue - * when stopping starting multiple transfers, this slows down that operation a lot - * and could result in transfers finishing before they are stopped etc. - */ - void setIsSuspended(bool isSuspended); - - /** - * The JobQueues will be informed of changes in the network connection - * If there is no network connection then the Scheduler won't act on - * the timerEvent or updateQueue - */ - void setHasNetworkConnection(bool hasConnection); - - /** - * Adds a queue to the scheduler. - * - * @param queue The queue that should be added - */ - void addQueue(JobQueue * queue); - - /** - * Deletes a queue from the scheduler. - * If some jobs in the given queue are being executed, they are - * first stopped, then removed from the scheduler. - * - * @param queue The queue that should be removed - */ - void delQueue(JobQueue * queue); - - /** - * @returns true if there is at least one Job in the Running state - */ - bool hasRunningJobs() const; - - /** - * @returns the number of jobs that are currently in a Running state - */ - int countRunningJobs() const; - - /** - * This function gets called by the KGet class whenever the settings - * have changed. - */ - void settingsChanged(); - - //JobQueue notifications - virtual void jobQueueChangedEvent(JobQueue * queue, JobQueue::Status status); - virtual void jobQueueMovedJobEvent(JobQueue * queue, Job * job); - virtual void jobQueueAddedJobEvent(JobQueue * queue, Job * job); - virtual void jobQueueAddedJobsEvent(JobQueue *queue, const QList jobs); - virtual void jobQueueRemovedJobEvent(JobQueue * queue, Job * job); - virtual void jobQueueRemovedJobsEvent(JobQueue *queue, const QList jobs); - - //Job notifications - virtual void jobChangedEvent(Job * job, Job::Status status); - virtual void jobChangedEvent(Job * job, Job::Policy status); - virtual void jobChangedEvent(Job * job, JobFailure failure); - - protected: - /** - * Updates the given queue, starting the jobs that come first in the queue - * and stopping all the other - * - * @param queue the queue to update - */ - void updateQueue( JobQueue * queue ); - - /** - * @return true if the given job should be running (and this depends - * on the job policy and on its jobQueue status) - * - * @param job the job to evaluate - */ - bool shouldBeRunning( Job * job ); - - private: - //Virtual QObject method - void timerEvent(QTimerEvent * event); - - /** - * Calls updateQueue for all queues - * @see updateQueue - */ - void updateAllQueues(); - - bool shouldUpdate() const; - - private: - QList m_queues; - QMap m_failedJobs; - - int m_failureCheckTimer; - - const int m_stallTime; - int m_stallTimeout; - int m_abortTimeout; - bool m_isSuspended; - bool m_hasConnection; -}; - -inline bool Scheduler::shouldUpdate() const -{ - return !m_isSuspended && m_hasConnection; -} -#endif diff --git a/kget/core/transfer.cpp b/kget/core/transfer.cpp deleted file mode 100644 index 0ed3c42c..00000000 --- a/kget/core/transfer.cpp +++ /dev/null @@ -1,341 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2008 - 2011 Lukas Appelhans - - 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. -*/ - -#include "core/transfer.h" - -#include "settings.h" - -#include "core/transferhandler.h" -#include "core/plugin/transferfactory.h" -#include "core/scheduler.h" - -#include -#include - -#include -#include - -static QTime currentUtcTime() -{ - return QDateTime::currentDateTimeUtc().time(); -} - -static int elapsedSecs(const QTime &time) -{ - const int msecs = time.msecsTo(currentUtcTime()); - if (msecs <= 0) { - return 0; - } - return (msecs / 1000); -} - -struct StatusStrings -{ - const char * context; - const char * name; -}; - -const StatusStrings STATUSTEXTS[] = { - {"", I18N_NOOP("Downloading....")}, - {I18N_NOOP2_NOSTRIP("transfer state: delayed", "Delayed")}, - {I18N_NOOP2_NOSTRIP("transfer state: stopped", "Stopped")}, - {I18N_NOOP2_NOSTRIP("transfer state: aborted", "Aborted")}, - {I18N_NOOP2_NOSTRIP("transfer state: finished", "Finished")}, - {"", ""},//TODO: Add FinishedKeepAlive status - {I18N_NOOP2_NOSTRIP("changing the destination of the file", "Changing destination")} -}; -const QStringList STATUSICONS = QStringList() << "media-playback-start" << "view-history" << "process-stop" << "dialog-error" << "dialog-ok" << "media-playback-start" << "media-playback-pause"; - -Transfer::Transfer(TransferGroup * parent, TransferFactory * factory, - Scheduler * scheduler, const KUrl & source, const KUrl & dest) - : Job(scheduler, parent), - m_source(source), m_dest(dest), - m_totalSize(0), m_downloadedSize(0), m_uploadedSize(0), - m_percent(0), m_downloadSpeed(0), m_uploadSpeed(0), - m_uploadLimit(0), m_downloadLimit(0), m_isSelected(false), - m_capabilities(0), m_visibleUploadLimit(0), m_visibleDownloadLimit(0), - m_ratio(0), m_handler(0), m_factory(factory) -{ -} - -Transfer::~Transfer() -{ -} - -void Transfer::setCapabilities(Capabilities capabilities) -{ - if (m_capabilities != capabilities) { - m_capabilities = capabilities; - emit capabilitiesChanged(); - } -} - -void Transfer::create() -{ - - init(); -} - -void Transfer::destroy(DeleteOptions options) -{ - deinit(options); - -} - -void Transfer::init() -{ -} - - -bool Transfer::setDirectory(const KUrl& newDirectory) -{ - Q_UNUSED(newDirectory) - - //the standard implemention always returns false - return false; -} - -int Transfer::elapsedTime() const -{ - if (status() == Job::Running) - return elapsedSecs(m_runningTime); - - return m_runningSeconds; -} - -int Transfer::averageDownloadSpeed() const -{ - const int runningSeconds = elapsedTime(); - if (runningSeconds) - { - return m_totalSize / runningSeconds; - } - - return 0; -} - -QHash > Transfer::availableMirrors(const KUrl &file) const -{ - Q_UNUSED(file) - - QHash > available; - available[m_source] = QPair(true, 1); - return available; -} - -void Transfer::setUploadLimit(int ulLimit, SpeedLimit limit) -{ - if (limit == Transfer::VisibleSpeedLimit) { - m_visibleUploadLimit = ulLimit; - if (ulLimit < m_uploadLimit || m_uploadLimit == 0) { - m_uploadLimit = ulLimit; - } - } else { - m_uploadLimit = ulLimit; - } - - setSpeedLimits(m_uploadLimit, m_downloadLimit); -} - -void Transfer::setDownloadLimit(int dlLimit, SpeedLimit limit) -{ - if (limit == Transfer::VisibleSpeedLimit) { - m_visibleDownloadLimit = dlLimit; - if (dlLimit < m_downloadLimit || m_downloadLimit == 0) { - m_downloadLimit = dlLimit; - } - } else { - m_downloadLimit = dlLimit; - } - - setSpeedLimits(m_uploadLimit, m_downloadLimit); -} - -int Transfer::uploadLimit(SpeedLimit limit) const -{ - if (limit == Transfer::VisibleSpeedLimit) - return m_visibleUploadLimit; - - return m_uploadLimit; -} - -int Transfer::downloadLimit(SpeedLimit limit) const -{ - if (limit == Transfer::VisibleSpeedLimit) - return m_visibleDownloadLimit; - - return m_downloadLimit; -} - -void Transfer::setMaximumShareRatio(double ratio) -{ - m_ratio = ratio; - checkShareRatio(); -} - -void Transfer::checkShareRatio() -{ - if (m_downloadedSize == 0 || m_ratio == 0) - return; - - if (m_uploadedSize / m_downloadedSize >= m_ratio) - setDownloadLimit(1, Transfer::InvisibleSpeedLimit);//If we set it to 0 we would have no limit xD - else - setDownloadLimit(0, Transfer::InvisibleSpeedLimit); -} - -void Transfer::setLog(const QString& message, Transfer::LogLevel level) -{ - QString msg("" + QTime::currentTime().toString() + " : "); - if (level == Log_Error) - { - msg += "" + message + ""; - } - if (level == Log_Warning) - { - msg += "" + message + ""; - } else { - msg += message; - } - m_log << msg; -} - -TransferHandler * Transfer::handler() -{ - if(!m_handler) - m_handler = m_factory->createTransferHandler(this, scheduler()); - - return m_handler; -} - -TransferTreeModel * Transfer::model() -{ - return group()->model(); -} - -void Transfer::save(const QDomElement &element) -{ - QDomElement e = element; - e.setAttribute("Source", m_source.url()); - e.setAttribute("Dest", m_dest.url()); - e.setAttribute("TotalSize", m_totalSize); - e.setAttribute("DownloadedSize", m_downloadedSize); - e.setAttribute("UploadedSize", m_uploadedSize); - e.setAttribute("DownloadLimit", m_visibleDownloadLimit); - e.setAttribute("UploadLimit", m_visibleUploadLimit); - e.setAttribute("ElapsedTime", status() == Job::Running ? elapsedSecs(m_runningTime) : m_runningSeconds); - e.setAttribute("Policy", policy() == Job::Start ? "Start" : (policy() == Job::Stop ? "Stop" : "None")); -} - -void Transfer::load(const QDomElement *element) -{ - if (!element) - { - setStatus(status(), i18nc("transfer state: stopped", "Stopped"), SmallIcon("process-stop")); - setStartStatus(status()); - return; - } - - const QDomElement e = *element; - - m_source = KUrl(e.attribute("Source")); - m_dest = KUrl(e.attribute("Dest")); - - m_totalSize = e.attribute("TotalSize").toULongLong(); - m_downloadedSize = e.attribute("DownloadedSize").toULongLong(); - m_uploadedSize = e.attribute("UploadedSize").toULongLong(); - m_percent = (m_totalSize ? ((100.0 * m_downloadedSize) / m_totalSize) : 0); - - if ((m_totalSize == m_downloadedSize) && (m_totalSize != 0)) { - setStartStatus(Job::Finished); - setStatus(startStatus()); - } else { - setStatus(status(), i18nc("transfer state: stopped", "Stopped"), SmallIcon("process-stop")); - setStartStatus(status()); - } - setUploadLimit(e.attribute("UploadLimit").toInt(), Transfer::VisibleSpeedLimit); - setDownloadLimit(e.attribute("DownloadLimit").toInt(), Transfer::VisibleSpeedLimit); - m_runningSeconds = e.attribute("ElapsedTime").toInt(); - if (Settings::startupAction() == 1) - { - setPolicy(Job::Start); - } - else if (Settings::startupAction() == 2) - { - setPolicy(Job::Stop); - } - else - { - if (e.attribute("Policy") == "Start") - setPolicy(Job::Start); - else if (e.attribute("Policy") == "Stop") - setPolicy(Job::Stop); - else - setPolicy(Job::None); - } -} - -void Transfer::setStatus(Job::Status jobStatus, const QString &text, const QPixmap &pix) -{ - const bool statusChanged = (status() != jobStatus); - QString statusText = text; - if (statusText.isEmpty()) { - statusText = i18nc(STATUSTEXTS[jobStatus].context, STATUSTEXTS[jobStatus].name); - } - - //always prefer pix, if it is set - if (!pix.isNull()) { - m_statusPixmap = pix; - } else if (statusChanged || m_statusPixmap.isNull()) { - m_statusPixmap = SmallIcon(STATUSICONS[jobStatus]); - } - - m_statusText = statusText; - - if (jobStatus == Job::Running && status() != Job::Running) - { - m_runningTime = currentUtcTime(); - m_runningTime.addSecs(m_runningSeconds); - } - if (jobStatus != Job::Running && status() == Job::Running) - m_runningSeconds = elapsedSecs(m_runningTime); - /** - * It's important to call job::setStatus AFTER having changed the - * icon or the text or whatever. - * This because this function also notifies about this change - * the scheduler which could also decide to change it another time - * as well. For example if a job status is set to Aborted, the scheduler - * could mark it to Delayed. This could trigger another icon or text - * change which would be the right one since the status of the Job - * has changed. If we set the icon or text after calling setStatus(), - * we can overwrite the last icon or text change. - */ - Job::setStatus(jobStatus); - -} - -void Transfer::setTransferChange(ChangesFlags change, bool postEvent) -{ - if (change & Tc_DownloadedSize || change & Tc_Status) { - change = change | Tc_RemainingTime; - } - handler()->setTransferChange(change, postEvent); -} - -QString Transfer::statusText(Job::Status status) -{ - return i18nc(STATUSTEXTS[status].context, STATUSTEXTS[status].name); -} - -QPixmap Transfer::statusPixmap(Job::Status status) -{ - return SmallIcon(STATUSICONS[status]); -} diff --git a/kget/core/transfer.h b/kget/core/transfer.h deleted file mode 100644 index f32a21a1..00000000 --- a/kget/core/transfer.h +++ /dev/null @@ -1,366 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2008 - 2011 Lukas Appelhans - - 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. -*/ - -#ifndef TRANSFER_H -#define TRANSFER_H - -#include "job.h" -#include "../kget_export.h" - -#include -#include -#include - -#include -#include - -class TransferHandler; -class TransferFactory; -class TransferGroup; -class Scheduler; -class TransferTreeModel; -class FileModel; -class Verifier; - -class KGET_EXPORT Transfer : public Job -{ - Q_OBJECT - friend class TransferHandler; - friend class TransferTreeModel; - public: - - /** - * Here we define the flags that should be shared by all the transfers. - * A transfer should also be able to define additional flags, in the future. - */ - enum TransferChange - { - Tc_None = 0x00000000, - // These flags respect the Model columns order NOTE: The model only checks the last 8 bits, so all values which need to be updated by the model should look like: 0x000000xx - Tc_Source = 0x00000001, - Tc_FileName = 0x00000002, - Tc_Status = 0x00000004, - Tc_TotalSize = 0x00000008, - Tc_Percent = 0x00000010, - Tc_DownloadSpeed = 0x00000020, - Tc_RemainingTime = 0x00000040, - // Misc - Tc_UploadSpeed = 0x00000100, - Tc_UploadLimit = 0x00000200, - Tc_DownloadLimit = 0x00000400, - Tc_CanResume = 0x00000800, - Tc_DownloadedSize = 0x00001000, - Tc_UploadedSize = 0x00002000, - Tc_Log = 0x00004000, - Tc_Group = 0x00008000, - Tc_Selection = 0x00010000 - }; - typedef int ChangesFlags; - - enum Capability - { - Cap_SpeedLimit = 0x00000001, - Cap_MultipleMirrors = 0x00000002, - Cap_Resuming = 0x00000004, - Cap_Renaming = 0x00000008, - Cap_Moving = 0x00000010, - Cap_FindFilesize = 0x00000020 - }; - Q_DECLARE_FLAGS(Capabilities, Capability) - - enum LogLevel - { - Log_Info, - Log_Warning, - Log_Error - }; - - enum SpeedLimit - { - VisibleSpeedLimit = 0x01, - InvisibleSpeedLimit = 0x02 - }; - - enum DeleteOption - { - DeleteTemporaryFiles = 0x00000001, - DeleteFiles = 0x00000002 - }; - Q_DECLARE_FLAGS(DeleteOptions, DeleteOption) - - Transfer(TransferGroup * parent, TransferFactory * factory, - Scheduler * scheduler, const KUrl & src, const KUrl & dest); - - virtual ~Transfer(); - - /** - * Returns the capabilities this Transfer supports - */ - Capabilities capabilities() const {return m_capabilities;} - - /** - * This functions gets called whenever a Transfer gets created. As opposed - * to init(), this isn't a virtual function and is not meant to be used in - * transfer plugins - */ - void create(); - - /** - * This functions gets called whenever a Transfer is going to be deleted. As opposed - * to deinit(), this isn't a virtual function and is not meant to be used in - * transfer plugins - */ - void destroy(DeleteOptions options); - - /** - * This function is called after the creation of a Transfer - * In transfer plugins you can put here whatever needs to be initialized - */ - virtual void init(); - - /** - * This function is called before the deletion of a Transfer - * In transfer plugins you can put here whatever needs to be deinitialized - */ - virtual void deinit(DeleteOptions options) {Q_UNUSED(options);} - - /** - * Tries to repair file - * @param file the file of a download that should be repaired, - * if not defined all files of a download are going to be repaird - * @return true if a repair started, false if it was not nescessary - */ - virtual bool repair(const KUrl &file = KUrl()) {Q_UNUSED(file) return false;} - - const KUrl & source() const {return m_source;} - const KUrl & dest() const {return m_dest;} - - /** - * @returns all files of this transfer - */ - virtual QList files() const {return QList() << m_dest;} - - /** - * @returns the directory the Transfer will be stored to - */ - virtual KUrl directory() const {return m_dest.directory();} - - /** - * Move the download to the new destination - * @param newDirectory is a directory where the download should be stored - * @returns true if newDestination can be used - */ - virtual bool setDirectory(const KUrl &newDirectory); - - //Transfer status - KIO::filesize_t totalSize() const {return m_totalSize;} - KIO::filesize_t downloadedSize() const {return m_downloadedSize;} - KIO::filesize_t uploadedSize() const {return m_uploadedSize;} - QString statusText() const {return m_statusText;} - QPixmap statusPixmap() const {return (error().pixmap.isNull() ? m_statusPixmap : error().pixmap);} - - static QString statusText(Job::Status status); - static QPixmap statusPixmap(Job::Status status); - - int percent() const {return m_percent;} - int downloadSpeed() const {return m_downloadSpeed;} - int averageDownloadSpeed() const; - int uploadSpeed() const {return m_uploadSpeed;} - virtual int remainingTime() const {return KIO::calculateRemainingSeconds(totalSize(), downloadedSize(), downloadSpeed());} - virtual int elapsedTime() const; - virtual bool isStalled() const {return (status() == Job::Running && downloadSpeed() == 0);} - virtual bool isWorking() const {return downloadSpeed() > 0;} - - /** - * The mirrors that are available - * bool if it is used, int how many paralell connections are allowed - * to the mirror - * @param file the file for which the availableMirrors should be get - */ - virtual QHash > availableMirrors(const KUrl &file) const; - - /** - * Set the mirrors, int the number of paralell connections to the mirror - * bool if the mirror should be used - * @param file the file for which the availableMirrors should be set - */ - virtual void setAvailableMirrors(const KUrl &file, const QHash > &mirrors) {Q_UNUSED(file) Q_UNUSED(mirrors)} - - /** - * Set the Transfer's UploadLimit - * @note this is not displayed in any GUI, use setVisibleUploadLimit(int) instead - * @param visibleUlLimit upload Limit - */ - void setUploadLimit(int ulLimit, SpeedLimit limit); - - /** - * Set the Transfer's UploadLimit, which are displayed in the GUI - * @note this is not displayed in any GUI, use setVisibleDownloadLimit(int) instead - * @param visibleUlLimit upload Limit - */ - void setDownloadLimit(int dlLimit, SpeedLimit limit); - - /** - * @return the UploadLimit, which is invisible in the GUI - */ - int uploadLimit(SpeedLimit limit) const; - - /** - * @return the DownloadLimit, which is invisible in the GUI - */ - int downloadLimit(SpeedLimit limit) const; - - /** - * Set the maximum share-ratio - * @param ratio the new maximum share-ratio - */ - void setMaximumShareRatio(double ratio); - - /** - * @return the maximum share-ratio - */ - double maximumShareRatio() {return m_ratio;} - - /** - * Recalculate the share ratio - */ - void checkShareRatio(); - - bool isSelected() const {return m_isSelected;} - - /** - * Transfer history - */ - const QStringList log() const; - - /** - * Defines the order between transfers - */ - bool operator<(const Transfer& t2) const; - - /** - * The owner group - */ - TransferGroup * group() const {return (TransferGroup *) m_jobQueue;} - - /** - * @return the associated TransferHandler - */ - TransferHandler * handler(); - - /** - * @returns the TransferTreeModel that owns this group - */ - TransferTreeModel * model(); - - /** - * @returns a pointer to the TransferFactory object - */ - TransferFactory * factory() const {return m_factory;} - - /** - * @returns a pointer to the FileModel containing all files of this download - */ - virtual FileModel * fileModel() {return 0;} - - /** - * @param file for which to get the verifier - * @return Verifier that allows you to add checksums manually verify a file etc. - */ - virtual Verifier * verifier(const KUrl &file) {Q_UNUSED(file) return 0;} - - /** - * Saves this transfer to the given QDomNode - * - * @param element The pointer to the QDomNode where the transfer will be saved - */ - virtual void save(const QDomElement &element); - - /** - * Loads the transfer's info from the QDomElement - * - * @param element The pointer to the QDomNode where info will be loaded from - */ - virtual void load(const QDomElement *element); - - signals: - /** - * Emitted when the capabilities of the Transfer change - */ - void capabilitiesChanged(); - - public slots: - /** - * Set Transfer history - */ - void setLog(const QString& message, Transfer::LogLevel level = Log_Info); - - protected: - /** - * Sets the Job status to jobStatus, the status text to text and - * the status pixmap to pix. - */ - void setStatus(Job::Status jobStatus, const QString &text = QString(), const QPixmap &pix = QPixmap()); - - /** - * Sets the capabilities and automatically emits capabilitiesChanged - */ - void setCapabilities(Capabilities capabilities); - - /** - * Makes the TransferHandler associated with this transfer know that - * a change in this transfer has occurred. - * - * @param change: the TransferChange flags to be set - */ - virtual void setTransferChange(ChangesFlags change, bool postEvent=false); - - /** - * Function used to set the SpeedLimits to the transfer - */ - virtual void setSpeedLimits(int uploadLimit, int downloadLimit) {Q_UNUSED(uploadLimit) Q_UNUSED(downloadLimit) } - - // --- Transfer information --- - KUrl m_source; - KUrl m_dest; - - QStringList m_log; - KIO::filesize_t m_totalSize; - KIO::filesize_t m_downloadedSize; - KIO::filesize_t m_uploadedSize; - int m_percent; - int m_downloadSpeed; - int m_uploadSpeed; - - int m_uploadLimit; - int m_downloadLimit; - - bool m_isSelected; - - private: - Capabilities m_capabilities; - int m_visibleUploadLimit; - int m_visibleDownloadLimit; - int m_runningSeconds; - double m_ratio; - - QString m_statusText; - QPixmap m_statusPixmap; - QTime m_runningTime; - - TransferHandler * m_handler; - TransferFactory * m_factory; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(Transfer::Capabilities) -Q_DECLARE_OPERATORS_FOR_FLAGS(Transfer::DeleteOptions) - -#endif diff --git a/kget/core/transfercontainer.cpp b/kget/core/transfercontainer.cpp deleted file mode 100644 index 26270e53..00000000 --- a/kget/core/transfercontainer.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 Urs Wolfer - - 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. -*/ - -#include "core/transfercontainer.h" - -#include - -TransferContainer::TransferContainer() -{ -} - -TransferContainer::~TransferContainer() -{ -} - -#include "moc_transfercontainer.cpp" diff --git a/kget/core/transfercontainer.h b/kget/core/transfercontainer.h deleted file mode 100644 index 1a9a8cd0..00000000 --- a/kget/core/transfercontainer.h +++ /dev/null @@ -1,45 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 Urs Wolfer - - 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. -*/ - -#ifndef TRANSFERCONTAINER_H -#define TRANSFERCONTAINER_H - -#include - -/** - * @brief TransferContainer class handles the transfers - * - * This class is the base for every single transfer. - * - */ - -class TransferContainer : public QObject -{ - Q_OBJECT - -public: - Q_FLAGS(TransferFlags) - - enum TransferFlag { - /** The transfer supports resuming and seeking */ - Tf_SupportsSegments = 0x01, - /** The container includes more than one file, e.g. torrent */ - Tf_MultipleFiles = 0x02 - }; - - Q_DECLARE_FLAGS(TransferFlags, TransferFlag) - - TransferContainer(); - ~TransferContainer(); -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(TransferContainer::TransferFlags) - -#endif diff --git a/kget/core/transferdatasource.cpp b/kget/core/transferdatasource.cpp deleted file mode 100644 index c698f144..00000000 --- a/kget/core/transferdatasource.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Manolo Valdes - - 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. -*/ - -#include "transferdatasource.h" - -#include - -TransferDataSource::TransferDataSource(const KUrl &srcUrl, QObject *parent) - : QObject(parent), - m_sourceUrl(srcUrl), - m_speed(0), - m_supposedSize(0), - m_paralellSegments(1), - m_currentSegments(0), - m_capabilities(0) -{ -} - -TransferDataSource::~TransferDataSource() -{ -} - -Transfer::Capabilities TransferDataSource::capabilities() const -{ - return m_capabilities; -} - -void TransferDataSource::setCapabilities(Transfer::Capabilities capabilities) -{ - m_capabilities = capabilities; - emit capabilitiesChanged(); -} - -void TransferDataSource::findFileSize(KIO::fileoffset_t segmentSize) -{ - Q_UNUSED(segmentSize); -} - -QPair TransferDataSource::removeConnection() -{ - return QPair(-1, -1); -} - -QList > TransferDataSource::assignedSegments() const -{ - return QList >(); -} - -int TransferDataSource::countUnfinishedSegments() const -{ - return 0; -} - -QPair TransferDataSource::split() -{ - return QPair(-1, -1); -} - -int TransferDataSource::paralellSegments() const -{ - return m_paralellSegments; -} - -void TransferDataSource::setParalellSegments(int paralellSegments) -{ - m_paralellSegments = paralellSegments; -} - -int TransferDataSource::currentSegments() const -{ - return m_currentSegments; -} - -int TransferDataSource::changeNeeded() const -{ - return paralellSegments() - currentSegments(); -} - - -#include "moc_transferdatasource.cpp" diff --git a/kget/core/transferdatasource.h b/kget/core/transferdatasource.h deleted file mode 100644 index c0761d2e..00000000 --- a/kget/core/transferdatasource.h +++ /dev/null @@ -1,251 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Manolo Valdes - - 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. -*/ - - -#ifndef TRANSFERDATASOURCE_H -#define TRANSFERDATASOURCE_H - -#include "kget_export.h" -#include "transfer.h" - -#include - -#include - -/** - * This Class is an interface for inter-plugins data change. - * allowing to use already implemented features from others plugins - */ -class KGET_EXPORT TransferDataSource : public QObject -{ - Q_OBJECT - public: - TransferDataSource(const KUrl &srcUrl, QObject *parent); - virtual ~TransferDataSource(); - - enum Error - { - Unknown, - WrongDownloadSize, - NotResumeable - }; - - /** - * Returns the capabilities this TransferDataSource supports - */ - Transfer::Capabilities capabilities() const; - - virtual void start() = 0; - virtual void stop() = 0; - - /** - * Tries to find the filesize if this capability is supported, - * if successfull it emits foundFileSize(TransferDataSource*,KIO::filesize_t,QPair) - * and assigns all segements to itself - * if not succesfull it will try to download the file nevertheless - * @note if stop is called and no size is found yet then this is aborted, i.e. needs to be - * called again if start is later called - * @param segmentSize the segments should have - */ - virtual void findFileSize(KIO::fileoffset_t segmentSize); - - /** - * Adds multiple continuous segments that should be downloaded by this TransferDataSource - * @param segmentSize first is always the general segmentSize, second the segmentSize - * of the last segment in the range. If just one (the last) segment was assigned, then - * first would not equal second, this is to ensure that first can be used to calculate the offset - * TransferDataSources have to handle all that internally. - * @param segmentRange first the beginning, second the end - */ - virtual void addSegments(const QPair &segmentSize, const QPair &segmentRange) = 0; - - /** - * Removes one connection, useful when setMaximumParalellDownloads was called with a lower number - * @return the segments that are removed (unassigned) now - * - */ - virtual QPair removeConnection(); - - KUrl sourceUrl() const {return m_sourceUrl;}//TODO - - /** - * returns the current speed of this data source - * @return the speed - */ - ulong currentSpeed() const {return m_speed;} - - /** - * Set the size the server used for downloading should report - * @param supposedSize the size the file should have - */ - virtual void setSupposedSize(KIO::filesize_t supposedSize) {m_supposedSize = supposedSize;} - - /** - * Returns the assignedSegments to this TransferDataSource - * Each connection is represented by a QPair, where the first int is the beginning - * segment and the last the ending segment - * @note an empty list is returned by default, the elements can also be (-1, -1) - */ - virtual QList > assignedSegments() const; - - /** - * Returns the number of unfinished Segments of the connection with the most - * unfinished segments - * Each TransferDataSource can have multiple connections and each connection - * can have multiple segments assigned - * @note default implemention returns 0 - */ - virtual int countUnfinishedSegments() const; - - /** - * If a connection of this TransferDataSource is assigned multiple (continuous) segments, then - * this method will split them (the unfinished ones) in half, it returns the beginning - * and the end of the now unassigned segments; (-1, -1) if there are none - * @note if only one segment is assigned to a connection split will also return (-1, -1) - */ - virtual QPair split();//TODO should split also take the current running segment into account? - - - //the following methods are used for managing the number of paralell connections - //subclasses have to keep track of the currentSegments - /** - * @return the number of paralell segments this DataSource is allowed to use, - * default is 1 - */ - virtual int paralellSegments() const; - - /** - * Sets the number of paralell segments this DataSource is allowed to use - */ - virtual void setParalellSegments(int paralellSegments); - - /** - * @return the number of paralell segments this DataSources currently uses - */ - virtual int currentSegments() const; - - /** - * Returns the missmatch of paralellSegments() and currentSegments() - * @return the number of segments to add/remove e.g. -1 means one segment to remove - */ - virtual int changeNeeded() const; - - signals: - /** - * Emitted after findFileSize is called successfully - * @param source that foudn the filesize - * @param fileSize that was found - * @param segmentRange that was calculated based on the segmentSize and that was assigned to - * source automatically - */ - void foundFileSize(TransferDataSource *source, KIO::filesize_t fileSize, const QPair &segmentRange); - - /** - * Emitted when the capabilities of the TransferDataSource change - */ - void capabilitiesChanged(); - - /** - * Emitted when the TransferDataSource finished the download on its own, e.g. when findFileSize - * is being called but no fileSize is found and instead the download finishes - * @param source the source that emmited this signal - * @param fileSize the fileSize of the finished file (calculated by the downloaded bytes) - */ - void finishedDownload(TransferDataSource *source, KIO::filesize_t fileSize); - - /** - * Returns data in the forms of chucks - * @note if the receiver set worked to wrong the TransferDataSource should cache the data - * @param offset the offset in the file - * @param data the downloaded data - * @param worked if the receiver could handle the data, if not, the sender should cache the data - */ - void data(KIO::fileoffset_t offset, const QByteArray &data, bool &worked); - - /** - * Returns data in the forms of URL List - * @param data in form of KUrl list - */ - void data(const QList &data); - - /** - * Returns found checksums with their type - * @param type the type of the checksum - * @param checksum the checksum - */ - void data(const QString type, const QString checksum); - - /** - * emitted when there is no more data - * @param source the datasource, sending the signal - */ - void finished(); - - /** - * emitted when an assigned segment finishes - * @param source the source that emmited this signal - * @param segmentNumber the number of the segment, to identify it - * @param connectionFinished true if all segments of this connection have been finished, - * if one segement (instead of a group of segments) has been asigned this is always true - */ - void finishedSegment(TransferDataSource *source, int segmentNumber, bool connectionFinished = true); - - /** - * Alert that datasource is no able to send any data - *@param source the datasource, sending the signal - */ - void broken(TransferDataSource *source, TransferDataSource::Error error); - - /** - * emitted when an assigned segment is broken - * @param source the source that emmited this signal - * @param segmentRange the range of the segments e.g. (1,1,) or (0, 10) - */ - void brokenSegments(TransferDataSource *source, QPair segmentRange); - - /** - * The speed of the download - * @param speed speed of the download - */ - void speed(ulong speed); - - /** - * Emitted when a Datasource itself decides to not download a specific segmentRange, - * e.g. when there are too many connections for this TransferDataSource - */ - void freeSegments(TransferDataSource *source, QPair segmentRange); - - void log(const QString &message, Transfer::LogLevel logLevel); - - /** - * Emitted when the filename of a url changes, e.g. when a link redirects - */ - void urlChanged(const KUrl &old, const KUrl &newUrl); - - protected: - /** - * Sets the capabilities and automatically emits capabilitiesChanged - */ - void setCapabilities(Transfer::Capabilities capabilities); - - private Q_SLOTS: - virtual void slotSpeed(ulong speed) {Q_UNUSED(speed)} - - protected: - KUrl m_sourceUrl; - ulong m_speed; - KIO::filesize_t m_supposedSize; - int m_paralellSegments; - int m_currentSegments; - - private: - Transfer::Capabilities m_capabilities; -}; -#endif diff --git a/kget/core/transfergroup.cpp b/kget/core/transfergroup.cpp deleted file mode 100644 index 793a35ae..00000000 --- a/kget/core/transfergroup.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "core/transfergroup.h" - -#include "core/transfergrouphandler.h" -#include "core/kget.h" - -#include -#include -#include -#include -#include - -#include -#include -#include - - -TransferGroup::TransferGroup(TransferTreeModel * model, Scheduler * parent, const QString & name) - : JobQueue(parent), - m_model(model), m_name(name), - m_totalSize(0), m_downloadedSize(0), m_uploadedSize(0), - m_percent(0), m_downloadSpeed(0), m_uploadSpeed(0), - m_downloadLimit(0), m_uploadLimit(0), - m_visibleDownloadLimit(0), m_visibleUploadLimit(0), - m_iconName("bookmark-new-list"), m_defaultFolder() -{ - m_handler = new TransferGroupHandler(parent, this); -} - -TransferGroup::~TransferGroup() -{ -} - -int TransferGroup::downloadSpeed() -{ - m_downloadSpeed = 0; - foreach(Job *job, runningJobs()) - { - Transfer *transfer = static_cast(job); - if (transfer) - m_downloadSpeed += transfer->downloadSpeed(); - } - return m_downloadSpeed; -} - -int TransferGroup::uploadSpeed() -{ - m_uploadSpeed = 0; - foreach(Job *job, runningJobs()) - { - Transfer *transfer = static_cast(job); - if (transfer) - m_uploadSpeed += transfer->uploadSpeed(); - } - return m_uploadSpeed; -} - - -bool TransferGroup::supportsSpeedLimits() -{ - QList jobs = runningJobs(); - foreach (Job *job, jobs) { - Transfer * transfer = static_cast(job); - if (!(transfer->capabilities() & Transfer::Cap_SpeedLimit)) { - return false; - } - } - - //empty jobs can't support a speed limit - return !jobs.isEmpty(); -} - -void TransferGroup::setStatus(Status queueStatus) -{ - JobQueue::setStatus(queueStatus); - - m_handler->setGroupChange(Gc_Status, true); -} - -void TransferGroup::append(Transfer * transfer) -{ - JobQueue::append(transfer); - - calculateSpeedLimits(); -} - -void TransferGroup::append(const QList &transfers) -{ - QList jobs; - foreach (Transfer *transfer, transfers) { - jobs << transfer; - } - JobQueue::append(jobs); - - calculateSpeedLimits(); -} - - -void TransferGroup::prepend(Transfer * transfer) -{ - JobQueue::prepend(transfer); - - calculateSpeedLimits(); -} - -void TransferGroup::insert(Transfer * transfer, Transfer * after) -{ - JobQueue::insert(transfer, after); - - calculateSpeedLimits(); -} - -void TransferGroup::remove(Transfer * transfer) -{ - JobQueue::remove(transfer); - - calculateSpeedLimits(); -} - -void TransferGroup::remove(const QList &transfers) -{ - QList jobs; - foreach (Transfer *transfer, transfers) { - jobs << transfer; - } - JobQueue::remove(jobs); - - calculateSpeedLimits(); -} - -void TransferGroup::move(Transfer * transfer, Transfer * after) -{ - if(transfer == after) - return; - - JobQueue::move(transfer, after); -} - -Transfer * TransferGroup::findTransfer(const KUrl &src) -{ - iterator it = begin(); - iterator itEnd = end(); - - for(; it!=itEnd ; ++it) - { - Transfer * t = (Transfer *) *it; - if( t->source().url() == src.url() ) - return t; - } - return 0; -} - -Transfer *TransferGroup::findTransferByDestination(const KUrl &dest) -{ - iterator it = begin(); - iterator itEnd = end(); - - for(; it!=itEnd ; ++it) { - Transfer *t = (Transfer *) *it; - if(t->dest().url() == dest.url()) { - return t; - } - } - return 0; -} - -void TransferGroup::setUploadLimit(int ulLimit, Transfer::SpeedLimit limit) -{ - if (limit == Transfer::VisibleSpeedLimit) { - m_visibleUploadLimit = ulLimit; - if (ulLimit < m_uploadLimit || m_uploadLimit == 0) - m_uploadLimit = ulLimit; - } else { - m_uploadLimit = ulLimit; - } - - calculateUploadLimit(); -} - -void TransferGroup::setDownloadLimit(int dlLimit, Transfer::SpeedLimit limit) -{ - if (limit == Transfer::VisibleSpeedLimit) { - m_visibleDownloadLimit = dlLimit; - if (dlLimit < m_downloadLimit || m_downloadLimit == 0) - m_downloadLimit = dlLimit; - } else { - m_downloadLimit = dlLimit; - } - - calculateDownloadLimit(); -} - -int TransferGroup::uploadLimit(Transfer::SpeedLimit limit) const -{ - if (limit == Transfer::VisibleSpeedLimit) - return m_visibleUploadLimit; - - return m_uploadLimit; -} - -int TransferGroup::downloadLimit(Transfer::SpeedLimit limit) const -{ - if (limit == Transfer::VisibleSpeedLimit) - return m_visibleDownloadLimit; - - return m_downloadLimit; -} - -void TransferGroup::calculateSpeedLimits() -{ - kDebug() << "We will calculate the new SpeedLimits now"; - calculateDownloadLimit(); - calculateUploadLimit(); -} - -void TransferGroup::calculateDownloadLimit() -{ - kDebug() << "Calculate new DownloadLimit of " + QString::number(m_downloadLimit); - if (supportsSpeedLimits()) - { - const QList running = runningJobs(); - int n = running.count(); - int pool = 0;//We create a pool where we have some KiB/s to go to other transfer's... - QList transfersNeedSpeed; - foreach (Job *job, running) { - Transfer * transfer = static_cast(job); - if (transfer) - { - if (m_downloadLimit == 0 && transfer->downloadLimit(Transfer::VisibleSpeedLimit) != 0) - continue; - else if (m_downloadLimit == 0 && transfer->downloadLimit(Transfer::VisibleSpeedLimit) == 0) - transfer->setDownloadLimit(0, Transfer::InvisibleSpeedLimit); - else if (transfer->downloadLimit(Transfer::VisibleSpeedLimit) < m_downloadLimit / n - && transfer->downloadLimit(Transfer::VisibleSpeedLimit) != 0) - /*If the transfer's visible download limit is under the new one, - we move the KiB/s which are different to the pool*/ - pool = pool + (m_downloadLimit / n - transfer->downloadLimit(Transfer::VisibleSpeedLimit)); - else if (transfer->downloadSpeed() + 10 < m_downloadLimit / n) - { - /*When the downloadSpeed of the transfer is under the new downloadLimit + 10 then we - set the downloadLimit to the downloadSpeed + 10*/ - pool = pool + m_downloadLimit / n - transfer->downloadSpeed() + 10; - transfer->setDownloadLimit(transfer->downloadSpeed() + 10, Transfer::InvisibleSpeedLimit); - } - else - { - transfer->setDownloadLimit(m_downloadLimit / n, Transfer::InvisibleSpeedLimit); - transfersNeedSpeed.append(transfer); - } - } - } - foreach (Transfer *transfer, transfersNeedSpeed) - { - transfer->setDownloadLimit(m_downloadLimit / n + pool / transfersNeedSpeed.count(), Transfer::InvisibleSpeedLimit); - } - } -} - -void TransferGroup::calculateUploadLimit() -{ - kDebug() << "Calculate new Upload Limit of " + QString::number(m_uploadLimit); - if (supportsSpeedLimits()) - { - const QList running = runningJobs(); - int n = running.count(); - int pool = 0;//We create a pool where we have some KiB/s to go to other transfer's... - QList transfersNeedSpeed; - foreach (Job *job, running) { - Transfer * transfer = static_cast(job); - if (transfer) - { - if (m_uploadLimit == 0 && transfer->uploadLimit(Transfer::VisibleSpeedLimit) != 0) - continue; - else if (m_uploadLimit == 0 && transfer->uploadLimit(Transfer::VisibleSpeedLimit) == 0) - transfer->setUploadLimit(0, Transfer::InvisibleSpeedLimit); - else if (transfer->uploadLimit(Transfer::VisibleSpeedLimit) < m_uploadLimit / n - && transfer->uploadLimit(Transfer::VisibleSpeedLimit) != 0) - /*If the transfer's visible upload limit is under the new one, - we move the KiB/s which are different to the pool*/ - pool = pool + (m_uploadLimit / n - transfer->uploadLimit(Transfer::VisibleSpeedLimit)); - else if (transfer->uploadSpeed() + 10 < m_uploadLimit / n) - { - /*When the uploadSpeed of the transfer is under the new uploadLimit + 10 then we - set the uploadLimit to the uploadSpeed + 10*/ - pool = pool + m_uploadLimit / n - transfer->uploadSpeed() + 10; - transfer->setUploadLimit(transfer->uploadSpeed() + 10, Transfer::InvisibleSpeedLimit); - } - else - { - transfer->setUploadLimit(m_uploadLimit / n, Transfer::InvisibleSpeedLimit); - transfersNeedSpeed.append(transfer); - } - } - } - foreach (Transfer *transfer, transfersNeedSpeed) - { - transfer->setUploadLimit(m_uploadLimit / n + pool / transfersNeedSpeed.count(), Transfer::InvisibleSpeedLimit); - } - } -} - -void TransferGroup::save(QDomElement e) // krazy:exclude=passbyvalue -{ - // kDebug() << " --> " << name(); - - e.setAttribute("Name", m_name); - e.setAttribute("DefaultFolder", m_defaultFolder); - e.setAttribute("DownloadLimit", m_visibleDownloadLimit); - e.setAttribute("UploadLimit", m_visibleUploadLimit); - e.setAttribute("Icon", m_iconName); - e.setAttribute("Status", status() == JobQueue::Running ? "Running" : "Stopped"); - e.setAttribute("RegExpPattern", m_regExp.pattern()); - - - iterator it = begin(); - iterator itEnd = end(); - - for( ; it!=itEnd; ++it ) - { - Transfer* transfer = static_cast(*it); - kDebug() << " --> " << name() << " transfer: " << transfer->source(); - QDomElement t = e.ownerDocument().createElement("Transfer"); - e.appendChild(t); - transfer->save(t); - } -} - -void TransferGroup::load(const QDomElement & e) -{ - kDebug() << "TransferGroup::load"; - - m_name = e.attribute("Name"); - m_defaultFolder = e.attribute("DefaultFolder"); - m_visibleDownloadLimit = e.attribute("DownloadLimit").toInt(); - m_visibleUploadLimit = e.attribute("UploadLimit").toInt(); - if (!e.attribute("Icon").isEmpty()) - m_iconName = e.attribute("Icon"); - - if (e.attribute("Status") == "Running") - setStatus(JobQueue::Running); - else - setStatus(JobQueue::Stopped); - - m_regExp.setPattern(e.attribute("RegExpPattern")); - - - QDomNodeList nodeList = e.elementsByTagName("Transfer"); - int nItems = nodeList.length(); - - QList elements; - for (int i = 0; i < nItems; ++i) { - elements << nodeList.item(i).toElement(); - } - - kDebug() << "TransferGroup::load ->" << "add" << nItems << "transfers"; - KGet::addTransfers(elements, name()); -} diff --git a/kget/core/transfergroup.h b/kget/core/transfergroup.h deleted file mode 100644 index e22232cd..00000000 --- a/kget/core/transfergroup.h +++ /dev/null @@ -1,325 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - Coypright (C) 2010 Matthias Fuchs - - 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. -*/ -#ifndef GROUP_H -#define GROUP_H - -#include - -#include -#include -#include - -#include "jobqueue.h" -#include "../kget_export.h" -#include "transfer.h" - - -#include - -class TransferGroupHandler; -class TransferTreeModel; - -/** - * class TransferGroup: - * - * This class abstracts the concept of transfer group by means of which - * the user can sort his transfers into categories. - * By definition, we want each TransferGroup (transfer group) to be a JobQueue. - * Moreover this class calculates information such as: - * - the size obtained by the sum of all the transfer's size - * - the size obtained by the sum of all the transfer's processed size - * - the global progress percentage within the group - * - the global speed within the group - */ -class KGET_EXPORT TransferGroup : public JobQueue -{ - Q_OBJECT - public: - enum GroupChange - { - Gc_None = 0x00000000, - // These flags respect the Model columns order - Gc_GroupName = 0x00000001, - Gc_Status = 0x00000002, - Gc_TotalSize = 0x00000004, - Gc_Percent = 0x00000008, - Gc_UploadSpeed = 0x00000010, - Gc_DownloadSpeed = 0x00000020, - // Misc - Gc_ProcessedSize = 0x00010000 - }; - - typedef int ChangesFlags; - - TransferGroup(TransferTreeModel * model, Scheduler * parent, const QString & name=QString()); - - virtual ~TransferGroup(); - - /** - * This function is reimplemented by JobQueue::setStatus - * - * @param queueStatus the new JobQueue status - */ - void setStatus(Status queueStatus); - - /** - * Appends a new transfer to the list of the transfers - * - * @param transfer the transfer to append - */ - void append(Transfer * transfer); - - /** - * Appends new transfers to the list of the transfers - * - * @param transfers to append - */ - void append(const QList &transfer); - - /** - * Prepends a new transfer to the list of the transfers - * - * @param transfer the transfer to prepend - */ - void prepend(Transfer * transfer); - - /** - * inserts a transfer to the current group after the given transfer - * - * @param transfer The transfer to add in the current Group - * @param after The transfer after which to add the transfer - */ - void insert(Transfer * transfer, Transfer * after); - - /** - * Removes the given transfer from the list of the transfers - * - * @param transfer the transfer to remove - */ - void remove(Transfer * transfer); - - /** - * Removes the given transfers from the list of the transfers - * - * @param transfers the transfers to remove - */ - void remove(const QList &transfers); - - /** - * Moves a transfer in the list - * - * @param transfer The transfer to move. Note that this transfer can - * belong to other groups. In this situation this - * transfer is deleted from the previous group and - * moved inside this one. - * @param after The transfer after which we have to move the given one - */ - void move(Transfer * transfer, Transfer * after); - - /** - * Finds the first transfer with source src - * - * @param src the url of the source location - * - * @return the transfer pointer if the transfer has been found. Otherwise - * it returns 0 - */ - Transfer * findTransfer(const KUrl &src); - - /** - * Finds the first transfer with destination dest - * - * @param dest the url of the destination location - * - * @return the transfer pointer if the transfer has been found, else return 0 - */ - Transfer *findTransferByDestination(const KUrl &dest); - - /** - * @returns the Job in the queue at the given index i - */ - Transfer * operator[] (int i) const {return (Transfer *)((* (JobQueue *)this)[i]);} - - /**Set the group name - * @param name group name - */ - void setName(const QString &name) {m_name=name;} - - /** - * @return the group name - */ - const QString & name() {return m_name;} - - /** - * @return the sum of the sizes of the transfers belonging to - * this group - */ - int totalSize() const {return m_totalSize;} - - /** - * @return the sum of the downloaded sizes of the transfers - * belonging to this group - */ - int downloadedSize() const {return m_downloadedSize;} - - /** - * @return the sum of the uploaded sizes of the transfers - * belonging to this group - */ - int uploadedSize() const {return m_uploadedSize;} - - /** - * @return the progress percentage - */ - int percent() const {return m_percent;} - - /** - * @return the sum of the download speeds of the running transfers - * belonging this group - */ - int downloadSpeed(); - - /** - * @return the sum of the download speeds of the running transfers - * belonging this group - */ - int uploadSpeed(); - - /** - * Set a default Folder for the group - * @param folder the new default folder - */ - void setDefaultFolder(QString folder) {m_defaultFolder = folder;} - - /** - * @return the groups default folder - */ - QString defaultFolder() {return m_defaultFolder;} - - /** - * Sets the regular expression of the group - * @param regexp the regular expression - */ - void setRegExp(const QRegExp ®Exp) {m_regExp = regExp;} - - /** - * @returns the regular expression of the group - */ - QRegExp regExp() {return m_regExp;} - - - /** - * @return true if the group supports SpeedLimits - */ - bool supportsSpeedLimits(); - - /** - * Set a Download-Limit for the group - * @param limit the new download-limit - * @note if limit is 0, no download-limit is set - */ - void setDownloadLimit(int dlLimit, Transfer::SpeedLimit limit); - - /** - * @return the group's Download-Limit - */ - int downloadLimit(Transfer::SpeedLimit limit) const; - - /** - * Set a Upload-Limit for the group - * @param limit the new upload-limit - * @note if limit is 0, no upload-limit is set - */ - void setUploadLimit(int ulLimit, Transfer::SpeedLimit limit); - - /** - * @return the group's Upload-Limit - */ - int uploadLimit(Transfer::SpeedLimit limit) const; - - /** - * Set the group's icon - * @param name the icon's name - */ - void setIconName(const QString &name) {m_iconName = name;} - - /** - * @returns the group's icon's name - */ - QString iconName() const {return m_iconName;} - - /** - * @return the group's icon - */ - QPixmap pixmap() {return KIcon(m_iconName).pixmap(32);} - - /** - * @return the handler associated with this group - */ - TransferGroupHandler * handler() const {return m_handler;} - - /** - * @returns the TransferTreeModel that owns this group - */ - TransferTreeModel * model() {return m_model;} - - /** - * Calculates the whole SpeedLimits - */ - void calculateSpeedLimits(); - - /** - * Calculates the DownloadLimits - */ - void calculateDownloadLimit(); - - /** - * Calculates the DownloadLimits - */ - void calculateUploadLimit(); - - /** - * Saves this group object to the given QDomNode - * - * @param n The QDomNode where the group will be saved - */ - void save(QDomElement e); - - /** - * Adds all the groups in the given QDomNode * to the group - * - * @param n The QDomNode where the group will look for the transfers to add - */ - void load(const QDomElement & e); - - private: - TransferTreeModel * m_model; - TransferGroupHandler * m_handler; - - //TransferGroup info - QString m_name; - int m_totalSize; - int m_downloadedSize; - int m_uploadedSize; - int m_percent; - int m_downloadSpeed; - int m_uploadSpeed; - int m_downloadLimit; - int m_uploadLimit; - int m_visibleDownloadLimit; - int m_visibleUploadLimit; - QString m_iconName; - QString m_defaultFolder; - QRegExp m_regExp; -}; - -#endif diff --git a/kget/core/transfergrouphandler.cpp b/kget/core/transfergrouphandler.cpp deleted file mode 100644 index f4ef0225..00000000 --- a/kget/core/transfergrouphandler.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ - -#include "core/transfergrouphandler.h" - -#include "core/kgetkjobadapter.h" -#include "core/transferhandler.h" -#include "core/transfertreemodel.h" -#include "core/transfer.h" -#include "core/kget.h" - -#include -#include -#include -#include -#include -#include - -TransferGroupHandler::TransferGroupHandler(Scheduler * scheduler, TransferGroup * parent) - : Handler(scheduler, parent), - m_group(parent), - m_changesFlags(Transfer::Tc_None) -{ -} - -TransferGroupHandler::~TransferGroupHandler() -{ -} - -void TransferGroupHandler::start() -{ - kDebug() << "TransferGroupHandler::start()"; - m_group->setStatus( JobQueue::Running ); -} - -void TransferGroupHandler::stop() -{ - kDebug() << "TransferGroupHandler::stop()"; - m_group->setStatus( JobQueue::Stopped ); -} - -void TransferGroupHandler::move(QList transfers, TransferHandler * after) -{ - //Check that the given transfer (after) belongs to this group - if( after && (after->group() != this) ) - return; - - QList::iterator it = transfers.begin(); - - for( ; it!=transfers.end() ; ++it ) - { - //Move the transfers in the JobQueue - if(after) - m_group->move( (*it)->m_transfer, after->m_transfer ); - else - m_group->move( (*it)->m_transfer, 0 ); - - after = *it; - } -} - -TransferHandler * TransferGroupHandler::operator[] (int i) -{ - // kDebug() << "TransferGroupHandler::operator[" << i << "]"; - - return (*m_group)[i]->handler(); -} - -void TransferGroupHandler::setName(const QString &name) -{ - m_group->setName(name); -} - -QVariant TransferGroupHandler::data(int column) -{ - // kDebug() << "TransferGroupHandler::data(" << column << ")"; - - switch(column) - { - case 0: - /*if (!m_group->supportsSpeedLimits() && - (m_group->downloadLimit(Transfer::VisibleSpeedLimit) != 0 || m_group->uploadLimit(Transfer::VisibleSpeedLimit) != 0)) - return name() + " - Does not supports SpeedLimits";//FIXME: Do a better text here - else*/ - return name(); - case 2: - if(m_group->size()) - return i18np("1 Item", "%1 Items", m_group->size()); - else - return QString(); -/* if (totalSize() != 0) - return KIO::convertSize(totalSize()); - else - return i18nc("not available", "n/a");*/ - case 3: -// return QString::number(percent())+'%'; // display progressbar instead - return QVariant(); - case 4: - if (downloadSpeed() == 0) - { - return QString(); - } - else - return i18n("%1/s", KIO::convertSize(downloadSpeed())); - default: - return QVariant(); - } -} - -TransferGroup::ChangesFlags TransferGroupHandler::changesFlags() -{ - return m_changesFlags; -} - -void TransferGroupHandler::resetChangesFlags() -{ - m_changesFlags = 0; -} - -int TransferGroupHandler::indexOf(TransferHandler * transfer) -{ - return m_group->indexOf(transfer->m_transfer); -} - -const QList TransferGroupHandler::transfers() -{ - QList transfers; - - TransferGroup::iterator it = m_group->begin(); - TransferGroup::iterator itEnd = m_group->end(); - - for( ; it!=itEnd ; ++it ) - { - transfers.append((static_cast(*it))->handler()); - } - return transfers; -} - -const QList & TransferGroupHandler::actions() -{ - createActions(); - - return m_actions; -} - -void TransferGroupHandler::setGroupChange(ChangesFlags change, bool notifyModel) -{ - m_changesFlags |= change; - - if (notifyModel) - m_group->model()->postDataChangedEvent(this); -} - -void TransferGroupHandler::createActions() -{ - if( !m_actions.empty() ) - return; - - QAction *startAction = KGet::actionCollection()->addAction("transfer_group_start"); - startAction->setText(i18nc("start transfergroup downloads", "Start")); - startAction->setIcon(KIcon("media-playback-start")); - QObject::connect(startAction, SIGNAL(triggered()), SLOT(start())); - m_actions.append(startAction); - - QAction *stopAction = KGet::actionCollection()->addAction("transfer_group_stop"); - stopAction->setText(i18nc("stop transfergroup downloads", "Stop")); - stopAction->setIcon(KIcon("media-playback-pause")); - QObject::connect(stopAction, SIGNAL(triggered()), SLOT(stop())); - m_actions.append(stopAction); - -} - -#include "moc_transfergrouphandler.cpp" diff --git a/kget/core/transfergrouphandler.h b/kget/core/transfergrouphandler.h deleted file mode 100644 index 57f07121..00000000 --- a/kget/core/transfergrouphandler.h +++ /dev/null @@ -1,268 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - - 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. -*/ - -#ifndef TRANSFERGROUPHANDLER_H -#define TRANSFERGROUPHANDLER_H - -#include - -#include "handler.h" -#include "transfergroup.h" -#include "../kget_export.h" -#include "kget.h" - -#include - -class QObjectInterface; -class TransferGroupObserver; -class TransferHandler; -class KGetKJobAdapter; -class Scheduler; - -class KGET_EXPORT TransferGroupHandler : public Handler -{ - Q_OBJECT - friend class GenericObserver; - friend class TransferGroup; - friend class TransferTreeModel; - friend class KGet; - public: - - typedef TransferGroup::ChangesFlags ChangesFlags; - - TransferGroupHandler(Scheduler * scheduler, TransferGroup * parent); - - ~TransferGroupHandler(); - - JobQueue::Status status() const {return m_group->status();} - - /** - * Moves a list of transfers belonging to this group to a new position, - * after the transfer named "after". All the transfers must belong to - * this group - * - * @param transfers The transfers to be be moved - * @param after The transfer after which the given transfers should be moved - */ - void move(QList transfers, TransferHandler * after); - - /** - * Sets the maximum number of jobs belonging to this queue that - * should executed simultaneously by the scheduler - * - * @param n The maximum number of jobs - */ - void setMaxSimultaneousJobs(int n); - - /** - * @returns the Job in the queue at the given index i - */ - TransferHandler * operator[] (int i); - - /** - * @returns the number of Transfers owned by this object - */ - int size() {return m_group->size();} - - /**Set the group name - * @param name group name - */ - void setName(const QString &name); - - /** - * @return the group name - */ - const QString & name() {return m_group->name();} - - /** - * @return the sum of the sizes of the transfers belonging to - * this group - */ - int totalSize() const {return m_group->totalSize();} - - /** - * @return the sum of the downloaded sizes of the transfers - * belonging to this group - */ - int downloadedSize() const {return m_group->downloadedSize();} - - /** - * @return the sum of the uploaded sizes of the transfers - * belonging to this group - */ - int uploadedSize() const {return m_group->uploadedSize();} - - /** - * @return the progress percentage - */ - int percent() const {return m_group->percent();} - - /** - * @return the sum of the download speeds of the running transfers - * belonging this group - */ - int downloadSpeed() const {return m_group->downloadSpeed();} - - /** - * @return the sum of the upload speeds of the running transfers - * belonging this group - */ - int uploadSpeed() const {return m_group->uploadSpeed();} - - /** - * @return the changes flags which are currently set on the transfer - */ - ChangesFlags changesFlags(); - - /** - * Set a default Folder for the group - * @param folder the new default folder - */ - void setDefaultFolder(QString folder) {m_group->setDefaultFolder(folder);} - - /** - * @return the groups default folder - */ - QString defaultFolder() {return m_group->defaultFolder();} - - /** - * Sets the regular expression of the group - * @param regexp the regular expression - */ - void setRegExp(const QRegExp ®exp) {m_group->setRegExp(regexp);} - - /** - * @returns the regular expression of the group - */ - QRegExp regExp() {return m_group->regExp();} - - - /** - * Set a Download-Limit for the group - * @param limit the new download-limit - * @note if limit is 0, no download-limit is set - */ - void setDownloadLimit(int dlLimit, Transfer::SpeedLimit limit) {m_group->setDownloadLimit(dlLimit, limit);} - - /** - * @return the group's Download-Limit - */ - int downloadLimit(Transfer::SpeedLimit limit) {return m_group->downloadLimit(limit);} - - /** - * Set a Upload-Limit for the group - * @param limit the new upload-limit - * @note this will not be displayed in the GUI - */ - void setUploadLimit(int ulLimit, Transfer::SpeedLimit limit) {m_group->setUploadLimit(ulLimit, limit);} - - /** - * @return the group's Upload-Limit - */ - int uploadLimit(Transfer::SpeedLimit limit) {return m_group->uploadLimit(limit);} - - /** - * Set the group's icon - * @param name the icon's name - */ - void setIconName(const QString &name) {m_group->setIconName(name);} - - /** - * @returns the group's icon's name - */ - QString iconName() const {return m_group->iconName();} - - /** - * @returns the group's icon - */ - QPixmap pixmap() {return m_group->pixmap();} - - /** - * @returns the data associated to this TransferGroup item. This is - * necessary to make the interview model/view work - */ - QVariant data(int column); - - /** - * @returns the number of columns associated to the group's data - */ - int columnCount() const {return 6;} - - /** - * @returns the index for the given transfer. If the transfer can't - * be found, it returns -1 - */ - int indexOf(TransferHandler * transfer); - - /** - * @returns a list containing all the transfers belonging to this group. - */ - const QList transfers(); - - /** - * @returns a pointer to a QObjectInterface object which is a QObject - * by means of which you can connect signals and slots for this - * transfer group. - */ - const QList & actions(); - - /** - * Calculates the whole SpeedLimits - */ - void calculateSpeedLimits() {m_group->calculateSpeedLimits();} - - /** - * Calculates the DownloadLimits - */ - void calculateDownloadLimit() {m_group->calculateDownloadLimit();} - - /** - * Calculates the DownloadLimits - */ - void calculateUploadLimit() {m_group->calculateUploadLimit();} - - public slots: - /** - * These are all JobQueue-related functions - */ - void start(); - void stop(); - - signals: - void groupChangedEvent(TransferGroupHandler * transfer, TransferGroupHandler::ChangesFlags flags); - - private: - /** - * Sets a change flag in the ChangesFlags variable. - * - * @param change The TransferChange flag to be set - * @param notifyModel notify the model about the change - */ - void setGroupChange(ChangesFlags change, bool notifyModel = false); - - /** - * Resets the changes flags - */ - void resetChangesFlags(); - - /** - * Creates all the QActions - */ - void createActions(); - - TransferGroup * m_group; - - QList m_actions; - - ChangesFlags m_changesFlags; -}; - -#endif diff --git a/kget/core/transfergroupscheduler.cpp b/kget/core/transfergroupscheduler.cpp deleted file mode 100644 index d8c51b7f..00000000 --- a/kget/core/transfergroupscheduler.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ -#include "transfergroupscheduler.h" - -#include "kget.h" -#include "transfergrouphandler.h" -#include "settings.h" - -TransferGroupScheduler::TransferGroupScheduler(QObject *parent) - : Scheduler(parent), - m_downloadLimit(0), - m_uploadLimit(0) -{ -} - -TransferGroupScheduler::~TransferGroupScheduler() -{ -} - -void TransferGroupScheduler::calculateSpeedLimits() -{ - calculateDownloadLimit(); - calculateUploadLimit(); -} - -void TransferGroupScheduler::calculateDownloadLimit() -{ - int n = KGet::allTransferGroups().count(); - int pool = 0;//We create a pool where we have some KiB/s to go to other groups... - QList transfergroupsNeedSpeed; - foreach (TransferGroupHandler *handler, KGet::allTransferGroups()) - { - if (!Settings::speedLimit()) - handler->setDownloadLimit(handler->downloadLimit(Transfer::VisibleSpeedLimit), Transfer::InvisibleSpeedLimit); - else if (handler->transfers().count() < 1) - { - pool = pool + downloadLimit() / n; - } - else if (downloadLimit() == 0 && handler->downloadLimit(Transfer::VisibleSpeedLimit) != 0) - continue; - else if (downloadLimit() == 0 && handler->downloadLimit(Transfer::VisibleSpeedLimit) == 0) - handler->setDownloadLimit(0, Transfer::InvisibleSpeedLimit); - else if (handler->downloadLimit(Transfer::VisibleSpeedLimit) < downloadLimit() / n - && handler->downloadLimit(Transfer::VisibleSpeedLimit) != 0) - /*If the handler's visible download limit is under the new one, - we move the KiB/s which are different to the pool*/ - pool = pool + (downloadLimit() / n - handler->downloadLimit(Transfer::VisibleSpeedLimit)); - else if (handler->downloadSpeed() + 10 < downloadLimit() / n) - { - /*When the downloadSpeed of the handler is under the new downloadLimit + 10 then we - set the downloadLimit to the downloadSpeed + 10*/ - pool = pool + downloadLimit() / n - handler->downloadSpeed() + 10; - handler->setDownloadLimit(handler->downloadSpeed() + 10, Transfer::InvisibleSpeedLimit); - } - else - { - handler->setDownloadLimit(downloadLimit() / n, Transfer::InvisibleSpeedLimit); - transfergroupsNeedSpeed.append(handler); - } - } - foreach (TransferGroupHandler *handler, transfergroupsNeedSpeed) - { - handler->setDownloadLimit(downloadLimit() / n + pool / transfergroupsNeedSpeed.count(), Transfer::InvisibleSpeedLimit); - } -} - -void TransferGroupScheduler::calculateUploadLimit() -{ - int n = KGet::allTransferGroups().count(); - kDebug() << n; - int pool = 0;//We create a pool where we have some KiB/s to go to other groups... - QList transfergroupsNeedSpeed; - foreach (TransferGroupHandler *handler, KGet::allTransferGroups()) - { - if (!Settings::speedLimit()) - handler->setUploadLimit(handler->uploadLimit(Transfer::VisibleSpeedLimit), Transfer::InvisibleSpeedLimit); - else if (handler->transfers().count() < 1) - pool = pool + uploadLimit() / n; - else if (uploadLimit() == 0 && handler->uploadLimit(Transfer::VisibleSpeedLimit) != 0) - continue; - else if (uploadLimit() == 0 && handler->uploadLimit(Transfer::VisibleSpeedLimit) == 0) - handler->setUploadLimit(0, Transfer::InvisibleSpeedLimit); - else if (handler->uploadLimit(Transfer::VisibleSpeedLimit) < uploadLimit() / n && handler->uploadLimit(Transfer::VisibleSpeedLimit) != 0) - /*If the handler's visible download limit is under the new one, - we move the KiB/s which are different to the pool*/ - pool = pool + (uploadLimit() / n - handler->uploadLimit(Transfer::VisibleSpeedLimit)); - else if (handler->uploadSpeed() + 10 < uploadLimit() / n) - { - /*When the downloadSpeed of the handler is under the new downloadLimit + 10 then we - set the downloadLimit to the downloadSpeed + 10*/ - pool = pool + uploadLimit() / n - handler->uploadSpeed() + 10; - handler->setUploadLimit(handler->uploadSpeed() + 10, Transfer::InvisibleSpeedLimit); - } - else - { - handler->setUploadLimit(uploadLimit() / n, Transfer::InvisibleSpeedLimit); - transfergroupsNeedSpeed.append(handler); - } - } - foreach (TransferGroupHandler *handler, transfergroupsNeedSpeed) - { - handler->setUploadLimit(uploadLimit() / n + pool / transfergroupsNeedSpeed.count(), Transfer::InvisibleSpeedLimit); - } -} - -void TransferGroupScheduler::setDownloadLimit(int limit) -{ - m_downloadLimit = limit; - calculateDownloadLimit(); -} - -void TransferGroupScheduler::setUploadLimit(int limit) -{ - m_uploadLimit = limit; - calculateUploadLimit(); -} - -#include "moc_transfergroupscheduler.cpp" diff --git a/kget/core/transfergroupscheduler.h b/kget/core/transfergroupscheduler.h deleted file mode 100644 index 07568ef8..00000000 --- a/kget/core/transfergroupscheduler.h +++ /dev/null @@ -1,73 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ - -#ifndef TRANSFERGROUPSCHEDULER_H -#define TRANSFERGROUPSCHEDULER_H - -#include "core/scheduler.h" - -/** - * @brief TransferGroupScheduler class: what handle all the transfers in kget. - * - * This class handles all transfers of KGet, it is a modified Scheduler - * - */ - -class TransferGroupScheduler : public Scheduler -{ - Q_OBJECT - public: - explicit TransferGroupScheduler(QObject *parent = 0); - ~TransferGroupScheduler(); - - /** - * Calculates the whole SpeedLimits - */ - void calculateSpeedLimits(); - - /** - * Calculates the DownloadLimits - */ - void calculateDownloadLimit(); - - /** - * Calculates the DownloadLimits - */ - void calculateUploadLimit(); - - /** - * Sets a download limit to the scheduler - * @param limit the download limit - */ - void setDownloadLimit(int limit); - - /** - * @return the transfergroupschedulers download limit - */ - int downloadLimit() const {return m_downloadLimit;} - - /** - * Sets a upload limit to the scheduler - * @param limit the upload limit - */ - void setUploadLimit(int limit); - - /** - * @return the transfergroupschedulers upload limit - */ - int uploadLimit() const {return m_uploadLimit;} - - private: - int m_downloadLimit; - int m_uploadLimit; -}; - -#endif - diff --git a/kget/core/transferhandler.cpp b/kget/core/transferhandler.cpp deleted file mode 100644 index 3b4315c9..00000000 --- a/kget/core/transferhandler.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - - 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. -*/ - -#include "core/transferhandler.h" - -#include "core/job.h" -#include "core/jobqueue.h" -#include "core/transfergroup.h" -#include "core/transfergrouphandler.h" -#include "core/transfertreemodel.h" -#include "core/plugin/transferfactory.h" -#include "settings.h" -#include "mainwindow.h" -#include "kgetkjobadapter.h" - -#include -#include -#include -#include - -TransferHandler::TransferHandler(Transfer * parent, Scheduler * scheduler) - : Handler(scheduler, parent), - m_transfer(parent), - m_changesFlags(Transfer::Tc_None) -{ - static int dBusObjIdx = 0; - m_dBusObjectPath = "/KGet/Transfers/" + QString::number(dBusObjIdx++); - - m_kjobAdapter = new KGetKJobAdapter(this, this); - - connect(m_transfer, SIGNAL(capabilitiesChanged()), this, SIGNAL(capabilitiesChanged())); -} - -TransferHandler::~TransferHandler() -{ -} - -Transfer::Capabilities TransferHandler::capabilities() const -{ - return m_transfer->capabilities(); -} - -void TransferHandler::start() -{ - if(m_transfer->group()->status() == JobQueue::Running) - { - m_transfer->setPolicy(Job::None); - KGet::model()->moveTransfer(m_transfer, m_transfer->group()); - } - else - { - m_transfer->setPolicy(Job::Start); - } -} - -void TransferHandler::stop() -{ - if (m_transfer->group()->status() == JobQueue::Stopped) - { - m_transfer->setPolicy(Job::None); - } - else - { - m_transfer->setPolicy(Job::Stop); - } -} - -int TransferHandler::elapsedTime() const -{ - return m_transfer->elapsedTime(); -} - -int TransferHandler::remainingTime() const -{ - return m_transfer->remainingTime(); -} - -KIO::filesize_t TransferHandler::totalSize() const -{ - return m_transfer->totalSize(); -} - -KIO::filesize_t TransferHandler::downloadedSize() const -{ - return m_transfer->downloadedSize(); -} - -KIO::filesize_t TransferHandler::uploadedSize() const -{ - return m_transfer->uploadedSize(); -} - -int TransferHandler::percent() const -{ - return m_transfer->percent(); -} - -int TransferHandler::downloadSpeed() const -{ - return m_transfer->downloadSpeed(); -} - -int TransferHandler::averageDownloadSped() const -{ - return m_transfer->averageDownloadSpeed(); -} - -int TransferHandler::uploadSpeed() const -{ - return m_transfer->uploadSpeed(); -} - -QVariant TransferHandler::data(int column) -{ - // kDebug() << "TransferHandler::data(" << column << ")"; - - switch(column) - { - case 0: - return dest().fileName(); - case 1: - if (status() == Job::Aborted && !error().text.isEmpty()) - return error().text; - return statusText(); - case 2: - if (totalSize() != 0) - return KIO::convertSize(totalSize()); - else - return i18nc("not available", "n/a"); - case 3: - // return QString::number(percent())+'%'; // display progressbar instead - return QVariant(); - case 4: - if (downloadSpeed() == 0) - { - if (m_transfer->isStalled()) - return i18n("Stalled"); - else - return QString(); - } - else - return i18n("%1/s", KIO::convertSize(downloadSpeed())); - case 5: - if (status() == Job::Running && downloadSpeed() != 0) - return KIO::convertSeconds(remainingTime()); - else - return QString(); - default: - return QVariant(); - } -} - -void TransferHandler::setSelected( bool select ) -{ - if( (select && !isSelected()) || (!select && isSelected()) ) - { - m_transfer->m_isSelected = select; - setTransferChange( Transfer::Tc_Selection, true ); - } -} - -bool TransferHandler::isSelected() const -{ - return m_transfer->m_isSelected; -} - -Transfer::ChangesFlags TransferHandler::changesFlags() const -{ - return m_changesFlags; -} - -void TransferHandler::resetChangesFlags() -{ - m_changesFlags = 0; -} - -void TransferHandler::destroy() -{ - kDebug() << "TransferHandler::destroy()"; -} - -void TransferHandler::setTransferChange(ChangesFlags change, bool notifyModel) -{ - m_changesFlags |= change; - - if (notifyModel) - { - // Notify the TransferTreeModel - m_transfer->model()->postDataChangedEvent(this); - - m_kjobAdapter->slotUpdateDescription(); - } -} - -QList TransferHandler::contextActions() -{ - QList actions; - if (status() != Job::Finished) - { - actions << KGet::actionCollection()->action("start_selected_download") - << KGet::actionCollection()->action("stop_selected_download"); - } - actions << KGet::actionCollection()->action("delete_selected_download") - << KGet::actionCollection()->action("redownload_selected_download") - << KGet::actionCollection()->action("select_all"); - - return actions; -} - -QList TransferHandler::factoryActions() -{ - QList actions; - foreach(QAction *action, m_transfer->factory()->actions(this)) - actions.append(action); - return actions; -} diff --git a/kget/core/transferhandler.h b/kget/core/transferhandler.h deleted file mode 100644 index c3b4b9a7..00000000 --- a/kget/core/transferhandler.h +++ /dev/null @@ -1,322 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - - 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. -*/ - - -#ifndef TRANSFERHANDLER_H -#define TRANSFERHANDLER_H - -#include -#include - -#include "handler.h" -#include "transfer.h" -#include "transfergroup.h" -#include "../kget_export.h" - - -class KGetKJobAdapter; - -/** - * Class TransferHandler: - * - * --- Overview --- - * This class is the representation of a Transfer object from the views' - * perspective (proxy pattern). In fact the views never handle directly the - * Transfer objects themselves (because this would break the model/view policy). - * As a general rule, all the code strictly related to the views should placed - * here (and not in the transfer implementation). - * Here we provide the same api available in the transfer class, but we change - * the implementation of some methods. - * Let's give an example about this: - * The start() function of a specific Transfer (let's say TransferKio) is a - * low level command that really makes the transfer start and should therefore - * be executed only by the scheduler. - * The start() function in this class is implemented in another way, since - * it requests the scheduler to execute the start command to this specific transfer. - * At this point the scheduler will evaluate this request and execute, if possible, - * the start() function directly in the TransferKio. - */ - -class KGET_EXPORT TransferHandler : public Handler -{ - Q_OBJECT - friend class KGet; - friend class TransferTreeModel; - friend class Transfer; - friend class TransferFactory; - friend class TransferGroupHandler; - public: - - typedef Transfer::ChangesFlags ChangesFlags; - - TransferHandler(Transfer * parent, Scheduler * scheduler); - - virtual ~TransferHandler(); - - Job::Status status() const {return m_transfer->status();} - Job::Error error() const {return m_transfer->error();} - Job::Status startStatus() const {return m_transfer->startStatus();} - int elapsedTime() const; - int remainingTime() const; - - void resolveError(int errorId) {m_transfer->resolveError(errorId);} - - /** - * Returns the capabilities the Transfer supports - */ - Transfer::Capabilities capabilities() const; - - /** - * Tries to repair file - * @param file the file of a download that should be repaired, - * if not defined all files of a download are going to be repaird - * @return true if a repair started, false if it was not nescessary - */ - bool repair(const KUrl &file = KUrl()) {return m_transfer->repair(file);} - - /** - * @return the transfer's group handler - */ - TransferGroupHandler * group() const {return m_transfer->group()->handler();} - - /** - * @return the source url - */ - const KUrl & source() const {return m_transfer->source();} - - /** - * @return the dest url - */ - const KUrl & dest() const {return m_transfer->dest();} - - /** - * @returns all files of this transfer - */ - QList files() const {return m_transfer->files();} - - /** - * @returns the directory the Transfer will be stored to - */ - KUrl directory() const {return m_transfer->directory();} - - /** - * Move the download to the new destination - * @param newDirectory is a directory where the download should be stored - * @returns true if newDestination can be used - */ - bool setDirectory(const KUrl &newDirectory) {return m_transfer->setDirectory(newDirectory);} - - /** - * The mirrors that are available - * bool if it is used, int how many paralell connections are allowed - * to the mirror - * @param file the file for which the availableMirrors should be get - */ - QHash > availableMirrors(const KUrl &file) const {return m_transfer->availableMirrors(file);} - - /** - * Set the mirrors, int the number of paralell connections to the mirror - * bool if the mirror should be used - * @param file the file for which the availableMirrors should be set - */ - void setAvailableMirrors(const KUrl &file, const QHash > &mirrors) {m_transfer->setAvailableMirrors(file, mirrors);} - - /** - * @return the total size of the transfer in bytes - */ - KIO::filesize_t totalSize() const; - - /** - * @return the downloaded size of the transfer in bytes - */ - KIO::filesize_t downloadedSize() const; - - /** - * @return the uploaded size of the transfer in bytes - */ - KIO::filesize_t uploadedSize() const; - - /** - * @return the progress percentage of the transfer - */ - int percent() const; - - /** - * @return the download speed of the transfer in bytes/sec - */ - int downloadSpeed() const; - - /** - * @return the average download speed of the transfer in bytes/sec - */ - int averageDownloadSped() const; - - /** - * @return the upload speed of the transfer in bytes/sec - */ - int uploadSpeed() const; - - /** - * Set an UploadLimit for the transfer - * @note this UploadLimit is not visible in the GUI - * @param ulLimit upload Limit - */ - void setUploadLimit(int ulLimit, Transfer::SpeedLimit limit) {m_transfer->setUploadLimit(ulLimit, limit);} - - /** - * Set a DownloadLimit for the transfer - * @note this DownloadLimit is not visible in the GUI - * @param dlLimit download Limit - */ - void setDownloadLimit(int dlLimit, Transfer::SpeedLimit limit) {m_transfer->setDownloadLimit(dlLimit, limit);} - - /** - * @return the upload Limit of the transfer in KiB - */ - int uploadLimit(Transfer::SpeedLimit limit) const {return m_transfer->uploadLimit(limit);} - - /** - * @return the download Limit of the transfer in KiB - */ - int downloadLimit(Transfer::SpeedLimit limit) const {return m_transfer->downloadLimit(limit);} - - /** - * Set the maximum share-ratio - * @param ratio the new maximum share-ratio - */ - void setMaximumShareRatio(double ratio) {m_transfer->setMaximumShareRatio(ratio);} - - /** - * @return the maximum share-ratio - */ - double maximumShareRatio() {return m_transfer->maximumShareRatio();} - - /** - * Recalculate the share ratio - */ - void checkShareRatio() {m_transfer->checkShareRatio();} - - /** - * @return a string describing the current transfer status - */ - QString statusText() const {return m_transfer->statusText();} - - /** - * @return a pixmap associated with the current transfer status - */ - QPixmap statusPixmap() const {return m_transfer->statusPixmap();} - - /** - * @returns the data associated to this Transfer item. This is - * necessary to make the interview model/view work - */ - QVariant data(int column); - - /** - * @returns the number of columns associated to the transfer's data - */ - int columnCount() const {return 6;} - - /** - * Selects the current transfer. Selecting transfers means that all - * the actions executed from the gui will apply also to the current - * transfer. - * - * @param select if true the current transfer is selected - * if false the current transfer is deselected - */ - void setSelected( bool select ); - - /** - * @returns true if the current transfer is selected - * @returns false otherwise - */ - bool isSelected() const; - - /** - * Returns the changes flags - */ - ChangesFlags changesFlags() const; - - /** - * @returns a list of a actions, which are associated with this TransferHandler - */ - QList contextActions(); - - /** - * @returns a list of the transfer's factory's actions - */ - QList factoryActions(); - - /** - * @returns the object path that will be shown in the DBUS interface - */ - QString dBusObjectPath() {return m_dBusObjectPath;} - - /** - * @returns the kJobAdapter object - */ - KGetKJobAdapter * kJobAdapter() {return m_kjobAdapter;} - - /** - * @returns a pointer to the FileModel containing all files of this download - */ - virtual FileModel * fileModel() {return m_transfer->fileModel();} - - /** - * @param file for which to get the verifier - * @return Verifier that allows you to add checksums manually verify a file etc. - */ - virtual Verifier * verifier(const KUrl &file) {return m_transfer->verifier(file);} - - public slots: - /** - * These are all Job-related functions - */ - virtual void start(); - virtual void stop(); - - signals: - /** - * Emitted when the capabilities of the Transfer change - */ - void capabilitiesChanged(); - void transferChangedEvent(TransferHandler * transfer, TransferHandler::ChangesFlags flags); - - private: - /** - * This functions gets called just before the handler is deleted - */ - void destroy(); - - /** - * Sets a change flag in the ChangesFlags variable. - * - * @param change The TransferChange flag to be set - * @param notifyModel if false the handler will not post an event to the model, - * if true the handler will post an event to the model - */ - void setTransferChange(ChangesFlags change, bool notifyModel = false); - - /** - * Resets the changes flags - */ - void resetChangesFlags(); - - Transfer * m_transfer; - - KGetKJobAdapter * m_kjobAdapter; - - QString m_dBusObjectPath; - - ChangesFlags m_changesFlags; -}; - -#endif diff --git a/kget/core/transferhistorystore.cpp b/kget/core/transferhistorystore.cpp deleted file mode 100644 index d1758358..00000000 --- a/kget/core/transferhistorystore.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - Copyright (C) 2008 by Javier Goday - - 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. -*/ -#include "core/transferhistorystore.h" -#include "core/transferhistorystore_xml_p.h" -#include "core/transferhistorystore_json_p.h" -#include "core/transfer.h" -#include "settings.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -TransferHistoryItem::TransferHistoryItem() : QObject() -{} - -TransferHistoryItem::TransferHistoryItem(const Transfer &transfer) : QObject() -{ - setDest(transfer.dest().pathOrUrl()); - setSource(transfer.source().url()); - setSize(transfer.totalSize()); - setDateTime(QDateTime::currentDateTime()); - - setState(transfer.status()); -} - -TransferHistoryItem::TransferHistoryItem(const TransferHistoryItem &item) : QObject() -{ - setDest(item.dest()); - setSource(item.source()); - setState(item.state()); - setSize(item.size()); - setDateTime(item.dateTime()); -} - -void TransferHistoryItem::setDest(const QString &dest) -{ - m_dest = dest; -} - -void TransferHistoryItem::setSource(const QString &source) -{ - m_source = source; -} - -void TransferHistoryItem::setState(int state) -{ - m_state = state; -} - -void TransferHistoryItem::setSize(int size) -{ - m_size = size; -} - -void TransferHistoryItem::setDateTime(const QDateTime &dateTime) -{ - m_dateTime = dateTime; -} - -QString TransferHistoryItem::dest() const -{ - return m_dest; -} - -QString TransferHistoryItem::source() const -{ - return m_source; -} - -int TransferHistoryItem::state() const -{ - return m_state; -} - -int TransferHistoryItem::size() const -{ - return m_size; -} - -QDateTime TransferHistoryItem::dateTime() const -{ - return m_dateTime; -} - -TransferHistoryItem& TransferHistoryItem::operator=(const TransferHistoryItem &item) -{ - setDest(item.dest()); - setSource(item.source()); - setState(item.state()); - setSize(item.size()); - setDateTime(item.dateTime()); - - return *this; -} - -bool TransferHistoryItem::operator==(const TransferHistoryItem& item) const -{ - return dest() == item.dest() && source() == item.source(); -} - -TransferHistoryStore::TransferHistoryStore() : QObject(), - m_items() -{ -} - -TransferHistoryStore::~TransferHistoryStore() -{ -} - -QList TransferHistoryStore::items() const -{ - return m_items; -} - -TransferHistoryStore *TransferHistoryStore::getStore() -{ - switch(Settings::historyBackend()) - { - case TransferHistoryStore::Xml: - return new XmlStore(KStandardDirs::locateLocal("appdata", "transferhistory.kgt")); - case TransferHistoryStore::Json: - default: - return new JsonStore(KStandardDirs::locateLocal("appdata", "transferhistory.json")); - } -} - -#include "moc_transferhistorystore.cpp" diff --git a/kget/core/transferhistorystore.h b/kget/core/transferhistorystore.h deleted file mode 100644 index 0e4320dd..00000000 --- a/kget/core/transferhistorystore.h +++ /dev/null @@ -1,102 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - Copyright (C) 2008 by Javier Goday - - 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. -*/ -#ifndef TRANSFERHISTORYSTORE_H -#define TRANSFERHISTORYSTORE_H - -#include "kget_export.h" - -#include -#include -#include -#include - -class Transfer; - -class KGET_EXPORT TransferHistoryItem : public QObject -{ -public: - TransferHistoryItem(); - TransferHistoryItem(const Transfer &transfer); - TransferHistoryItem(const TransferHistoryItem &); - - void setDest(const QString &dest); - void setSource(const QString &source); - void setState(int state); - void setSize(int size); - void setDateTime(const QDateTime &time); - - QString dest() const; - QString source() const; - int state() const; - int size() const; - QDateTime dateTime() const; - - TransferHistoryItem& operator=(const TransferHistoryItem&); - bool operator==(const TransferHistoryItem&) const; - -private: - QString m_dest; - QString m_source; - int m_state; - int m_size; - QDateTime m_dateTime; -}; - -class KGET_EXPORT TransferHistoryStore : public QObject -{ - Q_OBJECT -public: - enum Backend { - Json = 0, - Xml = 1 - }; - - TransferHistoryStore(); - ~TransferHistoryStore(); - - QList items() const; - - static TransferHistoryStore *getStore(); - -public slots: - virtual void load() {}; - virtual void clear() {}; - virtual void saveItem(const TransferHistoryItem &item) - { - Q_UNUSED(item) - }; - - virtual void saveItems(const QList &items) - { - foreach(const TransferHistoryItem &item, items) { - saveItem(item); - } - }; - virtual void deleteItem(const TransferHistoryItem &item) - { - Q_UNUSED(item) - }; - -signals: - void elementLoaded(int number, int total, const TransferHistoryItem &item); - void loadFinished(); - void saveFinished(); - void deleteFinished(); - -protected: - QList m_items; -}; - - - -Q_DECLARE_METATYPE(TransferHistoryItem) - -#endif diff --git a/kget/core/transferhistorystore_json.cpp b/kget/core/transferhistorystore_json.cpp deleted file mode 100644 index e5e2ee99..00000000 --- a/kget/core/transferhistorystore_json.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "core/transferhistorystore.h" -#include "core/transferhistorystore_json_p.h" - -#include -#include -#include - -JsonStore::JsonStore(const QString &database) - : TransferHistoryStore(), - m_dbName(database) -{ -} - -JsonStore::~JsonStore() -{ -} - -void JsonStore::load() -{ - m_items.clear(); - QFile dbFile(m_dbName); - if (dbFile.open(QFile::ReadOnly)) { - m_dbDoc = QJsonDocument::fromJson(dbFile.readAll()); - if (m_dbDoc.isNull()) { - kWarning() << m_dbDoc.errorString(); - } else { - const QVariantMap dbMap = m_dbDoc.toVariant().toMap(); - const QStringList dbKeys = dbMap.keys(); - - int counter = 1; - foreach (const QString &key, dbKeys) { - const QVariantMap keyMap = dbMap.value(key).toMap(); - - TransferHistoryItem item; - item.setSource(key); - item.setDest(keyMap.value("dest").toString()); - item.setState(keyMap.value("state").toInt()); - item.setDateTime(QDateTime::fromTime_t(keyMap.value("time").toUInt())); - item.setSize(keyMap.value("size").toInt()); - - m_items << item; - emit elementLoaded(counter, dbKeys.size(), item); - counter++; - } - } - - dbFile.close(); - } else { - // may not exist yet - kDebug() << "could not open" << m_dbName; - } - - emit loadFinished(); -} - -void JsonStore::clear() -{ - QFile::remove(m_dbName); -} - -void JsonStore::saveItem(const TransferHistoryItem &item) -{ - saveItems(QList() << item); -} - -void JsonStore::saveItems(const QList &items) -{ - QFile dbFile(m_dbName); - if (dbFile.open(QFile::WriteOnly)) { - QVariantMap dbMap = m_dbDoc.toVariant().toMap(); - - foreach (const TransferHistoryItem &item, items) { - QVariantMap itemMap; - itemMap.insert("dest", item.dest()); - itemMap.insert("state", item.state()); - itemMap.insert("time", item.dateTime().toTime_t()); - itemMap.insert("size", item.size()); - - dbMap.insert(item.source(), itemMap); - m_dbDoc = QJsonDocument::fromVariant(dbMap); - - m_items << item; - } - - const QByteArray dbData = m_dbDoc.toJson(); - if (dbFile.write(dbData.constData(), dbData.size()) != dbData.size()) { - kWarning() << "could not write data to" << m_dbName;; - } - - dbFile.close(); - } else { - kWarning() << "could not open" << m_dbName; - } - - emit saveFinished(); -} - -void JsonStore::deleteItem(const TransferHistoryItem &item) -{ - QFile dbFile(m_dbName); - if (dbFile.open(QFile::WriteOnly)) { - QVariantMap dbMap = m_dbDoc.toVariant().toMap(); - - dbMap.remove(item.source()); - m_dbDoc = QJsonDocument::fromVariant(dbMap); - - m_items.removeAll(item); - - const QByteArray dbData = m_dbDoc.toJson(); - if (dbFile.write(dbData.constData(), dbData.size()) != dbData.size()) { - kWarning() << "could not write data to" << m_dbName;; - } - - dbFile.close(); - } else { - kWarning() << "could not open" << m_dbName; - } - - emit deleteFinished(); -} - -#include "moc_transferhistorystore_json_p.cpp" diff --git a/kget/core/transferhistorystore_json_p.h b/kget/core/transferhistorystore_json_p.h deleted file mode 100644 index e71e0887..00000000 --- a/kget/core/transferhistorystore_json_p.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef TRANSFERHISTORYSTORE_JSON_P_H -#define TRANSFERHISTORYSTORE_JSON_P_H - -#include "transferhistorystore.h" - -#include -#include - -class TransferHistoryItem; -class JsonStore : public TransferHistoryStore -{ - Q_OBJECT -public: - JsonStore(const QString &database); - ~JsonStore(); - -public slots: - void load(); - void clear(); - void saveItem(const TransferHistoryItem &item); - void saveItems(const QList &items); - void deleteItem(const TransferHistoryItem &item); - -private: - QString m_dbName; - QJsonDocument m_dbDoc; -}; - -#endif diff --git a/kget/core/transferhistorystore_xml.cpp b/kget/core/transferhistorystore_xml.cpp deleted file mode 100644 index 5691da68..00000000 --- a/kget/core/transferhistorystore_xml.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - Copyright (C) 2008 by Javier Goday - - 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. -*/ - -#include "core/transferhistorystore.h" -#include "core/transferhistorystore_xml_p.h" - -#include -#include -#include -#include -#include -#include -#include - -XmlStore::SaveThread::SaveThread(QObject *parent, const QString &url, const QList &list) : QThread(parent), - m_url(url), - m_items(list), - m_item() -{ -} - -XmlStore::SaveThread::SaveThread(QObject *parent, const QString &url, const TransferHistoryItem &item) : QThread(parent), - m_url(url), - m_items(), - m_item(item) -{ -} - -void XmlStore::SaveThread::run() -{ - QFile file(m_url); - QDomDocument *doc; - QDomElement root; - - if (!file.exists()) - { - doc = new QDomDocument("Transfers"); - root = doc->createElement("Transfers"); - doc->appendChild(root); - } - else - { - doc = new QDomDocument(); - doc->setContent(&file); - file.close(); - root = doc->documentElement(); - doc->appendChild(root); - } - - QDomElement e = doc->createElement("Transfer"); - root.appendChild(e); - - e.setAttribute("Source", m_item.source()); - e.setAttribute("Dest", m_item.dest()); - e.setAttribute("Time", QDateTime::currentDateTime().toTime_t()); - e.setAttribute("Size", QString::number(m_item.size())); - e.setAttribute("State", QString::number(m_item.state())); - - if (file.open(QFile::WriteOnly | QFile::Truncate)) { - QTextStream stream( &file ); - doc->save( stream, 0 ); - file.close(); - } - delete doc; -} - -XmlStore::DeleteThread::DeleteThread(QObject *parent, const QString &url, const TransferHistoryItem &item) : QThread(parent), - m_url(url), - m_item(item), - m_items() -{ -} - -void XmlStore::DeleteThread::run() -{ - QDomDocument doc("tempHistory"); - QFile file(m_url); - - QString error; - int line; - int column; - - if (!doc.setContent(&file, &error, &line, &column)) - { - kDebug() << "Error1" << error << line << column; - return; - } - file.close(); - - QDomElement root = doc.documentElement(); - - QDomNodeList list = root.elementsByTagName("Transfer"); - - int nItems = list.length(); - - for (int i = 0 ; i < nItems ; i++) { - QDomElement element = list.item(i).toElement(); - - if(QString::compare(element.attribute("Source"), m_item.source()) == 0) { - root.removeChild(element); - } else { - TransferHistoryItem item; - item.setDest(element.attribute("Dest")); - item.setSource(element.attribute("Source")); - item.setSize(element.attribute("Size").toInt()); - item.setDateTime(QDateTime::fromTime_t(element.attribute("Time").toUInt())); - item.setState(element.attribute("State").toInt()); - m_items << item; - } - } - - if (file.open(QFile::WriteOnly | QFile::Truncate)) { - QTextStream stream( &file ); - doc.save(stream, 0); - file.close(); - doc.clear(); - } -} - -XmlStore::LoadThread::LoadThread(QObject *parent, const QString &url) : QThread(parent), - m_url(url) -{ -} - -void XmlStore::LoadThread::run() -{ - qRegisterMetaType("TransferHistoryItem"); - QDomDocument doc("tempHistory"); - QFile file(m_url); - - QString error; - int line; - int column; - int total; - - if (!doc.setContent(&file, &error, &line, &column)) - { - kDebug() << "Error1" << error << line << column; - file.close(); - return; - } - - QDomElement root = doc.documentElement(); - total = root.childNodes().size(); - - QDomNodeList list = root.elementsByTagName("Transfer"); - - int nItems = list.length(); - - for (int i = 0 ; i < nItems ; i++) - { - QDomElement dom = list.item(i).toElement(); - - TransferHistoryItem item; - item.setDest(dom.attribute("Dest")); - item.setSource(dom.attribute("Source")); - item.setSize(dom.attribute("Size").toInt()); - item.setDateTime(QDateTime::fromTime_t(dom.attribute("Time").toUInt())); - item.setState(dom.attribute("State").toInt()); - - emit elementLoaded(i, total, item); - } - doc.clear(); - file.close(); -} - -XmlStore::XmlStore(const QString &url) : TransferHistoryStore(), - m_storeUrl(url), - m_loadThread(0), - m_saveThread(0), - m_deleteThread(0) -{ -} - -XmlStore::~XmlStore() -{ - if(m_loadThread && m_loadThread->isRunning()) { - m_loadThread->terminate(); - } - - if(m_saveThread && m_saveThread->isRunning()) { - m_saveThread->terminate(); - } - - if(m_deleteThread && m_deleteThread->isRunning()) { - m_deleteThread->terminate(); - } - - delete m_loadThread; - delete m_saveThread; - delete m_deleteThread; -} - -void XmlStore::load() -{ - m_items.clear(); - // TODO: only load if necessary - m_loadThread = new XmlStore::LoadThread(this, m_storeUrl); - - connect(m_loadThread, SIGNAL(finished()), SIGNAL(loadFinished())); - connect(m_loadThread, SIGNAL(elementLoaded(int,int,TransferHistoryItem)), - SIGNAL(elementLoaded(int,int,TransferHistoryItem))); - connect(m_loadThread, SIGNAL(elementLoaded(int,int,TransferHistoryItem)), - SLOT(slotLoadElement(int,int,TransferHistoryItem))); - m_loadThread->start(); -} - -void XmlStore::clear() -{ - QFile::remove(m_storeUrl); -} - -void XmlStore::saveItem(const TransferHistoryItem &item) -{ - m_saveThread = new XmlStore::SaveThread(this, m_storeUrl, item); - - connect(m_saveThread, SIGNAL(finished()), SIGNAL(saveFinished())); - connect(m_saveThread, SIGNAL(elementLoaded(int,int,TransferHistoryItem)), - SIGNAL(elementLoaded(int,int,TransferHistoryItem))); - m_saveThread->start(); -} - -void XmlStore::deleteItem(const TransferHistoryItem &item) -{ - Q_UNUSED(item) - - m_deleteThread = new XmlStore::DeleteThread(this, m_storeUrl, item); - - connect(m_deleteThread, SIGNAL(finished()), SLOT(slotDeleteElement())); - - m_deleteThread->start(); -} - -void XmlStore::slotLoadElement(int number, int total, const TransferHistoryItem &item) -{ - Q_UNUSED(number) - Q_UNUSED(total) - m_items.append(item); -} - -void XmlStore::slotDeleteElement() -{ - m_items.clear(); - m_items << m_deleteThread->items(); - - emit loadFinished(); -} - -#include "moc_transferhistorystore_xml_p.cpp" diff --git a/kget/core/transferhistorystore_xml_p.h b/kget/core/transferhistorystore_xml_p.h deleted file mode 100644 index eaf8f855..00000000 --- a/kget/core/transferhistorystore_xml_p.h +++ /dev/null @@ -1,102 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - Copyright (C) 2008 by Javier Goday - - 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. -*/ -#ifndef TRANSFERHISTORYSTORE_XML_P_H -#define TRANSFERHISTORYSTORE_XML_P_H - -#include "transferhistorystore.h" - -#include -#include - -class TransferHistoryItem; -class XmlStore : public TransferHistoryStore -{ - Q_OBJECT -public: - XmlStore(const QString &url); - ~XmlStore(); - -public slots: - void load(); - void clear(); - void saveItem(const TransferHistoryItem &item); - void deleteItem(const TransferHistoryItem &item); - - void slotLoadElement(int number, int total, const TransferHistoryItem &item); - -private slots: - void slotDeleteElement(); - -private: - QString m_storeUrl; - - class LoadThread; - LoadThread *m_loadThread; - - class SaveThread; - SaveThread *m_saveThread; - - class DeleteThread; - DeleteThread *m_deleteThread; -}; - - -class XmlStore::LoadThread : public QThread -{ - Q_OBJECT -public: - LoadThread(QObject *parent, const QString &url); - - void run(); - -signals: - void elementLoaded(int number, int total, const TransferHistoryItem &item); - -private: - QString m_url; -}; - -class XmlStore::SaveThread : public QThread -{ - Q_OBJECT -public: - SaveThread(QObject *parent, const QString &url, const QList &list); - SaveThread(QObject *parent, const QString &url, const TransferHistoryItem &item); - - void run(); - -signals: - void elementLoaded(int number, int total, const TransferHistoryItem &item); - -private: - QString m_url; - QList m_items; - TransferHistoryItem m_item; -}; - -class XmlStore::DeleteThread : public QThread -{ - Q_OBJECT -public: - DeleteThread(QObject *parent, const QString &url, const TransferHistoryItem &item); - - void run(); - QList items() const - { - return m_items; - }; - -private: - QString m_url; - TransferHistoryItem m_item; - QList m_items; -}; -#endif diff --git a/kget/core/transfertreemodel.cpp b/kget/core/transfertreemodel.cpp deleted file mode 100644 index c6944ab7..00000000 --- a/kget/core/transfertreemodel.cpp +++ /dev/null @@ -1,789 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "core/transfertreemodel.h" - -#include "core/kget.h" -#include "core/transfertreeselectionmodel.h" -#include "core/transfergrouphandler.h" -#include "core/transfergroup.h" -#include "core/transferhandler.h" -#include "core/transfer.h" -#include "transferadaptor.h" -#include "dbus/dbustransferwrapper.h" -#include "settings.h" -#include "transfergroupscheduler.h" - -#include -#include -#include - -ItemMimeData::ItemMimeData() - : QMimeData() -{ -} - -ItemMimeData::~ItemMimeData() -{ -} - -void ItemMimeData::appendTransfer(const QWeakPointer &transfer) -{ - m_transfers.append(transfer); -} - -QList > ItemMimeData::transfers() const -{ - return m_transfers; -} - -ModelItem::ModelItem(Handler * handler) - : QStandardItem(), - m_handler(handler) -{ -} - -ModelItem::~ModelItem() -{ -} - -void ModelItem::emitDataChanged() -{ - QStandardItem::emitDataChanged(); -} - -Handler * ModelItem::handler() -{ - return m_handler; -} - -bool ModelItem::isGroup() -{ - return false; -} - -GroupModelItem * ModelItem::asGroup() -{ - return dynamic_cast(this); -} - -TransferModelItem * ModelItem::asTransfer() -{ - return dynamic_cast(this); -} - - -TransferModelItem::TransferModelItem(TransferHandler *handler) - : ModelItem(handler), - m_transferHandler(handler) -{ -} - -TransferModelItem::~TransferModelItem() -{ -} - -QVariant TransferModelItem::data(int role) const -{ - if (role == Qt::DisplayRole) - return m_transferHandler->data(column()); - else if (role == Qt::DecorationRole) - { - switch (column()) - { - case 0: { - //store the icon for speed improvements, KIconLoader should make sure, that - //the icon data gets shared - if (m_mimeType.isNull()) { - m_mimeType = KIcon(KMimeType::iconNameForUrl(m_transferHandler->dest().url())); - } - - return m_mimeType; - } - case 1: - return m_transferHandler->statusPixmap(); - } - } - if (role == Qt::TextAlignmentRole) - { - switch (column()) - { - case 0: // name - return QVariant(Qt::AlignLeft | Qt::AlignVCenter); - default: - return Qt::AlignCenter; - } - } - // KextendableItemDelegate::ShowExtensionIndicatorRole - // tells the KExtendableItemDelegate which column contains the extender icon - if (role == Qt::UserRole + 200) - { - if (column() == 0) - return true; - else - return false; - } - return QVariant(); -} - -TransferHandler * TransferModelItem::transferHandler() -{ - return m_transferHandler; -} - - -GroupModelItem::GroupModelItem(TransferGroupHandler *handler) - : ModelItem(handler), - m_groupHandler(handler) -{ -} - -GroupModelItem::~GroupModelItem() -{ -} - -QVariant GroupModelItem::data(int role) const -{ - if (role == Qt::DisplayRole) { - return m_groupHandler->data(column()); - } - if (role == Qt::TextAlignmentRole) - { - switch (column()) - { - case 0: // name - return Qt::AlignVCenter; - case 2: // size - case 3: // speed - case 4: //progress - return Qt::AlignCenter; - default: - return QVariant(Qt::AlignLeft | Qt::AlignBottom); - } - } - if (role == Qt::DecorationRole && column() == 0) - return m_groupHandler->pixmap(); - return QVariant(); -} - -TransferGroupHandler * GroupModelItem::groupHandler() -{ - //kDebug() << m_groupHandler->name(); - return m_groupHandler; -} - -bool GroupModelItem::isGroup() -{ - return true; -} - - -TransferTreeModel::TransferTreeModel(Scheduler * scheduler) - : QStandardItemModel(), - m_scheduler(scheduler), - m_timerId(-1) -{ - m_transferGroups.clear(); - m_transfers.clear(); -} - -TransferTreeModel::~TransferTreeModel() -{ - -} - -void TransferTreeModel::addGroup(TransferGroup * group) -{ - QList items; - for (int i = 0; i != group->handler()->columnCount(); i++) - items << new GroupModelItem(group->handler()); - - appendRow(items); - - m_transferGroups.append(static_cast(items.first())); - - emit groupAddedEvent(group->handler()); - - KGet::m_scheduler->addQueue(group); -} - -void TransferTreeModel::delGroup(TransferGroup * group) -{ - if (m_transferGroups.count() <= 1) //If there is only one group left, we should not remove it - return; - GroupModelItem *item = itemFromTransferGroupHandler(group->handler()); - if (!item) { - return; - } - - QList transfers; - JobQueue::iterator it; - for (it = group->begin(); it != group->end(); ++it) { - transfers << static_cast(*it); - } - delTransfers(transfers); - - m_transferGroups.removeAll(item); - removeRow(item->row()); - - m_changedGroups.removeAll(group->handler()); - - emit groupRemovedEvent(group->handler()); - - KGet::m_scheduler->delQueue(group); -} - -void TransferTreeModel::addTransfers(const QList &transfers, TransferGroup *group) -{ - ModelItem *parentItem = itemFromTransferGroupHandler(group->handler()); - const QModelIndex parentIndex = parentItem->index(); - beginInsertRows(parentItem->index(), parentItem->rowCount(), parentItem->rowCount() + transfers.count() - 1); - - //HACK blocks all signals from the model when adding multiple items, - //that way rowsInserted gets only emitted once, and not constantly when doing appendRow - //change this once there is a better way to append many transfers at once - blockSignals(true); - - //now create and add the new items - QList handlers; - group->append(transfers); - foreach (Transfer *transfer, transfers) { - TransferHandler *handler = transfer->handler(); - handlers << handler; - - QList items; - for (int i = 0; i != handler->columnCount(); ++i) { - items << new TransferModelItem(handler); - } - - parentItem->appendRow(items); - - m_transfers.append(static_cast(items.first())); - - DBusTransferWrapper * wrapper = new DBusTransferWrapper(handler); - new TransferAdaptor(wrapper); - QDBusConnection::sessionBus().registerObject(handler->dBusObjectPath(), wrapper); - } - - //notify the rest of the changes - blockSignals(false); - endInsertRows(); - emit transfersAddedEvent(handlers); -} - -void TransferTreeModel::delTransfers(const QList &t) -{ - QList transfers = t; - QList handlers; - - //find all valid items and sort them according to their groups - QHash > groups; - QHash > groupsTransfer; - { - QList::iterator it; - for (it = transfers.begin(); it != transfers.end(); ) { - TransferModelItem *item = itemFromTransferHandler((*it)->handler()); - if (item) { - handlers << (*it)->handler(); - groups[(*it)->group()] << item; - groupsTransfer[(*it)->group()] << *it; - ++it; - } else { - it = transfers.erase(it); - } - } - } - - emit transfersAboutToBeRemovedEvent(handlers); - - //remove the items from the model - { - QHash >::iterator it; - for (it = groups.begin(); it != groups.end(); ++it) { - const int numItems = (*it).count(); - QStandardItem *parentItem = (*it).first()->parent(); - QModelIndex parentIndex = parentItem->index(); - if (numItems == parentItem->rowCount()) { - for (int i = 0; i < numItems; ++i) { - m_transfers.removeAll((*it)[i]); - } - removeRows(0, numItems, parentIndex); - continue; - } - - int rowStart = (*it).first()->row(); - int numRows = 1; - m_transfers.removeAll((*it).first()); - for (int i = 1; i < numItems; ++i) { - //previous item is neighbour - if (rowStart + numRows == (*it)[i]->row()) { - ++numRows; - //no neighbour, so start again - } else { - removeRows(rowStart, numRows, parentIndex); - rowStart = (*it)[i]->row(); - numRows = 1; - } - m_transfers.removeAll((*it)[i]); - } - //remove last items - removeRows(rowStart, numRows, parentIndex); - } - } - - foreach(Transfer *transfer, transfers) { - QDBusConnection::sessionBus().unregisterObject(transfer->handler()->dBusObjectPath()); - m_changedTransfers.removeAll(transfer->handler()); - } - - { - QHash >::iterator it; - for (it = groupsTransfer.begin(); it != groupsTransfer.end(); ++it) { - it.key()->remove(it.value()); - } - } - - emit transfersRemovedEvent(handlers); -} - -TransferModelItem * TransferTreeModel::itemFromTransferHandler(TransferHandler * handler) -{ - foreach (TransferModelItem * item, m_transfers) - { - if (handler == item->transferHandler()) - return item; - } - return 0; -} - -GroupModelItem * TransferTreeModel::itemFromTransferGroupHandler(TransferGroupHandler * handler) -{ - foreach (GroupModelItem * item, m_transferGroups) - { - if (handler == item->groupHandler()) - return item; - } - return 0; -} - -ModelItem * TransferTreeModel::itemFromHandler(Handler * handler) -{ - TransferHandler *transfer = qobject_cast(handler); - if (transfer) { - return itemFromTransferHandler(transfer); - } - return itemFromTransferGroupHandler(qobject_cast(handler)); -} - -ModelItem * TransferTreeModel::itemFromIndex(const QModelIndex &index) const -{ - QStandardItem *item = QStandardItemModel::itemFromIndex(index); - if (item) - return dynamic_cast(item); - return 0; -} - -void TransferTreeModel::moveTransfer(Transfer * transfer, TransferGroup * destGroup, Transfer * after) -{ - if( (after) && (destGroup != after->group()) ) - return; - - int position = transfer->group()->indexOf(transfer); - - TransferGroup * oldGroup = transfer->group(); - - bool sameGroup = false; - - if (destGroup == transfer->group()) - { - sameGroup = true; - if (after) - destGroup->move(transfer, after); - else - destGroup->move(transfer, 0); - } - else - { - transfer->group()->remove(transfer); - - if (after) - destGroup->insert(transfer, after); - else - destGroup->prepend(transfer); - - transfer->m_jobQueue = destGroup; - } - QList items = itemFromHandler(oldGroup->handler())->takeRow(position); - itemFromHandler(destGroup->handler())->insertRow(destGroup->indexOf(transfer), items); - - if (!sameGroup) - emit transferMovedEvent(transfer->handler(), destGroup->handler()); - - KGet::selectionModel()->clearSelection(); -} - -void TransferTreeModel::moveTransfer(TransferHandler *transfer, TransferGroupHandler *destGroup, TransferHandler *after) -{ - Transfer *afterTransfer = 0; - if (after) { - afterTransfer = after->m_transfer; - } - moveTransfer(transfer->m_transfer, destGroup->m_group, afterTransfer); -} - -QList TransferTreeModel::transferGroups() -{ - QList transferGroups; - foreach (GroupModelItem * item, m_transferGroups) { - transferGroups << item->groupHandler()->m_group; - } - - return transferGroups; -} - -TransferGroup * TransferTreeModel::findGroup(const QString & groupName) -{ - foreach (GroupModelItem * group, m_transferGroups) - { - if (group->groupHandler()->name() == groupName) - return group->groupHandler()->m_group; - } - return 0; -} - -Transfer * TransferTreeModel::findTransfer(const KUrl &src) -{ - /*foreach (TransferGroup * group, transferGroups()) - { - Transfer * t = group->findTransfer(src); - if (t) - return t; - }*/ - foreach (TransferModelItem * transfer, m_transfers) - { - if (transfer->transferHandler()->source() == src) - return transfer->transferHandler()->m_transfer; - } - return 0; -} - -Transfer *TransferTreeModel::findTransferByDestination(const KUrl &dest) -{ - /*foreach (TransferGroup * group, transferGroups()) - { - Transfer * t = group->findTransferByDestination(dest); - if (t) - return t; - }*/ - foreach (TransferModelItem * transfer, m_transfers) - { - if (transfer->transferHandler()->dest() == dest) - return transfer->transferHandler()->m_transfer; - } - return 0; -} - -Transfer * TransferTreeModel::findTransferByDBusObjectPath(const QString & dbusObjectPath) -{ - foreach (TransferModelItem * transfer, m_transfers) - { - if (transfer->transferHandler()->dBusObjectPath() == dbusObjectPath) - return transfer->transferHandler()->m_transfer; - } - return 0; -} - -void TransferTreeModel::postDataChangedEvent(TransferHandler * transfer) -{ - if(m_timerId == -1) - m_timerId = startTimer(1000); - - m_changedTransfers.append(transfer); -} - -void TransferTreeModel::postDataChangedEvent(TransferGroupHandler * group) -{ - if(m_timerId == -1) - m_timerId = startTimer(1000); - - m_changedGroups.append(group); -} - -Qt::ItemFlags TransferTreeModel::flags (const QModelIndex & index) const -{ - // kDebug() << "TransferTreeModel::flags()"; - if (!index.isValid()) - return Qt::ItemIsEnabled; - - Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - - if (!index.parent().isValid()) - { - if(index.column() == 0) - flags |= Qt::ItemIsDropEnabled; - } - else - flags |= Qt::ItemIsDragEnabled; - - //flags |= Qt::ItemIsDropEnabled; - - // We can edit all the groups but the default one - if(index.row() > 0) { - flags |= Qt::ItemIsEditable; - } - - return flags; -} - -QVariant TransferTreeModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Horizontal && role == Qt::DisplayRole) - { - return columnName(section); - } - - return QVariant(); -} - -Qt::DropActions TransferTreeModel::supportedDropActions() const -{ - return Qt::CopyAction | Qt::MoveAction; -} - -QStringList TransferTreeModel::mimeTypes() const -{ - QStringList types; - types << "kget/transfer_pointer"; - return types; -} - -QMimeData * TransferTreeModel::mimeData(const QModelIndexList &indexes) const -{ - ItemMimeData *mimeData = new ItemMimeData(); - - QModelIndexList sortedIndexes = indexes; - qSort(sortedIndexes.begin(), sortedIndexes.end(), qGreater()); - foreach (const QModelIndex &index, sortedIndexes) { - if (index.isValid() && index.column() == 0 && index.parent().isValid()) { - ModelItem *item = itemFromIndex(index); - if (!item->isGroup()) { - mimeData->appendTransfer(QWeakPointer(item->asTransfer()->transferHandler())); - } - } - } - - mimeData->setData("kget/transfer_pointer", QByteArray()); - return mimeData; -} - -bool TransferTreeModel::dropMimeData(const QMimeData * mdata, Qt::DropAction action, int row, int column, const QModelIndex &parent) -{ - if (action == Qt::IgnoreAction) - return true; - - const ItemMimeData *itemData = qobject_cast(mdata); - if (!itemData) { - kWarning() << "Unsuported mime data dropped."; - return false; - } - - TransferGroup *destGroup = findGroup(data(parent, Qt::DisplayRole).toString()); - if (!destGroup) { - kWarning() << "No group could be found where the transfers should be inserted to."; - return false; - } - - if (parent.isValid()) - kDebug() << "TransferTreeModel::dropMimeData" << " " << row << " " - << column; - - QList > transfers = itemData->transfers(); - kDebug() << "TransferTreeModel::dropMimeData:" << transfers.count() << "transfers."; - - const bool droppedInsideGroup = parent.isValid(); - Transfer * after = 0; - for (int i = 0; i < transfers.count(); ++i) { - bool b = destGroup->size() > row && row - 1 >= 0; - if (b) - kDebug() << "TRANSFER AFTER:" << destGroup->operator[](row - 1)->source(); - else - kDebug() << "TRANSFER AFTER NOT EXISTING"; - - if (!after) { - bool rowValid = (row - 1 >= 0) && (destGroup->size() >= row); - if (droppedInsideGroup && rowValid) { - after = destGroup->operator[](row - 1);//insert at the correct position - } - } - - if (transfers[i].isNull()) { - kWarning() << "The moved transfer has been deleted inbetween."; - } else { - moveTransfer(transfers[i].data()->m_transfer, destGroup, after); - } - } - return true; -} - -QString TransferTreeModel::columnName(int column) -{ - switch(column) { - case 0: - return i18nc("name of download", "Name"); - case 1: - return i18nc("status of download", "Status"); - case 2: - return i18nc("size of download", "Size"); - case 3: - return i18nc("progress of download", "Progress"); - case 4: - return i18nc("speed of download", "Speed"); - case 5: - return i18nc("remaining time of download", "Remaining Time"); - } - return QString(); -} - -int TransferTreeModel::column(Transfer::TransferChange flag) -{ - switch(flag) { - case Transfer::Tc_FileName: - return 0; - case Transfer::Tc_Status: - return 1; - case Transfer::Tc_TotalSize: - return 2; - case Transfer::Tc_Percent: - return 3; - case Transfer::Tc_DownloadSpeed: - return 4; - case Transfer::Tc_RemainingTime: - return 5; - default: - return -1; - } - return -1; -} - -int TransferTreeModel::column(TransferGroup::GroupChange flag) -{ - switch(flag) { - case TransferGroup::Gc_GroupName: - return 0; - case TransferGroup::Gc_Status: - return 1; - case TransferGroup::Gc_TotalSize: - return 2; - case TransferGroup::Gc_Percent: - return 3; - case TransferGroup::Gc_DownloadSpeed: - return 4; - default: - return -1; - } - return -1; -} - -void TransferTreeModel::timerEvent(QTimerEvent *event) -{ - Q_UNUSED(event) - // kDebug() << "TransferTreeModel::timerEvent"; - - QMap updatedTransfers; - QMap updatedGroups; - - foreach (TransferHandler * transfer, m_changedTransfers) - { - if (!updatedTransfers.contains(transfer)) { - TransferGroupHandler * group = transfer->group(); - ModelItem * item = itemFromHandler(group); - Transfer::ChangesFlags changesFlags = transfer->changesFlags(); - - emit transfer->transferChangedEvent(transfer, changesFlags); - - int row = group->indexOf(transfer); - - // kDebug() << "CHILD = " << item->child(row, column(Transfer::Tc_FileName)); - - // Now, check that model child items already exist (there are some cases when the transfer - // can notify for changes before the gui has been correctly initialized) - if(item->child(row, 0)) { - if (changesFlags & Transfer::Tc_FileName) - static_cast(item->child(row, column(Transfer::Tc_FileName)))->emitDataChanged(); - if (changesFlags & Transfer::Tc_Status) - static_cast(item->child(row, column(Transfer::Tc_Status)))->emitDataChanged(); - if (changesFlags & Transfer::Tc_TotalSize) - static_cast(item->child(row, column(Transfer::Tc_TotalSize)))->emitDataChanged(); - if (changesFlags & Transfer::Tc_Percent) - static_cast(item->child(row, column(Transfer::Tc_Percent)))->emitDataChanged(); - if (changesFlags & Transfer::Tc_DownloadSpeed) - static_cast(item->child(row, column(Transfer::Tc_DownloadSpeed)))->emitDataChanged(); - if (changesFlags & Transfer::Tc_RemainingTime) - static_cast(item->child(row, column(Transfer::Tc_RemainingTime)))->emitDataChanged(); - - transfer->resetChangesFlags(); - updatedTransfers.insert(transfer,changesFlags); - } - } - } - - if(!updatedTransfers.isEmpty()) - emit transfersChangedEvent(updatedTransfers); - - foreach(TransferGroupHandler * group, m_changedGroups) - { - if(!updatedGroups.contains(group)) - { - TransferGroup::ChangesFlags changesFlags = group->changesFlags(); - - emit group->groupChangedEvent(group, changesFlags); - - int row = itemFromHandler(group)->row(); - - if (changesFlags & TransferGroup::Gc_GroupName) - static_cast(item(row, column(TransferGroup::Gc_GroupName)))->emitDataChanged(); - if (changesFlags & TransferGroup::Gc_Status) - static_cast(item(row, column(TransferGroup::Gc_Status)))->emitDataChanged(); - if (changesFlags & TransferGroup::Gc_TotalSize) - static_cast(item(row, column(TransferGroup::Gc_TotalSize)))->emitDataChanged(); - if (changesFlags & TransferGroup::Gc_Percent) - static_cast(item(row, column(TransferGroup::Gc_Percent)))->emitDataChanged(); - if (changesFlags & TransferGroup::Gc_DownloadSpeed) - static_cast(item(row, column(TransferGroup::Gc_DownloadSpeed)))->emitDataChanged(); - - /*for(int i=0; i<8; i++) - { - if(((changesFlags >> i) & 0x00000001)) - { - QStandardItem *groupItem = itemFromHandler(group); - dynamic_cast(invisibleRootItem()->child(groupItem->row(), i))->emitDataChanged(); - //QModelIndex index = createIndex(m_transferGroups.indexOf(group->m_group), i, group); - //emit dataChanged(index,index); - } - }*/ - - group->resetChangesFlags(); - updatedGroups.insert(group, changesFlags); - } - } - - if(!updatedGroups.isEmpty()) - emit groupsChangedEvent(updatedGroups); - - m_changedTransfers.clear(); - m_changedGroups.clear(); - - killTimer(m_timerId); - m_timerId = -1; -} - -#include "moc_transfertreemodel.cpp" diff --git a/kget/core/transfertreemodel.h b/kget/core/transfertreemodel.h deleted file mode 100644 index cf943c96..00000000 --- a/kget/core/transfertreemodel.h +++ /dev/null @@ -1,195 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef TRANSFERTREEMODEL_H -#define TRANSFERTREEMODEL_H - -#include -#include -#include -#include - -#include "../kget_export.h" -#include "core/transfer.h" -#include "core/transfergroup.h" -#include "core/handler.h" - -class KUrl; - -class TransferGroupHandler; -class TransferGroup; -class TransferHandler; -class Transfer; -class Scheduler; -class TransferModelItem; -class GroupModelItem; - -class ItemMimeData : public QMimeData -{ - Q_OBJECT - public: - ItemMimeData(); - ~ItemMimeData(); - - /** - * Appends a transfer to the list of transfers. - * The weakpointer is there to check later on, that the transfer still exists - */ - void appendTransfer(const QWeakPointer &transfer); - - /** - * Returns all appended transfers - * The weakpointer is there to check later on, that the transfer still exists - */ - QList > transfers() const; - - private: - QList > m_transfers; -}; - -class KGET_EXPORT ModelItem : public QStandardItem -{ - public: - ModelItem(Handler * handler); - virtual ~ModelItem(); - - virtual QVariant data(int role = Qt::UserRole + 1) const = 0; - void emitDataChanged(); - Handler * handler(); - virtual bool isGroup(); - - GroupModelItem * asGroup(); - TransferModelItem * asTransfer(); - - private: - Handler * m_handler; -}; - -class KGET_EXPORT TransferModelItem : public ModelItem -{ - public: - TransferModelItem(TransferHandler *handler); - virtual ~TransferModelItem(); - - virtual QVariant data(int role = Qt::UserRole + 1) const; - - TransferHandler * transferHandler(); - - private: - TransferHandler * m_transferHandler; - mutable KIcon m_mimeType; -}; - -class KGET_EXPORT GroupModelItem : public ModelItem -{ - public: - GroupModelItem(TransferGroupHandler *handler); - virtual ~GroupModelItem(); - - virtual QVariant data(int role = Qt::UserRole + 1) const; - - TransferGroupHandler * groupHandler(); - - virtual bool isGroup(); - - private: - TransferGroupHandler * m_groupHandler; -}; - -class KGET_EXPORT TransferTreeModel : public QStandardItemModel -{ - Q_OBJECT - - friend class TransferGroupHandler; - friend class TransferGroup; - friend class TransferHandler; - friend class Transfer; - - public: - enum Columns { - Name, - Status, - Size, - Progress, - Speed, - RemainingTime - }; - TransferTreeModel(Scheduler * scheduler); - ~TransferTreeModel(); - - void addGroup(TransferGroup * group); - void delGroup(TransferGroup * group); - - void addTransfers(const QList &transfers, TransferGroup *group); - void delTransfers(const QList &transfers); - - TransferModelItem * itemFromTransferHandler(TransferHandler * handler); - GroupModelItem * itemFromTransferGroupHandler(TransferGroupHandler * handler); - ModelItem * itemFromHandler(Handler * handler); - - ModelItem * itemFromIndex(const QModelIndex &index) const; - - void moveTransfer(Transfer * transfer, TransferGroup * destGroup, Transfer * after = 0); - void moveTransfer(TransferHandler *transfer, TransferGroupHandler *destGroup, TransferHandler *after = 0); - - QList transferGroups(); - - TransferGroup * findGroup(const QString & groupName); - Transfer * findTransfer(const KUrl &src); - Transfer * findTransferByDestination(const KUrl &dest); - Transfer * findTransferByDBusObjectPath(const QString & dbusObjectPath); - - void postDataChangedEvent(TransferHandler * transfer); - void postDataChangedEvent(TransferGroupHandler * group); - - Qt::ItemFlags flags (const QModelIndex & index) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; - - //Drag & drop functions - Qt::DropActions supportedDropActions() const; - QStringList mimeTypes() const; - QMimeData * mimeData(const QModelIndexList &indexes) const; - bool dropMimeData(const QMimeData *mdata, - Qt::DropAction action, int row, int column, - const QModelIndex &parent); - - static QString columnName(int column); - static int column(Transfer::TransferChange flag); - static int column(TransferGroup::GroupChange flag); - - signals: - void groupAddedEvent(TransferGroupHandler *); - void groupRemovedEvent(TransferGroupHandler *); - void groupsChangedEvent(QMap); - void transfersAddedEvent(QList transfers); - void transfersAboutToBeRemovedEvent(const QList &transfers); - void transfersRemovedEvent(const QList &transfers); - void transferMovedEvent(TransferHandler *, TransferGroupHandler *); - void transfersChangedEvent(QMap); - - private: - void timerEvent(QTimerEvent *event); - - Scheduler * m_scheduler; - - // Timer related variables - QList m_changedTransfers; - QList m_changedGroups; - - QList m_transferGroups; - QList m_transfers; - - int m_timerId; -}; - -#endif diff --git a/kget/core/transfertreeselectionmodel.cpp b/kget/core/transfertreeselectionmodel.cpp deleted file mode 100644 index 2e6fd942..00000000 --- a/kget/core/transfertreeselectionmodel.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - - 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. -*/ - -#include "core/transfertreeselectionmodel.h" - -#include "core/transfertreemodel.h" - -#include - -TransferTreeSelectionModel::TransferTreeSelectionModel(QAbstractItemModel * model) - : QItemSelectionModel(model) -{ -} - -TransferTreeSelectionModel::~TransferTreeSelectionModel() -{ -} - -#include "moc_transfertreeselectionmodel.cpp" diff --git a/kget/core/transfertreeselectionmodel.h b/kget/core/transfertreeselectionmodel.h deleted file mode 100644 index 30cc5419..00000000 --- a/kget/core/transfertreeselectionmodel.h +++ /dev/null @@ -1,25 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - - 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. -*/ - -#ifndef TRANSFERTREESELECTIONMODEL_H -#define TRANSFERTREESELECTIONMODEL_H - -#include - -class TransferTreeSelectionModel : public QItemSelectionModel -{ - Q_OBJECT - - public: - TransferTreeSelectionModel(QAbstractItemModel * model); - virtual ~TransferTreeSelectionModel(); -}; - -#endif diff --git a/kget/core/urlchecker.cpp b/kget/core/urlchecker.cpp deleted file mode 100644 index 48beff71..00000000 --- a/kget/core/urlchecker.cpp +++ /dev/null @@ -1,873 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2007-2009 Lukas Appelhans * -* Copyright (C) 2008 Dario Freddi * -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 "urlchecker.h" -#include "urlchecker_p.h" -#include "mainwindow.h" -#include "core/filedeleter.h" -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfertreemodel.h" -#include "settings.h" - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -ExistingTransferDialog::ExistingTransferDialog(const QString &text, const QString &caption, QWidget *parent) - : KDialog(parent) -{ - setCaption(caption.isEmpty() ? i18n("Question") : caption); - setModal(true); - setButtons(0); - - QWidget *widget = new QWidget(this); - QVBoxLayout *layout = new QVBoxLayout; - QHBoxLayout *bottomLayout = new QHBoxLayout; - - QLabel *label = new QLabel(text, this); - layout->addWidget(label); - layout->addWidget(new KSeparator(Qt::Horizontal, this)); - - m_applyAll = new QCheckBox(i18n("Appl&y to all"), this); - bottomLayout->addStretch(1); - bottomLayout->addWidget(m_applyAll); - - KDialogButtonBox *buttonBox = new KDialogButtonBox(this); - buttonBox->addButton(KStandardGuiItem::yes(), QDialogButtonBox::YesRole, this, SLOT(slotYesClicked())); - buttonBox->addButton(KStandardGuiItem::no(), QDialogButtonBox::NoRole, this, SLOT(slotNoClicked())); - buttonBox->addButton(KStandardGuiItem::cancel(), QDialogButtonBox::RejectRole, this, SLOT(slotCancelClicked())); - bottomLayout->addWidget(buttonBox); - layout->addLayout(bottomLayout, 0); - - widget->setLayout(layout); - setMainWidget(widget); -} - -void ExistingTransferDialog::slotYesClicked() -{ - done(m_applyAll->isChecked() ? KDialog::User2 : KDialog::Yes); -} - -void ExistingTransferDialog::slotNoClicked() -{ - done(m_applyAll->isChecked() ? KDialog::User1 : KDialog::No); -} - -void ExistingTransferDialog::slotCancelClicked() -{ - done(QDialog::Rejected); -} - - -UrlChecker::UrlChecker(UrlType type) - : m_type(type), - m_cancle(false), - m_overwriteAll(false), - m_autoRenameAll(false), - m_skipAll(false) -{ -} - -UrlChecker::~UrlChecker() -{ -} - -///Static methods following - -struct lessThan -{ - bool operator()(const KUrl &lhs, const KUrl &rhs) const - { - return lhs.url() < rhs.url(); - } -}; - -void UrlChecker::removeDuplicates(KUrl::List &urls) -{ - std::sort(urls.begin(), urls.end(), lessThan());//sort the urls, to find duplicates fast - urls.erase(std::unique(urls.begin(), urls.end(), - std::bind(&KUrl::equals, std::placeholders::_1, std::placeholders::_2, - KUrl::RemoveTrailingSlash)), urls.end()); -} - -UrlChecker::UrlError UrlChecker::checkUrl(const KUrl &url, const UrlChecker::UrlType type, bool showNotification) -{ - switch (type) { - case Source: - return checkSource(url, showNotification); - case Destination: - return checkDestination(url, showNotification); - case Folder: - return checkFolder(url, showNotification); - } - - return NoError; -} - -bool UrlChecker::wouldOverwrite(const KUrl &source, const KUrl &dest) -{ - return (dest.isLocalFile() && QFile::exists(dest.toLocalFile()) && source != dest && !FileDeleter::isFileBeingDeleted(dest)); -} - -UrlChecker::UrlError UrlChecker::checkSource(const KUrl &src, bool showNotification) -{ - //NOTE hasPath is not used, as this would dissallow adresses like http://www.kde.org/ as there is no path - UrlError error = NoError; - if (src.isEmpty()) { - return Empty; - } - if (error == NoError && !src.isValid()) { - error = Invalid; - } - if (error == NoError && src.protocol().isEmpty()){ - error = NoProtocol; - } -#if 0 - if (error == NoError && !src.hasHost()) { - //FIXME deactivated to allow file://.... etc - error = NoHost; - } -#endif - - if (error == NoError && src.fileName().isEmpty()) { - // URLs without a filename (e.g. https://foobar.com/) are not supported - error = NoFileName; - } - - //TODO also check sourceUrl.url() != KUrl(sourceUrl.url()).fileName() as in NewTransferDialog::setSource? - - if (showNotification && (error != NoError)) { - kDebug() << "Source:" << src << "has error:" << error; - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/error", - message(src, Source, error) - ); - notification->send(); - } - - return error; -} - -UrlChecker::UrlError UrlChecker::checkDestination(const KUrl &destination, bool showNotification) -{ - UrlError error = NoError; - - if (destination.isEmpty()) { - error = Empty; - } - - if (error == NoError) { - //not supposed to be a folder - QFileInfo fileInfo(destination.pathOrUrl()); - if (!destination.isValid() || fileInfo.isDir()) { - error = Invalid; - } - - if (error == NoError && !QFileInfo(destination.directory()).isWritable()) { - error = NotWriteable; - } - } - - if (showNotification && (error != NoError)) { - kDebug() << "Destination:" << destination << "has error:" << error; - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/error", - message(destination, Destination, error) - ); - notification->send(); - } - - return error; -} - - -UrlChecker::UrlError UrlChecker::checkFolder(const KUrl &folder, bool showNotification) -{ - UrlError error = NoError; - - const QString destDir = folder.pathOrUrl(); - if (folder.isEmpty() || destDir.isEmpty()) { - error = Empty; - } - - if (error == NoError) { - //has to be a folder - QFileInfo fileInfo(destDir); - if (!folder.isValid() || !fileInfo.isDir()) { - error = Invalid; - } - - //has to be writeable - if (error == NoError && !fileInfo.isWritable()) { - error = NotWriteable; - } - } - - if (showNotification && (error != NoError)) { - kDebug() << "Folder:" << folder << "has error:" << error; - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/error", - message(folder, Folder, error) - ); - notification->send(); - } - - return error; -} - -KUrl UrlChecker::destUrl(const KUrl &destOrFolder, const KUrl &source, const QString &fileName) -{ - KUrl dest = destOrFolder; - if (QFileInfo(dest.toLocalFile()).isDir()) { - QString usedFileName = (fileName.isEmpty() ? source.fileName() : fileName); - if (usedFileName.isEmpty()) { - usedFileName = KUrl::toPercentEncoding(source.prettyUrl(), "/"); - } - dest.adjustPath(KUrl::AddTrailingSlash); - dest.setFileName(usedFileName); - } else if (!fileName.isEmpty()) { - dest.setFileName(fileName); - } - - return dest; -} - -TransferHandler *UrlChecker::existingTransfer(const KUrl &url, const UrlChecker::UrlType type, UrlChecker::UrlWarning *warning) -{ - UrlWarning temp; - UrlWarning &warn = (warning ? (*warning) : temp); - warn = NoWarning; - - switch (type) { - case Source: - return existingSource(url, warn); - case Destination: - return existingDestination(url, warn); - default: - return 0; - } -} - -TransferHandler *UrlChecker::existingSource(const KUrl &source, UrlChecker::UrlWarning &warning) -{ - // Check if a transfer with the same url already exists - Transfer *transfer = KGet::m_transferTreeModel->findTransfer(source); - if (transfer) { - if (transfer->status() == Job::Finished) { - warning = ExistingFinishedTransfer; - } else { - warning = ExistingTransfer; - } - } - - return (transfer ? transfer->handler() : 0); -} - -TransferHandler *UrlChecker::existingDestination(const KUrl &url, UrlChecker::UrlWarning &warning) -{ - Transfer *transfer = KGet::m_transferTreeModel->findTransferByDestination(url); - if (transfer) { - if (transfer->status() == Job::Finished) { - warning = ExistingFinishedTransfer; - } else { - warning = ExistingTransfer; - } - } else if (QFile::exists(url.pathOrUrl())) { - warning = ExistingFile; - } - - return (transfer ? transfer->handler() : 0); -} - - -QString UrlChecker::message(const KUrl &url, const UrlChecker::UrlType type, const UrlChecker::UrlError error) -{ - if (url.isEmpty()) { - if (type == Folder) { - switch (error) { - case Empty: - return i18n("No download directory specified."); - case Invalid: - return i18n("Invalid download directory specified."); - case NotWriteable: - return i18n("Download directory is not writeable."); - default: - return QString(); - } - } - if (type == Destination) { - switch (error) { - case Empty: - return i18n("No download destination specified."); - case Invalid: - return i18n("Invalid download destination specified."); - case NotWriteable: - return i18n("Download destination is not writeable."); - default: - return QString(); - } - } - if (type == Source) { - switch (error) { - case Empty: - return i18n("No URL specified."); - case Invalid: - return i18n("Malformed URL."); - case NoProtocol: - return i18n("Malformed URL, protocol missing."); - case NoHost: - return i18n("Malformed URL, host missing."); - case NoFileName: - return i18n("Malformed URL, filename missing."); - default: - return QString(); - } - } - } else { - const QString urlString = url.prettyUrl(); - if (type == Folder) { - switch (error) { - case Empty: - return i18n("No download directory specified."); - case Invalid: - return i18n("Invalid download directory specified:\n%1", urlString); - case NotWriteable: - return i18n("Download directory is not writeable:\n%1", urlString); - default: - return QString(); - } - } - if (type == Destination) { - switch (error) { - case Empty: - return i18n("No download destination specified."); - case Invalid: - return i18n("Invalid download destination specified:\n%1", urlString); - case NotWriteable: - return i18n("Download destination is not writeable:\n%1", urlString); - default: - return QString(); - } - } - if (type == Source) { - switch (error) { - case Empty: - return i18n("No URL specified."); - case Invalid: - return i18n("Malformed URL:\n%1", urlString); - case NoProtocol: - return i18n("Malformed URL, protocol missing:\n%1", urlString); - case NoHost: - return i18n("Malformed URL, host missing:\n%1", urlString); - case NoFileName: - return i18n("Malformed URL, filename missing:\n%1", urlString); - default: - return QString(); - } - } - } - - return QString(); -} - -QString UrlChecker::message(const KUrl &url, const UrlChecker::UrlType type, const UrlChecker::UrlWarning warning) -{ - if (url.isEmpty()) { - if (type == Destination) { - switch (warning) { - case ExistingFile: - return i18n("File already exists. Overwrite it?"); - case ExistingFinishedTransfer: - return i18n("You have already downloaded that file from another location.\nDownload and delete the previous one?"); - case ExistingTransfer: - return i18n("You are already downloading that file from another location.\nDownload and delete the previous one?"); - default: - return QString(); - } - } - if (type == Source) { - switch (warning) { - case ExistingFile: - return i18n("File already exists. Overwrite it?"); - case ExistingFinishedTransfer: - return i18n("You have already completed a download from that location. Download it again?"); - case ExistingTransfer: - return i18n("You have a download in progress from that location.\nDelete it and download again?"); - default: - return QString(); - } - } - } else { - const QString urlString = url.prettyUrl(); - if (type == Destination) { - switch (warning) { - case ExistingFile: - return i18n("File already exists:\n%1\nOverwrite it?", urlString); - case ExistingFinishedTransfer: - return i18n("You have already downloaded that file from another location.\nDownload and delete the previous one?"); - case ExistingTransfer: - return i18n("You are already downloading that file from another location.\nDownload and delete the previous one?"); - default: - return QString(); - } - } - if (type == Source) { - switch (warning) { - case ExistingFinishedTransfer: - return i18n("You have already completed a download from the location: \n\n%1\n\nDownload it again?", urlString); - case ExistingTransfer: - return i18n("You have a download in progress from the location: \n\n%1\n\nDelete it and download again?", urlString); - default: - return QString(); - } - } - } - - return QString(); -} - -QString UrlChecker::message(const KUrl::List &urls, const UrlChecker::UrlType type, const UrlChecker::UrlError error) -{ - QString urlsString; - if (!urls.isEmpty()) { - urlsString = urls.first().prettyUrl(); - for (int i = 1; i < urls.count(); ++i) { - urlsString += '\n' + urls[i].prettyUrl(); - } - urlsString = QString("

\%1

").arg(urlsString); - } - - if (urls.isEmpty()) { - if ((type == Folder) || (type == Destination)) { - return message(KUrl(), type, error); - } - if (type == Source) { - switch (error) { - case Empty: - return i18n("No URL specified."); - case Invalid: - return i18n("Malformed URLs."); - case NoProtocol: - return i18n("Malformed URLs, protocol missing."); - case NoHost: - return i18n("Malformed URLs, host missing."); - case NoFileName: - return i18n("Malformed URLs, filename missing."); - default: - return QString(); - } - } - } else { - switch (error) { - case Empty: - return i18n("No URL specified."); - case Invalid: - return i18n("Malformed URLs:\n%1", urlsString); - case NoProtocol: - return i18n("Malformed URLs, protocol missing:\n%1", urlsString); - case NoHost: - return i18n("Malformed URLs, host missing:\n%1", urlsString); - case NoFileName: - return i18n("Malformed URLs, filename missing:\n%1", urlsString); - case NotWriteable: - return i18n("Destinations are not writable:\n%1", urlsString); - default: - return QString(); - } - } - - return QString(); -} - -QString UrlChecker::message(const KUrl::List &urls, const UrlChecker::UrlType type, const UrlChecker::UrlWarning warning) -{ - QString urlsString; - if (!urls.isEmpty()) { - urlsString = urls.first().prettyUrl(); - for (int i = 1; i < urls.count(); ++i) { - urlsString += '\n' + urls[i].prettyUrl(); - } - urlsString = QString("

\%1

").arg(urlsString); - } - - if (urls.isEmpty()) { - if (type == Destination) { - switch (warning) { - case ExistingFile: - return i18n("Files exist already. Overwrite them?"); - case ExistingFinishedTransfer: - return i18n("You have already completed downloads at those destinations. Download them again?"); - case ExistingTransfer: - return i18n("You have downloads in progress to these destinations.\nDelete them and download again?"); - default: - return QString(); - } - } - if (type == Source) { - switch (warning) { - case ExistingFinishedTransfer: - return i18n("You have already completed downloads from these locations. Download them again?"); - case ExistingTransfer: - return i18n("You have downloads in progress from these locations.\nDelete them and download again?"); - default: - return QString(); - } - } - } else { - if (type == Destination) { - switch (warning) { - case ExistingFile: - return i18n("Files exist already:\n%1\nOverwrite them?", urlsString); - case ExistingFinishedTransfer: - return i18n("You have already completed downloads at those destinations: \n\n%1\n\n Download them again?", urlsString); - case ExistingTransfer: - return i18n("You have downloads in progress to these destinations: \n\n%1\n\nDelete them and download again?", urlsString); - default: - return QString(); - } - } - if (type == Source) { - switch (warning) { - case ExistingFinishedTransfer: - return i18n("You have already completed downloads from these locations: \n\n%1\n\nDownload them again?", urlsString); - case ExistingTransfer: - return i18n("You have downloads in progress from these locations: \n\n%1\n\nDelete them and download again?", urlsString); - default: - QString(); - } - } - } - - return QString(); -} - - -KUrl::List UrlChecker::hasExistingTransferMessages(const KUrl::List &urls, const UrlChecker::UrlType type) -{ - UrlWarning warning; - QHash > > splitWarnings; - KUrl::List urlsToDownload; - - //collect all errors - foreach(const KUrl &url, urls) { - TransferHandler *transfer = existingTransfer(url, type, &warning); - if (transfer) { - splitWarnings[warning] << qMakePair(url, transfer); - } else { - urlsToDownload << url; - } - } - - //First ask about unfinished existing transfers - QList >::const_iterator it; - QList >::const_iterator itEnd; - QList orderOfExecution; - QList toDelete; - orderOfExecution << ExistingTransfer << ExistingFinishedTransfer; - for (int i = 0; i < orderOfExecution.count(); ++i) { - warning = orderOfExecution[i]; - if (splitWarnings.contains(warning)) { - QList > existing = splitWarnings[warning]; - itEnd = existing.constEnd(); - bool isYesAll = false; - bool isNoAll = false; - for (it = existing.constBegin(); it != itEnd; ++it) { - if (isYesAll) { - urlsToDownload << it->first; - toDelete << it->second; - continue; - } - - if (isNoAll) { - break; - } - - int result; - if (Settings::filesOverwrite() || (Settings::filesAutomaticRename() && (warning != ExistingTransfer))) { - result = YesAll; - } else { - result = hasExistingDialog(it->first, type, warning); - } - switch (result) { - case YesAll: - isYesAll = true; - case Yes: - urlsToDownload << it->first; - toDelete << it->second; - break; - case NoAll: - isNoAll = true; - case No: - break; - case Cancel: - default: - removeTransfers(toDelete); - return urlsToDownload; - } - } - } - } - - removeTransfers(toDelete); - return urlsToDownload; -} - -void UrlChecker::removeTransfers(const QList &toRemove) -{ - QList transfers = toRemove; - transfers.removeAll(0); - if (!transfers.isEmpty()) { - KGet::delTransfers(transfers); - } -} - - -int UrlChecker::hasExistingDialog(const KUrl &url, const UrlChecker::UrlType type, const UrlChecker::UrlWarning warning) -{ - QWidget *parent = KGet::m_mainWindow; - - //getting the caption - QString caption; - if (type == Source) { - switch (warning) { - case ExistingFinishedTransfer: - caption = i18n("Delete it and download again?"); - break; - case ExistingTransfer: - caption = i18n("Download it again?"); - break; - default: - break; - } - } else if (type == Destination) { - switch (warning) { - case ExistingFinishedTransfer: - case ExistingTransfer: - caption = i18n("File already downloaded. Download anyway?"); - break; - case ExistingFile: - caption = i18n("File already exists"); - break; - default: - break; - } - } - - QScopedPointer dialog(new ExistingTransferDialog(message(url, type, warning), caption, parent)); - - const int result = dialog->exec(); - switch (result) { - case QDialog::Rejected: - return Cancel; - case KDialog::Yes: - return Yes; - case KDialog::User2: - return YesAll; - case KDialog::No: - return No; - case KDialog::User1: - return NoAll; - default: - return result; - } -} - -///Non static methods following - -void UrlChecker::clear() -{ - m_correctUrls.clear(); - m_splitErrorUrls.clear(); - m_cancle = false; - m_overwriteAll = false; - m_autoRenameAll = false; - m_skipAll = false; -} - -UrlChecker::UrlType UrlChecker::type() const -{ - return m_type; -} - -void UrlChecker::setType(UrlChecker::UrlType type) -{ - clear(); - m_type = type; -} - -UrlChecker::UrlError UrlChecker::addUrl(const KUrl &url) -{ - const UrlError error = checkUrl(url, m_type); - if (error == NoError) { - m_correctUrls << url; - } else { - m_splitErrorUrls[error] << url; - } - - return error; -} - -bool UrlChecker::addUrls(const KUrl::List &urls) -{ - bool worked = true; - foreach (const KUrl &url, urls) { - const UrlError error = addUrl(url); - if (error != NoError) { - worked = false; - } - } - - return worked; -} - -void UrlChecker::existingTransfers() -{ - m_correctUrls = hasExistingTransferMessages(correctUrls(), m_type); -} - -KUrl UrlChecker::checkExistingFile(const KUrl &source, const KUrl &destination) -{ - KUrl newDestination = destination; - - //any url is ignored - if (m_cancle) { - return KUrl(); - } - - if (Settings::filesOverwrite()) { - m_overwriteAll = true; - } else if (Settings::filesAutomaticRename()) { - m_autoRenameAll = true; - } - - if (wouldOverwrite(source, destination)) { - KIO::RenameDialog_Mode args = static_cast(KIO::M_MULTI | KIO::M_SKIP | KIO::M_OVERWRITE); - QScopedPointer dlg(new KIO::RenameDialog(KGet::m_mainWindow, i18n("File already exists"), source, - destination, args)); - - ///in the following cases no dialog needs to be shown - if (m_skipAll) { //only existing are ignored - return KUrl(); - } else if (m_overwriteAll) { - FileDeleter::deleteFile(newDestination); - return newDestination; - } else if (m_autoRenameAll) { - newDestination = dlg->autoDestUrl(); - return newDestination; - } - - ///now show the dialog and look at the result - const int result = dlg->exec(); - switch (result) { - case KIO::R_OVERWRITE: { - //delete the file, that way it won't show up in future calls of this method - FileDeleter::deleteFile(newDestination); - return newDestination; - } - case KIO::R_OVERWRITE_ALL: { - - //delete the file, that way it won't show up in future calls of this method - FileDeleter::deleteFile(newDestination); - m_overwriteAll = true; - return newDestination; - } - case KIO::R_RENAME: - //call it again, as there is no check on the user input - return checkExistingFile(source, dlg->newDestUrl()); - case KIO::R_AUTO_RENAME: - newDestination = dlg->autoDestUrl(); - m_autoRenameAll = true; - return newDestination; - case KIO::R_SKIP: - return KUrl(); - case KIO::R_AUTO_SKIP: - m_skipAll = true; - return KUrl(); - case KIO::R_CANCEL: - m_cancle = true; - return KUrl(); - default: - return KUrl(); - } - } - - return newDestination; -} - - -KUrl::List UrlChecker::correctUrls() const -{ - return m_correctUrls; -} - -KUrl::List UrlChecker::errorUrls() const -{ - KUrl::List urls; - - QHash::const_iterator it; - QHash::const_iterator itEnd = m_splitErrorUrls.constEnd(); - for (it = m_splitErrorUrls.constBegin(); it != itEnd; ++it) { - urls << (*it); - } - - return urls; -} - -QHash UrlChecker::splitErrorUrls() const -{ - return m_splitErrorUrls; -} - -void UrlChecker::displayErrorMessages() -{ - QHash::const_iterator it; - QHash::const_iterator itEnd = m_splitErrorUrls.constEnd(); - for (it = m_splitErrorUrls.constBegin(); it != itEnd; ++it) { - QString m; - if (it->count() > 1) { - m = message(*it, m_type, it.key()); - } else if (!it->isEmpty()) { - m = message(it->first(), m_type, it.key()); - } - - if (!m.isEmpty()) { - KNotification* notification = KGet::showNotification( - KGet::m_mainWindow, - "kget/error", - m - ); - notification->send(); - } - } -} diff --git a/kget/core/urlchecker.h b/kget/core/urlchecker.h deleted file mode 100644 index 0d07fab6..00000000 --- a/kget/core/urlchecker.h +++ /dev/null @@ -1,310 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 KGET_URL_CHECKER_H -#define KGET_URL_CHECKER_H - -#include "../kget_export.h" - -#include - -class Transfer; -class TransferHandler; - -/** - * This class provides static methods to check if urls are valid, and if not - * provides enums to see what is not valid and provides translated error messages - */ -class KGET_EXPORT UrlChecker -{ - public: - enum UrlType { - Source, - Destination, - Folder - }; - - /** - * Before using UrlChecker you have to specify a type - * You can either do that in the constructor and later - * via setType - * - * @see setType - */ - explicit UrlChecker(UrlType type); - ~UrlChecker(); - - /** - * Removes duplicates of a list of urls - */ - static void removeDuplicates(KUrl::List &urls); - - //NOTE only first found error is reported, i.e. NotWriteable before ExistingFile if both are the case - enum UrlError { - //General - NoError = 0, - Empty, - Invalid, - - //Source only - NoProtocol, - NoHost, - NoFileName, - - //Destination and Folder only - NotWriteable - }; - - enum UrlWarning { - NoWarning = 0, - //Source and Destination only - ExistingFinishedTransfer, - ExistingTransfer, - - //Destination only - ExistingFile - }; - - /** - * Folder: - * Checks if the destination url points to is a folder that is writeable and existent. - * - * Destination: - * Checks if url points to a file (can be non-existent) and if the - * directory this file is (would) be in is existent and writeable - * - * @param type all types supported here - * @param showNotification true shows a notification if an error is found - * @note checkExisting is not done within this method - * @note you can use the convenience methods checkSource, checkDestination, checkFolder - * directly - * @see checkExisting - */ - static UrlError checkUrl(const KUrl &url, const UrlType type, bool showNotification = false); - - /** - * Convenience method of checkUrl - * @param showNotification true shows a notification if an error is found - */ - static UrlError checkSource(const KUrl &source, bool showNotification = false); - - /** - * Convenience method of checkUrl - * @param showNotification true shows a notification if an error is found - */ - static UrlError checkDestination(const KUrl &destination, bool showNotification = false); - - /** - * Convenience method of checkUrl - * @param showNotification true shows a notification if an error is found - */ - static UrlError checkFolder(const KUrl &folder, bool showNotification = false); - - /** - * Checks if source is local and exists already - * @note If both dest and source are the same and local, then false will be returned - * since it is assumed, that local files are either not handled by any - * transfer plugin or are e.g. torrent files and thus can have the same source/dest. - * Also keep in mind that false will be returned if dest is being removed - * at the moment. Avoid to ask a user twice in worst case. - */ - static bool wouldOverwrite(const KUrl &source, const KUrl &dest); - - /** - * Checks if there is an existing transfer for url with type - * @param type *Source checks if there is a transfer with the same source - * *Destination checks if there is a transfer with the same destination - * @return if an existing transfer is found it will be returned, - * otherwise 0 will be returned - * @note checkUrl check is not done and UrlType Folder is not supported - * Keep in mind, that the same transfers could be found via Source and Destination! - * @see checkUrl - */ - static TransferHandler *existingTransfer(const KUrl &url, const UrlType type, UrlWarning *warning = 0); - - /** - * @note UrlType folder is not supported, the result then is undefined! - */ - static KUrl::List hasExistingTransferMessages(const KUrl::List &urls, const UrlType type); - - /** - * Get a describing message for UrlError - * @param url is only needed here to include it in some error messages, - * if url is empty, then it won't be used. - * @note this method does no checks, it only creates messages based on the error code - * @see checkUrl - */ - static QString message(const KUrl &url, const UrlType type, const UrlError error); - - /** - * Get a describing message for UrlWarning - * @param url is only needed here to include it in some error messages, - * if url is empty, then it won't be used. - * @note this method does no checks, it only creates messages based on the warning code - * @see existingTransfer fileExists - */ - static QString message(const KUrl &url, const UrlType type, const UrlWarning warning); - - /** - * Convenience method for multiple urls (urls can be empty) - * @see message - */ - static QString message(const KUrl::List &urls, const UrlType type, const UrlError error); - - /** - * Convenience method for multiple urls (urls can be empty) - * @see message - */ - static QString message(const KUrl::List &urls, const UrlType type, const UrlWarning warning); - - /** - * Takes an url to a source and an url to either the destination or a folder - * and returns a destination url. - * - * @param destOrFolder *is an existing folder then a file name derived from source - * will be appended to it and returned - * *otherwise no modification will be done and destOrFolder will be returned - * @note no checkUrl check happens! - * @see checkUrl - */ - static KUrl destUrl(const KUrl &destOrFolder, const KUrl &source, const QString &fileName = QString()); - - ///Non static methods following - - UrlType type() const; - - /** - * Sets the type for the following operations to type - * @note calls clear - * @see clear - */ - void setType(UrlType type); - - /** - * Clears all data, like correctUrls, errorUrls, responses from checkExistingFile ... - */ - void clear(); - - /** - * Checks url of type() - * @return UrlError, None if no error has been found - * @note checkExisting is not done within this method - * @note both this method and checkUrls() will store all correct - * urls in correctUrls() and the others in errorUrls() and - * splitErrorUrls() - */ - UrlError addUrl(const KUrl &url); - - /** - * Does checkUrl for a list of urls. - * @return true if all urls are valid, false, if at least one url is invalid - * @note checkExisting is not done within this method - * @note both this method and checkUrl() will store all correct - * urls in correctUrls() and the others in errorUrls() and - * splitErrorUrls() - * @see addUrl - */ - bool addUrls(const KUrl::List &urls); - - /** - * Displays error messages for the collected urls if any are needed - */ - void displayErrorMessages(); - - /** - * Returns the correct urls collected with the last call to urlCollectErrors - * @see urlCollectErrors - */ - KUrl::List correctUrls() const; - - /** - * Checks all correctUrls() if there are existing Transfers - * for the specified UrlType and asks the user how to proceed. - * - * After this urls where the user decided that they should not be downloaded - * won't be in correctUrls anymore. - * @note UrlType folder is not supported, the result then is undefined! - * @return urls to download, after user interaction - * @see correctUrls errorUrls splitErrorUrls - */ - void existingTransfers(); - - /** - * Checks if the file at destination exists already, source needs to be defined - * to have a nice dialog and to make sure that both source and destination aren't - * the same - * @note This method does _not_ affect other methods like correctUrls or existingTransfers - * etc., though responses like overwrite all files are stored in case you call this method - * again you can clear that with clear. - * @return returns the destination to download the file to, if empty then the file - * should not be downloaded - * @see clear - */ - KUrl checkExistingFile(const KUrl &source, const KUrl &destination); - - /** - * Returns all wrong urls - * @note the oder of the urls is not guaranteed to be the same as it initially was - * @see urlCollectErrors splitErrorUrls existingTransfers - */ - KUrl::List errorUrls()const; - - /** - * Returns all wrong urls collected with the last call to urlCollectErrors - * or existingTransfers categorized by their errors - * @note urls without an error (UrlError == None) are not included - * @see urlCollectErrors correctUrls errorUrls existingTransfers - */ - QHash splitErrorUrls() const; - - private: - static TransferHandler *existingSource(const KUrl &url, UrlWarning &warning); - static TransferHandler *existingDestination(const KUrl &url, UrlWarning &warning); - static int hasExistingDialog(const KUrl &url, const UrlChecker::UrlType type, const UrlWarning warning);//TODO description --> returncode etc.! - static void removeTransfers(const QList &toRemove); - - enum ExistingDialogReturn { - Cancel = 0, - - //old stuff is overwritten/deleted - Yes, - YesAll, - - //new stuff is not used - No, - NoAll - }; - - private: - UrlType m_type; - KUrl::List m_correctUrls; - QHash m_splitErrorUrls; - - QHash > m_existingTransfers; - KUrl::List m_nonExistingUrls; - - //Existing files stuff - bool m_cancle; - bool m_overwriteAll; - bool m_autoRenameAll; - bool m_skipAll; -}; - - -#endif diff --git a/kget/core/urlchecker_p.h b/kget/core/urlchecker_p.h deleted file mode 100644 index 72bde7e5..00000000 --- a/kget/core/urlchecker_p.h +++ /dev/null @@ -1,47 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 URL_CHECKER_P_H -#define URL_CHECKER_P_H - -#include - -#include - -/** - * Asks if existing transfers should be overwritten - */ -class ExistingTransferDialog : public KDialog -{ - Q_OBJECT - - public: - ExistingTransferDialog(const QString &text, const QString &caption, QWidget *parent = 0); - - private slots: - void slotYesClicked(); - void slotNoClicked(); - void slotCancelClicked(); - - private: - QCheckBox *m_applyAll; -}; - -#endif - diff --git a/kget/core/verificationdelegate.cpp b/kget/core/verificationdelegate.cpp deleted file mode 100644 index f4b5993d..00000000 --- a/kget/core/verificationdelegate.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 "verificationdelegate.h" -#include "verifier.h" -#include "verificationmodel.h" - -#include -#include - -class VerificationDelegatePrivate -{ -public: - VerificationDelegatePrivate() - { - } - - ~VerificationDelegatePrivate() - { - } - - QStringList hashTypes; -}; - -VerificationDelegate::VerificationDelegate(QObject *parent) - : QStyledItemDelegate(parent), - d(new VerificationDelegatePrivate) -{ - d->hashTypes = Verifier::supportedVerficationTypes(); - d->hashTypes.sort(); -} - -QWidget *VerificationDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - - if (index.isValid()) { - if (index.column() == VerificationModel::Type) { - if (d->hashTypes.count()) { - KComboBox *hashTypes = new KComboBox(parent); - hashTypes->addItems(d->hashTypes); - - return hashTypes; - } - } else if (index.column() == VerificationModel::Checksum) { - return new KLineEdit(parent); - } - } - - return 0; -} - -void VerificationDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (index.isValid() && editor) { - if (index.column() == VerificationModel::Type) { - KComboBox *hashTypes = static_cast(editor); - const QString hashType = index.data().toString(); - hashTypes->setCurrentItem(hashType); - } else if (index.column() == VerificationModel::Checksum) { - KLineEdit *line = static_cast(editor); - const QString checksum = index.data().toString(); - line->setText(checksum); - } - } -} - -void VerificationDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (index.isValid() && editor && model) { - if (index.column() == VerificationModel::Type) { - KComboBox *hashTypes = static_cast(editor); - model->setData(index, hashTypes->currentText()); - } else if (index.column() == VerificationModel::Checksum) { - KLineEdit *line = static_cast(editor); - model->setData(index, line->text()); - } - } -} - -void VerificationDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(index) - editor->setGeometry(option.rect); -} - -QSize VerificationDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - //make the sizeHint a little bit nicer to have more beautiful editors - QSize hint; - hint.setWidth(QStyledItemDelegate::sizeHint(option, index).width()); - hint.setHeight(option.fontMetrics.height() + 7); - return hint; -} diff --git a/kget/core/verificationdelegate.h b/kget/core/verificationdelegate.h deleted file mode 100644 index 7b825865..00000000 --- a/kget/core/verificationdelegate.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 VERIFICATION_DELEGATE_H -#define VERIFICATION_DELEGATE_H - -#include "../kget_export.h" - -#include - -class KGET_EXPORT VerificationDelegate : public QStyledItemDelegate -{ - Q_OBJECT - - public: - VerificationDelegate(QObject *parent = 0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - - private: - class VerificationDelegatePrivate *d; - - friend class VerificationDelegatePrivate; -}; - -#endif diff --git a/kget/core/verificationmodel.cpp b/kget/core/verificationmodel.cpp deleted file mode 100644 index 75180b1f..00000000 --- a/kget/core/verificationmodel.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 "verificationmodel.h" -#include "verifier.h" - -#include - -#include -#include -#include - -class VerificationModelPrivate -{ -public: - VerificationModelPrivate() - { - } - - ~VerificationModelPrivate() - { - } - - QStringList types; - QStringList checksums; - QList verificationStatus; -}; - -VerificationModel::VerificationModel(QObject *parent) - : QAbstractTableModel(parent), - d(new VerificationModelPrivate) -{ -} - -QVariant VerificationModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) { - return QVariant(); - } - - if ((index.column() == VerificationModel::Type) && (role == Qt::DisplayRole)) { - return d->types.at(index.row()); - } else if ((index.column() == VerificationModel::Checksum) && (role == Qt::DisplayRole)) { - return d->checksums.at(index.row()); - } else if (index.column() == VerificationModel::Verified) { - const int status = d->verificationStatus.at(index.row()); - if (role == Qt::DecorationRole) { - switch (status) { - case Verifier::Verified: - return KIcon("dialog-ok"); - case Verifier::NotVerified: - return KIcon("dialog-close"); - case Verifier::NoResult: - default: - return KIcon(); - } - } else if (role == Qt::EditRole) { - return status; - } - } - - return QVariant(); -} - -Qt::ItemFlags VerificationModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) { - return 0; - } - - Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if (index.column() == VerificationModel::Type) - { - flags |= Qt::ItemIsEditable; - } - else if (index.column() == VerificationModel::Checksum) - { - flags |= Qt::ItemIsEditable; - } - - return flags; -} - -bool VerificationModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (!index.isValid() || index.row() >= d->types.count()) { - return false; - } - - if ((index.column() == VerificationModel::Type) && role == Qt::EditRole) { - const QString type = value.toString(); - if (Verifier::supportedVerficationTypes().contains(type) && !d->types.contains(type)) { - d->types[index.row()] = type; - emit dataChanged(index, index); - return true; - } - } else if ((index.column() == VerificationModel::Checksum) && role == Qt::EditRole) { - const QModelIndex typeIndex = index.sibling(index.row(), VerificationModel::Type); - const QString type = typeIndex.data().toString(); - const QString checksum = value.toString(); - if (Verifier::isChecksum(type, checksum)) { - d->checksums[index.row()] = checksum; - emit dataChanged(index, index); - return true; - } - } else if (index.column() == VerificationModel::Verified && role == Qt::EditRole) { - d->verificationStatus[index.row()] = value.toInt(); - emit dataChanged(index, index); - return true; - } - - return false; -} - -int VerificationModel::rowCount(const QModelIndex &parent) const -{ - Q_UNUSED(parent) - - return d->types.length(); -} - -int VerificationModel::columnCount(const QModelIndex &parent) const -{ - Q_UNUSED(parent) - - return 3; -} - -QVariant VerificationModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if ((orientation != Qt::Horizontal) || (role != Qt::DisplayRole)) { - return QVariant(); - } - - if (section == VerificationModel::Type) { - return i18nc("the type of the hash, e.g. MD5", "Type"); - } else if (section == VerificationModel::Checksum) { - return i18nc("the used hash for verification", "Hash"); - } else if (section == VerificationModel::Verified) { - return i18nc("verification-result of a file, can be true/false", "Verified"); - } - - return QVariant(); -} - -bool VerificationModel::removeRows(int row, int count, const QModelIndex &parent) -{ - if (parent.isValid() || (row < 0) || (count < 1) || (row + count > rowCount())) { - return false; - } - - beginRemoveRows(parent, row, row + count - 1); - while (count) { - d->types.removeAt(row); - d->checksums.removeAt(row); - d->verificationStatus.removeAt(row); - --count; - } - endRemoveRows(); - - return true; -} - -void VerificationModel::addChecksum(const QString &type, const QString &checksum, int verified) -{ - if (!Verifier::isChecksum(type, checksum)) { - kWarning() << "Could not add checksum.\nType:" << type << "\nChecksum:" << checksum; - return; - } - - //if the hashtype already exists in the model, then replace it - int position = d->types.indexOf(type); - if (position > -1) { - d->checksums[position] = checksum; - const QModelIndex index = this->index(position, VerificationModel::Checksum, QModelIndex()); - emit dataChanged(index, index); - return; - } - - int rows = rowCount(); - beginInsertRows(QModelIndex(), rows, rows); - d->types.append(type); - d->checksums.append(checksum.toLower()); - d->verificationStatus.append(verified); - endInsertRows(); -} - -void VerificationModel::addChecksums(const QHash &checksums) -{ - QHash::const_iterator it; - QHash::const_iterator itEnd = checksums.constEnd(); - for (it = checksums.constBegin(); it != itEnd; ++it) { - addChecksum(it.key(), it.value()); - } -} - -void VerificationModel::setVerificationStatus(const QString &type, int verified) -{ - const int position = d->types.indexOf(type); - if (position > -1) { - d->verificationStatus[position] = verified; - const QModelIndex index = this->index(position, VerificationModel::Verified, QModelIndex()); - emit dataChanged(index, index); - } -} diff --git a/kget/core/verificationmodel.h b/kget/core/verificationmodel.h deleted file mode 100644 index dcb782a1..00000000 --- a/kget/core/verificationmodel.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 VERIFICATION_MODEL_H -#define VERIFICATION_MODEL_H - -#include "../kget_export.h" - -#include - -class VerificationModelPrivate; - -class KGET_EXPORT VerificationModel : public QAbstractTableModel -{ - Q_OBJECT - - public: - VerificationModel(QObject *parent = 0); - - enum dataType - { - Type, - Checksum, - Verified - }; - - QVariant data(const QModelIndex &index, int role) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - - /** - * Add a checksum that is later used in the verification process - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param type the type of the checksum - * @param checksum the checksum - * @param verified if the file has been verified using this checksum - */ - void addChecksum(const QString &type, const QString &checksum, int verified = 0); - - /** - * Add multiple checksums that will later be used in the verification process - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param checksums - */ - void addChecksums(const QHash &checksums); - - /** - * Sets the verificationStatus for type - */ - void setVerificationStatus(const QString &type, int verified); - - private: - VerificationModelPrivate *d; - - friend class VerificationModelPrivate; -}; - -#endif diff --git a/kget/core/verificationthread.cpp b/kget/core/verificationthread.cpp deleted file mode 100644 index d8fcc562..00000000 --- a/kget/core/verificationthread.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 "verificationthread.h" -#include "verifier.h" - -#include - -#include - -VerificationThread::VerificationThread(QObject *parent) - : QThread(parent), - m_abort(false), - m_length(0), - m_type(Nothing) -{ -} - -VerificationThread::~VerificationThread() -{ - m_mutex.lock(); - m_abort = true; - m_mutex.unlock(); - - wait(); -} - -void VerificationThread::verifiy(const QString &type, const QString &checksum, const KUrl &file) -{ - QMutexLocker locker(&m_mutex); - m_types.append(type); - m_checksums.append(checksum); - m_files.append(file); - m_type = Verify; - - if (!isRunning()) - { - start(); - } -} - -void VerificationThread::findBrokenPieces(const QString &type, const QList checksums, KIO::filesize_t length, const KUrl &file) -{ - QMutexLocker locker(&m_mutex); - m_types.clear(); - m_types.append(type); - m_checksums = checksums; - m_files.clear(); - m_files.append(file); - m_length = length; - m_type = BrokenPieces; - - if (!isRunning()) - { - start(); - } -} - -void VerificationThread::run() -{ - if (m_type == Nothing) - { - return; - } - - if (m_type == Verify) - { - doVerify(); - } - else if (m_type == BrokenPieces) - { - doBrokenPieces(); - } -} - -void VerificationThread::doVerify() -{ - m_mutex.lock(); - bool run = m_files.count(); - m_mutex.unlock(); - - while (run && !m_abort) - { - m_mutex.lock(); - const QString type = m_types.takeFirst(); - const QString checksum = m_checksums.takeFirst(); - const KUrl url = m_files.takeFirst(); - m_mutex.unlock(); - - if (type.isEmpty() || checksum.isEmpty()) - { - m_mutex.lock(); - run = m_files.count(); - m_mutex.unlock(); - continue; - } - - const QString hash = Verifier::checksum(url, type); - kDebug() << "Type:" << type << "Calculated checksum:" << hash << "Entered checksum:" << checksum; - const bool fileVerified = (hash == checksum); - - m_mutex.lock(); - emit verified(type, fileVerified, url); - emit verified(fileVerified); - run = m_files.count(); - m_mutex.unlock(); - } -} - -void VerificationThread::doBrokenPieces() -{ - m_mutex.lock(); - const QString type = m_types.takeFirst(); - const QStringList checksums = m_checksums; - m_checksums.clear(); - const KUrl url = m_files.takeFirst(); - const KIO::filesize_t length = m_length; - m_mutex.unlock(); - - QList broken; - - if (QFile::exists(url.pathOrUrl())) - { - QFile file(url.pathOrUrl()); - if (!file.open(QIODevice::ReadOnly)) - { - emit brokenPieces(broken, length); - return; - } - - const KIO::filesize_t fileSize = file.size(); - if (!length || !fileSize) - { - emit brokenPieces(broken, length); - return; - } - - const QStringList fileChecksums = Verifier::partialChecksums(url, type, length).checksums(); - if (fileChecksums.size() != checksums.size()) - { - kDebug() << "Number of checksums differs!"; - emit brokenPieces(broken, length); - return; - } - - for (int i = 0; i < checksums.size(); ++i) - { - if (fileChecksums.at(i) != checksums.at(i)) - { - const int brokenStart = length * i; - kDebug() << url << "broken segment" << i << "start" << brokenStart << "length" << length; - broken.append(brokenStart); - } - } - } - - emit brokenPieces(broken, length); -} diff --git a/kget/core/verificationthread.h b/kget/core/verificationthread.h deleted file mode 100644 index d21cbf65..00000000 --- a/kget/core/verificationthread.h +++ /dev/null @@ -1,77 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 VERIFICATION_THREAD_H -#define VERIFICATION_THREAD_H - -#include -#include - -#include -#include - -class VerificationThread : public QThread -{ - Q_OBJECT - - public: - VerificationThread(QObject *parent = 0); - ~VerificationThread(); - - void verifiy(const QString &type, const QString &checksum, const KUrl &file); - - void findBrokenPieces(const QString &type, const QList checksums, KIO::filesize_t length, const KUrl &file); - - private: - enum WorkType - { - Nothing, - Verify, - BrokenPieces - }; - - void doVerify(); - void doBrokenPieces(); - - signals: - /** - * Emitted when the verification of a file finishes, connect to this signal - * if you do the verification for one file only and do not want to bother with - * file and type - */ - void verified(bool verified); - - void verified(const QString &type, bool verified, const KUrl &file); - - void brokenPieces(const QList &offsets, KIO::filesize_t length); - - protected: - void run(); - - private: - QMutex m_mutex; - bool m_abort; - QStringList m_types; - QStringList m_checksums; - QList m_files; - KIO::filesize_t m_length; - WorkType m_type; -}; - -#endif diff --git a/kget/core/verifier.cpp b/kget/core/verifier.cpp deleted file mode 100644 index 6376307b..00000000 --- a/kget/core/verifier.cpp +++ /dev/null @@ -1,592 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 "verifier_p.h" -#include "verificationmodel.h" -#include "../dbus/dbusverifierwrapper.h" -#include "verifieradaptor.h" -#include "settings.h" - -#include -#include -#include -#include - -#include - -//TODO use mutable to make some methods const? -const QStringList VerifierPrivate::SUPPORTED = (QStringList() << "sha512" << "sha256" << "sha1" << "md5"); -const QString VerifierPrivate::MD5 = QString("md5"); -const int VerifierPrivate::MD5LENGTH = 32; -const QString VerifierPrivate::SHA1 = QString("sha1"); -const int VerifierPrivate::SHA1LENGTH = 40; -const QString VerifierPrivate::SHA256 = QString("sha256"); -const int VerifierPrivate::SHA256LENGTH = 64; -const QString VerifierPrivate::SHA512 = QString("sha512"); -const int VerifierPrivate::SHA512LENGTH = 128; -const int VerifierPrivate::PARTSIZE = 500 * 1024; - -VerifierPrivate::~VerifierPrivate() -{ - delete model; - qDeleteAll(partialSums.begin(), partialSums.end()); -} - -QString VerifierPrivate::calculatePartialChecksum(QFile *file, const QString &type, KIO::fileoffset_t startOffset, int pieceLength, KIO::filesize_t fileSize) -{ - if (!file) - { - return QString(); - } - - if (!fileSize) - { - fileSize = file->size(); - } - //longer than the file, so adapt it - if (static_cast(fileSize) < startOffset + pieceLength) - { - pieceLength = fileSize - startOffset; - } - - if (type != MD5 && type != SHA1 && type != SHA256 && type != SHA512) { - return QString(); - } - - //we only read 512kb each time, to save RAM - int numData = pieceLength / PARTSIZE; - KIO::fileoffset_t dataRest = pieceLength % PARTSIZE; - - if (!numData && !dataRest) - { - return QString(); - } - - QCryptographicHash *hash = 0; - if (type == MD5) { - hash = new QCryptographicHash(QCryptographicHash::Md5); - } else if (type == SHA1) { - hash = new QCryptographicHash(QCryptographicHash::Sha1); - } else if (type == SHA256) { - hash = new QCryptographicHash(QCryptographicHash::Sha256); - } else if (type == SHA512) { - hash = new QCryptographicHash(QCryptographicHash::Sha512); - } - int k = 0; - for (k = 0; k < numData; ++k) - { - if (!file->seek(startOffset + PARTSIZE * k)) - { - return QString(); - } - - QByteArray data = file->read(PARTSIZE); - hash->addData(data); - } - - //now read the rest - if (dataRest) - { - if (!file->seek(startOffset + PARTSIZE * k)) - { - return QString(); - } - - QByteArray data = file->read(dataRest); - hash->addData(data); - } - - return QString(hash->result().toHex()); -} - -QStringList VerifierPrivate::orderChecksumTypes(Verifier::ChecksumStrength strength) const -{ - QStringList checksumTypes; - if (strength == Verifier::Weak) { - for (int i = SUPPORTED.count() - 1; i >= 0; --i) { - checksumTypes.append(SUPPORTED.at(i)); - } - } else if (strength == Verifier::Strong) { - for (int i = SUPPORTED.count() - 1; i >= 0; --i) { - checksumTypes.append(SUPPORTED.at(i)); - } - checksumTypes.move(0, checksumTypes.count() - 1); // md5 last position - } else if (strength == Verifier::Strongest) { - checksumTypes = SUPPORTED; - } - - return checksumTypes; -} - -Verifier::Verifier(const KUrl &dest, QObject *parent) - : QObject(parent), - d(new VerifierPrivate(this)) -{ - d->dest = dest; - d->status = NoResult; - - static int dBusObjIdx = 0; - d->dBusObjectPath = "/KGet/Verifiers/" + QString::number(dBusObjIdx++); - - DBusVerifierWrapper *wrapper = new DBusVerifierWrapper(this); - new VerifierAdaptor(wrapper); - QDBusConnection::sessionBus().registerObject(d->dBusObjectPath, wrapper); - - qRegisterMetaType("KIO::filesize_t"); - qRegisterMetaType("KIO::fileoffset_t"); - qRegisterMetaType >("QList"); - - d->model = new VerificationModel(); - connect(&d->thread, SIGNAL(verified(QString,bool,KUrl)), this, SLOT(changeStatus(QString,bool))); - connect(&d->thread, SIGNAL(brokenPieces(QList,KIO::filesize_t)), this, SIGNAL(brokenPieces(QList,KIO::filesize_t))); -} - -Verifier::~Verifier() -{ - delete d; -} - -QString Verifier::dBusObjectPath() const -{ - return d->dBusObjectPath; -} - -KUrl Verifier::destination() const -{ - return d->dest; -} - -void Verifier::setDestination(const KUrl &destination) -{ - d->dest = destination; -} - -Verifier::VerificationStatus Verifier::status() const -{ - return d->status; -} - -VerificationModel *Verifier::model() -{ - return d->model; -} - -QStringList Verifier::supportedVerficationTypes() -{ - QStringList supported; - if (!supported.contains(VerifierPrivate::MD5)) - { - supported << VerifierPrivate::MD5; - supported << VerifierPrivate::SHA1 << VerifierPrivate::SHA256; - supported << VerifierPrivate::SHA512; - } - - return supported; - -} - -int Verifier::diggestLength(const QString &type) -{ - if (type == VerifierPrivate::MD5) { - return VerifierPrivate::MD5LENGTH; - } else if (type == VerifierPrivate::SHA1) { - return VerifierPrivate::SHA1LENGTH; - } else if (type == VerifierPrivate::SHA256) { - return VerifierPrivate::SHA256LENGTH; - } else if (type == VerifierPrivate::SHA512) { - return VerifierPrivate::SHA512LENGTH; - } - - return 0; -} - -bool Verifier::isChecksum(const QString &type, const QString &checksum) -{ - const int length = diggestLength(type); - const QString pattern = QString("[0-9a-z]{%1}").arg(length); - //needs correct length and only word characters - if (length && (checksum.length() == length) && checksum.toLower().contains(QRegExp(pattern))) - { - return true; - } - - return false; -} - -QString Verifier::cleanChecksumType(const QString &type) -{ - QString hashType = type.toUpper(); - if (hashType.contains(QRegExp("^SHA\\d+"))) { - hashType.insert(3, '-'); - } - - return hashType; -} - -bool Verifier::isVerifyable() const -{ - return QFile::exists(d->dest.pathOrUrl()) && d->model->rowCount(); -} - -bool Verifier::isVerifyable(const QModelIndex &index) const -{ - int row = -1; - if (index.isValid()) - { - row = index.row(); - } - if (QFile::exists(d->dest.pathOrUrl()) && (row >= 0) && (row < d->model->rowCount())) - { - return true; - } - return false; -} - -Checksum Verifier::availableChecksum(Verifier::ChecksumStrength strength) const -{ - Checksum pair; - - //check if there is at least one entry - QModelIndex index = d->model->index(0, 0); - if (!index.isValid()) - { - return pair; - } - - const QStringList available = supportedVerficationTypes(); - const QStringList supported = d->orderChecksumTypes(strength); - for (int i = 0; i < supported.count(); ++i) { - QModelIndexList indexList = d->model->match(index, Qt::DisplayRole, supported.at(i)); - if (!indexList.isEmpty() && available.contains(supported.at(i))) { - QModelIndex match = d->model->index(indexList.first().row(), VerificationModel::Checksum); - pair.first = supported.at(i); - pair.second = match.data().toString(); - break; - } - } - - return pair; -} - -QList Verifier::availableChecksums() const -{ - QList checksums; - - for (int i = 0; i < d->model->rowCount(); ++i) { - const QString type = d->model->index(i, VerificationModel::Type).data().toString(); - const QString hash = d->model->index(i, VerificationModel::Checksum).data().toString(); - checksums << qMakePair(type, hash); - } - - return checksums; -} - -QPair Verifier::availablePartialChecksum(Verifier::ChecksumStrength strength) const -{ - QPair pair; - QString type; - PartialChecksums *checksum = 0; - - const QStringList available = supportedVerficationTypes(); - const QStringList supported = d->orderChecksumTypes(strength); - for (int i = 0; i < supported.size(); ++i) { - if (d->partialSums.contains(supported.at(i)) && available.contains(supported.at(i))) { - type = supported.at(i); - checksum = d->partialSums[type]; - break; - } - } - - return QPair(type, checksum); -} - -void Verifier::changeStatus(const QString &type, bool isVerified) -{ - kDebug() << "Verified:" << isVerified; - d->status = isVerified ? Verifier::Verified : Verifier::NotVerified; - d->model->setVerificationStatus(type, d->status); - emit verified(isVerified); -} - -void Verifier::verify(const QModelIndex &index) -{ - int row = -1; - if (index.isValid()) { - row = index.row(); - } - - QString type; - QString checksum; - - if (row == -1) { - Checksum pair = availableChecksum(static_cast(Settings::checksumStrength())); - type = pair.first; - checksum = pair.second; - } else if ((row >= 0) && (row < d->model->rowCount())) { - type = d->model->index(row, VerificationModel::Type).data().toString(); - checksum = d->model->index(row, VerificationModel::Checksum).data().toString(); - } - - d->thread.verifiy(type, checksum, d->dest); -} - -void Verifier::brokenPieces() const -{ - QPair pair = availablePartialChecksum(static_cast(Settings::checksumStrength())); - QList checksums; - KIO::filesize_t length = 0; - if (pair.second) { - checksums = pair.second->checksums(); - length = pair.second->length(); - } - d->thread.findBrokenPieces(pair.first, checksums, length, d->dest); -} - -QString Verifier::checksum(const KUrl &dest, const QString &type) -{ - QStringList supported = supportedVerficationTypes(); - if (!supported.contains(type)) { - return QString(); - } - - QFile file(dest.pathOrUrl()); - if (!file.open(QIODevice::ReadOnly)) { - return QString(); - } - - if (type == VerifierPrivate::MD5) { - QCryptographicHash hasher(QCryptographicHash::Md5); - hasher.addData(&file); - return hasher.result().toHex(); - } else if (type == VerifierPrivate::SHA1) { - QCryptographicHash hasher(QCryptographicHash::Sha1); - hasher.addData(&file); - return hasher.result().toHex(); - } else if (type == VerifierPrivate::SHA256) { - QCryptographicHash hasher(QCryptographicHash::Sha256); - hasher.addData(&file); - return hasher.result().toHex(); - } else if (type == VerifierPrivate::SHA512) { - QCryptographicHash hasher(QCryptographicHash::Sha512); - hasher.addData(&file); - return hasher.result().toHex(); - } - - return QString(); -} - -PartialChecksums Verifier::partialChecksums(const KUrl &dest, const QString &type, KIO::filesize_t length) -{ - QStringList checksums; - - QStringList supported = supportedVerficationTypes(); - if (!supported.contains(type)) - { - return PartialChecksums(); - } - - QFile file(dest.pathOrUrl()); - if (!file.open(QIODevice::ReadOnly)) - { - return PartialChecksums(); - } - - const KIO::filesize_t fileSize = file.size(); - if (!fileSize) - { - return PartialChecksums(); - } - - int numPieces = 0; - - //the piece length has been defined - if (length) - { - numPieces = fileSize / length; - } - else - { - length = VerifierPrivate::PARTSIZE; - numPieces = fileSize / length; - if (numPieces > 100) - { - numPieces = 100; - length = fileSize / numPieces; - } - } - - //there is a rest, so increase numPieces by one - if (fileSize % length) - { - ++numPieces; - } - - PartialChecksums partialChecksums; - - //create all the checksums for the pieces - for (int i = 0; i < numPieces; ++i) - { - QString hash = VerifierPrivate::calculatePartialChecksum(&file, type, length * i, length, fileSize); - if (hash.isEmpty()) - { - file.close(); - return PartialChecksums(); - } - checksums.append(hash); - } - - partialChecksums.setLength(length); - partialChecksums.setChecksums(checksums); - file.close(); - return partialChecksums; -} - -void Verifier::addChecksum(const QString &type, const QString &checksum, int verified) -{ - d->model->addChecksum(type, checksum, verified); -} - -void Verifier::addChecksums(const QHash &checksums) -{ - d->model->addChecksums(checksums); -} - -void Verifier::addPartialChecksums(const QString &type, KIO::filesize_t length, const QStringList &checksums) -{ - if (!d->partialSums.contains(type) && length && !checksums.isEmpty()) - { - d->partialSums[type] = new PartialChecksums(length, checksums); - } -} - -KIO::filesize_t Verifier::partialChunkLength() const -{ - QStringList::const_iterator it; - QStringList::const_iterator itEnd = VerifierPrivate::SUPPORTED.constEnd(); - for (it = VerifierPrivate::SUPPORTED.constBegin(); it != itEnd; ++it) - { - if (d->partialSums.contains(*it)) - { - return d->partialSums[*it]->length(); - } - } - - return 0; -} - -void Verifier::save(const QDomElement &element) -{ - QDomElement e = element; - e.setAttribute("verificationStatus", d->status); - - QDomElement verification = e.ownerDocument().createElement("verification"); - for (int i = 0; i < d->model->rowCount(); ++i) - { - QDomElement hash = e.ownerDocument().createElement("hash"); - hash.setAttribute("type", d->model->index(i, VerificationModel::Type).data().toString()); - hash.setAttribute("verified", d->model->index(i, VerificationModel::Verified).data(Qt::EditRole).toInt()); - QDomText value = e.ownerDocument().createTextNode(d->model->index(i, VerificationModel::Checksum).data().toString()); - hash.appendChild(value); - verification.appendChild(hash); - } - - QHash::const_iterator it; - QHash::const_iterator itEnd = d->partialSums.constEnd(); - for (it = d->partialSums.constBegin(); it != itEnd; ++it) - { - QDomElement pieces = e.ownerDocument().createElement("pieces"); - pieces.setAttribute("type", it.key()); - pieces.setAttribute("length", (*it)->length()); - QList checksums = (*it)->checksums(); - for (int i = 0; i < checksums.size(); ++i) - { - QDomElement hash = e.ownerDocument().createElement("hash"); - hash.setAttribute("piece", i); - QDomText value = e.ownerDocument().createTextNode(checksums[i]); - hash.appendChild(value); - pieces.appendChild(hash); - } - verification.appendChild(pieces); - } - e.appendChild(verification); -} - -void Verifier::load(const QDomElement &e) -{ - if (e.hasAttribute("verificationStatus")) - { - const int status = e.attribute("verificationStatus").toInt(); - switch (status) - { - case NoResult: - d->status = NoResult; - break; - case NotVerified: - d->status = NotVerified; - break; - case Verified: - d->status = Verified; - break; - default: - d->status = NotVerified; - break; - } - } - - QDomElement verification = e.firstChildElement("verification"); - QDomNodeList const hashList = verification.elementsByTagName("hash"); - - for (uint i = 0; i < hashList.length(); ++i) - { - const QDomElement hash = hashList.item(i).toElement(); - const QString value = hash.text(); - const QString type = hash.attribute("type"); - const int verificationStatus = hash.attribute("verified").toInt(); - if (!type.isEmpty() && !value.isEmpty()) - { - d->model->addChecksum(type, value, verificationStatus); - } - } - - QDomNodeList const piecesList = verification.elementsByTagName("pieces"); - - for (uint i = 0; i < piecesList.length(); ++i) - { - QDomElement pieces = piecesList.at(i).toElement(); - - const QString type = pieces.attribute("type"); - const KIO::filesize_t length = pieces.attribute("length").toULongLong(); - QStringList partialChecksums; - - const QDomNodeList partialHashList = pieces.elementsByTagName("hash"); - for (int i = 0; i < partialHashList.size(); ++i)//TODO give this function the size of the file, to calculate how many hashs are needed as an additional check, do that check in addPartialChecksums?! - { - const QString hash = partialHashList.at(i).toElement().text(); - if (hash.isEmpty()) - { - break; - } - partialChecksums.append(hash); - } - - addPartialChecksums(type, length, partialChecksums); - } -} - -#include "moc_verifier.cpp" diff --git a/kget/core/verifier.h b/kget/core/verifier.h deleted file mode 100644 index 9fdd1324..00000000 --- a/kget/core/verifier.h +++ /dev/null @@ -1,261 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 VERIFIER_H -#define VERIFIER_H - -#include -#include - -#include -#include -#include - -#include "../kget_export.h" - -#include -#include -class TransferHandler; -class VerificationModel; -class VerifierPrivate; -typedef QPair Checksum; - - -class KGET_EXPORT PartialChecksums -{ - public: - PartialChecksums() - : m_length(0) - { - } - - PartialChecksums(KIO::filesize_t len, const QStringList &sums) - : m_length(len), m_checksums(sums) - { - } - - bool isValid() const {return (length() && m_checksums.count());} - - KIO::filesize_t length() const {return m_length;} - void setLength(KIO::filesize_t length) {m_length = length;} - - QStringList checksums() const {return m_checksums;} - void setChecksums(const QStringList &checksums) {m_checksums = checksums;} - - private: - KIO::filesize_t m_length; - QStringList m_checksums; -}; - -Q_DECLARE_METATYPE(PartialChecksums) - -class KGET_EXPORT Verifier : public QObject -{ - Q_OBJECT - - public: - explicit Verifier(const KUrl &dest, QObject *parent = 0); - ~Verifier(); - - enum VerificationStatus - { - NoResult, //either not tried, or not enough information - NotVerified, - Verified - }; - - enum ChecksumStrength - { - Weak, - Strong, - Strongest - }; - - /** - * @returns the object path that will be shown in the DBUS interface - */ - QString dBusObjectPath() const; - - KUrl destination() const; - void setDestination(const KUrl &destination);//TODO handle the case when m_thread is working, while the file gets moved - - VerificationStatus status() const; - - /** - * Returns the supported verification types - * @return the supported verification types (e.g. MD5, SHA1 ...) - */ - static QStringList supportedVerficationTypes(); - - /** - * Returns the diggest length of type - * @param type the checksum type for which to get the diggest length - * @return the length the diggest should have - */ - static int diggestLength(const QString &type); - - /** - * Tries to check if the checksum is a checksum and if it is supported - * it compares the diggestLength and checks if there are only alphanumerics in checksum - * @param type of the checksum - * @param checksum the checksum you want to check - */ - static bool isChecksum(const QString &type, const QString &checksum); - - /** - * Cleans the checksum type, that it should match the official name, i.e. upper case - * e.g. SHA-1 instead of sha1 - */ - static QString cleanChecksumType(const QString &type); - - /** - * Creates the checksum type of the file dest - */ - static QString checksum(const KUrl &dest, const QString &type); - - /** - * Create partial checksums of type for file dest - * @note the length of the partial checksum (if not defined = 0) is not less than 512 kb - * and there won't be more partial checksums than 101 - */ - static PartialChecksums partialChecksums(const KUrl &dest, const QString &type, KIO::filesize_t length = 0); - - /** - * @note only call verify() when this function returns true - * @return true if the downloaded file exists and a supported checksum is set - */ - bool isVerifyable() const; - - /** - * Convenience function if only a row of the model should be checked - * @note only call verify() when this function returns true - * @param row the row in the model of the checksum - * @return true if the downloaded file exists and a supported checksum is set - */ - bool isVerifyable(const QModelIndex &index) const; - - /** - * Call this method if you want to verify() in its own thread, then signals with - * the result are emitted - * @param row of the model should be checked, if not defined the a checkum defined by - * Verifier::ChecksumStrength will be used - */ - void verify(const QModelIndex &index = QModelIndex()); - - /** - * Call this method after calling verify() with a negative result, it will - * emit a list of the broken pieces, if PartialChecksums were defined, - * otherwise and in case of any error an empty list will be emitted - */ - void brokenPieces() const; - - /** - * Add a checksum that is later used in the verification process - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param type the type of the checksum - * @param checksum the checksum - * @param verified if the file has been verified using this checksum - * @note uses VerificationModel internally - * @see VerificationModel - */ - void addChecksum(const QString &type, const QString &checksum, int verified = 0); - - /** - * Add multiple checksums that will later be used in the verification process - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param checksums - * @note uses VerificationModel internally - * @see VerificationModel - */ - void addChecksums(const QHash &checksums); - - /** - * Add partial checksums that can be used as repairinformation - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param type the type of the checksums - * @param length the length of each piece - * @param checksums the checksums, first entry is piece number 0 - */ - void addPartialChecksums(const QString &type, KIO::filesize_t length, const QStringList &checksums); - - /** - * Returns the length of the "best" partialChecksums - */ - KIO::filesize_t partialChunkLength() const; - - /** - * Returns a checksum and a type - * @param strength the strength the checksum-type should have; - * weak is md5 > ... (md5 preferred), strong is sha1 > - * sha256 > sha384 > sha512 (sha1 preferred), strongest is sha512 > - * sha384 > sha256 ... < (sha512 preferred) - * If the category does not match then any checksum is taken - */ - Checksum availableChecksum(ChecksumStrength strength) const; - - /** - * Returns all set checksums - */ - QList availableChecksums() const; - - /** - * Returns a PartialChecksum and a type - * @param strength the strength the checksum-type should have; - * weak is md5 > ... (md5 preferred), strong is sha1 > - * sha256 > sha384 > sha512 > ... (sha1 preferred), strongest is sha512 > - * sha384 > sha256 ... (sha512 preferred) - * If the category does not match then any checksum is taken - */ - QPair availablePartialChecksum(Verifier::ChecksumStrength strength) const; - - /** - * @return the model that stores the hash-types and checksums - */ - VerificationModel *model(); - - void save(const QDomElement &element); - void load(const QDomElement &e); - - signals: - /** - * Emitted when the verification of a file finishes - */ - void verified(bool verified); - - /** - * Emitted when brokenPiecesThreaded finishes, the list can be empty, while length will be always set - */ - void brokenPieces(const QList &offsets, KIO::filesize_t length); - - private slots: - void changeStatus(const QString &type, bool verified); - - private: - VerifierPrivate *const d; - - friend class VerifierPrivate; -}; - -#endif //VERIFIER_H diff --git a/kget/core/verifier_p.h b/kget/core/verifier_p.h deleted file mode 100644 index 6a1df051..00000000 --- a/kget/core/verifier_p.h +++ /dev/null @@ -1,67 +0,0 @@ -/************************************************************************** -* Copyright (C) 2009-2011 Matthias Fuchs * -* * -* 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 VERIFIER_P_H -#define VERIFIER_P_H - -class PartialChecksums; -class Verifier; - -#include "verifier.h" -#include "verificationthread.h" - -class VerifierPrivate -{ -public: - VerifierPrivate(Verifier *verifier) - : q(verifier), - model(0) - { - } - - ~VerifierPrivate(); - - static QString calculatePartialChecksum(QFile *file, const QString &type, KIO::fileoffset_t startOffset, int pieceLength, KIO::filesize_t fileSize = 0); - QStringList orderChecksumTypes(Verifier::ChecksumStrength strength) const; - - - Verifier *q; - - QString dBusObjectPath; - VerificationModel *model; - KUrl dest; - Verifier::VerificationStatus status; - - QHash partialSums; - - mutable VerificationThread thread; - - static const QStringList SUPPORTED; - static const QString MD5; - static const int MD5LENGTH; - static const QString SHA1; - static const int SHA1LENGTH; - static const QString SHA256; - static const int SHA256LENGTH; - static const QString SHA512; - static const int SHA512LENGTH; - static const int PARTSIZE; -}; - -#endif diff --git a/kget/dbus/dbuskgetwrapper.cpp b/kget/dbus/dbuskgetwrapper.cpp deleted file mode 100644 index fac79983..00000000 --- a/kget/dbus/dbuskgetwrapper.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/************************************************************************** -* Copyright (C) 2006 - 2008 Urs Wolfer * -* Copyright (C) 2006 Dario Massarin * -* Copyright (C) 2008 - 2009 Lukas Appelhans * -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "dbuskgetwrapper.h" - -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfertreemodel.h" -#include "core/plugin/transferfactory.h" -#include "mainwindow.h" -#include "settings.h" -#include "ui/droptarget.h" -#include "ui/linkview/kget_linkview.h" -#include "ui/newtransferdialog.h" - -#include - -DBusKGetWrapper::DBusKGetWrapper(MainWindow *parent) - : QObject(parent), - m_mainWindow(parent) -{ - foreach (TransferHandler *handler, KGet::allTransfers()) { - m_transfers[handler] = qMakePair(handler->source().pathOrUrl(), handler->dBusObjectPath()); - } - - TransferTreeModel *model = KGet::model(); - - connect(model, SIGNAL(transfersAddedEvent(QList)), this, SLOT(slotTransfersAdded(QList))); - connect(model, SIGNAL(transfersRemovedEvent(QList)), this, SLOT(slotTransfersRemoved(QList))); -} - -DBusKGetWrapper::~DBusKGetWrapper() -{ -} - -QStringList DBusKGetWrapper::addTransfer(const QString& src, const QString& dest, bool start) -{ - QStringList dBusPaths; - - - // split src for the case it is a QStringList (e.g. from konqueror plugin) - QList addedTransfers = KGet::addTransfer(src.split(';'), dest, QString(), start); - - foreach (TransferHandler *handler, addedTransfers) { - dBusPaths.append(handler->dBusObjectPath()); - } - - return dBusPaths; -} - -bool DBusKGetWrapper::delTransfer(const QString& dbusObjectPath) -{ - kDebug() << "deleting Transfer"; - - Transfer *transfer = KGet::model()->findTransferByDBusObjectPath(dbusObjectPath); - - if (transfer) { - return KGet::delTransfer(transfer->handler()); - } - - return false; -} - -void DBusKGetWrapper::showNewTransferDialog(const QStringList &urls) -{ - NewTransferDialogHandler::showNewTransferDialog(urls); -} - -bool DBusKGetWrapper::dropTargetVisible() const -{ - return m_mainWindow->m_drop->isVisible(); -} - -void DBusKGetWrapper::setDropTargetVisible(bool setVisible) -{ - if (setVisible != Settings::showDropTarget()) { - m_mainWindow->m_drop->setDropTargetVisible(setVisible); - } -} - -void DBusKGetWrapper::setOfflineMode(bool offline) -{ - KGet::setSchedulerRunning(offline); -} - -bool DBusKGetWrapper::offlineMode() const -{ - return !KGet::schedulerRunning(); -} - -QVariantMap DBusKGetWrapper::transfers() const -{ - const QList > transfers = m_transfers.values(); - QVariantMap result; - for (int i = 0; i < transfers.count(); ++i) { - result.insert(transfers[i].first, transfers[i].second); - } - - return result; -} - -void DBusKGetWrapper::slotTransfersAdded(const QList &transfers) -{ - QStringList urls; - QStringList objectPaths; - foreach (TransferHandler *transfer, transfers) { - const QString url = transfer->source().pathOrUrl(); - const QString objectPath = transfer->dBusObjectPath(); - urls << url; - objectPaths << objectPath; - m_transfers[transfer] = qMakePair(url, objectPath); - } - - emit transfersAdded(urls, objectPaths); -} - -void DBusKGetWrapper::slotTransfersRemoved(const QList &transfers) -{ - QStringList urls; - QStringList objectPaths; - foreach (TransferHandler *transfer, transfers) { - const QPair removed = m_transfers[transfer]; - urls << removed.first; - objectPaths << removed.second; - } - - emit transfersRemoved(urls, objectPaths); -} - -void DBusKGetWrapper::importLinks(const QList &links) -{ - KGetLinkView *link_view = new KGetLinkView(m_mainWindow); - link_view->setLinks(links); - link_view->show(); -} - -bool DBusKGetWrapper::isSupported(const QString &url) const -{ - foreach (TransferFactory * factory, KGet::factories()) { - kDebug() << "Check" << factory->objectName() << "for" << url << "it is?" << factory->isSupported(KUrl(url)); - if (factory->isSupported(KUrl(url))) - return true; - } - return false; -} - -#include "moc_dbuskgetwrapper.cpp" diff --git a/kget/dbus/dbuskgetwrapper.h b/kget/dbus/dbuskgetwrapper.h deleted file mode 100644 index 41eb74f9..00000000 --- a/kget/dbus/dbuskgetwrapper.h +++ /dev/null @@ -1,65 +0,0 @@ -/************************************************************************** -* Copyright (C) 2006 - 2008 Urs Wolfer * -* Copyright (C) 2006 Dario Massarin * -* Copyright (C) 2008 - 2009 Lukas Appelhans * -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 DBUSKGETWRAPPER -#define DBUSKGETWRAPPER - -#include -#include - -class MainWindow; -class TransferHandler; - -class DBusKGetWrapper : public QObject -{ - Q_OBJECT - - public: - DBusKGetWrapper(MainWindow *parent); - ~DBusKGetWrapper(); - - QStringList addTransfer(const QString& src, const QString& destDir = QString(), bool start = false); - bool delTransfer(const QString& dbusObjectPath); - void showNewTransferDialog(const QStringList &urls); - bool dropTargetVisible() const; - void setDropTargetVisible(bool setVisible); - void setOfflineMode(bool online); - bool offlineMode() const; - QVariantMap transfers() const; - void importLinks(const QList &links); - bool isSupported(const QString &url) const; - - signals: - void transferAddedRemoved(); - void transfersAdded(const QStringList &urls, const QStringList &dBusObjectPaths); - void transfersRemoved(const QStringList &urls, const QStringList &dbusObjectPaths); - - private slots: - void slotTransfersAdded(const QList &transfers); - void slotTransfersRemoved(const QList &transfers); - - private: - MainWindow *m_mainWindow; - QHash > m_transfers; -}; - -#endif diff --git a/kget/dbus/dbustransferwrapper.cpp b/kget/dbus/dbustransferwrapper.cpp deleted file mode 100644 index 29859916..00000000 --- a/kget/dbus/dbustransferwrapper.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ -#include "dbustransferwrapper.h" -#include "transfergrouphandler.h" -#include "verifier.h" - -DBusTransferWrapper::DBusTransferWrapper(TransferHandler *parent) - : QObject(parent), - m_transfer(parent) -{ - connect(m_transfer, SIGNAL(transferChangedEvent(TransferHandler*,TransferHandler::ChangesFlags)), this, SLOT(slotTransferChanged(TransferHandler*,TransferHandler::ChangesFlags))); - connect(m_transfer, SIGNAL(capabilitiesChanged()), this, SIGNAL(capabilitiesChanged())); -} - -DBusTransferWrapper::~DBusTransferWrapper() -{ -} - -int DBusTransferWrapper::capabilities() const -{ - return m_transfer->capabilities(); -} - -void DBusTransferWrapper::start() -{ - m_transfer->start(); -} - -void DBusTransferWrapper::stop() -{ - m_transfer->stop(); -} - -int DBusTransferWrapper::status() const -{ - return (int)m_transfer->status(); -} - -int DBusTransferWrapper::elapsedTime() const -{ - return m_transfer->elapsedTime(); -} - -int DBusTransferWrapper::remainingTime() const -{ - return m_transfer->remainingTime(); -} - -QString DBusTransferWrapper::groupName() const -{ - return m_transfer->group()->name(); -} - -QString DBusTransferWrapper::source() const -{ - return m_transfer->source().pathOrUrl(); -} - -QString DBusTransferWrapper::dest() const -{ - return m_transfer->dest().pathOrUrl(); -} - -bool DBusTransferWrapper::setDirectory(const QString &directory) -{ - return m_transfer->setDirectory(KUrl(directory)); -} - -qulonglong DBusTransferWrapper::totalSize() const -{ - return m_transfer->totalSize(); -} - -qulonglong DBusTransferWrapper::downloadedSize() const -{ - return m_transfer->downloadedSize(); -} - -qulonglong DBusTransferWrapper::uploadedSize() const -{ - return m_transfer->uploadedSize(); -} - -int DBusTransferWrapper::percent() const -{ - return m_transfer->percent(); -} - -int DBusTransferWrapper::downloadSpeed() const -{ - return m_transfer->downloadSpeed(); -} - -int DBusTransferWrapper::uploadSpeed() const -{ - return m_transfer->uploadSpeed(); -} - -void DBusTransferWrapper::setUploadLimit(int ulLimit, int limit) -{ - m_transfer->setUploadLimit(ulLimit, (Transfer::SpeedLimit)limit); -} - -void DBusTransferWrapper::setDownloadLimit(int dlLimit, int limit) -{ - m_transfer->setDownloadLimit(dlLimit, (Transfer::SpeedLimit)limit); -} - -int DBusTransferWrapper::uploadLimit(int limit) const -{ - return m_transfer->uploadLimit((Transfer::SpeedLimit)limit); -} - -int DBusTransferWrapper::downloadLimit(int limit) const -{ - return m_transfer->downloadLimit((Transfer::SpeedLimit)limit); -} - -void DBusTransferWrapper::setMaximumShareRatio(double ratio) -{ - m_transfer->setMaximumShareRatio(ratio); -} - -double DBusTransferWrapper::maximumShareRatio() -{ - return m_transfer->maximumShareRatio(); -} - -QString DBusTransferWrapper::statusText() const -{ - return m_transfer->statusText(); -} - -QDBusVariant DBusTransferWrapper::statusPixmap() const -{ - return QDBusVariant(QVariant::fromValue(m_transfer->statusPixmap())); -} - -void DBusTransferWrapper::slotTransferChanged(TransferHandler *transfer, TransferHandler::ChangesFlags changeFlags) -{ - Q_UNUSED(transfer) - - emit transferChangedEvent(changeFlags); -} - -QString DBusTransferWrapper::verifier(const QString &file) -{ - Verifier *verifier = m_transfer->verifier(KUrl(file)); - if (verifier) { - return verifier->dBusObjectPath(); - } - - return QString(); -} - -bool DBusTransferWrapper::repair(const QString &file) -{ - return m_transfer->repair(KUrl(file)); - -} - -#include "moc_dbustransferwrapper.cpp" diff --git a/kget/dbus/dbustransferwrapper.h b/kget/dbus/dbustransferwrapper.h deleted file mode 100644 index 0561d4d7..00000000 --- a/kget/dbus/dbustransferwrapper.h +++ /dev/null @@ -1,164 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ -#ifndef DBUSTRANSFERWRAPPER_H -#define DBUSTRANSFERWRAPPER_H - -#include "core/transferhandler.h" - -#include - -class TransferHandler; - -class DBusTransferWrapper : public QObject -{ - Q_OBJECT - public: - DBusTransferWrapper(TransferHandler * parent); - ~DBusTransferWrapper(); - - public slots: - int capabilities() const; - void start(); - void stop(); - int status() const; - int elapsedTime() const; - int remainingTime() const; - - /** - * @return the transfer's group's name - */ - QString groupName() const; - - /** - * @return the source url - */ - QString source() const; - - /** - * @return the dest url - */ - QString dest() const; - - /** - * Move the download to the new destination - * @param newDirectory is a directory where the download should be stored - * @returns true if newDestination can be used - */ - bool setDirectory(const QString &directory); - - /** - * @return the total size of the transfer in bytes - */ - qulonglong totalSize() const; - - /** - * @return the downloaded size of the transfer in bytes - */ - qulonglong downloadedSize() const; - - /** - * @return the uploaded size of the transfer in bytes - */ - qulonglong uploadedSize() const; - - /** - * @return the progress percentage of the transfer - */ - int percent() const; - - /** - * @return the download speed of the transfer in bytes/sec - */ - int downloadSpeed() const; - - /** - * @return the upload speed of the transfer in bytes/sec - */ - int uploadSpeed() const; - - /** - * Set an UploadLimit for the transfer - * @note this UploadLimit is not visible in the GUI - * @param ulLimit upload Limit - */ - void setUploadLimit(int ulLimit, int limit); - - /** - * Set a DownloadLimit for the transfer - * @note this DownloadLimit is not visible in the GUI - * @param dlLimit download Limit - */ - void setDownloadLimit(int dlLimit, int limit); - - /** - * @return the upload Limit of the transfer in KiB - */ - int uploadLimit(int limit) const; - - /** - * @return the download Limit of the transfer in KiB - */ - int downloadLimit(int limit) const; - - /** - * Set the maximum share-ratio - * @param ratio the new maximum share-ratio - */ - void setMaximumShareRatio(double ratio); - - /** - * @return the maximum share-ratio - */ - double maximumShareRatio(); - - /** - * @return a string describing the current transfer status - */ - QString statusText() const; - - /** - * @return a pixmap associated with the current transfer status - */ - QDBusVariant statusPixmap() const; - - /** - * Returns the dBusObjectPath to the verifier - * @param file for wich to return the verifier - */ - QString verifier(const QString &file); - - /** - * Tries to repair file - * @param file the file of a download that should be repaired, - * if not defined all files of a download are going to be repaird - * @return true if a repair started, false if it was not nescessary - */ - bool repair(const QString &file); - - signals: - /** - * Emitted when the transfer changes - */ - void transferChangedEvent(int transferChange); - - /** - * Emitted whe the capabilities of the transfer changes - */ - void capabilitiesChanged(); - - private slots: - void slotTransferChanged(TransferHandler *transfer, TransferHandler::ChangesFlags changeflags); - - private: - TransferHandler *m_transfer; -}; - -#endif diff --git a/kget/dbus/dbusverifierwrapper.cpp b/kget/dbus/dbusverifierwrapper.cpp deleted file mode 100644 index 5172bc30..00000000 --- a/kget/dbus/dbusverifierwrapper.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 "dbusverifierwrapper.h" -#include "core/verifier.h" -#include "core/verificationmodel.h" - -DBusVerifierWrapper::DBusVerifierWrapper(Verifier *verifier) - : QObject(verifier), - m_verifier(verifier) -{ - connect(m_verifier, SIGNAL(brokenPieces(QList,KIO::filesize_t)), this, SLOT(slotBrokenPieces(QList,KIO::filesize_t))); - connect(m_verifier, SIGNAL(verified(bool)), this, SIGNAL(verified(bool))); -} - -DBusVerifierWrapper::~DBusVerifierWrapper() -{ -} - -QString DBusVerifierWrapper::destination() const -{ - return m_verifier->destination().pathOrUrl(); -} - -void DBusVerifierWrapper::addChecksum(const QString &type, const QString &hash) -{ - m_verifier->model()->addChecksum(type, hash); -} - -void DBusVerifierWrapper::addPartialChecksums(const QString &type, qulonglong length, const QStringList &checksums) -{ - m_verifier->addPartialChecksums(type, length, checksums); -} - -bool DBusVerifierWrapper::isVerifyable() const -{ - return m_verifier->isVerifyable(); -} - -void DBusVerifierWrapper::verify() -{ - m_verifier->verify(); -} - -void DBusVerifierWrapper::brokenPieces() const -{ - m_verifier->brokenPieces(); -} - -void DBusVerifierWrapper::slotBrokenPieces(const QList &offsets, KIO::filesize_t length) -{ - //FIXME seems to work correct though is not correctly received at TestTransfers or maybe wrong converted -// QList broken; -// for (int i = 0; i < brokenPieces.count(); ++i) { -// broken << brokenPieces[i]; -// } -// -// QDBusVariant dbusBroken; -// dbusBroken.setVariant(QVariant(broken)); -// emit this->brokenPieces(dbusBroken); - - QStringList broken; - for (int i = 0; i < offsets.count(); ++i) { - broken << QString::number(offsets[i]); - } - - emit brokenPieces(broken, length); -} - - -#include "moc_dbusverifierwrapper.cpp" diff --git a/kget/dbus/dbusverifierwrapper.h b/kget/dbus/dbusverifierwrapper.h deleted file mode 100644 index acb41857..00000000 --- a/kget/dbus/dbusverifierwrapper.h +++ /dev/null @@ -1,88 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2010 Matthias Fuchs * -* * -* 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 DBUSVERIFIERWRAPPER_H -#define DBUSVERIFIERWRAPPER_H - -#include -#include - -class Verifier; - -class DBusVerifierWrapper : public QObject -{ - Q_OBJECT - public: - DBusVerifierWrapper(Verifier *parent); - ~DBusVerifierWrapper(); - - public slots: - /** - * @return the dest url - */ - QString destination() const; - - /** - * Adds a checksum to the transfer - */ - void addChecksum(const QString &type, const QString &hash); - - /** - * Add partial checksums that can be used as repairinformation - * @note only one checksum per type can be added (one MD5, one SHA1 etc.), - * the newer overwrites the older and a checksum can only be added if it is - * supported by the verifier - * @param type the type of the checksums - * @param length the length of each piece - * @param checksums the checksums, first entry is piece number 0 - */ - void addPartialChecksums(const QString &type, qulonglong length, const QStringList &checksums); - - bool isVerifyable() const; - - void verify(); - - /** - * Call this method after calling verify() with a negative result, it will - * emit a list of the broken pieces, if PartialChecksums were defined, - * otherwise and in case of any error an empty list will be emitted - */ - void brokenPieces() const; - - signals: - /** - * Emitted when the verification of a file finishes - */ - void verified(bool verified); - - /** - * Emitted when brokenPiecesThreaded finishes, the list can be empty - * @param offsets of the broken pieces, they are the beginning - * @param length of broken pieces - */ - void brokenPieces(const QStringList &offsets, qulonglong length); - - private slots: - void slotBrokenPieces(const QList &offsets, KIO::filesize_t length); - - private: - Verifier *m_verifier; -}; - -#endif diff --git a/kget/dbus/org.kde.kget.main.xml b/kget/dbus/org.kde.kget.main.xml deleted file mode 100644 index 17d6e31c..00000000 --- a/kget/dbus/org.kde.kget.main.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kget/dbus/org.kde.kget.transfer.xml b/kget/dbus/org.kde.kget.transfer.xml deleted file mode 100644 index b850e35c..00000000 --- a/kget/dbus/org.kde.kget.transfer.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kget/dbus/org.kde.kget.verifier.xml b/kget/dbus/org.kde.kget.verifier.xml deleted file mode 100644 index f335de37..00000000 --- a/kget/dbus/org.kde.kget.verifier.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kget/desktop/CMakeLists.txt b/kget/desktop/CMakeLists.txt deleted file mode 100644 index 19a4ccdb..00000000 --- a/kget/desktop/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -# associate KGet with the correct mimetypes -configure_file(kget.desktop.cmake ${CMAKE_CURRENT_BINARY_DIR}/kget.desktop) - -install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/kget.desktop DESTINATION ${KDE4_XDG_APPS_INSTALL_DIR}) -install(FILES kget_download.desktop DESTINATION -${KDE4_SERVICES_INSTALL_DIR}/ServiceMenus) - -# For DBus activation: -kde4_add_dbus_service(org.kde.kget.service.in) diff --git a/kget/desktop/kget.desktop.cmake b/kget/desktop/kget.desktop.cmake deleted file mode 100755 index c9cd0f25..00000000 --- a/kget/desktop/kget.desktop.cmake +++ /dev/null @@ -1,162 +0,0 @@ -# KDE Config File -[Desktop Entry] -Type=Application -Exec=kget --icon '%i' --caption '%c' %U -Icon=kget -Terminal=false -MimeType=@SUPPORTED_KGET_MIMETYPES@ -Name=KGet -Name[ar]=KGet -Name[ast]=KGet -Name[be]=KGet -Name[bg]=KGet -Name[bn]=কে-গেট -Name[br]=KGet -Name[bs]=KGet -Name[ca]=KGet -Name[ca@valencia]=KGet -Name[cs]=KGet -Name[cy]=KNôl -Name[da]=KGet -Name[de]=KGet -Name[el]=KGet -Name[en_GB]=KGet -Name[eo]=KGet -Name[es]=KGet -Name[et]=KGet -Name[eu]=KGet -Name[fi]=KGet -Name[fr]=KGet -Name[ga]=KGet -Name[gl]=KGet -Name[he]=KGet -Name[hi]=के-गेट -Name[hne]=के-गेट -Name[hr]=KGet -Name[hu]=KGet -Name[ia]=KGet -Name[is]=KGet -Name[it]=KGet -Name[ja]=KGet -Name[kk]=KGet -Name[km]=KGet -Name[ko]=KGet -Name[lt]=KGet -Name[lv]=KGet -Name[mk]=KGet -Name[ml]=കെഗെറ്റ് -Name[mr]=के-गेट -Name[ms]=KGet -Name[nb]=KGet -Name[nds]=KGet -Name[ne]=केडीई गेट -Name[nl]=KGet -Name[nn]=KGet -Name[pa]=ਕੇ-ਗੈੱਟ -Name[pl]=KGet -Name[pt]=KGet -Name[pt_BR]=KGet -Name[ro]=KGet -Name[ru]=KGet -Name[se]=KGet -Name[si]=KGet -Name[sk]=KGet -Name[sl]=KGet -Name[sq]=KGet -Name[sr]=К‑гет -Name[sr@ijekavian]=К‑гет -Name[sr@ijekavianlatin]=KGet -Name[sr@latin]=KGet -Name[sv]=Kget -Name[ta]=கேகெட் -Name[tg]=KGet -Name[th]=ดาวน์โหลด-K -Name[tr]=KGet -Name[ug]=KGet -Name[uk]=KGet -Name[vi]=KGet -Name[wa]=KGet -Name[xh]=KGet -Name[x-test]=xxKGetxx -Name[zh_CN]=KGet -Name[zh_HK]=KGet -Name[zh_TW]=檔案傳輸_KGet -GenericName=Download Manager -GenericName[ar]=مدير التّنزيل -GenericName[ast]=Xestor de baxaes -GenericName[be]=Праграма сцягвання файлаў -GenericName[bg]=Изтегляне на файлове -GenericName[bn]=ডাউনলোড ম্যানেজার -GenericName[br]=Merour enkargañ -GenericName[bs]=Menadžer preuzimanja -GenericName[ca]=Gestor de baixades -GenericName[ca@valencia]=Gestor de baixades -GenericName[cs]=Správce stahování -GenericName[cy]=Rheolydd Lawrlwytho -GenericName[da]=Håndtering af download -GenericName[de]=Download-Manager -GenericName[el]=Διαχειριστής λήψεων αρχείων -GenericName[en_GB]=Download Manager -GenericName[eo]=Elŝuta administrilo -GenericName[es]=Gestor de descargas -GenericName[et]=Allalaadimiste haldur -GenericName[eu]=Deskarga-kudeatzailea -GenericName[fa]=مدیر بارگیری -GenericName[fi]=Tiedostonlataaja -GenericName[fr]=Gestionnaire de téléchargements -GenericName[ga]=Bainisteoir Íosluchtaithe -GenericName[gl]=Xestor de transferencias -GenericName[he]=מנהל הורדות -GenericName[hi]=डाउनलोड प्रबंधक -GenericName[hne]=डाउनलोड प्रबंधक -GenericName[hr]=Upravitelj preuzimanja -GenericName[hu]=Letöltéskezelő -GenericName[ia]=Gerente de discargamento -GenericName[is]=Niðurhalsstjóri -GenericName[it]=Gestore degli scaricamenti -GenericName[ja]=ダウンロードマネージャ -GenericName[kk]=Жүктеп алу менеджері -GenericName[km]=កម្មវិធី​គ្រប់គ្រង​ការ​ទាញយក -GenericName[ko]=다운로드 관리자 -GenericName[lt]=Siuntimų valdymas -GenericName[lv]=Lejupielāžu pārvaldnieks -GenericName[mk]=Менаџер за симнувања -GenericName[ml]=ഇറക്കിവെക്കല്‍ കാര്യസ്ഥന്‍ -GenericName[mr]=डाउनलोड व्यवस्थापक -GenericName[nb]=Nedlastingsbehandler -GenericName[nds]=Daalladenpleger -GenericName[ne]=डाउनलोड प्रबन्धक -GenericName[nl]=Downloadbeheerder -GenericName[nn]=Nedlastingshandsamar -GenericName[pa]=ਡਾਊਨਲੋਡ ਮੈਨੇਜਰ -GenericName[pl]=Zarządzanie pobieraniem -GenericName[pt]=Gestor de Transferências -GenericName[pt_BR]=Gerenciador de downloads -GenericName[ro]=Administrator descărcări -GenericName[ru]=Диспетчер загрузок -GenericName[si]=බාගැනීම් කළමනාකරු -GenericName[sk]=Správca sťahovania -GenericName[sl]=Upravljalnik prenosov -GenericName[sq]=Organizuesi i Shkarkimeve -GenericName[sr]=Менаџер преузимања -GenericName[sr@ijekavian]=Менаџер преузимања -GenericName[sr@ijekavianlatin]=Menadžer preuzimanja -GenericName[sr@latin]=Menadžer preuzimanja -GenericName[sv]=Nerladdningshanterare -GenericName[ta]=பதிவிறக்க மேலாளர் -GenericName[tg]=Мудири Боркунӣ -GenericName[th]=เครื่องมือจัดการการดาวน์โหลด -GenericName[tr]=İndirme Yöneticisi -GenericName[ug]=چۈشۈرۈش باشقۇرغۇسى -GenericName[uk]=Керування звантаженнями -GenericName[uz]=Yozib olish boshqaruvchisi -GenericName[uz@cyrillic]=Ёзиб олиш бошқарувчиси -GenericName[vi]=Trình quản lý việc tải tập tin -GenericName[wa]=Manaedjeu d' aberwetaedje -GenericName[x-test]=xxDownload Managerxx -GenericName[zh_CN]=下载管理器 -GenericName[zh_HK]=下載管理員 -GenericName[zh_TW]=下載管理員 -Categories=Qt;KDE;Network;FileTransfer; -StartupNotify=false -X-DocPath=kget/index.html diff --git a/kget/desktop/kget_download.desktop b/kget/desktop/kget_download.desktop deleted file mode 100644 index 055a83e8..00000000 --- a/kget/desktop/kget_download.desktop +++ /dev/null @@ -1,81 +0,0 @@ -[Desktop Entry] -Actions=KGetDownload; -Type=Service -Icon= -Name= -X-KDE-ServiceTypes=KonqPopupMenu/Plugin,all/allfiles -X-KDE-ExcludeServiceTypes=kdedevice/* -X-KDE-Protocol=!file - -[Desktop Action KGetDownload] -Exec=kget %U -Icon=kget -Name=Download with KGet -Name[ar]=نزّل بـ KGet -Name[ast]=Baxada con KGet -Name[be]=Сцягнуць праз KGet -Name[bg]=Изтегляне с KGet -Name[bn]=কে-গেট দিয়ে ডাউনলোড -Name[br]=Enkargañ gant KGet -Name[bs]=Preuzmi KGetom -Name[ca]=Baixa amb el KGet -Name[ca@valencia]=Baixa amb el KGet -Name[cs]=Stáhnout pomocí KGet -Name[da]=Download med KGet -Name[de]=Mit KGet herunterladen -Name[el]=Λήψη αρχείου με το KGet -Name[en_GB]=Download with KGet -Name[eo]=Elŝuti per KGet -Name[es]=Descarga con KGet -Name[et]=Laadi alla KGeti abil -Name[eu]=Deskargatu KGet-ekin -Name[fa]=بارگیری با KGet -Name[fi]=Hae KGet-ohjelmalla -Name[fr]=Télécharger avec KGet -Name[ga]=Íosluchtaigh le KGet -Name[gl]=Obter con KGet -Name[he]=הורד בעזרת KGet -Name[hi]=के-गेट के साथ डाउनलोड करें -Name[hne]=के-गेट के साथ डाउनलोड करव -Name[hr]=Preuzmi KGetom -Name[hu]=Letöltés a KGettel -Name[ia]=Discarga con KGet -Name[is]=Sækja með KGet -Name[it]=Scarica con KGet -Name[ja]=KGet でダウンロード -Name[kk]=KGet көмегімен жүктеп алу -Name[km]=ទាញយក​ដោយ​ប្រើ KGet -Name[ko]=KGet으로 다운로드 -Name[lt]=Atsisiųsti su KGet -Name[lv]=Lejupielādēt ar KGet -Name[ml]=കെഗെറ്റുപയോഗിച്ച് ഇറക്കിവെക്കല്‍ -Name[mr]=के-गेटने डाउनलोड करा -Name[nb]=Nedlasting med KGet -Name[nds]=Daalladen mit KGet -Name[ne]=केडीई गेटसँग डाउनलोड गर्नुहोस् -Name[nl]=Met KGet downloaden -Name[nn]=Last ned med KGet -Name[pa]=KGet ਨਾਲ ਡਾਊਨਲੋਡ -Name[pl]=Pobierz za pomocą KGet -Name[pt]=Obter com o KGet -Name[pt_BR]=Baixar com o KGet -Name[ro]=Descarcă cu KGet -Name[ru]=Загрузить с помощью KGet -Name[si]=KGet සමඟ බාගන්න -Name[sk]=Stiahnuť pomocou KGet -Name[sl]=Prejmi s KGet -Name[sq]=Shkarko me KGet -Name[sr]=Преузми К‑гетом -Name[sr@ijekavian]=Преузми К‑гетом -Name[sr@ijekavianlatin]=Preuzmi KGetom -Name[sr@latin]=Preuzmi KGetom -Name[sv]=Ladda ner med Kget -Name[th]=ดาวน์โหลดด้วย 'ดาวน์โหลด-K' -Name[tr]=KGet ile İndir -Name[ug]=KGet تا چۈشۈر -Name[uk]=Звантажити через KGet -Name[vi]=Tải với KGet -Name[x-test]=xxDownload with KGetxx -Name[zh_CN]=用 KGet 下载 -Name[zh_HK]=以 KGet 下載 -Name[zh_TW]=用 KGet 下載 diff --git a/kget/desktop/org.kde.kget.service.in b/kget/desktop/org.kde.kget.service.in deleted file mode 100644 index 64d187b6..00000000 --- a/kget/desktop/org.kde.kget.service.in +++ /dev/null @@ -1,3 +0,0 @@ -[D-BUS Service] -Name=org.kde.kget -Exec=@KDE4_BIN_INSTALL_DIR@/kget diff --git a/kget/extensions/CMakeLists.txt b/kget/extensions/CMakeLists.txt deleted file mode 100644 index 0046c25e..00000000 --- a/kget/extensions/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(webinterface) diff --git a/kget/extensions/webinterface/CMakeLists.txt b/kget/extensions/webinterface/CMakeLists.txt deleted file mode 100644 index c5e0b31d..00000000 --- a/kget/extensions/webinterface/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(www) diff --git a/kget/extensions/webinterface/httpserver.cpp b/kget/extensions/webinterface/httpserver.cpp deleted file mode 100644 index ea314a46..00000000 --- a/kget/extensions/webinterface/httpserver.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 - 2009 Urs Wolfer - Copyright (C) 2010 Matthias Fuchs - Copyright (C) 2011 Lukas Appelhans - Copyright (C) 2022 Ivailo Monev - - 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. -*/ - -#include "httpserver.h" - -#include "core/transferhandler.h" -#include "core/transfergrouphandler.h" -#include "core/kget.h" -#include "settings.h" - -#include -#include -#include - -#include -#include -#include - -HttpServer::HttpServer(QWidget *parent) - : KHTTP(parent), - m_passwdstore(nullptr) -{ - setServerID("KGet"); - - m_passwdstore = new KPasswdStore(this); - m_passwdstore->setStoreID("KGet"); - - if (m_passwdstore && m_passwdstore->openStore(parent->winId())) { - const QString usr = Settings::webinterfaceUser(); - const QString pwd = m_passwdstore->getPasswd("Webinterface", parent->winId()); - if (!setAuthenticate(usr.toUtf8(), pwd.toUtf8())) { - KNotification* notification = KGet::showNotification( - parent, - "kget/error", i18nc("@info", "Unable to set the WebInterface authorization: %1", errorString()) - ); - notification->send(); - return; - } - if (!start(QHostAddress::Any, Settings::webinterfacePort())) { - KNotification* notification = KGet::showNotification( - parent, - "kget/error", i18nc("@info", "Unable to start WebInterface: %1", errorString()) - ); - notification->send(); - return; - } - } else { - KNotification* notification = KGet::showNotification( - parent, - "kget/error", i18n("Unable to start WebInterface: Could not open KPasswdStore") - ); - notification->send(); - } -} - -HttpServer::~HttpServer() -{ -} - -void HttpServer::settingsChanged() -{ - QWidget* parentwidget = qobject_cast(parent()); - if (m_passwdstore && m_passwdstore->openStore(parentwidget->winId())) { - const QString usr = Settings::webinterfaceUser(); - const QString pwd = m_passwdstore->getPasswd("Webinterface"); - stop(); - if (!setAuthenticate(usr.toUtf8(), pwd.toUtf8())) { - KNotification* notification = KGet::showNotification( - parentwidget, - "kget/error", - i18nc("@info", "Unable to set the WebInterface authorization: %1", errorString()) - ); - notification->send(); - return; - } - if (!start(QHostAddress::Any, Settings::webinterfacePort())) { - KNotification* notification = KGet::showNotification( - parentwidget, - "kget/error", - i18nc("@info", "Unable to restart WebInterface: %1", errorString()) - ); - notification->send(); - return; - } - } -} - -void HttpServer::respond(const QByteArray &url, QByteArray *outdata, - ushort *outhttpstatus, KHTTPHeaders *outheaders, - QString *outfilePath) -{ - Q_UNUSED(outfilePath); - *outhttpstatus = 200; - - QByteArray data; - - // qDebug() << Q_FUNC_INFO << url; - if (url.endsWith("data.json")) { - data.append("{\"downloads\":["); - bool needsToBeClosed = false; - foreach(TransferHandler *transfer, KGet::allTransfers()) { - if (needsToBeClosed) - data.append(","); // close the last line - data.append(QString("{\"name\":\"" + transfer->source().fileName() + - "\", \"src\":\"" + transfer->source().prettyUrl() + - "\", \"dest\":\"" + transfer->dest().pathOrUrl() + - "\", \"status\":\"" + transfer->statusText() + - "\", \"size\":\"" + KIO::convertSize(transfer->totalSize()) + - "\", \"progress\":\"" + QString::number(transfer->percent()) + "%" - "\", \"speed\":\"" + i18nc("@item speed of transfer per seconds", "%1/s", - KIO::convertSize(transfer->downloadSpeed())) + "\"}").toUtf8()); - needsToBeClosed = true; - } - data.append("]}"); - } else if (url.startsWith("/do")) { - QString args = url.right(url.length() - 4); - - if (!args.isEmpty()) { - QString action; - QString data; - QString group; - QStringList argList = args.split('&'); - foreach (const QString &s, argList) { - QStringList map = s.split('='); - if (map.at(0) == "action") - action = map.at(1); - else if (map.at(0) == "data") - data = KUrl::fromPercentEncoding(QByteArray(map.at(1).toUtf8())); - // action specific parameters - else if (map.at(0) == "group") - group = KUrl::fromPercentEncoding(QByteArray(map.at(1).toUtf8())); - } - kDebug() << action << data << group; - if (action == "add") { - //find a folder to store the download in - QString defaultFolder; - - //prefer the defaultFolder of the selected group - TransferGroupHandler *groupHandler = KGet::findGroup(group); - if (groupHandler) { - defaultFolder = groupHandler->defaultFolder(); - } - if (defaultFolder.isEmpty()) { - QList groups = KGet::groupsFromExceptions(KUrl(data)); - if (groups.isEmpty() || groups.first()->defaultFolder().isEmpty()) { - defaultFolder = KGet::generalDestDir(); - } else { - // take first item of default folder list (which should be the best one) - groupHandler = groups.first(); - group = groupHandler->name(); - defaultFolder = groupHandler->defaultFolder(); - } - } - KGet::addTransfer(data, defaultFolder, KUrl(data).fileName(), group); - data.append(QString("Ok, %1 added!").arg(data).toUtf8()); - } else if (action == "start") { - TransferHandler *transfer = KGet::findTransfer(data); - if (transfer) - transfer->start(); - } else if (action == "stop") { - TransferHandler *transfer = KGet::findTransfer(data); - if (transfer) - transfer->stop(); - } else if (action == "remove") { - TransferHandler *transfer = KGet::findTransfer(data); - if (transfer) - KGet::delTransfer(transfer); - } else { - kWarning() << "not implemented action" << action << data; - } - } - } else { // read it from filesystem - QString fileName = QString(url).remove(".."); // disallow changing directory - if (fileName.endsWith('/')) - fileName = "index.htm"; - - QString path = KStandardDirs::locate("data", "kget/www/" + fileName); - QFile file(path); - - if (path.isEmpty() || !file.open(QIODevice::ReadOnly)) { - *outhttpstatus = 404; - // DO NOT TRANSLATE THE FOLLOWING MESSAGE! webserver messages are never translated. - QString notfoundText = QString("404 Not Found" - "

Not Found

The requested URL %1 " - "was not found on this server.") - .arg(url.constData()); - data.append(notfoundText.toUtf8()); - } else { - while (!file.atEnd()) { - data.append(file.readLine()); - } - } - if (fileName == "index.htm") { // translations - data.replace("#{KGet Webinterface}", i18nc("@label", "KGet Web Interface").toUtf8()); - data.replace("#{Nr}", i18nc("@label number", "Nr").toUtf8()); - data.replace("#{File name}", i18nc("@label", "File name").toUtf8()); - data.replace("#{Finished}", i18nc("@label Progress of transfer", "Finished").toUtf8()); - data.replace("#{Speed}", i18nc("@label Speed of transfer", "Speed").toUtf8()); - data.replace("#{Status}", i18nc("@label Status of transfer", "Status").toUtf8()); - data.replace("#{Start}", i18nc("@action:button start a transfer", "Start").toUtf8()); - data.replace("#{Stop}", i18nc("@action:button", "Stop").toUtf8()); - data.replace("#{Remove}", i18nc("@action:button", "Remove").toUtf8()); - data.replace("#{Source:}", i18nc("@label Download from", "Source:").toUtf8()); - data.replace("#{Saving to:}", i18nc("@label Save download to", "Saving to:").toUtf8()); - data.replace("#{Webinterface}", i18nc("@label Title in header", "Web Interface").toUtf8()); - data.replace("#{Settings}", i18nc("@action", "Settings").toUtf8()); - data.replace("#{Refresh}", i18nc("@action", "Refresh").toUtf8()); - data.replace("#{Enter URL: }", i18nc("@action", "Enter URL: ").toUtf8()); - data.replace("#{OK}", i18nc("@action:button", "OK").toUtf8()); - data.replace("#{Refresh download list every}", - i18nc("@action Refresh download list every x (seconds)", "Refresh download list every").toUtf8()); - data.replace("#{seconds}", i18nc("@action (Refresh very x )seconds", "seconds").toUtf8()); - data.replace("#{Save Settings}", i18nc("@action:button", "Save Settings").toUtf8()); - data.replace("#{Downloads}", i18nc("@title", "Downloads").toUtf8()); - data.replace("#{KGet Webinterface | Valid XHTML 1.0 Strict & CSS}", - i18nc("@label text in footer", "KGet Web Interface | Valid XHTML 1.0 Strict & CSS").toUtf8().replace('&', "&")); - - // delegate group combobox - QString groupOptions = ""; - Q_FOREACH(const QString &group, KGet::transferGroupNames()) - groupOptions += QString("").arg(group); - data.replace("#{groups}", groupOptions.toUtf8()); - } - } - - // for HTTP information see: http://www.jmarshall.com/easy/http/ - if (url.endsWith(".png") && *outhttpstatus == 200) { - outheaders->insert("Content-Type", "image/png"); - } else if (url.endsWith(".json") && *outhttpstatus == 200) { - outheaders->insert("Content-Type", "application/x-json"); - } else if (url.endsWith(".gif") && *outhttpstatus == 200) { - outheaders->insert("Content-Type", "image/gif"); - } else if (url.endsWith(".js") && *outhttpstatus == 200) { - outheaders->insert("Content-Type", "text/javascript"); - } else if (url.endsWith(".htc") && *outhttpstatus == 200) { - outheaders->insert("Content-Type", "text/x-component"); - } else { - outheaders->insert("Content-Type", "text/html; charset=UTF-8"); - } - - outdata->append(data); -} diff --git a/kget/extensions/webinterface/httpserver.h b/kget/extensions/webinterface/httpserver.h deleted file mode 100644 index 6034b0aa..00000000 --- a/kget/extensions/webinterface/httpserver.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Urs Wolfer - - 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. -*/ - -#ifndef HTTPSERVER_H -#define HTTPSERVER_H - -#include - -#include -#include - -class HttpServer : public KHTTP -{ - Q_OBJECT -public: - HttpServer(QWidget *parent = 0); - ~HttpServer(); - - void settingsChanged(); - -protected: - void respond( - const QByteArray &url, - QByteArray *outdata, ushort *httpstatus, KHTTPHeaders *outheaders, QString *outfilePath - ) final; - -private: - KPasswdStore *m_passwdstore; -}; - -#endif // HTTPSERVER_H diff --git a/kget/extensions/webinterface/www/CMakeLists.txt b/kget/extensions/webinterface/www/CMakeLists.txt deleted file mode 100644 index 2aea2156..00000000 --- a/kget/extensions/webinterface/www/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -install( - FILES - index.htm - mootools-core-yc.js - mootools-more.js - favicon.ico - header-background.png - header-separator.png - hi64-apps-kget.png - new-download-background.png - png_hack/blank.gif - png_hack/iepngfix.htc - preferences-system.png - title-border-bottom-downloads.png - title-border-bottom-settings.png - view-refresh.png - DESTINATION ${KDE4_DATA_INSTALL_DIR}/kget/www -) diff --git a/kget/extensions/webinterface/www/favicon.ico b/kget/extensions/webinterface/www/favicon.ico deleted file mode 100644 index 8aff2219..00000000 Binary files a/kget/extensions/webinterface/www/favicon.ico and /dev/null differ diff --git a/kget/extensions/webinterface/www/header-background.png b/kget/extensions/webinterface/www/header-background.png deleted file mode 100644 index e089316c..00000000 Binary files a/kget/extensions/webinterface/www/header-background.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/header-separator.png b/kget/extensions/webinterface/www/header-separator.png deleted file mode 100644 index 732a7494..00000000 Binary files a/kget/extensions/webinterface/www/header-separator.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/hi64-apps-kget.png b/kget/extensions/webinterface/www/hi64-apps-kget.png deleted file mode 100644 index 6396fd36..00000000 Binary files a/kget/extensions/webinterface/www/hi64-apps-kget.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/index.htm b/kget/extensions/webinterface/www/index.htm deleted file mode 100644 index 82830108..00000000 --- a/kget/extensions/webinterface/www/index.htm +++ /dev/null @@ -1,403 +0,0 @@ - - - - - - -#{KGet Webinterface} - - - - - - - -
-
-
- -
-
-

  

-
-
-
-
-
-
-
-

#{Settings}

-
-
- - - -      - -
-
-
- -

#{Downloads}

-
-
-
- -
- - diff --git a/kget/extensions/webinterface/www/mootools-core-yc.js b/kget/extensions/webinterface/www/mootools-core-yc.js deleted file mode 100644 index 752b98ce..00000000 --- a/kget/extensions/webinterface/www/mootools-core-yc.js +++ /dev/null @@ -1,349 +0,0 @@ -//MooTools, , My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2008 Valerio Proietti, , MIT Style License. - -var MooTools={version:"1.2.1",build:"0d4845aab3d9a4fdee2f0d4a6dd59210e4b697cf"};var Native=function(K){K=K||{};var A=K.name;var I=K.legacy;var B=K.protect; -var C=K.implement;var H=K.generics;var F=K.initialize;var G=K.afterImplement||function(){};var D=F||I;H=H!==false;D.constructor=Native;D.$family={name:"native"}; -if(I&&F){D.prototype=I.prototype;}D.prototype.constructor=D;if(A){var E=A.toLowerCase();D.prototype.$family={name:E};Native.typize(D,E);}var J=function(N,L,O,M){if(!B||M||!N.prototype[L]){N.prototype[L]=O; -}if(H){Native.genericize(N,L,B);}G.call(N,L,O);return N;};D.alias=function(N,L,O){if(typeof N=="string"){if((N=this.prototype[N])){return J(this,L,N,O); -}}for(var M in N){this.alias(M,N[M],L);}return this;};D.implement=function(M,L,O){if(typeof M=="string"){return J(this,M,L,O);}for(var N in M){J(this,N,M[N],L); -}return this;};if(C){D.implement(C);}return D;};Native.genericize=function(B,C,A){if((!A||!B[C])&&typeof B.prototype[C]=="function"){B[C]=function(){var D=Array.prototype.slice.call(arguments); -return B.prototype[C].apply(D.shift(),D);};}};Native.implement=function(D,C){for(var B=0,A=D.length;B-1:this.indexOf(A)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim(); -},camelCase:function(){return this.replace(/-\D/g,function(A){return A.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(A){return("-"+A.charAt(0).toLowerCase()); -});},capitalize:function(){return this.replace(/\b[a-z]/g,function(A){return A.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1"); -},toInt:function(A){return parseInt(this,A||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(B){var A=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); -return(A)?A.slice(1).hexToRgb(B):null;},rgbToHex:function(B){var A=this.match(/\d{1,3}/g);return(A)?A.rgbToHex(B):null;},stripScripts:function(B){var A=""; -var C=this.replace(/]*>([\s\S]*?)<\/script>/gi,function(){A+=arguments[1]+"\n";return"";});if(B===true){$exec(A);}else{if($type(B)=="function"){B(A,C); -}}return C;},substitute:function(A,B){return this.replace(B||(/\\?\{([^{}]+)\}/g),function(D,C){if(D.charAt(0)=="\\"){return D.slice(1);}return(A[C]!=undefined)?A[C]:""; -});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(B){for(var A in this){if(this.hasOwnProperty(A)&&this[A]===B){return A;}}return null; -},hasValue:function(A){return(Hash.keyOf(this,A)!==null);},extend:function(A){Hash.each(A,function(C,B){Hash.set(this,B,C);},this);return this;},combine:function(A){Hash.each(A,function(C,B){Hash.include(this,B,C); -},this);return this;},erase:function(A){if(this.hasOwnProperty(A)){delete this[A];}return this;},get:function(A){return(this.hasOwnProperty(A))?this[A]:null; -},set:function(A,B){if(!this[A]||this.hasOwnProperty(A)){this[A]=B;}return this;},empty:function(){Hash.each(this,function(B,A){delete this[A];},this); -return this;},include:function(B,C){var A=this[B];if(A==undefined){this[B]=C;}return this;},map:function(B,C){var A=new Hash;Hash.each(this,function(E,D){A.set(D,B.call(C,E,D,this)); -},this);return A;},filter:function(B,C){var A=new Hash;Hash.each(this,function(E,D){if(B.call(C,E,D,this)){A.set(D,E);}},this);return A;},every:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&!B.call(C,this[A],A)){return false; -}}return true;},some:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&B.call(C,this[A],A)){return true;}}return false;},getKeys:function(){var A=[]; -Hash.each(this,function(C,B){A.push(B);});return A;},getValues:function(){var A=[];Hash.each(this,function(B){A.push(B);});return A;},toQueryString:function(A){var B=[]; -Hash.each(this,function(F,E){if(A){E=A+"["+E+"]";}var D;switch($type(F)){case"object":D=Hash.toQueryString(F,E);break;case"array":var C={};F.each(function(H,G){C[G]=H; -});D=Hash.toQueryString(C,E);break;default:D=E+"="+encodeURIComponent(F);}if(F!=undefined){B.push(D);}});return B.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"}); -var Event=new Native({name:"Event",initialize:function(A,F){F=F||window;var K=F.document;A=A||F.event;if(A.$extended){return A;}this.$extended=true;var J=A.type; -var G=A.target||A.srcElement;while(G&&G.nodeType==3){G=G.parentNode;}if(J.test(/key/)){var B=A.which||A.keyCode;var M=Event.Keys.keyOf(B);if(J=="keydown"){var D=B-111; -if(D>0&&D<13){M="f"+D;}}M=M||String.fromCharCode(B).toLowerCase();}else{if(J.match(/(click|mouse|menu)/i)){K=(!K.compatMode||K.compatMode=="CSS1Compat")?K.html:K.body; -var I={x:A.pageX||A.clientX+K.scrollLeft,y:A.pageY||A.clientY+K.scrollTop};var C={x:(A.pageX)?A.pageX-F.pageXOffset:A.clientX,y:(A.pageY)?A.pageY-F.pageYOffset:A.clientY}; -if(J.match(/DOMMouseScroll|mousewheel/)){var H=(A.wheelDelta)?A.wheelDelta/120:-(A.detail||0)/3;}var E=(A.which==3)||(A.button==2);var L=null;if(J.match(/over|out/)){switch(J){case"mouseover":L=A.relatedTarget||A.fromElement; -break;case"mouseout":L=A.relatedTarget||A.toElement;}if(!(function(){while(L&&L.nodeType==3){L=L.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){L=false; -}}}}return $extend(this,{event:A,type:J,page:I,client:C,rightClick:E,wheel:H,relatedTarget:L,target:G,code:B,key:M,shift:A.shiftKey,control:A.ctrlKey,alt:A.altKey,meta:A.metaKey}); -}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault(); -},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault(); -}else{this.event.returnValue=false;}return this;}});var Class=new Native({name:"Class",initialize:function(B){B=B||{};var A=function(){for(var E in this){if($type(this[E])!="function"){this[E]=$unlink(this[E]); -}}this.constructor=A;if(Class.prototyping){return this;}var D=(this.initialize)?this.initialize.apply(this,arguments):this;if(this.options&&this.options.initialize){this.options.initialize.call(this); -}return D;};for(var C in Class.Mutators){if(!B[C]){continue;}B=Class.Mutators[C](B,B[C]);delete B[C];}$extend(A,this);A.constructor=Class;A.prototype=B; -return A;}});Class.Mutators={Extends:function(C,A){Class.prototyping=A.prototype;var B=new A;delete B.parent;B=Class.inherit(B,C);delete Class.prototyping; -return B;},Implements:function(A,B){$splat(B).each(function(C){Class.prototying=C;$extend(A,($type(C)=="class")?new C:C);delete Class.prototyping;});return A; -}};Class.extend({inherit:function(B,E){var A=arguments.callee.caller;for(var D in E){var C=E[D];var G=B[D];var F=$type(C);if(G&&F=="function"){if(C!=G){if(A){C.__parent=G; -B[D]=C;}else{Class.override(B,D,C);}}}else{if(F=="object"){B[D]=$merge(G,C);}else{B[D]=C;}}}if(A){B.parent=function(){return arguments.callee.caller.__parent.apply(this,arguments); -};}return B;},override:function(B,A,E){var D=Class.prototyping;if(D&&B[A]!=D[A]){D=null;}var C=function(){var F=this.parent;this.parent=D?D[A]:B[A];var G=E.apply(this,arguments); -this.parent=F;return G;};B[A]=C;}});Class.implement({implement:function(){var A=this.prototype;$each(arguments,function(B){Class.inherit(A,B);});return this; -}});var Chain=new Class({$chain:[],chain:function(){this.$chain.extend(Array.flatten(arguments));return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false; -},clearChain:function(){this.$chain.empty();return this;}});var Events=new Class({$events:{},addEvent:function(C,B,A){C=Events.removeOn(C);if(B!=$empty){this.$events[C]=this.$events[C]||[]; -this.$events[C].include(B);if(A){B.internal=true;}}return this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);}return this;},fireEvent:function(C,B,A){C=Events.removeOn(C); -if(!this.$events||!this.$events[C]){return this;}this.$events[C].each(function(D){D.create({bind:this,delay:A,"arguments":B})();},this);return this;},removeEvent:function(B,A){B=Events.removeOn(B); -if(!this.$events[B]){return this;}if(!A.internal){this.$events[B].erase(A);}return this;},removeEvents:function(C){if($type(C)=="object"){for(var D in C){this.removeEvent(D,C[D]); -}return this;}if(C){C=Events.removeOn(C);}for(var D in this.$events){if(C&&C!=D){continue;}var B=this.$events[D];for(var A=B.length;A--;A){this.removeEvent(D,B[A]); -}}return this;}});Events.removeOn=function(A){return A.replace(/^on([A-Z])/,function(B,C){return C.toLowerCase();});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments)); -if(!this.addEvent){return this;}for(var A in this.options){if($type(this.options[A])!="function"||!(/^on[A-Z]/).test(A)){continue;}this.addEvent(A,this.options[A]); -delete this.options[A];}return this;}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(A,B){var C=Element.Constructors.get(A); -if(C){return C(B);}if(typeof A=="string"){return document.newElement(A,B);}return $(A).set(B);},afterImplement:function(A,B){Element.Prototype[A]=B;if(Array[A]){return ; -}Elements.implement(A,function(){var C=[],G=true;for(var E=0,D=this.length;E";}return $.element(this.createElement(A)).set(B);},newTextNode:function(A){return this.createTextNode(A); -},getDocument:function(){return this;},getWindow:function(){return this.window;}});Window.implement({$:function(B,C){if(B&&B.$family&&B.uid){return B;}var A=$type(B); -return($[A])?$[A](B,C,this.document):null;},$$:function(A){if(arguments.length==1&&typeof A=="string"){return this.document.getElements(A);}var F=[];var C=Array.flatten(arguments); -for(var D=0,B=C.length;D1);A.each(function(E){var F=this.getElementsByTagName(E.trim());(B)?C.extend(F):C=F;},this);return new Elements(C,{ddup:B,cash:!D}); -}});(function(){var H={},F={};var I={input:"checked",option:"selected",textarea:(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerHTML":"value"}; -var C=function(L){return(F[L]||(F[L]={}));};var G=function(N,L){if(!N){return ;}var M=N.uid;if(Browser.Engine.trident){if(N.clearAttributes){var P=L&&N.cloneNode(false); -N.clearAttributes();if(P){N.mergeAttributes(P);}}else{if(N.removeEvents){N.removeEvents();}}if((/object/i).test(N.tagName)){for(var O in N){if(typeof N[O]=="function"){N[O]=$empty; -}}Element.dispose(N);}}if(!M){return ;}H[M]=F[M]=null;};var D=function(){Hash.each(H,G);if(Browser.Engine.trident){$A(document.getElementsByTagName("object")).each(G); -}if(window.CollectGarbage){CollectGarbage();}H=F=null;};var J=function(N,L,S,M,P,R){var O=N[S||L];var Q=[];while(O){if(O.nodeType==1&&(!M||Element.match(O,M))){if(!P){return $(O,R); -}Q.push(O);}O=O[L];}return(P)?new Elements(Q,{ddup:false,cash:!R}):null;};var E={html:"innerHTML","class":"className","for":"htmlFor",text:(Browser.Engine.trident||(Browser.Engine.webkit&&Browser.Engine.version<420))?"innerText":"textContent"}; -var B=["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"];var K=["value","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"]; -Hash.extend(E,B.associate(B));Hash.extend(E,K.associate(K.map(String.toLowerCase)));var A={before:function(M,L){if(L.parentNode){L.parentNode.insertBefore(M,L); -}},after:function(M,L){if(!L.parentNode){return ;}var N=L.nextSibling;(N)?L.parentNode.insertBefore(M,N):L.parentNode.appendChild(M);},bottom:function(M,L){L.appendChild(M); -},top:function(M,L){var N=L.firstChild;(N)?L.insertBefore(M,N):L.appendChild(M);}};A.inside=A.bottom;Hash.each(A,function(L,M){M=M.capitalize();Element.implement("inject"+M,function(N){L(this,$(N,true)); -return this;});Element.implement("grab"+M,function(N){L($(N,true),this);return this;});});Element.implement({set:function(O,M){switch($type(O)){case"object":for(var N in O){this.set(N,O[N]); -}break;case"string":var L=Element.Properties.get(O);(L&&L.set)?L.set.apply(this,Array.slice(arguments,1)):this.setProperty(O,M);}return this;},get:function(M){var L=Element.Properties.get(M); -return(L&&L.get)?L.get.apply(this,Array.slice(arguments,1)):this.getProperty(M);},erase:function(M){var L=Element.Properties.get(M);(L&&L.erase)?L.erase.apply(this):this.removeProperty(M); -return this;},setProperty:function(M,N){var L=E[M];if(N==undefined){return this.removeProperty(M);}if(L&&B[M]){N=!!N;}(L)?this[L]=N:this.setAttribute(M,""+N); -return this;},setProperties:function(L){for(var M in L){this.setProperty(M,L[M]);}return this;},getProperty:function(M){var L=E[M];var N=(L)?this[L]:this.getAttribute(M,2); -return(B[M])?!!N:(L)?N:N||null;},getProperties:function(){var L=$A(arguments);return L.map(this.getProperty,this).associate(L);},removeProperty:function(M){var L=E[M]; -(L)?this[L]=(L&&B[M])?false:"":this.removeAttribute(M);return this;},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this; -},hasClass:function(L){return this.className.contains(L," ");},addClass:function(L){if(!this.hasClass(L)){this.className=(this.className+" "+L).clean(); -}return this;},removeClass:function(L){this.className=this.className.replace(new RegExp("(^|\\s)"+L+"(?:\\s|$)"),"$1");return this;},toggleClass:function(L){return this.hasClass(L)?this.removeClass(L):this.addClass(L); -},adopt:function(){Array.flatten(arguments).each(function(L){L=$(L,true);if(L){this.appendChild(L);}},this);return this;},appendText:function(M,L){return this.grab(this.getDocument().newTextNode(M),L); -},grab:function(M,L){A[L||"bottom"]($(M,true),this);return this;},inject:function(M,L){A[L||"bottom"](this,$(M,true));return this;},replaces:function(L){L=$(L,true); -L.parentNode.replaceChild(this,L);return this;},wraps:function(M,L){M=$(M,true);return this.replaces(M).grab(M,L);},getPrevious:function(L,M){return J(this,"previousSibling",null,L,false,M); -},getAllPrevious:function(L,M){return J(this,"previousSibling",null,L,true,M);},getNext:function(L,M){return J(this,"nextSibling",null,L,false,M);},getAllNext:function(L,M){return J(this,"nextSibling",null,L,true,M); -},getFirst:function(L,M){return J(this,"nextSibling","firstChild",L,false,M);},getLast:function(L,M){return J(this,"previousSibling","lastChild",L,false,M); -},getParent:function(L,M){return J(this,"parentNode",null,L,false,M);},getParents:function(L,M){return J(this,"parentNode",null,L,true,M);},getChildren:function(L,M){return J(this,"nextSibling","firstChild",L,true,M); -},getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument;},getElementById:function(O,N){var M=this.ownerDocument.getElementById(O); -if(!M){return null;}for(var L=M.parentNode;L!=this;L=L.parentNode){if(!L){return null;}}return $.element(M,N);},getSelected:function(){return new Elements($A(this.options).filter(function(L){return L.selected; -}));},getComputedStyle:function(M){if(this.currentStyle){return this.currentStyle[M.camelCase()];}var L=this.getDocument().defaultView.getComputedStyle(this,null); -return(L)?L.getPropertyValue([M.hyphenate()]):null;},toQueryString:function(){var L=[];this.getElements("input, select, textarea",true).each(function(M){if(!M.name||M.disabled){return ; -}var N=(M.tagName.toLowerCase()=="select")?Element.getSelected(M).map(function(O){return O.value;}):((M.type=="radio"||M.type=="checkbox")&&!M.checked)?null:M.value; -$splat(N).each(function(O){if(typeof O!="undefined"){L.push(M.name+"="+encodeURIComponent(O));}});});return L.join("&");},clone:function(O,L){O=O!==false; -var R=this.cloneNode(O);var N=function(V,U){if(!L){V.removeAttribute("id");}if(Browser.Engine.trident){V.clearAttributes();V.mergeAttributes(U);V.removeAttribute("uid"); -if(V.options){var W=V.options,S=U.options;for(var T=W.length;T--;){W[T].selected=S[T].selected;}}}var X=I[U.tagName.toLowerCase()];if(X&&U[X]){V[X]=U[X]; -}};if(O){var P=R.getElementsByTagName("*"),Q=this.getElementsByTagName("*");for(var M=P.length;M--;){N(P[M],Q[M]);}}N(R,this);return $(R);},destroy:function(){Element.empty(this); -Element.dispose(this);G(this,true);return null;},empty:function(){$A(this.childNodes).each(function(L){Element.destroy(L);});return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this; -},hasChild:function(L){L=$(L,true);if(!L){return false;}if(Browser.Engine.webkit&&Browser.Engine.version<420){return $A(this.getElementsByTagName(L.tagName)).contains(L); -}return(this.contains)?(this!=L&&this.contains(L)):!!(this.compareDocumentPosition(L)&16);},match:function(L){return(!L||(L==this)||(Element.get(this,"tag")==L)); -}});Native.implement([Element,Window,Document],{addListener:function(O,N){if(O=="unload"){var L=N,M=this;N=function(){M.removeListener("unload",N);L(); -};}else{H[this.uid]=this;}if(this.addEventListener){this.addEventListener(O,N,false);}else{this.attachEvent("on"+O,N);}return this;},removeListener:function(M,L){if(this.removeEventListener){this.removeEventListener(M,L,false); -}else{this.detachEvent("on"+M,L);}return this;},retrieve:function(M,L){var O=C(this.uid),N=O[M];if(L!=undefined&&N==undefined){N=O[M]=L;}return $pick(N); -},store:function(M,L){var N=C(this.uid);N[M]=L;return this;},eliminate:function(L){var M=C(this.uid);delete M[L];return this;}});window.addListener("unload",D); -})();Element.Properties=new Hash;Element.Properties.style={set:function(A){this.style.cssText=A;},get:function(){return this.style.cssText;},erase:function(){this.style.cssText=""; -}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();}};Element.Properties.html=(function(){var C=document.createElement("div"); -var A={table:[1,"","
"],select:[1,""],tbody:[2,"","
"],tr:[3,"","
"]}; -A.thead=A.tfoot=A.tbody;var B={set:function(){var E=Array.flatten(arguments).join("");var F=Browser.Engine.trident&&A[this.get("tag")];if(F){var G=C;G.innerHTML=F[1]+E+F[2]; -for(var D=F[0];D--;){G=G.firstChild;}this.empty().adopt(G.childNodes);}else{this.innerHTML=E;}}};B.erase=B.set;return B;})();if(Browser.Engine.webkit&&Browser.Engine.version<420){Element.Properties.text={get:function(){if(this.innerText){return this.innerText; -}var A=this.ownerDocument.newElement("div",{html:this.innerHTML}).inject(this.ownerDocument.body);var B=A.innerText;A.destroy();return B;}};}Element.Properties.events={set:function(A){this.addEvents(A); -}};Native.implement([Element,Window,Document],{addEvent:function(E,G){var H=this.retrieve("events",{});H[E]=H[E]||{keys:[],values:[]};if(H[E].keys.contains(G)){return this; -}H[E].keys.push(G);var F=E,A=Element.Events.get(E),C=G,I=this;if(A){if(A.onAdd){A.onAdd.call(this,G);}if(A.condition){C=function(J){if(A.condition.call(this,J)){return G.call(this,J); -}return true;};}F=A.base||F;}var D=function(){return G.call(I);};var B=Element.NativeEvents[F];if(B){if(B==2){D=function(J){J=new Event(J,I.getWindow()); -if(C.call(I,J)===false){J.stop();}};}this.addListener(F,D);}H[E].values.push(D);return this;},removeEvent:function(C,B){var A=this.retrieve("events");if(!A||!A[C]){return this; -}var F=A[C].keys.indexOf(B);if(F==-1){return this;}A[C].keys.splice(F,1);var E=A[C].values.splice(F,1)[0];var D=Element.Events.get(C);if(D){if(D.onRemove){D.onRemove.call(this,B); -}C=D.base||C;}return(Element.NativeEvents[C])?this.removeListener(C,E):this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);}return this; -},removeEvents:function(A){if($type(A)=="object"){for(var C in A){this.removeEvent(C,A[C]);}return this;}var B=this.retrieve("events");if(!B){return this; -}if(!A){for(var C in B){this.removeEvents(C);}this.eliminate("events");}else{if(B[A]){while(B[A].keys[0]){this.removeEvent(A,B[A].keys[0]);}B[A]=null;}}return this; -},fireEvent:function(D,B,A){var C=this.retrieve("events");if(!C||!C[D]){return this;}C[D].keys.each(function(E){E.create({bind:this,delay:A,"arguments":B})(); -},this);return this;},cloneEvents:function(D,A){D=$(D);var C=D.retrieve("events");if(!C){return this;}if(!A){for(var B in C){this.cloneEvents(D,B);}}else{if(C[A]){C[A].keys.each(function(E){this.addEvent(A,E); -},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1}; -(function(){var A=function(B){var C=B.relatedTarget;if(C==undefined){return true;}if(C===false){return false;}return($type(this)!="document"&&C!=this&&C.prefix!="xul"&&!this.hasChild(C)); -};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:A},mouseleave:{base:"mouseout",condition:A},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}}); -})();Element.Properties.styles={set:function(A){this.setStyles(A);}};Element.Properties.opacity={set:function(A,B){if(!B){if(A==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden"; -}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(A==1)?"":"alpha(opacity="+A*100+")"; -}this.style.opacity=A;this.store("opacity",A);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(A){return this.set("opacity",A,true); -},getOpacity:function(){return this.get("opacity");},setStyle:function(B,A){switch(B){case"opacity":return this.set("opacity",parseFloat(A));case"float":B=(Browser.Engine.trident)?"styleFloat":"cssFloat"; -}B=B.camelCase();if($type(A)!="string"){var C=(Element.Styles.get(B)||"@").split(" ");A=$splat(A).map(function(E,D){if(!C[D]){return"";}return($type(E)=="number")?C[D].replace("@",Math.round(E)):E; -}).join(" ");}else{if(A==String(Number(A))){A=Math.round(A);}}this.style[B]=A;return this;},getStyle:function(G){switch(G){case"opacity":return this.get("opacity"); -case"float":G=(Browser.Engine.trident)?"styleFloat":"cssFloat";}G=G.camelCase();var A=this.style[G];if(!$chk(A)){A=[];for(var F in Element.ShortStyles){if(G!=F){continue; -}for(var E in Element.ShortStyles[F]){A.push(this.getStyle(E));}return A.join(" ");}A=this.getComputedStyle(G);}if(A){A=String(A);var C=A.match(/rgba?\([\d\s,]+\)/); -if(C){A=A.replace(C[0],C[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(A)))){if(G.test(/^(height|width)$/)){var B=(G=="width")?["left","right"]:["top","bottom"],D=0; -B.each(function(H){D+=this.getStyle("border-"+H+"-width").toInt()+this.getStyle("padding-"+H).toInt();},this);return this["offset"+G.capitalize()]-D+"px"; -}if((Browser.Engine.presto)&&String(A).test("px")){return A;}if(G.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return A;},setStyles:function(B){for(var A in B){this.setStyle(A,B[A]); -}return this;},getStyles:function(){var A={};Array.each(arguments,function(B){A[B]=this.getStyle(B);},this);return A;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"}); -Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(G){var F=Element.ShortStyles; -var B=Element.Styles;["margin","padding"].each(function(H){var I=H+G;F[H][I]=B[I]="@px";});var E="border"+G;F.border[E]=B[E]="@px @ rgb(@, @, @)";var D=E+"Width",A=E+"Style",C=E+"Color"; -F[E]={};F.borderWidth[D]=F[E][D]=B[D]="@px";F.borderStyle[A]=F[E][A]=B[A]="@";F.borderColor[C]=F[E][C]=B[C]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(H,I){if(B(this)){this.getWindow().scrollTo(H,I); -}else{this.scrollLeft=H;this.scrollTop=I;}return this;},getSize:function(){if(B(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight}; -},getScrollSize:function(){if(B(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(B(this)){return this.getWindow().getScroll(); -}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var I=this,H={x:0,y:0};while(I&&!B(I)){H.x+=I.scrollLeft;H.y+=I.scrollTop;I=I.parentNode; -}return H;},getOffsetParent:function(){var H=this;if(B(H)){return null;}if(!Browser.Engine.trident){return H.offsetParent;}while((H=H.parentNode)&&!B(H)){if(D(H,"position")!="static"){return H; -}}return null;},getOffsets:function(){if(Browser.Engine.trident){var L=this.getBoundingClientRect(),J=this.getDocument().documentElement;return{x:L.left+J.scrollLeft-J.clientLeft,y:L.top+J.scrollTop-J.clientTop}; -}var I=this,H={x:0,y:0};if(B(this)){return H;}while(I&&!B(I)){H.x+=I.offsetLeft;H.y+=I.offsetTop;if(Browser.Engine.gecko){if(!F(I)){H.x+=C(I);H.y+=G(I); -}var K=I.parentNode;if(K&&D(K,"overflow")!="visible"){H.x+=C(K);H.y+=G(K);}}else{if(I!=this&&Browser.Engine.webkit){H.x+=C(I);H.y+=G(I);}}I=I.offsetParent; -}if(Browser.Engine.gecko&&!F(this)){H.x-=C(this);H.y-=G(this);}return H;},getPosition:function(K){if(B(this)){return{x:0,y:0};}var L=this.getOffsets(),I=this.getScrolls(); -var H={x:L.x-I.x,y:L.y-I.y};var J=(K&&(K=$(K)))?K.getPosition():{x:0,y:0};return{x:H.x-J.x,y:H.y-J.y};},getCoordinates:function(J){if(B(this)){return this.getWindow().getCoordinates(); -}var H=this.getPosition(J),I=this.getSize();var K={left:H.x,top:H.y,width:I.x,height:I.y};K.right=K.left+K.width;K.bottom=K.top+K.height;return K;},computePosition:function(H){return{left:H.x-E(this,"margin-left"),top:H.y-E(this,"margin-top")}; -},position:function(H){return this.setStyles(this.computePosition(H));}});Native.implement([Document,Window],{getSize:function(){var I=this.getWindow(); -if(Browser.Engine.presto||Browser.Engine.webkit){return{x:I.innerWidth,y:I.innerHeight};}var H=A(this);return{x:H.clientWidth,y:H.clientHeight};},getScroll:function(){var I=this.getWindow(); -var H=A(this);return{x:I.pageXOffset||H.scrollLeft,y:I.pageYOffset||H.scrollTop};},getScrollSize:function(){var I=A(this);var H=this.getSize();return{x:Math.max(I.scrollWidth,H.x),y:Math.max(I.scrollHeight,H.y)}; -},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var H=this.getSize();return{top:0,left:0,bottom:H.y,right:H.x,height:H.y,width:H.x}; -}});var D=Element.getComputedStyle;function E(H,I){return D(H,I).toInt()||0;}function F(H){return D(H,"-moz-box-sizing")=="border-box";}function G(H){return E(H,"border-top-width"); -}function C(H){return E(H,"border-left-width");}function B(H){return(/^(?:body|html)$/i).test(H.tagName);}function A(H){var I=H.getDocument();return(!I.compatMode||I.compatMode=="CSS1Compat")?I.html:I.body; -}})();Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y; -},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x; -},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x;}});Native.implement([Document,Element],{getElements:function(H,G){H=H.split(","); -var C,E={};for(var D=0,B=H.length;D1),cash:!G});}});Element.implement({match:function(B){if(!B||(B==this)){return true;}var D=Selectors.Utils.parseTagAndID(B); -var A=D[0],E=D[1];if(!Selectors.Filters.byID(this,E)||!Selectors.Filters.byTag(this,A)){return false;}var C=Selectors.Utils.parseSelector(B);return(C)?Selectors.Utils.filter(this,C,{}):true; -}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)}; -Selectors.Utils={chk:function(B,C){if(!C){return true;}var A=$uid(B);if(!C[A]){return C[A]=true;}return false;},parseNthArgument:function(F){if(Selectors.Cache.nth[F]){return Selectors.Cache.nth[F]; -}var C=F.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!C){return false;}var E=parseInt(C[1]);var B=(E||E===0)?E:1;var D=C[2]||false;var A=parseInt(C[3])||0; -if(B!=0){A--;while(A<1){A+=B;}while(A>=B){A-=B;}}else{B=A;D="index";}switch(D){case"n":C={a:B,b:A,special:"n"};break;case"odd":C={a:2,b:0,special:"n"}; -break;case"even":C={a:2,b:1,special:"n"};break;case"first":C={a:0,special:"index"};break;case"last":C={special:"last-child"};break;case"only":C={special:"only-child"}; -break;default:C={a:(B-1),special:"index"};}return Selectors.Cache.nth[F]=C;},parseSelector:function(E){if(Selectors.Cache.parsed[E]){return Selectors.Cache.parsed[E]; -}var D,H={classes:[],pseudos:[],attributes:[]};while((D=Selectors.RegExps.combined.exec(E))){var I=D[1],G=D[2],F=D[3],B=D[5],C=D[6],J=D[7];if(I){H.classes.push(I); -}else{if(C){var A=Selectors.Pseudo.get(C);if(A){H.pseudos.push({parser:A,argument:J});}else{H.attributes.push({name:C,operator:"=",value:J});}}else{if(G){H.attributes.push({name:G,operator:F,value:B}); -}}}}if(!H.classes.length){delete H.classes;}if(!H.attributes.length){delete H.attributes;}if(!H.pseudos.length){delete H.pseudos;}if(!H.classes&&!H.attributes&&!H.pseudos){H=null; -}return Selectors.Cache.parsed[E]=H;},parseTagAndID:function(B){var A=B.match(Selectors.RegExps.tag);var C=B.match(Selectors.RegExps.id);return[(A)?A[1]:"*",(C)?C[1]:false]; -},filter:function(F,C,E){var D;if(C.classes){for(D=C.classes.length;D--;D){var G=C.classes[D];if(!Selectors.Filters.byClass(F,G)){return false;}}}if(C.attributes){for(D=C.attributes.length; -D--;D){var B=C.attributes[D];if(!Selectors.Filters.byAttribute(F,B.name,B.operator,B.value)){return false;}}}if(C.pseudos){for(D=C.pseudos.length;D--;D){var A=C.pseudos[D]; -if(!Selectors.Filters.byPseudo(F,A.parser,A.argument,E)){return false;}}}return true;},getByTagAndID:function(B,A,D){if(D){var C=(B.getElementById)?B.getElementById(D,true):Element.getElementById(B,D,true); -return(C&&Selectors.Filters.byTag(C,A))?[C]:[];}else{return B.getElementsByTagName(A);}},search:function(I,H,N){var B=[];var C=H.trim().replace(Selectors.RegExps.splitter,function(Y,X,W){B.push(X); -return":)"+W;}).split(":)");var J,E,U;for(var T=0,P=C.length;T":function(H,G,I,A,F){var C=Selectors.Utils.getByTagAndID(G,I,A);for(var E=0,D=C.length;EA){return false;}}return(C==A);},even:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n+1",A); -},odd:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n",A);}});Element.Events.domready={onAdd:function(A){if(Browser.loaded){A.call(this); -}}};(function(){var B=function(){if(Browser.loaded){return ;}Browser.loaded=true;window.fireEvent("domready");document.fireEvent("domready");};if(Browser.Engine.trident){var A=document.createElement("div"); -(function(){($try(function(){A.doScroll("left");return $(A).inject(document.body).set("html","temp").dispose();}))?B():arguments.callee.delay(50);})(); -}else{if(Browser.Engine.webkit&&Browser.Engine.version<525){(function(){(["loaded","complete"].contains(document.readyState))?B():arguments.callee.delay(50); -})();}else{window.addEvent("load",B);document.addEvent("DOMContentLoaded",B);}}})();var JSON=new Hash({$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(A){return JSON.$specialChars[A]||"\\u00"+Math.floor(A.charCodeAt()/16).toString(16)+(A.charCodeAt()%16).toString(16); -},encode:function(B){switch($type(B)){case"string":return'"'+B.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';case"array":return"["+String(B.map(JSON.encode).filter($defined))+"]"; -case"object":case"hash":var A=[];Hash.each(B,function(E,D){var C=JSON.encode(E);if(C){A.push(JSON.encode(D)+":"+C);}});return"{"+A+"}";case"number":case"boolean":return String(B); -case false:return"null";}return null;},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null; -}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(B,A){this.key=B; -this.setOptions(A);},write:function(B){B=encodeURIComponent(B);if(this.options.domain){B+="; domain="+this.options.domain;}if(this.options.path){B+="; path="+this.options.path; -}if(this.options.duration){var A=new Date();A.setTime(A.getTime()+this.options.duration*24*60*60*1000);B+="; expires="+A.toGMTString();}if(this.options.secure){B+="; secure"; -}this.options.document.cookie=this.key+"="+B;return this;},read:function(){var A=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)"); -return(A)?decodeURIComponent(A[1]):null;},dispose:function(){new Cookie(this.key,$merge(this.options,{duration:-1})).write("");return this;}});Cookie.write=function(B,C,A){return new Cookie(B,A).write(C); -};Cookie.read=function(A){return new Cookie(A).read();};Cookie.dispose=function(B,A){return new Cookie(B,A).dispose();};var Swiff=new Class({Implements:[Options],options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"transparent",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object; -},initialize:function(L,M){this.instance="Swiff_"+$time();this.setOptions(M);M=this.options;var B=this.id=M.id||this.instance;var A=$(M.container);Swiff.CallBacks[this.instance]={}; -var E=M.params,G=M.vars,F=M.callBacks;var H=$extend({height:M.height,width:M.width},M.properties);var K=this;for(var D in F){Swiff.CallBacks[this.instance][D]=(function(N){return function(){return N.apply(K.object,arguments); -};})(F[D]);G[D]="Swiff.CallBacks."+this.instance+"."+D;}E.flashVars=Hash.toQueryString(G);if(Browser.Engine.trident){H.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"; -E.movie=L;}else{H.type="application/x-shockwave-flash";H.data=L;}var J=''; -}}J+="";this.object=((A)?A.empty():new Element("div")).set("html",J).firstChild;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this.toElement(),A); -return this;},inject:function(A){$(A,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments)); -}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction(''+__flash__argumentsToXML(arguments,2)+""); -return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore"},initialize:function(A){this.subject=this.subject||this; -this.setOptions(A);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();var B=this.options.wait;if(B===false){this.options.link="cancel"; -}},getTransition:function(){return function(A){return -(Math.cos(Math.PI*A)-1)/2;};},step:function(){var A=$time();if(A=(7-4*B)/11){C=A*A-Math.pow((11-6*B-11*D)/4,2); -break;}}return C;},Elastic:function(B,A){return Math.pow(2,10*--B)*Math.cos(20*B*Math.PI*(A[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(B,A){Fx.Transitions[B]=new Fx.Transition(function(C){return Math.pow(C,[A+2]); -});});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false},initialize:function(A){this.xhr=new Browser.Request(); -this.setOptions(A);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return ; -}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML}; -this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}this.xhr.onreadystatechange=$empty;},isSuccess:function(){return((this.status>=200)&&(this.status<300)); -},processScripts:function(A){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(A);}return A.stripScripts(this.options.evalScripts); -},success:function(B,A){this.onSuccess(this.processScripts(B),A);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain(); -},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(A,B){this.headers.set(A,B); -return this;},getHeader:function(A){return $try(function(){return this.xhr.getResponseHeader(A);}.bind(this));},check:function(A){if(!this.running){return true; -}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));return false;}return false; -},send:function(I){if(!this.check(arguments.callee,I)){return this;}this.running=true;var G=$type(I);if(G=="string"||G=="element"){I={data:I};}var D=this.options; -I=$extend({data:D.data,url:D.url,method:D.method},I);var E=I.data,B=I.url,A=I.method;switch($type(E)){case"element":E=$(E).toQueryString();break;case"object":case"hash":E=Hash.toQueryString(E); -}if(this.options.format){var H="format="+this.options.format;E=(E)?H+"&"+E:H;}if(this.options.emulation&&["put","delete"].contains(A)){var F="_method="+A; -E=(E)?F+"&"+E:F;A="post";}if(this.options.urlEncoded&&A=="post"){var C=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers.set("Content-type","application/x-www-form-urlencoded"+C); -}if(E&&A=="get"){B=B+(B.contains("?")?"&":"?")+E;E=null;}this.xhr.open(A.toUpperCase(),B,this.options.async);this.xhr.onreadystatechange=this.onStateChange.bind(this); -this.headers.each(function(K,J){try{this.xhr.setRequestHeader(J,K);}catch(L){this.fireEvent("exception",[J,K]);}},this);this.fireEvent("request");this.xhr.send(E); -if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty; -this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var A={};["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(B){A[B]=function(){var C=Array.link(arguments,{url:String.type,data:$defined}); -return this.send($extend(C,{method:B.toLowerCase()}));};});Request.implement(A);})();Element.Properties.send={set:function(A){var B=this.retrieve("send"); -if(B){B.cancel();}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},A)); -},get:function(A){if(A||!this.retrieve("send")){if(A||!this.retrieve("send:options")){this.set("send",A);}this.store("send",new Request(this.retrieve("send:options"))); -}return this.retrieve("send");}};Element.implement({send:function(A){var B=this.get("send");B.send({data:this,url:A||B.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,evalScripts:true,filter:false},processHTML:function(C){var B=C.match(/]*>([\s\S]*?)<\/body>/i); -C=(B)?B[1]:C;var A=new Element("div");return $try(function(){var D=""+C+"",G;if(Browser.Engine.trident){G=new ActiveXObject("Microsoft.XMLDOM"); -G.async=false;G.loadXML(D);}else{G=new DOMParser().parseFromString(D,"text/xml");}D=G.getElementsByTagName("root")[0];for(var F=0,E=D.childNodes.length; -F. Copyright (c) 2006-2008 Valerio Proietti, , MIT Style License. - -Fx.Slide=new Class({Extends:Fx,options:{mode:"vertical"},initialize:function(B,A){this.addEvent("complete",function(){this.open=(this.wrapper["offset"+this.layout.capitalize()]!=0); -if(this.open&&Browser.Engine.webkit419){this.element.dispose().inject(this.wrapper);}},true);this.element=this.subject=$(B);this.parent(A);var C=this.element.retrieve("wrapper"); -this.wrapper=C||new Element("div",{styles:$extend(this.element.getStyles("margin","position"),{overflow:"hidden"})}).wraps(this.element);this.element.store("wrapper",this.wrapper).setStyle("margin",0); -this.now=[];this.open=true;},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;},horizontal:function(){this.margin="margin-left"; -this.layout="width";this.offset=this.element.offsetWidth;},set:function(A){this.element.setStyle(this.margin,A[0]);this.wrapper.setStyle(this.layout,A[1]); -return this;},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B[F]=Fx.compute(E[F],D[F],C);});return B;},start:function(B,E){if(!this.check(arguments.callee,B,E)){return this; -}this[E||this.options.mode]();var D=this.element.getStyle(this.margin).toInt();var C=this.wrapper.getStyle(this.layout).toInt();var A=[[D,C],[0,this.offset]]; -var G=[[D,C],[-this.offset,0]];var F;switch(B){case"in":F=A;break;case"out":F=G;break;case"toggle":F=(this.wrapper["offset"+this.layout.capitalize()]==0)?A:G; -}return this.parent(F[0],F[1]);},slideIn:function(A){return this.start("in",A);},slideOut:function(A){return this.start("out",A);},hide:function(A){this[A||this.options.mode](); -this.open=false;return this.set([-this.offset,0]);},show:function(A){this[A||this.options.mode]();this.open=true;return this.set([0,this.offset]);},toggle:function(A){return this.start("toggle",A); -}});Element.Properties.slide={set:function(B){var A=this.retrieve("slide");if(A){A.cancel();}return this.eliminate("slide").store("slide:options",$extend({link:"cancel"},B)); -},get:function(A){if(A||!this.retrieve("slide")){if(A||!this.retrieve("slide:options")){this.set("slide",A);}this.store("slide",new Fx.Slide(this,this.retrieve("slide:options"))); -}return this.retrieve("slide");}};Element.implement({slide:function(D,E){D=D||"toggle";var B=this.get("slide"),A;switch(D){case"hide":B.hide(E);break;case"show":B.show(E); -break;case"toggle":var C=this.retrieve("slide:flag",B.open);B[(C)?"slideOut":"slideIn"](E);this.store("slide:flag",!C);A=true;break;default:B.start(D,E); -}if(!A){this.eliminate("slide:flag");}return this;}});var Tips=new Class({Implements:[Events,Options],options:{onShow:function(A){A.setStyle("visibility","visible"); -},onHide:function(A){A.setStyle("visibility","hidden");},showDelay:100,hideDelay:100,className:null,offsets:{x:16,y:16},fixed:false},initialize:function(){var C=Array.link(arguments,{options:Object.type,elements:$defined}); -this.setOptions(C.options||null);this.tip=new Element("div").inject(document.body);if(this.options.className){this.tip.addClass(this.options.className); -}var B=new Element("div",{"class":"tip-top"}).inject(this.tip);this.container=new Element("div",{"class":"tip"}).inject(this.tip);var A=new Element("div",{"class":"tip-bottom"}).inject(this.tip); -this.tip.setStyles({position:"absolute",top:0,left:0,visibility:"hidden"});if(C.elements){this.attach(C.elements);}},attach:function(A){$$(A).each(function(D){var G=D.retrieve("tip:title",D.get("title")); -var F=D.retrieve("tip:text",D.get("rel")||D.get("href"));var E=D.retrieve("tip:enter",this.elementEnter.bindWithEvent(this,D));var C=D.retrieve("tip:leave",this.elementLeave.bindWithEvent(this,D)); -D.addEvents({mouseenter:E,mouseleave:C});if(!this.options.fixed){var B=D.retrieve("tip:move",this.elementMove.bindWithEvent(this,D));D.addEvent("mousemove",B); -}D.store("tip:native",D.get("title"));D.erase("title");},this);return this;},detach:function(A){$$(A).each(function(C){C.removeEvent("mouseenter",C.retrieve("tip:enter")||$empty); -C.removeEvent("mouseleave",C.retrieve("tip:leave")||$empty);C.removeEvent("mousemove",C.retrieve("tip:move")||$empty);C.eliminate("tip:enter").eliminate("tip:leave").eliminate("tip:move"); -var B=C.retrieve("tip:native");if(B){C.set("title",B);}});return this;},elementEnter:function(B,A){$A(this.container.childNodes).each(Element.dispose); -var D=A.retrieve("tip:title");if(D){this.titleElement=new Element("div",{"class":"tip-title"}).inject(this.container);this.fill(this.titleElement,D);}var C=A.retrieve("tip:text"); -if(C){this.textElement=new Element("div",{"class":"tip-text"}).inject(this.container);this.fill(this.textElement,C);}this.timer=$clear(this.timer);this.timer=this.show.delay(this.options.showDelay,this); -this.position((!this.options.fixed)?B:{page:A.getPosition()});},elementLeave:function(A){$clear(this.timer);this.timer=this.hide.delay(this.options.hideDelay,this); -},elementMove:function(A){this.position(A);},position:function(D){var B=window.getSize(),A=window.getScroll();var E={x:this.tip.offsetWidth,y:this.tip.offsetHeight}; -var C={x:"left",y:"top"};for(var F in C){var G=D.page[F]+this.options.offsets[F];if((G+E[F]-A[F])>B[F]){G=D.page[F]-this.options.offsets[F]-E[F];}this.tip.setStyle(C[F],G); -}},fill:function(A,B){(typeof B=="string")?A.set("html",B):A.adopt(B);},show:function(){this.fireEvent("show",this.tip);},hide:function(){this.fireEvent("hide",this.tip); -}}); \ No newline at end of file diff --git a/kget/extensions/webinterface/www/new-download-background.png b/kget/extensions/webinterface/www/new-download-background.png deleted file mode 100644 index 5de998ba..00000000 Binary files a/kget/extensions/webinterface/www/new-download-background.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/png_hack/blank.gif b/kget/extensions/webinterface/www/png_hack/blank.gif deleted file mode 100644 index 75b945d2..00000000 Binary files a/kget/extensions/webinterface/www/png_hack/blank.gif and /dev/null differ diff --git a/kget/extensions/webinterface/www/png_hack/iepngfix.htc b/kget/extensions/webinterface/www/png_hack/iepngfix.htc deleted file mode 100644 index 5b61a298..00000000 --- a/kget/extensions/webinterface/www/png_hack/iepngfix.htc +++ /dev/null @@ -1,68 +0,0 @@ - - - - - diff --git a/kget/extensions/webinterface/www/preferences-system.png b/kget/extensions/webinterface/www/preferences-system.png deleted file mode 100644 index 456b436b..00000000 Binary files a/kget/extensions/webinterface/www/preferences-system.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/title-border-bottom-downloads.png b/kget/extensions/webinterface/www/title-border-bottom-downloads.png deleted file mode 100644 index 9dd275ba..00000000 Binary files a/kget/extensions/webinterface/www/title-border-bottom-downloads.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/title-border-bottom-settings.png b/kget/extensions/webinterface/www/title-border-bottom-settings.png deleted file mode 100644 index 120c9f8d..00000000 Binary files a/kget/extensions/webinterface/www/title-border-bottom-settings.png and /dev/null differ diff --git a/kget/extensions/webinterface/www/view-refresh.png b/kget/extensions/webinterface/www/view-refresh.png deleted file mode 100644 index 39fd8cad..00000000 Binary files a/kget/extensions/webinterface/www/view-refresh.png and /dev/null differ diff --git a/kget/kget.notifyrc b/kget/kget.notifyrc deleted file mode 100644 index 815661b8..00000000 --- a/kget/kget.notifyrc +++ /dev/null @@ -1,807 +0,0 @@ -[kget] -IconName=kget -Comment=KGet Download Manager -Comment[bg]=Изтегляне на файлове (KGet) -Comment[bs]=Menadžer preuzimanja KGet -Comment[ca]=Gestor de baixades KGet -Comment[ca@valencia]=Gestor de baixades KGet -Comment[cs]=Správce stahování KGet -Comment[da]=KGet downloadhåndtering -Comment[de]=KGet-Download-Verwaltung -Comment[el]=Διαχειριστής λήψεων KGet -Comment[en_GB]=KGet Download Manager -Comment[es]=Gestor de descargas KGet -Comment[et]=KGeti allalaadimiste haldur -Comment[eu]=KGet-en deskarga-kudeatzailea -Comment[fi]=KGet-tiedostonlataaja -Comment[fr]=Gestionnaire de téléchargements KGet -Comment[ga]=Bainisteoir Íosluchtaithe KGet -Comment[gl]=Xestor de descargas KGet -Comment[hr]=Upravitelj preuzimanja KGet -Comment[hu]=KGet letöltéskezelő -Comment[ia]=Gerente de discargar KGet -Comment[is]=KGet niðurhalsstjóri -Comment[it]=Gestore degli scaricamenti KGet -Comment[ja]=KGet ダウンロードマネージャ -Comment[kk]=KGet жүктеу менеджері -Comment[km]=កម្មវិធី​គ្រប់គ្រង​ការ​ទាញយក KGet -Comment[ko]=KGet 다운로드 관리자 -Comment[lt]=KGet siuntimų valdymas -Comment[mr]=के-गेट डाउनलोड व्यवस्थापक -Comment[nb]=KGet Nedlastingshåndterer -Comment[nds]=KGet - Daalladen-Pleger -Comment[nl]=KGet-downloadbeheerder -Comment[pa]=ਕੇਗਿੱਟ ਡਾਊਨਲੋਡ ਮੈਨੇਜਰ -Comment[pl]=Zarządzanie pobieraniem KGet -Comment[pt]=Gestor de Transferências KGet -Comment[pt_BR]=Gerenciador de downloads KGet -Comment[ro]=Administrator descărcări KGet -Comment[ru]=Диспетчер загрузок KGet -Comment[si]=KGet බාගැනීම් කළමනාකරු -Comment[sk]=Správca sťahovania KGet -Comment[sl]=Upravljalnik prejemov KGet -Comment[sr]=Менаџер преузимања К‑гет -Comment[sr@ijekavian]=Менаџер преузимања К‑гет -Comment[sr@ijekavianlatin]=Menadžer preuzimanja KGet -Comment[sr@latin]=Menadžer preuzimanja KGet -Comment[sv]=Kget nerladdningshanterare -Comment[th]=เครื่องมือจัดการการดาวน์โหลด (KGet) -Comment[tr]=KGet İndirme Yöneticisi -Comment[ug]=KGet چۈشۈرۈش باشقۇرغۇچ -Comment[uk]=Керування звантаженнями KGet -Comment[wa]=Manaedjeu d' aberwetaedje KGet -Comment[x-test]=xxKGet Download Managerxx -Comment[zh_CN]=KGet 下载管理器 -Comment[zh_TW]=KGet 下載管理員 - -[kget/added] -Name=Transfer Added -Name[ar]=التحويل أضيف -Name[ast]=Tresferencia Amestada -Name[bg]=Преносът е добавен -Name[bs]=Prenos dodat -Name[ca]=Transferència afegida -Name[ca@valencia]=Transferència afegida -Name[cs]=Přidán přenos -Name[da]=Overførsel tilføjet -Name[de]=Download hinzugefügt -Name[el]=Προστέθηκε μεταφορά -Name[en_GB]=Transfer Added -Name[eo]=Ŝuto aldoniĝis -Name[es]=Transferencia añadida -Name[et]=Ülekanne lisatud -Name[eu]=Deskarga gehituta -Name[fi]=Siirto lisätty -Name[fr]=Transfert ajouté -Name[ga]=Cuireadh Aistriú Leis -Name[gl]=Engadiuse unha transferencia -Name[hi]=ट्रांसफर जोड़ा -Name[hne]=ट्रांसफर जोड़ा -Name[hr]=Dodan prijenos -Name[hu]=Letöltés felvéve -Name[ia]=Transferimento addite -Name[is]=Færslu bætt við -Name[it]=Trasferimento aggiunto -Name[ja]=ダウンロード追加 -Name[kk]=Берілім қосылды -Name[km]=បាន​បន្ថែម​ការផ្ទេរ -Name[ko]=전송 추가됨 -Name[lt]=Siuntimas įdėtas -Name[lv]=Pārsūtīšana pievienota -Name[ml]=സ്ഥാനമാറ്റം ചേര്‍ത്തിട്ടുണ്ട് -Name[nb]=Overføring lagt til -Name[nds]=Överdregen toföögt -Name[nl]=Overdracht toegevoegd -Name[nn]=Overføring lagd til -Name[pa]=ਟਰਾਂਸਫਰ ਸ਼ਾਮਲ ਕੀਤਾ -Name[pl]=Dodano transfer -Name[pt]=Transferência Adicionada -Name[pt_BR]=Transferência adicionada -Name[ro]=Transfer adăugat -Name[ru]=Загрузка добавлена -Name[si]=හුවමාරුව එක් විය -Name[sk]=Prenos bol pridaný -Name[sl]=Prenos dodan -Name[sr]=Пренос додат -Name[sr@ijekavian]=Пренос додат -Name[sr@ijekavianlatin]=Prenos dodat -Name[sr@latin]=Prenos dodat -Name[sv]=Överföring tillagd -Name[tr]=Aktarım Eklendi -Name[ug]=يوللاش قوشۇلدى -Name[uk]=Додано перенесення -Name[wa]=Berwetaedje radjouté -Name[x-test]=xxTransfer Addedxx -Name[zh_CN]=添加了任务 -Name[zh_TW]=已新增傳輸 -Comment=A new download has been added -Comment[ar]=تنزيلات جديدة أضيفت -Comment[ast]=Amestóse una baxada -Comment[bg]=Добавено е ново изтегляне -Comment[bn]=একটি নতুন ডাউনলোড যোগ করা হয়েছে -Comment[bs]=Novo preuzimanje je dodato -Comment[ca]=S'ha afegit una baixada nova -Comment[ca@valencia]=S'ha afegit una baixada nova -Comment[cs]=Byl přidán nový přenos -Comment[da]=En ny download er blevet tilføjet -Comment[de]=Ein neuer Download ist hinzugefügt worden -Comment[el]=Προστέθηκε μια νέα λήψη -Comment[en_GB]=A new download has been added -Comment[eo]=Nova elŝuto aldoniĝis -Comment[es]=Se ha añadido una nueva descarga -Comment[et]=Lisati uus allalaadimine -Comment[eu]=Deskarga berri bat gehitu da -Comment[fi]=Uusi haku lisätty -Comment[fr]=Un nouveau téléchargement a été ajouté -Comment[ga]=Cuireadh íosluchtú nua leis -Comment[gl]=Engadiuse unha transferencia nova -Comment[he]=הורדה חדשה הוספה -Comment[hi]=नया डाउनलोड जोड़ा गया है -Comment[hne]=नवा डाउनलोड जोड़ दे गे हे -Comment[hr]=Dodano je novo preuzimanje -Comment[hu]=Új letöltés lett felvéve -Comment[ia]=Un nove transferimento ha essite addite -Comment[is]=Nýju niðurhali hefur verið bætt við -Comment[it]=È stato aggiunto un nuovo scaricamento -Comment[ja]=新しいダウンロードが追加されました -Comment[kk]=Жаңа бір берлімі пайда болды -Comment[km]=បាន​បន្ថែម​ការ​ទាញយក​ថ្មី​មួយ -Comment[ko]=새 다운로드가 추가됨 -Comment[lt]=Pridėtas naujas atsiuntimas -Comment[lv]=Ir pievienota jauna lejupielāde -Comment[ml]=ഒരു പുതിയ ഇറക്കിവെപ്പു് ചേര്‍ത്തിട്ടുണ്ട് -Comment[nb]=En ny nedlasting er blitt lagt til -Comment[nds]=En nieg Överdregen wöör toföögt -Comment[nl]=Er is een nieuwe download toegevoegd -Comment[nn]=Ei ny nedlasting er lagd til -Comment[pa]=ਇੱਕ ਨਵਾਂ ਡਾਊਨਲੋਡ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ -Comment[pl]=Nowe zlecenie pobrania pliku zostało dodane -Comment[pt]=Foi adicionada uma transferência nova -Comment[pt_BR]=Um novo download foi adicionado -Comment[ro]=A fost adăugată o nouă descărcare -Comment[ru]=Добавлено новое задание загрузки -Comment[si]=නව බාගැනීමක් එක් විය -Comment[sk]=Nové sťahovanie bolo pridané -Comment[sl]=Dodan je bil nov prejem -Comment[sr]=Ново преузимање је додато -Comment[sr@ijekavian]=Ново преузимање је додато -Comment[sr@ijekavianlatin]=Novo preuzimanje je dodato -Comment[sr@latin]=Novo preuzimanje je dodato -Comment[sv]=En ny nerladdning har lagts till -Comment[th]=เพิ่มการดาวน์โหลดรายการใหม่แล้ว -Comment[tr]=Yeni dosya eklendi -Comment[ug]=يېڭى بىر چۈشۈرۈش قوشۇلدى -Comment[uk]=Було додано нове перенесення -Comment[uz]=Yangi yozib olish qoʻshildi -Comment[uz@cyrillic]=Янги ёзиб олиш қўшилди -Comment[wa]=On novea aberwetaedje a stî radjouté -Comment[x-test]=xxA new download has been addedxx -Comment[zh_CN]=添加了新下载 -Comment[zh_HK]=已新增新的下載 -Comment[zh_TW]=已新增新的傳輸 -Sound=KDE-K3B-Insert-Medium.ogg -Actions= - -[kget/started] -Name=Download Started -Name[ar]=التنزيل بدأ -Name[ast]=Anicióse Baxada -Name[bg]=Изтеглянето започна -Name[bs]=Preuzimanje pokrenuto -Name[ca]=S'ha iniciat la baixada -Name[ca@valencia]=S'ha iniciat la baixada -Name[cs]=Stahování zahájeno -Name[da]=Download startet -Name[de]=Download gestartet -Name[el]=Η μεταφορά εκκινήθηκε -Name[en_GB]=Download Started -Name[eo]=Elŝuto komenciĝis -Name[es]=Descarga comenzada -Name[et]=Allalaadimine alustatud -Name[eu]=Deskarga hasita -Name[fi]=Haku alkoi -Name[fr]=Téléchargement démarré -Name[ga]=Tosaíodh an tÍosluchtú -Name[gl]=Comezou a transferencia -Name[hi]=डाउनलोड प्रारंभ -Name[hne]=डाउनलोड सुरू -Name[hr]=Započelo preuzimanje -Name[hu]=Egy letöltés elkezdődött -Name[ia]=Discargamento initiate -Name[is]=Niðurhal gangsett -Name[it]=Scaricamento avviato -Name[ja]=ダウンロード開始 -Name[kk]=Жүктеп алу басталды -Name[km]=បាន​ចាប់ផ្ដើម​ការ​ទាញយក -Name[ko]=다운로드 시작됨 -Name[lt]=Atsiuntimas pradėtas -Name[lv]=Lejupielāde uzsākta -Name[ml]=ഇറക്കിവെപ്പ്‍ തുടങ്ങി -Name[nb]=Nedlasting startet -Name[nds]=Daalladen anfungen -Name[nl]=Download gestart -Name[nn]=Nedlastinga har starta -Name[pa]=ਡਾਊਨਲੋਡ ਸ਼ੁਰੂ ਕੀਤਾ -Name[pl]=Pobieranie rozpoczęte -Name[pt]=Transferência Iniciada -Name[pt_BR]=Download iniciado -Name[ro]=Descărcare începută -Name[ru]=Загрузка начата -Name[si]=බාගත ආරම්භ විය -Name[sk]=Sťahovanie bolo spustené -Name[sl]=Prejem začet -Name[sq]=Nisje e Shkarkimit -Name[sr]=Преузимање покренуто -Name[sr@ijekavian]=Преузимање покренуто -Name[sr@ijekavianlatin]=Preuzimanje pokrenuto -Name[sr@latin]=Preuzimanje pokrenuto -Name[sv]=Nerladdning startad -Name[th]=เริ่มทำการดาวน์โหลดแล้ว -Name[tr]=İndirme İşlemi Başladı -Name[ug]=چۈشۈرۈش باشلاندى -Name[uk]=Почато звантаження -Name[wa]=Aberwetaedje ataké -Name[x-test]=xxDownload Startedxx -Name[zh_CN]=开始下载 -Name[zh_TW]=下載已開始 -Comment=Downloading started -Comment[ar]=يجري التنزيل -Comment[ast]=Baxada entamada -Comment[bg]=Изтеглянето започна -Comment[bn]=ডাউনলোড আরম্ভ করল -Comment[br]=Kroget eo an enkargañ -Comment[bs]=Preuzimanje je pokrenuto -Comment[ca]=S'ha iniciat la baixada -Comment[ca@valencia]=S'ha iniciat la baixada -Comment[cs]=Bylo zahájeno stahování -Comment[da]=Download startet -Comment[de]=Herunterladen gestartet -Comment[el]=Η λήψη του αρχείου ξεκίνησε -Comment[en_GB]=Downloading started -Comment[eo]=Elŝutado komencita -Comment[es]=Descarga comenzada -Comment[et]=Allalaadimine alustatud -Comment[eu]=Deskarga hasi da -Comment[fi]=Tiedoston hakeminen alkoi -Comment[fr]=Téléchargement démarré -Comment[ga]=Tosaíodh an t-íosluchtú -Comment[gl]=Comezou a transferencia -Comment[he]=ההורדה התחילה -Comment[hi]=डाउनलोड प्रारंभ -Comment[hne]=डाउनलोड सुरू -Comment[hr]=Započelo preuzimanje -Comment[hu]=Egy letöltés elkezdődött -Comment[ia]=Discargamento initiate -Comment[is]=Niðurhali byrjað -Comment[it]=Scaricamento avviato -Comment[ja]=ダウンロードを開始しました -Comment[kk]=Жүктеп алу процесі басталды -Comment[km]=បាន​ចាប់ផ្ដើម​ការ​ទាញយក -Comment[ko]=다운로드 시작됨 -Comment[lt]=Atsiuntimas pradėtas -Comment[lv]=Lejupielāde ir sākta -Comment[ml]=ഇറക്കിവെക്കല്‍ തുടങ്ങി -Comment[nb]=Nedlasting er startet -Comment[nds]=Daalladen hett start -Comment[nl]=Het downloaden is gestart -Comment[nn]=Nedlastinga har starta -Comment[pa]=ਡਾਊਨਲੋਡ ਸ਼ੁਰੂ ਕੀਤਾ ਗਿਆ -Comment[pl]=Pobieranie pliku zostało rozpoczęte -Comment[pt]=A transferência começou -Comment[pt_BR]=Download iniciado -Comment[ro]=Descărcarea a început -Comment[ru]=Загрузка начата -Comment[si]=බාගත කිරීම ආරම්භ විය -Comment[sk]=Sťahovanie bolo spustené -Comment[sl]=Prejemanje začeto -Comment[sq]=Shkarkimi nisi -Comment[sr]=Преузимање је покренуто -Comment[sr@ijekavian]=Преузимање је покренуто -Comment[sr@ijekavianlatin]=Preuzimanje je pokrenuto -Comment[sr@latin]=Preuzimanje je pokrenuto -Comment[sv]=Nerladdning startad -Comment[th]=การดาวน์โหลดเริ่มแล้ว -Comment[tr]=Dosya indirme başladı -Comment[ug]=چۈشۈرۈشنى باشلاۋاتىدى -Comment[uk]=Почато звантаження -Comment[uz]=Yozib olish boshlandi -Comment[uz@cyrillic]=Ёзиб олиш бошланди -Comment[wa]=Dj' a ataké l' aberwetaedje -Comment[x-test]=xxDownloading startedxx -Comment[zh_CN]=下载已开始 -Comment[zh_HK]=下載已開始 -Comment[zh_TW]=下載已開始 -Sound=KDE-K3B-Insert-Medium.ogg -Actions= - -[kget/finished] -Name=Download Finished -Name[ar]=التنزيل انتهى -Name[ast]=Baxada finada -Name[bg]=Изтеглянето приключи -Name[bs]=Preuzimanje završeno -Name[ca]=Ha acabat la baixada -Name[ca@valencia]=Ha acabat la baixada -Name[cs]=Stahování ukončeno -Name[da]=Download afsluttet -Name[de]=Download abgeschlossen -Name[el]=Η μεταφορά ολοκληρώθηκε -Name[en_GB]=Download Finished -Name[eo]=Elŝuto finis -Name[es]=Descarga finalizada -Name[et]=Allalaadimine lõpetatud -Name[eu]=Deskarga amaituta -Name[fi]=Haku valmistui -Name[fr]=Téléchargement terminé -Name[ga]=Críochnaíodh an tÍosluchtú -Name[gl]=Rematou a transferencia -Name[hi]=डाउनलोड सम्पन्न -Name[hne]=डाउनलोड पूरा -Name[hr]=Završeno preuzimanje -Name[hu]=Egy letöltés befejeződött -Name[ia]=Discargamento terminate -Name[is]=Niðurhali lokið -Name[it]=Scaricamento completato -Name[ja]=ダウンロード完了 -Name[kk]=Жүктеп алу аяқталды -Name[km]=បាន​បញ្ចប់​ការ​ទាញយក -Name[ko]=다운로드 완료됨 -Name[lt]=Atsiuntimas baigtas -Name[lv]=Lejupielāde pabeigta -Name[ml]=ഇറക്കിവെപ്പ്‍ അവസാനിച്ചു -Name[nb]=Nedlasting ferdig -Name[nds]=Daalladen afslaten -Name[nl]=Download voltooid -Name[nn]=Nedlastinga er ferdig -Name[pa]=ਡਾਊਨਲੋਡ ਮੁਕੰਮਲ ਹੋਇਆ -Name[pl]=Pobieranie zakończone -Name[pt]=Transferência Terminada -Name[pt_BR]=Download concluído -Name[ro]=Descărcare încheiată -Name[ru]=Загрузка завершена -Name[si]=බාගැනීම අවසන් -Name[sk]=Sťahovanie bolo dokončené -Name[sl]=Prejem končan -Name[sq]=Shkarkimi Përfundoi -Name[sr]=Преузимање завршено -Name[sr@ijekavian]=Преузимање завршено -Name[sr@ijekavianlatin]=Preuzimanje završeno -Name[sr@latin]=Preuzimanje završeno -Name[sv]=Nerladdning klar -Name[th]=ดาวน์โหลดเสร็จสิ้นแล้ว -Name[tr]=İndirme İşlemi Bitti -Name[ug]=چۈشۈرۈش تامام -Name[uk]=Звантаження завершено -Name[wa]=Aberwetaedje fini -Name[x-test]=xxDownload Finishedxx -Name[zh_CN]=下载完成 -Name[zh_TW]=下載已完成 -Comment=Downloading finished -Comment[ar]=التنزيل انتهى -Comment[ast]=Baxada finada -Comment[bg]=Изтеглянето приключи -Comment[bn]=ডাউনলোড শেষ করল -Comment[br]=Echu eo an enkargañ -Comment[bs]=Preuzimanje je završeno -Comment[ca]=Ha acabat la baixada -Comment[ca@valencia]=Ha acabat la baixada -Comment[cs]=Stahování bylo dokončeno -Comment[da]=Download afsluttet -Comment[de]=Herunterladen abgeschlossen -Comment[el]=Η λήψη του αρχείου ολοκληρώθηκε -Comment[en_GB]=Downloading finished -Comment[eo]=Elŝuto finita -Comment[es]=Descarga finalizada -Comment[et]=Allalaadimine lõpetatud -Comment[eu]=Deskarga amaitu da -Comment[fi]=Tiedoston haku valmistui -Comment[fr]=Téléchargement terminé -Comment[ga]=Críochnaíodh an t-íosluchtú -Comment[gl]=Rematou a transferencia -Comment[he]=ההורדה הסתיימה -Comment[hi]=डाउनलोडिंग सम्पन्न -Comment[hne]=डाउनलोडिंग पूरा -Comment[hr]=Završeno preuzimanje -Comment[hu]=Egy letöltés befejeződött -Comment[ia]=Discargamento finite -Comment[is]=Niðurhali lokið -Comment[it]=Scaricamento completato -Comment[ja]=ダウンロードが完了しました -Comment[kk]=Жүктеп алу процесі аяқталды -Comment[km]=បាន​បញ្ចប់​ការ​ទាញយក -Comment[ko]=다운로드 완료됨 -Comment[lt]=Atsiuntimas baigtas -Comment[lv]=Lejupielāde ir pabeigta -Comment[ml]=ഇറക്കിവെക്കല്‍ അവസാനിച്ചു -Comment[nb]=Nedlasting ferdig -Comment[nds]=Daalladen beendt -Comment[nl]=Het downloaden is voltooid -Comment[nn]=Nedlastinga er ferdig -Comment[pa]=ਡਾਊਨਲੋਡ ਮੁਕੰਮਲ ਹੋਇਆ -Comment[pl]=Pobieranie pliku zostało zakończone -Comment[pt]=A transferência terminou -Comment[pt_BR]=Download concluído -Comment[ro]=Descărcarea s-a încheiat -Comment[ru]=Загрузка завершена -Comment[si]=බාගත කිරීම අවසන් -Comment[sk]=Sťahovanie bolo dokončené -Comment[sl]=Prejemanje končano -Comment[sq]=Shkarkimi përfundoi -Comment[sr]=Преузимање је завршено -Comment[sr@ijekavian]=Преузимање је завршено -Comment[sr@ijekavianlatin]=Preuzimanje je završeno -Comment[sr@latin]=Preuzimanje je završeno -Comment[sv]=Nerladdning klar -Comment[th]=การดาวน์โหลดเสร็จสิ้นแล้ว -Comment[tr]=Dosya indirme tamamlandı -Comment[ug]=چۈشۈرۈش تاماملاندى -Comment[uk]=Звантаження завершено -Comment[wa]=Dj' a fini l' aberwetaedje -Comment[x-test]=xxDownloading finishedxx -Comment[zh_CN]=下载已完成 -Comment[zh_HK]=下載已完成 -Comment[zh_TW]=下載已完成 -Sound=KDE-K3B-Finish-Success.ogg -Actions=Popup - -[kget/finishedall] -Name=All Downloads Finished -Name[ar]=كل التنزيلات انتهت -Name[ast]=Fináronse toles baxaes -Name[bg]=Всички изтегляния са приключили -Name[bs]=Sva preuzimanja su završena -Name[ca]=Han acabat totes les baixades -Name[ca@valencia]=Han acabat totes les baixades -Name[cs]=Všechna stahování byla dokončena -Name[da]=Alle downloads afsluttede -Name[de]=Alle Downloads abgeschlossen -Name[el]=Όλες οι λήψεις αρχείων ολοκληρώθηκαν -Name[en_GB]=All Downloads Finished -Name[eo]=Ĉiuj elŝutoj finiĝis -Name[es]=Se han finalizado todas las descargas -Name[et]=Kõik allalaadimised lõpetatud -Name[eu]=Deskarga guztiak amaituta -Name[fi]=Kaikki tiedostojen haut ovat valmistuneet -Name[fr]=Tous les téléchargements sont terminés -Name[ga]=Críochnaíodh Gach Íosluchtú -Name[gl]=Remataron todas as transferencias -Name[hi]=सभी डाउनलोड सम्पन्न -Name[hne]=सब्बो डाउनलोड पूरा -Name[hr]=Sva preuzimanja završena -Name[hu]=Minden letöltés befejeződött -Name[ia]=Omne discargamentos terminate -Name[is]=Öllum niðurhölum lokið -Name[it]=Tutti gli scaricamenti completati -Name[ja]=全ダウンロード完了 -Name[kk]=Барлық жүктеп алу аяқталды -Name[km]=បាន​បញ្ចប់​ការ​ទាញយក​ទាំងអស់ -Name[ko]=모든 다운로드가 완료됨 -Name[lt]=Visi atsiuntimai baigti -Name[lv]=Visas lejupielādes pabeigtas -Name[ml]=ഇറക്കിവെക്കല്‍ മുഴുവന്‍ അവസാനിച്ചു -Name[nb]=Alle nedlastinger ferdige -Name[nds]=All Daalladen afslaten -Name[nl]=Alle downloads voltooid -Name[nn]=Alle nedlastingar er ferdige -Name[pa]=ਸਭ ਡਾਊਨਲੋਡ ਮੁਕੰਮਲ ਹੋਏ -Name[pl]=Pobieranie wszystkich plików zostało zakończone -Name[pt]=Todas as Transferências Terminaram -Name[pt_BR]=Todos os downloads foram concluídos -Name[ro]=Toate descărcările încheiate -Name[ru]=Все загрузки завершены -Name[si]=සියළු බාගත කිරිම් අවසන් -Name[sk]=Všetky sťahovania boli dokončené -Name[sl]=Vsi prejemi končani -Name[sr]=Сва преузимања су завршена -Name[sr@ijekavian]=Сва преузимања су завршена -Name[sr@ijekavianlatin]=Sva preuzimanja su završena -Name[sr@latin]=Sva preuzimanja su završena -Name[sv]=Alla nerladdningar klara -Name[th]=การดาวน์โหลดทั้งหมดเสร็จสิ้นแล้ว -Name[tr]=Tüm İndirme İşlemleri Tamamlandı -Name[ug]=ھەممە چۈشۈرۈشلەر تاماملاندى -Name[uk]=Всі звантаження завершено -Name[wa]=Tos les aberwetaedjes finis -Name[x-test]=xxAll Downloads Finishedxx -Name[zh_CN]=所有下载都已完成 -Name[zh_TW]=所有下載均已完成 -Comment=All downloads finished -Comment[ar]=كل التنزيلات إنتهت -Comment[ast]=Fináronse toles baxaes -Comment[bg]=Всички изтегляния са приключили -Comment[bn]=সব ডাউনলোড শেষ করল -Comment[bs]=Sva preuzimanja su završena -Comment[ca]=Han acabat totes les baixades -Comment[ca@valencia]=Han acabat totes les baixades -Comment[cs]=Všechna stahování byla dokončena -Comment[da]=Alle download afsluttet -Comment[de]=Alle Downloads sind abgeschlossen worden -Comment[el]=Όλες οι λήψεις αρχείων ολοκληρώθηκαν -Comment[en_GB]=All downloads finished -Comment[eo]=Ĉiuj elŝutoj finitaj -Comment[es]=Han finalizado todas las descargas -Comment[et]=Kõik allalaadimised lõpetatud -Comment[eu]=Deskarga guztiak amaituta -Comment[fi]=Kaikki tiedostojen haut ovat valmistuneet -Comment[fr]=Tous les téléchargements sont terminés -Comment[ga]=Críochnaíodh gach íosluchtú -Comment[gl]=Remataron todas as transferencias -Comment[he]=כל ההורדות הסתיימו -Comment[hi]=सभी डाउनलोड सम्पन्न -Comment[hne]=सब्बो डाउनलोड पूरा -Comment[hr]=Sva preuzimanja završena -Comment[hu]=Minden letöltés befejeződött -Comment[ia]=Omne discargamentos terminate -Comment[is]=Öllum niðurhölum lokið -Comment[it]=Tutti gli scaricamenti completati -Comment[ja]=すべてのダウンロードが完了しました -Comment[kk]=Барлық жүктеп алу процестері аяқталды -Comment[km]=បាន​បញ្ចប់​ការ​ទាញយក​ទាំងអស់ -Comment[ko]=모든 다운로드가 완료됨 -Comment[lt]=Visi atsiuntimai baigti -Comment[lv]=Visas lejupielādes ir pabeigtas -Comment[ml]=ഇറക്കിവെക്കല്‍ മുഴുവന്‍ അവസാനിച്ചു -Comment[nb]=Alle nedlastinger er ferdige -Comment[nds]=All Daalladen afslaten -Comment[nl]=Alle downloads zijn voltooid -Comment[nn]=Alle nedlastingar er ferdige -Comment[pa]=ਡਾਊਨਲੋਡ ਮੁਕੰਮਲ ਹੋਏ -Comment[pl]=Pobieranie wszystkich plików zostało zakończone -Comment[pt]=Todas as transferências terminaram -Comment[pt_BR]=Todos os downloads foram concluídos -Comment[ro]=Toate descărcările s-au încheiat -Comment[ru]=Все загрузки завершены -Comment[si]=සියළු බාගත කිරීම් අවසන් -Comment[sk]=Všetky sťahovania boli dokončené -Comment[sl]=Vsi prejemi končani -Comment[sr]=Сва преузимања су завршена -Comment[sr@ijekavian]=Сва преузимања су завршена -Comment[sr@ijekavianlatin]=Sva preuzimanja su završena -Comment[sr@latin]=Sva preuzimanja su završena -Comment[sv]=Alla nerladdningar klara -Comment[th]=การดาวน์โหลดทั้งหมดเสร็จสิ้นแล้ว -Comment[tr]=Tüm dosyaların indirilmesi tamamlandı -Comment[ug]=ھەممە چۈشۈرۈشلەر تاماملاندى -Comment[uk]=Всі звантаження завершено -Comment[uz]=Hamma yozib olishlar tugadi -Comment[uz@cyrillic]=Ҳамма ёзиб олишлар тугади -Comment[wa]=Tos les aberwetaedjes finis -Comment[x-test]=xxAll downloads finishedxx -Comment[zh_CN]=所有下载都已完成 -Comment[zh_HK]=所有下載已完成 -Comment[zh_TW]=所有下載均已完成 -Sound=KDE-K3B-Finish-Success.ogg -Actions=Popup - -[kget/error] -Name=Error Occurred -Name[ast]=Hebo un Fallu -Name[bg]=Възникна грешка -Name[bs]=Desila se greška -Name[ca]=Hi ha hagut un error -Name[ca@valencia]=Hi ha hagut un error -Name[cs]=Nastala chyba -Name[da]=Fejl opstod -Name[de]=Fehler aufgetreten -Name[el]=Παρουσιάστηκε σφάλμα -Name[en_GB]=Error Occurred -Name[es]=Ha ocurrido un error -Name[et]=Tekkis viga -Name[eu]=Errorea gertatu da -Name[fi]=Tapahtui virhe -Name[fr]=Une erreur est survenue -Name[ga]=Tharla Earráid -Name[gl]=Produciuse un erro -Name[hr]=Dogodila se greška -Name[hu]=Hiba történt -Name[ia]=Il occurreva un error -Name[it]=Si è verificato un errore -Name[ja]=エラー発生 -Name[kk]=Қате пайда болды -Name[km]=កំហុស​បានកើត​ឡើង -Name[ko]=오류가 발생함 -Name[lt]=Įvyko klaida -Name[lv]=Gadījās kļūda -Name[mr]=त्रुटी निर्माण झाली -Name[nb]=En feil oppstod -Name[nds]=Fehler vörkamen -Name[nl]=Er deed zich een fout voor -Name[nn]=Det oppstod ein feil -Name[pa]=ਗਲਤੀ ਆਈ -Name[pl]=Wystąpił błąd -Name[pt]=Ocorreu um Erro -Name[pt_BR]=Ocorreu um erro -Name[ro]=A intervenit o eroare -Name[ru]=Ошибка -Name[si]=දෝශයක් හට ගැණිනි -Name[sk]=Nastala chyba -Name[sl]=Prišlo je do napake -Name[sr]=Грешка -Name[sr@ijekavian]=Грешка -Name[sr@ijekavianlatin]=Greška -Name[sr@latin]=Greška -Name[sv]=Fel inträffade -Name[th]=เกิดข้อผิดพลาดขึ้น -Name[tr]=Hata Oluştu -Name[ug]=خاتالىق كۆرۈلدى -Name[uk]=Сталася помилка -Name[x-test]=xxError Occurredxx -Name[zh_CN]=发生错误 -Name[zh_TW]=發生錯誤 -Comment=An Error has Occurred -Comment[ast]=Hebo un Fallu -Comment[bg]=Възникна грешка -Comment[bs]=Došlo je do greške -Comment[ca]=Hi ha hagut un error -Comment[ca@valencia]=Hi ha hagut un error -Comment[cs]=Nastala chyba -Comment[da]=En fejl er opstået -Comment[de]=Es ist ein Fehler aufgetreten -Comment[el]=Παρουσιάστηκε ένα σφάλμα -Comment[en_GB]=An Error has Occurred -Comment[es]=Ha ocurrido un error -Comment[et]=Tekkis viga -Comment[eu]=Errore bat gertatu da -Comment[fi]=Tapahtui virhe -Comment[fr]=Une erreur est survenue -Comment[ga]=Tharla Earráid -Comment[gl]=Aconteceu un erro -Comment[hr]=Dogodila se greška -Comment[hu]=Hiba történt -Comment[ia]=Un error ha occurrite -Comment[it]=Si è verificato un errore -Comment[ja]=エラーが発生しました -Comment[kk]=Бір қате пайда болды -Comment[km]=កំហុស​បាន​កើត​ឡើង -Comment[ko]=연결 오류가 발생함 -Comment[lt]=Įvyko klaida -Comment[lv]=Gadījusies kļūda -Comment[mr]=त्रुटी निर्माण झाली आहे -Comment[nb]=Det oppsto en feil -Comment[nds]=Dat hett en Fehler geven -Comment[nl]=Er is een fout opgetreden -Comment[nn]=Det oppstod ein feil -Comment[pa]=ਇੱਕ ਗਲਤੀ ਆਈ ਹੈ -Comment[pl]=Wystąpił błąd -Comment[pt]=Ocorreu um Erro -Comment[pt_BR]=Ocorreu um erro -Comment[ro]=A intervenit o eroare -Comment[ru]=Произошла ошибка -Comment[si]=දෝශයක් හට ගැණිනි -Comment[sk]=Nastala chyba -Comment[sl]=Prišlo je do napake -Comment[sr]=Дошло је до грешке -Comment[sr@ijekavian]=Дошло је до грешке -Comment[sr@ijekavianlatin]=Došlo je do greške -Comment[sr@latin]=Došlo je do greške -Comment[sv]=Ett fel har inträffat -Comment[th]=เกิดข้อผิดพลาดขึ้น -Comment[tr]=Bir Hata Oluştu -Comment[ug]=بىر خاتالىق كۆرۈلدى -Comment[uk]=Сталася помилка -Comment[wa]=Åk n' a nén stî -Comment[x-test]=xxAn Error has Occurredxx -Comment[zh_CN]=发生了一个错误 -Comment[zh_TW]=發生錯誤 -Sound=KDE-Sys-App-Error.ogg -Actions=Popup,Sound - -[kget/notification] -Name=Information -Name[ar]=معلومة -Name[ast]=Información -Name[bg]=Данни -Name[bs]=Informacija -Name[ca]=Informació -Name[ca@valencia]=Informació -Name[cs]=Informace -Name[da]=Information -Name[de]=Information -Name[el]=Πληροφορίες -Name[en_GB]=Information -Name[eo]=Informoj -Name[es]=Información -Name[et]=Info -Name[eu]=Informazioa -Name[fi]=Tietoa -Name[fr]=Informations -Name[ga]=Eolas -Name[gl]=Información -Name[hne]=जानकारी -Name[hr]=Informacije -Name[hsb]=Informacija -Name[hu]=Információ -Name[ia]=Information -Name[is]=Upplýsingar -Name[it]=Informazioni -Name[ja]=情報 -Name[kk]=Мәлімет -Name[km]=ព័ត៌មាន -Name[ko]=정보 -Name[lt]=Informacija -Name[lv]=Informācija -Name[mai]=सूचना -Name[ml]=വിവരം -Name[mr]=माहिती -Name[nb]=Informasjon -Name[nds]=Informatschonen -Name[nl]=Informatie -Name[nn]=Informasjon -Name[oc]=Entresenhas -Name[pa]=ਜਾਣਕਾਰੀ -Name[pl]=Informacje -Name[pt]=Informação -Name[pt_BR]=Informações -Name[ro]=Informație -Name[ru]=Сведения -Name[si]=තොරතුරු -Name[sk]=Informácia -Name[sl]=Podatek -Name[sq]=Informacion -Name[sr]=Информација -Name[sr@ijekavian]=Информација -Name[sr@ijekavianlatin]=Informacija -Name[sr@latin]=Informacija -Name[sv]=Information -Name[th]=ข้อมูลรายละเอียด -Name[tr]=Bilgiler -Name[ug]=ئۇچۇر -Name[uk]=Інформація -Name[x-test]=xxInformationxx -Name[zh_CN]=信息 -Name[zh_TW]=資訊 -Comment=User Notified of Information -Comment[ast]=Notificación d'información d'usuariu -Comment[bg]=Потребителят е уведомен за данните -Comment[bs]=Korisnik je izvješten o nečemu -Comment[ca]=L'usuari ha estat informat -Comment[ca@valencia]=L'usuari ha estat informat -Comment[cs]=Uživatel upozorněn na informace -Comment[da]=Brugeren er bekendtgjort med information -Comment[de]=Der Benutzer ist über eine Information benachrichtigt worden -Comment[el]=Ενημέρωση χρήστη με πληροφορίες -Comment[en_GB]=User Notified of Information -Comment[es]=Notificación de información de usuario -Comment[et]=Kasutajale teada antud teave -Comment[eu]=Erabiltzailearen informazio-jakinarazpena -Comment[fi]=Käyttäjälle ilmoitetut tiedot -Comment[fr]=Notification de l'utilisateur des informations -Comment[ga]=Cuireadh Eolas in Iúl don Úsáideoir -Comment[gl]=Notificouse o usuario -Comment[hr]=Korisnik je obaviješten -Comment[hu]=Értesítő üzenet -Comment[ia]=Usator esseva notificate de information -Comment[is]=Notandi látinn vita um upplýsingar -Comment[it]=Notifica all'utente dell'informazione -Comment[ja]=お知らせする情報があります -Comment[kk]=Пайдаланушыны құлақтандыру -Comment[km]=ព័ត៌មាន​ដែលបាន​ជូនដំណឹង​ដោយ​អ្នកប្រើ -Comment[ko]=사용자에 의한 정보 알림 -Comment[lt]=Naudotojui pranešta apie informaciją -Comment[lv]=Lietotājam paziņots par informāciju -Comment[nb]=Bruker varslet om informasjonen -Comment[nds]=En Bruker hett en Bescheed kregen -Comment[nl]=Gebruiker gewezen op informatie -Comment[nn]=Brukaren har fått informasjon -Comment[pl]=Użytkownik powiadomiony o informacji -Comment[pt]=Utilizador Notificado da Informação -Comment[pt_BR]=Usuários notificados da informação -Comment[ro]=Utilizator notificat de informație -Comment[ru]=Пользователь получил информацию -Comment[si]=පරිශීලක දැන්වූ තොරතුරු -Comment[sk]=Užívateľ bol upozornený na informáciu -Comment[sl]=Uporabnik obveščen o podatku -Comment[sr]=Корисник је извештен о нечему -Comment[sr@ijekavian]=Корисник је извијештен о нечему -Comment[sr@ijekavianlatin]=Korisnik je izviješten o nečemu -Comment[sr@latin]=Korisnik je izvešten o nečemu -Comment[sv]=Användare underrättad om information -Comment[tr]=Kullanıcıya Bildirilen Bilgiler -Comment[ug]=ئىشلەتكۈچى ئۇقتۇرۇش ئۇچۇرى -Comment[uk]=Сповіщення користувача щодо інформації -Comment[wa]=L' uzeu est notifyî d' ene informåcion -Comment[x-test]=xxUser Notified of Informationxx -Comment[zh_CN]=用户收到消息通知 -Comment[zh_TW]=使用者資訊通知 -Sound=KDE-Sys-App-Message.ogg -Actions=Popup,Sound diff --git a/kget/kget_export.h b/kget/kget_export.h deleted file mode 100644 index 1ba05da9..00000000 --- a/kget/kget_export.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - - 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. -*/ - -#ifndef KGET_EXPORT_H -#define KGET_EXPORT_H - -#include -#include - -/* needed for KDE_EXPORT macros */ -#include - -/* export statements for unix */ -#ifdef kgetcore_EXPORTS -# define KGET_EXPORT KDE_EXPORT -#else -# define KGET_EXPORT KDE_IMPORT -#endif - - -/** - * @short Declares a class as plugin. - * - * Exports a common symbol in a shared library used as an entry point for - * the creation of an istance of the class. - * - * Usage example: - * KGET_EXPORT_PLUGIN( CoolKgetPlugin ); - * class CoolKgetPlugin : public KGetPlugin { - * .... - * } - */ -#define KGET_EXPORT_PLUGIN( classname ) \ - K_PLUGIN_FACTORY( KGetFactory, registerPlugin< classname >(); ) \ - K_EXPORT_PLUGIN( KGetFactory("classname") ) - -#define KGET_EXPORT_PLUGIN_CONFIG( classname ) \ - K_PLUGIN_FACTORY( KGetFactory, registerPlugin< classname >(); ) \ - K_EXPORT_PLUGIN( KGetFactory( "classname" ) ) - -#endif diff --git a/kget/main.cpp b/kget/main.cpp deleted file mode 100644 index 5b7c521d..00000000 --- a/kget/main.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 by Patrick Charbonnier - Based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - - 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. -*/ - -#include -#include -#include -#include -#include -#include - -#include "core/kget.h" -#include "dbus/dbuskgetwrapper.h" -#include "mainadaptor.h" -#include "settings.h" -#include "mainwindow.h" -#include "ui/newtransferdialog.h" - -#if defined Q_WS_X11 - #include -#endif - -class KGetApp : public KUniqueApplication -{ -public: - KGetApp() - : KUniqueApplication(), kget( 0 ) - { - } - - ~KGetApp() - { - delete kget; - } - - int newInstance() - { - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - if (!kget) - { -#ifndef NDEBUG - kget = new MainWindow(!args->isSet("showDropTarget"), args->isSet("startWithoutAnimation"), args->isSet("test")); -#else - kget = new MainWindow(!args->isSet("showDropTarget"), args->isSet("startWithoutAnimation"), false); -#endif - - DBusKGetWrapper *wrapper = new DBusKGetWrapper(kget); - new MainAdaptor(wrapper); - QDBusConnection::sessionBus().registerObject("/KGet", wrapper); - } else { - - //BEGIN taken from "kuniqueapplication.cpp" -#ifdef Q_WS_X11 - // This is the line that handles window activation if necessary, - // and what's important, it does it properly. If you reimplement newInstance(), - // and don't call the inherited one, use this (but NOT when newInstance() - // is called for the first time, like here). - KStartupInfo::setNewStartupId(kget, startupId()); -#endif - //END - - kget->show(); - } - - if (args->isSet("showDropTarget")) - Settings::setShowDropTarget( true ); - - KUrl::List l; - for (int i = 0; i < args->count(); i++) - { - QString txt(args->arg(i)); - if ( txt.endsWith( QLatin1String(".kgt"), Qt::CaseInsensitive ) ) - KGet::load( txt ); - else - l.push_back(KUrl(args->arg(i))); - } - - args->clear(); - - if (!l.isEmpty()) - NewTransferDialogHandler::showNewTransferDialog(l); - - return 0; - } - -private: - MainWindow * kget; -}; - - -int main(int argc, char *argv[]) -{ - KAboutData aboutData("kget", 0, ki18n("KGet"), - QByteArray("2." + QByteArray::number(KDE_VERSION_MINOR) + '.' + QByteArray::number(KDE_VERSION_RELEASE)), - ki18n("An advanced download manager for KDE"), - KAboutData::License_GPL, - ki18n("(C) 2005 - 2012, The KGet developers\n" - "(C) 2001 - 2002, Patrick Charbonnier\n" - "(C) 2002, Carsten Pfeiffer\n" - "(C) 1998 - 2000, Matej Koss")); - - aboutData.addAuthor(ki18n("Lukas Appelhans"), ki18n("Maintainer, Core Developer, Torrent Plugin Author"), "l.appelhans@gmx.de"); - aboutData.addAuthor(ki18n("Dario Massarin"), ki18n("Core Developer"), "nekkar@libero.it"); - aboutData.addAuthor(ki18n("Urs Wolfer"), ki18n("Core Developer"), "uwolfer@kde.org"); - aboutData.addAuthor(ki18n("Manolo Valdes"), ki18n("Core Developer, Multithreaded Plugin Author"), "nolis71cu@gmail.com"); - aboutData.addAuthor(ki18n("Matthias Fuchs"), ki18n("Core Developer"), "mat69@gmx.net"); - aboutData.addAuthor(ki18n("Javier Goday"), ki18n("Developer"), "jgoday@gmail.com"); - aboutData.addAuthor(ki18n("Aish Raj Dahal"), ki18n("Google Summer of Code Student")); - aboutData.addAuthor(ki18n("Patrick Charbonnier"), ki18n("Former Developer"), "pch@freeshell.org"); - aboutData.addAuthor(ki18n("Carsten Pfeiffer"), ki18n("Former Developer"), "pfeiffer@kde.org"); - aboutData.addAuthor(ki18n("Matej Koss"), ki18n("Former Developer")); - aboutData.addCredit(ki18n("Joris Guisson"), ki18n("BTCore (KTorrent) Developer"), "joris.guisson@gmail.com"); - aboutData.addCredit(ki18n("Mensur Zahirovic (Nookie)"), ki18n("Design of Web Interface"), "linuxsajten@gmail.com"); - - KCmdLineArgs::init(argc, argv, &aboutData); - - KCmdLineOptions option; - option.add("showDropTarget", ki18n("Start KGet with drop target")); - option.add("hideMainWindow", ki18n("Start KGet with hidden main window")); - option.add("startWithoutAnimation", ki18n("Start KGet without drop target animation")); -#ifdef DEBUG - option.add("test", ki18n("Execute Unit Testing")); -#endif - option.add("+[URL(s)]", ki18n("URL(s) to download")); - KCmdLineArgs::addCmdLineOptions(option); - - if (!KGetApp::start()) - { - fprintf(stderr, "kget is already running!\n"); - exit(0); - } - - KGetApp kApp; - - return kApp.exec(); -} diff --git a/kget/mainwindow.cpp b/kget/mainwindow.cpp deleted file mode 100644 index 99fba6fa..00000000 --- a/kget/mainwindow.cpp +++ /dev/null @@ -1,1139 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 by Patrick Charbonnier - Based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - Copyright (C) 2002 Carsten Pfeiffer - Copyright (C) 2006 - 2008 Urs Wolfer - Copyright (C) 2006 Dario Massarin - Copyright (C) 2008 - 2011 Lukas Appelhans - Copyright (C) 2009 - 2010 Matthias Fuchs - - 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. -*/ - -#include "mainwindow.h" - -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfergrouphandler.h" -#include "core/transfertreemodel.h" -#include "core/transfertreeselectionmodel.h" -#include "settings.h" -#include "conf/autopastemodel.h" -#include "conf/preferencesdialog.h" -#include "ui/viewscontainer.h" -#include "ui/tray.h" -#include "ui/droptarget.h" -#include "ui/newtransferdialog.h" -#include "ui/history/transferhistory.h" -#include "ui/groupsettingsdialog.h" -#include "ui/transfersettingsdialog.h" -#include "ui/linkview/kget_linkview.h" -#include "extensions/webinterface/httpserver.h" -#ifdef DO_KGET_TEST -# include "tests/testkget.h" -# include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "core/verifier.h" -#include -#include -#include - -MainWindow::MainWindow(bool showMainwindow, bool startWithoutAnimation, bool doTesting, QWidget *parent) - : KXmlGuiWindow( parent ), - m_drop(0), - m_dock(0), - clipboardTimer(0), - m_startWithoutAnimation(startWithoutAnimation), - m_doTesting(doTesting), - m_webinterface(0) -{ - // do not quit the app when it has been minimized to system tray and a new transfer dialog - // gets opened and closed again. - qApp->setQuitOnLastWindowClosed(false); - setAttribute(Qt::WA_DeleteOnClose, false); - - // create the model - m_kget = KGet::self( this ); - - m_viewsContainer = new ViewsContainer(this); - - // create actions - setupActions(); - - setupGUI(KXmlGuiWindow::ToolBar | KXmlGuiWindow::Keys | KXmlGuiWindow::Save | KXmlGuiWindow::Create); - - setCentralWidget(m_viewsContainer); - - setWindowTitle(i18n("KGet")); - - init(); - - // restore position, size and visibility - setAutoSaveSettings(); - if ( Settings::showMain() && showMainwindow) - show(); - else - hide(); -} - -MainWindow::~MainWindow() -{ - // save window state - saveAutoSaveSettings(); - - // save the user's transfers - KGet::save(); - - // .. and write config to disk - Settings::self()->writeConfig(); - - delete m_drop; - delete m_kget; -} - -QSize MainWindow::sizeHint() const -{ - return QSize(738, 380); -} - -int MainWindow::transfersPercent() -{ - int percent = 0; - int activeTransfers = 0; - foreach (const TransferHandler *handler, KGet::allTransfers()) { - if (handler->status() == Job::Running) { - activeTransfers ++; - percent += handler->percent(); - } - } - - if (activeTransfers > 0) { - return percent/activeTransfers; - } - else { - return -1; - } -} - -void MainWindow::setupActions() -{ - KAction *newDownloadAction = actionCollection()->addAction("new_download"); - newDownloadAction->setText(i18n("&New Download...")); - newDownloadAction->setIcon(KIcon("document-new")); - newDownloadAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_N)); - newDownloadAction->setHelpText(i18n("Opens a dialog to add a transfer to the list")); - connect(newDownloadAction, SIGNAL(triggered()), SLOT(slotNewTransfer())); - - KAction *openAction = actionCollection()->addAction("import_transfers"); - openAction->setText(i18n("&Import Transfers...")); - openAction->setIcon(KIcon("document-open")); - openAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_I)); - openAction->setHelpText(i18n("Imports a list of transfers")); - connect(openAction, SIGNAL(triggered()), SLOT(slotImportTransfers())); - - KAction *exportAction = actionCollection()->addAction("export_transfers"); - exportAction->setText(i18n("&Export Transfers List...")); - exportAction->setIcon(KIcon("document-export")); - exportAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_E)); - exportAction->setHelpText(i18n("Exports the current transfers into a file")); - connect(exportAction, SIGNAL(triggered()), SLOT(slotExportTransfers())); - - KAction *priorityTop = actionCollection()->addAction("priority_top"); - priorityTop->setText(i18n("Top Priority")); - priorityTop->setIcon(KIcon("arrow-up-double")); - priorityTop->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_PageUp)); - priorityTop->setHelpText(i18n("Download selected transfer first")); - connect(priorityTop, SIGNAL(triggered()), this, SLOT(slotPriorityTop())); - - KAction *priorityBottom = actionCollection()->addAction("priority_bottom"); - priorityBottom->setText(i18n("Least Priority")); - priorityBottom->setIcon(KIcon("arrow-down-double")); - priorityBottom->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_PageDown)); - priorityBottom->setHelpText(i18n("Download selected transfer last")); - connect(priorityBottom, SIGNAL(triggered()), this, SLOT(slotPriorityBottom())); - - KAction *priorityUp = actionCollection()->addAction("priority_up"); - priorityUp->setText(i18n("Increase Priority")); - priorityUp->setIcon(KIcon("arrow-up")); - priorityUp->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_Up)); - priorityUp->setHelpText(i18n("Increase priority for selected transfer")); - connect(priorityUp, SIGNAL(triggered()), this, SLOT(slotPriorityUp())); - - KAction *priorityDown = actionCollection()->addAction("priority_down"); - priorityDown->setText(i18n("Decrease Priority")); - priorityDown->setIcon(KIcon("arrow-down")); - priorityDown->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_Down)); - priorityDown->setHelpText(i18n("Decrease priority for selected transfer")); - connect(priorityDown, SIGNAL(triggered()), this, SLOT(slotPriorityDown())); - - //FIXME: Not needed maybe because the normal delete already deletes groups? - KAction *deleteGroupAction = actionCollection()->addAction("delete_groups"); - deleteGroupAction->setText(i18n("Delete Group")); - deleteGroupAction->setIcon(KIcon("edit-delete")); - deleteGroupAction->setHelpText(i18n("Delete selected group")); - connect(deleteGroupAction, SIGNAL(triggered()), SLOT(slotDeleteGroup())); - - KAction *renameGroupAction = actionCollection()->addAction("rename_groups"); - renameGroupAction->setText(i18n("Rename Group...")); - renameGroupAction->setIcon(KIcon("edit-rename")); - connect(renameGroupAction, SIGNAL(triggered()), SLOT(slotRenameGroup())); - - KAction *setIconGroupAction = actionCollection()->addAction("seticon_groups"); - setIconGroupAction->setText(i18n("Set Icon...")); - setIconGroupAction->setIcon(KIcon("preferences-desktop-icons")); - setIconGroupAction->setHelpText(i18n("Select a custom icon for the selected group")); - connect(setIconGroupAction, SIGNAL(triggered()), SLOT(slotSetIconGroup())); - - m_autoPasteAction = new KToggleAction(KIcon("edit-paste"), - i18n("Auto-Paste Mode"), actionCollection()); - actionCollection()->addAction("auto_paste", m_autoPasteAction); - m_autoPasteAction->setChecked(Settings::autoPaste()); - m_autoPasteAction->setWhatsThis(i18n("Auto paste button toggles the auto-paste mode " - "on and off.\nWhen set, KGet will periodically scan " - "the clipboard for URLs and paste them automatically.")); - connect(m_autoPasteAction, SIGNAL(triggered()), SLOT(slotToggleAutoPaste())); - - // local - Destroys all sub-windows and exits - KStandardAction::quit(this, SLOT(slotQuit()), actionCollection()); - // local - Standard configure actions - KStandardAction::preferences(this, SLOT(slotPreferences()), actionCollection()); - - KStandardAction::configureNotifications(this, SLOT(slotConfigureNotifications()), actionCollection()); - m_menubarAction = KStandardAction::showMenubar(this, SLOT(slotShowMenubar()), actionCollection()); - m_menubarAction->setChecked(!menuBar()->isHidden()); - - // Transfer related actions - actionCollection()->addAction(KStandardAction::SelectAll, "select_all", m_viewsContainer, SLOT(selectAll())); - - KAction *deleteSelectedAction = actionCollection()->addAction("delete_selected_download"); - deleteSelectedAction->setText(i18nc("delete selected transfer item", "Remove Selected")); - deleteSelectedAction->setIcon(KIcon("edit-delete")); - deleteSelectedAction->setShortcuts(KShortcut(Qt::Key_Delete)); - deleteSelectedAction->setHelpText(i18n("Removes selected transfer and deletes files from disk if it's not finished")); - connect(deleteSelectedAction, SIGNAL(triggered()), SLOT(slotDeleteSelected())); - - KAction *deleteAllFinishedAction = actionCollection()->addAction("delete_all_finished"); - deleteAllFinishedAction->setText(i18nc("delete all finished transfers", "Remove All Finished")); - deleteAllFinishedAction->setIcon(KIcon("edit-clear-list")); - deleteAllFinishedAction->setHelpText(i18n("Removes all finished transfers and leaves all files on disk")); - connect(deleteAllFinishedAction, SIGNAL(triggered()), SLOT(slotDeleteFinished())); - - KAction *deleteSelectedIncludingFilesAction = actionCollection()->addAction("delete_selected_download_including_files"); - deleteSelectedIncludingFilesAction->setText(i18nc("delete selected transfer item and files", "Remove Selected and Delete Files")); - deleteSelectedIncludingFilesAction->setIcon(KIcon("edit-delete")); - deleteSelectedIncludingFilesAction->setHelpText(i18n("Removes selected transfer and deletes files from disk in any case")); - connect(deleteSelectedIncludingFilesAction, SIGNAL(triggered()), SLOT(slotDeleteSelectedIncludingFiles())); - - KAction *redownloadSelectedAction = actionCollection()->addAction("redownload_selected_download"); - redownloadSelectedAction->setText(i18nc("redownload selected transfer item", "Redownload Selected")); - redownloadSelectedAction->setIcon(KIcon("view-refresh")); - connect(redownloadSelectedAction, SIGNAL(triggered()), SLOT(slotRedownloadSelected())); - - KAction *startAllAction = actionCollection()->addAction("start_all_download"); - startAllAction->setText(i18n("Start All")); - startAllAction->setIcon(KIcon("media-seek-forward")); - startAllAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_R)); - startAllAction->setHelpText(i18n("Starts / resumes all transfers")); - connect(startAllAction, SIGNAL(triggered()), SLOT(slotStartAllDownload())); - - KAction *startSelectedAction = actionCollection()->addAction("start_selected_download"); - startSelectedAction->setText(i18n("Start Selected")); - startSelectedAction->setIcon(KIcon("media-playback-start")); - startSelectedAction->setHelpText(i18n("Starts / resumes selected transfer")); - connect(startSelectedAction, SIGNAL(triggered()), SLOT(slotStartSelectedDownload())); - - KAction *stopAllAction = actionCollection()->addAction("stop_all_download"); - stopAllAction->setText(i18n("Pause All")); - stopAllAction->setIcon(KIcon("media-playback-pause")); - stopAllAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_P)); - stopAllAction->setHelpText(i18n("Pauses all transfers")); - connect(stopAllAction, SIGNAL(triggered()), SLOT(slotStopAllDownload())); - - KAction *stopSelectedAction = actionCollection()->addAction("stop_selected_download"); - stopSelectedAction->setText(i18n("Stop Selected")); - stopSelectedAction->setIcon(KIcon("media-playback-pause")); - stopSelectedAction->setHelpText(i18n("Pauses selected transfer")); - connect(stopSelectedAction, SIGNAL(triggered()), SLOT(slotStopSelectedDownload())); - - KActionMenu *startActionMenu = new KActionMenu(KIcon("media-playback-start"), i18n("Start"), - actionCollection()); - actionCollection()->addAction("start_menu", startActionMenu); - startActionMenu->setDelayed(true); - startActionMenu->addAction(startSelectedAction); - startActionMenu->addAction(startAllAction); - connect(startActionMenu, SIGNAL(triggered()), SLOT(slotStartDownload())); - - KActionMenu *stopActionMenu = new KActionMenu(KIcon("media-playback-pause"), i18n("Pause"), - actionCollection()); - actionCollection()->addAction("stop_menu", stopActionMenu); - stopActionMenu->setDelayed(true); - stopActionMenu->addAction(stopSelectedAction); - stopActionMenu->addAction(stopAllAction); - connect(stopActionMenu, SIGNAL(triggered()), SLOT(slotStopDownload())); - - KAction *openDestAction = actionCollection()->addAction("transfer_open_dest"); - openDestAction->setText(i18n("Open Destination")); - openDestAction->setIcon(KIcon("document-open")); - connect(openDestAction, SIGNAL(triggered()), SLOT(slotTransfersOpenDest())); - - KAction *openFileAction = actionCollection()->addAction("transfer_open_file"); - openFileAction->setText(i18n("Open File")); - openFileAction->setIcon(KIcon("document-open")); - connect(openFileAction, SIGNAL(triggered()), SLOT(slotTransfersOpenFile())); - - KAction *showDetailsAction = new KToggleAction(KIcon("document-properties"), i18n("Show Details"), actionCollection()); - actionCollection()->addAction("transfer_show_details", showDetailsAction); - connect(showDetailsAction, SIGNAL(triggered()), SLOT(slotTransfersShowDetails())); - - KAction *copyUrlAction = actionCollection()->addAction("transfer_copy_source_url"); - copyUrlAction->setText(i18n("Copy URL to Clipboard")); - copyUrlAction->setIcon(KIcon("edit-copy")); - connect(copyUrlAction, SIGNAL(triggered()), SLOT(slotTransfersCopySourceUrl())); - - KAction *transferHistoryAction = actionCollection()->addAction("transfer_history"); - transferHistoryAction->setText(i18n("&Transfer History")); - transferHistoryAction->setIcon(KIcon("view-history")); - transferHistoryAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_H)); - connect(transferHistoryAction, SIGNAL(triggered()), SLOT(slotTransferHistory())); - - KAction *transferGroupSettingsAction = actionCollection()->addAction("transfer_group_settings"); - transferGroupSettingsAction->setText(i18n("&Group Settings")); - transferGroupSettingsAction->setIcon(KIcon("preferences-system")); - transferGroupSettingsAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_G)); - connect(transferGroupSettingsAction, SIGNAL(triggered()), SLOT(slotTransferGroupSettings())); - - KAction *transferSettingsAction = actionCollection()->addAction("transfer_settings"); - transferSettingsAction->setText(i18n("&Transfer Settings")); - transferSettingsAction->setIcon(KIcon("preferences-system")); - transferSettingsAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_T)); - connect(transferSettingsAction, SIGNAL(triggered()), SLOT(slotTransferSettings())); - - KAction *listLinksAction = actionCollection()->addAction("import_links"); - listLinksAction->setText(i18n("Import &Links...")); - listLinksAction->setIcon(KIcon("view-list-text")); - listLinksAction->setShortcuts(KShortcut(Qt::CTRL + Qt::Key_L)); - connect(listLinksAction, SIGNAL(triggered()), SLOT(slotShowListLinks())); - - //create the download finished actions which can be displayed in the toolbar - KSelectAction *downloadFinishedActions = new KSelectAction(i18n("After downloads finished action"), this);//TODO maybe with name?? - actionCollection()->addAction("download_finished_actions", downloadFinishedActions); - downloadFinishedActions->setHelpText(i18n("Choose an action that is executed after all downloads have been finished.")); - - KAction *noAction = downloadFinishedActions->addAction(i18n("No Action")); - connect(noAction, SIGNAL(triggered()), SLOT(slotDownloadFinishedActions())); - downloadFinishedActions->addAction(noAction); - - KAction *quitAction = downloadFinishedActions->addAction(i18n("Quit KGet")); - quitAction->setData(KGet::Quit); - connect(quitAction, SIGNAL(triggered()), SLOT(slotDownloadFinishedActions())); - downloadFinishedActions->addAction(quitAction); - -#ifdef HAVE_KWORKSPACE - KAction *shutdownAction = downloadFinishedActions->addAction(i18n("Turn Off Computer")); - shutdownAction->setData(KGet::Shutdown); - connect(shutdownAction, SIGNAL(triggered()), SLOT(slotDownloadFinishedActions())); - downloadFinishedActions->addAction(shutdownAction); - - KAction *hibernateAction = downloadFinishedActions->addAction(i18n("Hibernate Computer")); - hibernateAction->setData(KGet::Hibernate); - connect(hibernateAction, SIGNAL(triggered()), SLOT(slotDownloadFinishedActions())); - downloadFinishedActions->addAction(hibernateAction); - - KAction *suspendAction = downloadFinishedActions->addAction(i18n("Suspend Computer")); - suspendAction->setData(KGet::Suspend); - connect(suspendAction, SIGNAL(triggered()), SLOT(slotDownloadFinishedActions())); - downloadFinishedActions->addAction(suspendAction); -#endif - - if (Settings::afterFinishActionEnabled()) { - downloadFinishedActions->setCurrentItem(Settings::afterFinishAction() + 1); - } else { - downloadFinishedActions->setCurrentItem(0); - } -} - -void MainWindow::slotDownloadFinishedActions() -{ - KAction *action = static_cast(QObject::sender()); - bool ok; - const int type = action->data().toInt(&ok); - if (ok) { - Settings::self()->setAfterFinishAction(type); - } - - //only after finish actions have a number assigned - Settings::self()->setAfterFinishActionEnabled(ok); - Settings::self()->writeConfig(); - slotNewConfig(); -} - -void MainWindow::init() -{ - //Here we import the user's transfers. - KGet::load( KStandardDirs::locateLocal("appdata", "transfers.kgt") ); - - if(Settings::enableSystemTray()) { - m_dock = new Tray(this); - } - - // enable dropping - setAcceptDrops(true); - - // enable hide toolbar - setStandardToolBarMenuEnabled(true); - - // DropTarget - m_drop = new DropTarget(this); - - if (Settings::firstRun()) { - m_drop->setDropTargetVisible(false); - - // reset the FirstRun config option - Settings::setFirstRun(false); - } - - if (Settings::showDropTarget() && !m_startWithoutAnimation) - m_drop->setDropTargetVisible(true); - - //auto paste stuff - lastClipboard = QApplication::clipboard()->text( QClipboard::Clipboard ).trimmed(); - clipboardTimer = new QTimer(this); - connect(clipboardTimer, SIGNAL(timeout()), SLOT(slotCheckClipboard())); - if ( Settings::autoPaste() ) - clipboardTimer->start(1000); - - if (Settings::webinterfaceEnabled()) - m_webinterface = new HttpServer(this); - - if (Settings::speedLimit()) - { - KGet::setGlobalDownloadLimit(Settings::globalDownloadLimit()); - KGet::setGlobalUploadLimit(Settings::globalUploadLimit()); - } - else - { - KGet::setGlobalDownloadLimit(0); - KGet::setGlobalUploadLimit(0); - } - - connect(KGet::model(), SIGNAL(transfersAddedEvent(QList)), this, SLOT(slotUpdateTitlePercent())); - connect(KGet::model(), SIGNAL(transfersRemovedEvent(QList)), this, SLOT(slotUpdateTitlePercent())); - connect(KGet::model(), SIGNAL(transfersChangedEvent(QMap)), - SLOT(slotTransfersChanged(QMap))); - connect(KGet::model(), SIGNAL(groupsChangedEvent(QMap)), - SLOT(slotGroupsChanged(QMap))); - -#ifdef DO_KGET_TEST - if (m_doTesting) - { - // Unit testing - TestKGet unitTest; - QTest::qExec(&unitTest); - } -#endif -} - -void MainWindow::slotToggleDropTarget() -{ - m_drop->setDropTargetVisible(!m_drop->isVisible()); -} - -void MainWindow::slotNewTransfer() -{ - NewTransferDialogHandler::showNewTransferDialog(KUrl()); -} - -void MainWindow::slotImportTransfers() -{ - QString filename = KFileDialog::getOpenFileName(KUrl(), - "*.kgt *.torrent|" + i18n("All Openable Files") + - " (*.kgt *.torrent)", this, i18n("Open File")); - - if(filename.endsWith(QLatin1String(".kgt"))) - { - KGet::load(filename); - return; - } - - if(!filename.isEmpty()) - KGet::addTransfer( KUrl( filename ) ); -} - -void MainWindow::slotUpdateTitlePercent() -{ - int percent = transfersPercent(); - if (percent != -1) { - setWindowTitle(i18nc("window title including overall download progress in percent", "KGet - %1%", percent)); - } else { - setWindowTitle(i18n("KGet")); - } -} - -void MainWindow::slotTransfersChanged(QMap transfers) -{ - QMapIterator it(transfers); - - //QList finishedTransfers; - bool update = false; - - while (it.hasNext()) { - it.next(); - - //TransferHandler * transfer = it.key(); - Transfer::ChangesFlags transferFlags = it.value(); - - if (transferFlags & Transfer::Tc_Percent || transferFlags & Transfer::Tc_Status) { - update = true; - break; - } - - // kDebug() << it.key() << ": " << it.value(); - } - - if (update) - slotUpdateTitlePercent(); -} - -void MainWindow::slotGroupsChanged(QMap groups) -{ - bool update = false; - foreach (const TransferGroup::ChangesFlags &groupFlags, groups) - { - if (groupFlags & TransferGroup::Gc_Percent) - { - update = true; - break; - } - } - if (update) - slotUpdateTitlePercent(); -} - -void MainWindow::slotQuit() -{ - if (KGet::schedulerRunning()) { - if (KMessageBox::warningYesNo(this, - i18n("Some transfers are still running.\n" - "Are you sure you want to close KGet?"), - i18n("Confirm Quit"), - KStandardGuiItem::quit(), KStandardGuiItem::cancel(), - "ExitWithActiveTransfers") != KMessageBox::Yes) - return; - } - - Settings::self()->writeConfig(); - qApp->quit(); -} - -void MainWindow::slotPreferences() -{ - //never reuse the preference dialog, to make sure its settings are always reloaded - PreferencesDialog * dialog = new PreferencesDialog( this, Settings::self() ); - dialog->setAttribute(Qt::WA_DeleteOnClose); - - // keep us informed when the user changes settings - connect( dialog, SIGNAL(settingsChanged(QString)), - this, SLOT(slotNewConfig()) ); - - dialog->show(); -} - -void MainWindow::slotExportTransfers() -{ - const QString filename = KFileDialog::getSaveFileName - (KUrl(), - "*.kgt|" + i18n("KGet Transfer List") + " (*.kgt)\n*.txt|" + i18n("Text File") + " (*.txt)", - this, - i18n("Export Transfers") - ); - - if (!filename.isEmpty()) { - const bool plain = !filename.endsWith("kgt"); - KGet::save(filename, plain); - } -} - -void MainWindow::slotDeleteGroup() -{ - QList groups = KGet::selectedTransferGroups(); - if (groups.count() != KGet::allTransferGroups().count()) { - KGet::delGroups(groups); - } -} - -void MainWindow::slotRenameGroup() -{ - bool ok = true; - QString groupName; - - foreach(TransferGroupHandler * it, KGet::selectedTransferGroups()) - { - groupName = KInputDialog::getText(i18n("Enter Group Name"), - i18n("Group name:"), it->name(), &ok, this); - if(ok) - it->setName(groupName); - } -} - -void MainWindow::slotSetIconGroup() -{ - KIconDialog dialog(this); - QString iconName = dialog.getIcon(); - TransferTreeSelectionModel *selModel = KGet::selectionModel(); - - QModelIndexList indexList = selModel->selectedRows(); - - if (!iconName.isEmpty()) - { - foreach (TransferGroupHandler *group, KGet::selectedTransferGroups()) - { - group->setIconName(iconName); - } - } - //emit dataChanged(indexList.first(),indexList.last()); -} - -void MainWindow::slotStartDownload() -{ - if (KGet::selectedTransfers().size() == 0 && KGet::selectedTransferGroups().size() == 0) { - slotStartAllDownload(); - } else { - slotStartSelectedDownload(); - } -} - -void MainWindow::slotStartAllDownload() -{ - KGet::setSchedulerRunning(true); -} - -void MainWindow::slotStartSelectedDownload() -{ - KGet::setSuspendScheduler(true); - foreach (TransferHandler *transfer, KGet::selectedTransfers()) { - transfer->start(); - } - foreach (TransferGroupHandler *group, KGet::selectedTransferGroups()) { - group->start(); - } - KGet::setSuspendScheduler(false); -} - -void MainWindow::slotStopDownload() -{ - if (KGet::selectedTransfers().size() == 0 && KGet::selectedTransferGroups().size() == 0) { - slotStopAllDownload(); - } else { - slotStopSelectedDownload(); - } -} - -void MainWindow::slotStopAllDownload() -{ - KGet::setSchedulerRunning(false); - - // This line ensures that each transfer is stopped. In the handler class - // the policy of the transfer will be correctly setted to None - foreach (TransferHandler * it, KGet::allTransfers()) - it->stop(); -} - -void MainWindow::slotStopSelectedDownload() -{ - KGet::setSuspendScheduler(true); - foreach (TransferHandler *transfer, KGet::selectedTransfers()) { - transfer->stop(); - } - foreach (TransferGroupHandler *group, KGet::selectedTransferGroups()) { - group->stop(); - } - KGet::setSuspendScheduler(false); -} - -void MainWindow::slotDeleteSelected() -{ - foreach (TransferHandler * it, KGet::selectedTransfers()) - { - if (it->status() != Job::Finished && it->status() != Job::FinishedKeepAlive) { - if (KMessageBox::warningYesNo(this, - i18np("Are you sure you want to delete the selected transfer?", - "Are you sure you want to delete the selected transfers?", KGet::selectedTransfers().count()), - i18n("Confirm transfer delete"), - KStandardGuiItem::remove(), KStandardGuiItem::cancel()) == KMessageBox::No) - { - return; - } - break; - } - } - - const QList selectedTransfers = KGet::selectedTransfers(); - if (!selectedTransfers.isEmpty()) { - foreach (TransferHandler *it, selectedTransfers) { - m_viewsContainer->closeTransferDetails(it);//TODO make it take QList? - } - KGet::delTransfers(KGet::selectedTransfers()); - } else { - //no transfers selected, delete groups if any are selected - slotDeleteGroup(); - } -} - -void MainWindow::slotDeleteSelectedIncludingFiles() -{ - const QList selectedTransfers = KGet::selectedTransfers(); - - if (!selectedTransfers.isEmpty()) { - if (KMessageBox::warningYesNo(this, - i18np("Are you sure you want to delete the selected transfer including files?", - "Are you sure you want to delete the selected transfers including files?", selectedTransfers.count()), - i18n("Confirm transfer delete"), - KStandardGuiItem::remove(), KStandardGuiItem::cancel()) == KMessageBox::No) { - return; - } - foreach (TransferHandler *it, selectedTransfers) { - m_viewsContainer->closeTransferDetails(it);//TODO make it take QList? - } - KGet::delTransfers(KGet::selectedTransfers(), KGet::DeleteFiles); - } else { - //no transfers selected, delete groups if any are selected - slotDeleteGroup(); - } -} - -void MainWindow::slotRedownloadSelected() -{ - foreach(TransferHandler * it, KGet::selectedTransfers()) - { - KGet::redownloadTransfer(it); - } -} - -void MainWindow::slotPriorityTop() -{ - QList selected = KGet::selectedTransfers(); - TransferHandler *after = 0; - TransferGroupHandler *group = 0; - foreach (TransferHandler *transfer, selected) { - if (!transfer) { - continue; - } - - //previous transfer was not of the same group, so after has to be reset as the group - if (!group || (group != transfer->group())) { - after = 0; - group = transfer->group(); - } - KGet::model()->moveTransfer(transfer, group, after); - after = transfer; - } -} - -void MainWindow::slotPriorityBottom() -{ - QList selected = KGet::selectedTransfers(); - QList groupTransfers; - TransferHandler *after = 0; - TransferGroupHandler *group = 0; - foreach (TransferHandler *transfer, selected) { - if (!transfer) { - continue; - } - - //previous transfer was not of the same group, so after has to be reset as the group - if (!group || (group != transfer->group())) { - group = transfer->group(); - groupTransfers = group->transfers(); - if (groupTransfers.isEmpty()) { - after = 0; - } else { - after = groupTransfers.last(); - } - } - - KGet::model()->moveTransfer(transfer, group, after); - after = transfer; - } -} - -void MainWindow::slotPriorityUp() -{ - QList selected = KGet::selectedTransfers(); - QList groupTransfers; - TransferHandler *after = 0; - int newIndex = -1; - TransferGroupHandler *group = 0; - foreach (TransferHandler *transfer, selected) { - if (!transfer) { - continue; - } - - //previous transfer was not of the same group, so group has to be reset - if (!group || (group != transfer->group())) { - group = transfer->group(); - groupTransfers = group->transfers(); - } - - after = 0; - if (!groupTransfers.isEmpty()) { - int index = groupTransfers.indexOf(transfer); - - //do not move higher than the first place - if (index > 0) { - //if only Transfers at the top are select do not change their order - if ((index - 1) != newIndex) { - newIndex = index - 1; - if (newIndex - 1 >= 0) { - after = groupTransfers[newIndex - 1]; - } - - //keep the list with the actual movements synchronised - groupTransfers.move(index, newIndex); - - KGet::model()->moveTransfer(transfer, group, after); - } else { - newIndex = index; - } - } else { - newIndex = 0; - } - } - } -} - -void MainWindow::slotPriorityDown() -{ - QList selected = KGet::selectedTransfers(); - QList groupTransfers; - int newIndex = -1; - TransferGroupHandler *group = 0; - for (int i = selected.count() - 1; i >= 0; --i) { - TransferHandler *transfer = selected[i]; - if (!transfer) { - continue; - } - - //previous transfer was not of the same group, so group has to be reset - if (!group || (group != transfer->group())) { - group = transfer->group(); - groupTransfers = group->transfers(); - } - - if (!groupTransfers.isEmpty()) { - int index = groupTransfers.indexOf(transfer); - - //do not move lower than the last place - if ((index != -1) && (index + 1 < groupTransfers.count())) { - //if only Transfers at the top are select do not change their order - if ((index + 1) != newIndex) { - newIndex = index + 1; - TransferHandler *after = groupTransfers[newIndex]; - - - //keep the list with the actual movements synchronised - groupTransfers.move(index, newIndex); - - KGet::model()->moveTransfer(transfer, group, after); - } else { - newIndex = index; - } - } else { - newIndex = index; - } - } - } -} - -void MainWindow::slotTransfersOpenDest() -{ - QStringList openedDirs; - foreach(TransferHandler * it, KGet::selectedTransfers()) - { - QString directory = it->dest().directory(); - if( !openedDirs.contains( directory ) ) - { - new KRun(directory, this, 0, true, false); - openedDirs.append( directory ); - } - } -} - -void MainWindow::slotTransfersOpenFile() -{ - foreach(TransferHandler * it, KGet::selectedTransfers()) - { - new KRun(it->dest(), this, 0, true, false); - } -} - -void MainWindow::slotTransfersShowDetails() -{ - foreach(TransferHandler * it, KGet::selectedTransfers()) - { - m_viewsContainer->showTransferDetails(it); - } -} - -void MainWindow::slotTransfersCopySourceUrl() -{ - foreach(TransferHandler * it, KGet::selectedTransfers()) - { - QString sourceurl = it->source().url(); - QClipboard *cb = QApplication::clipboard(); - cb->setText(sourceurl, QClipboard::Selection); - cb->setText(sourceurl, QClipboard::Clipboard); - } -} - -void MainWindow::slotDeleteFinished() -{ - foreach(TransferHandler * it, KGet::finishedTransfers()) { - m_viewsContainer->closeTransferDetails(it); - } - KGet::delTransfers(KGet::finishedTransfers()); -} - -void MainWindow::slotConfigureNotifications() -{ - KNotificationConfigWidget::configure("kget", this); -} - -void MainWindow::slotNewToolbarConfig() -{ - createGUI(); -} - -void MainWindow::slotNewConfig() -{ - // Update here properties modified in the config dialog and not - // parsed often by the code. When clicking Ok or Apply of - // PreferencesDialog, this function is called. - - if (m_drop) - m_drop->setDropTargetVisible(Settings::showDropTarget(), false); - - if (Settings::enableSystemTray() && !m_dock) { - m_dock = new Tray(this); - } else if (!Settings::enableSystemTray() && m_dock) { - setVisible(true); - delete m_dock; - m_dock = 0; - } - - if (clipboardTimer) { - if (Settings::autoPaste()) - clipboardTimer->start(1000); - else - clipboardTimer->stop(); - } - m_autoPasteAction->setChecked(Settings::autoPaste()); - - if (Settings::webinterfaceEnabled() && !m_webinterface) { - m_webinterface = new HttpServer(this); - } else if (m_webinterface && !Settings::webinterfaceEnabled()) { - delete m_webinterface; - m_webinterface = 0; - } else if (m_webinterface) { - m_webinterface->settingsChanged(); - } - - if (Settings::speedLimit()) - { - KGet::setGlobalDownloadLimit(Settings::globalDownloadLimit()); - KGet::setGlobalUploadLimit(Settings::globalUploadLimit()); - } - else - { - KGet::setGlobalDownloadLimit(0); - KGet::setGlobalUploadLimit(0); - } - - KGet::settingsChanged(); -} - -void MainWindow::slotToggleAutoPaste() -{ - bool autoPaste = !Settings::autoPaste(); - Settings::setAutoPaste( autoPaste ); - - if (autoPaste) - clipboardTimer->start(1000); - else - clipboardTimer->stop(); - m_autoPasteAction->setChecked(autoPaste); -} - -void MainWindow::slotCheckClipboard() -{ - const QString clipData = QApplication::clipboard()->text( QClipboard::Clipboard ).trimmed(); - - if (clipData != lastClipboard) { - lastClipboard = clipData; - if (lastClipboard.isEmpty()) - return; - - const KUrl url = KUrl(lastClipboard); - if (url.isValid() && !url.protocol().isEmpty() && url.hasPath() && url.hasHost() && !url.isLocalFile()) { - bool add = false; - const QString urlString = url.url(); - - //check the combined whitelist and blacklist - const QList types = Settings::autoPasteTypes(); - const QList syntaxes = Settings::autoPastePatternSyntaxes(); - const QStringList patterns = Settings::autoPastePatterns(); - const Qt::CaseSensitivity cs = (Settings::autoPasteCaseSensitive() ? Qt::CaseSensitive : Qt::CaseInsensitive); - for (int i = 0; i < types.count(); ++i) { - const QRegExp::PatternSyntax syntax = (syntaxes[i] == AutoPasteModel::Wildcard ? QRegExp::Wildcard : QRegExp::RegExp2); - QRegExp rx(patterns[i], cs, syntax); - if (rx.exactMatch(urlString)) { - add = (types[i] == AutoPasteModel::Include); - break; - } - } - - if (add) { - KGet::addTransfer(url); - } - } - } -} - -void MainWindow::slotShowMenubar() -{ - if (m_menubarAction->isChecked()) - menuBar()->show(); - else - menuBar()->hide(); -} - -void MainWindow::setSystemTrayDownloading(bool running) -{ - if (m_dock) - m_dock->setDownloading(running); -} - -void MainWindow::slotTransferHistory() -{ - TransferHistory *history = new TransferHistory(); - history->exec(); -} - -void MainWindow::slotTransferGroupSettings() -{ - QList list = KGet::selectedTransferGroups(); - foreach(TransferGroupHandler* group, list) - { - QPointer settings = new GroupSettingsDialog(this, group); - settings->exec(); - delete settings; - } -} - -void MainWindow::slotTransferSettings() -{ - QList list = KGet::selectedTransfers(); - foreach(TransferHandler* transfer, list) - { - QPointer settings = new TransferSettingsDialog(this, transfer); - settings->exec(); - delete settings; - } -} - -/** slots for link list **/ -void MainWindow::slotShowListLinks() -{ - KGetLinkView *link_view = new KGetLinkView(this); - link_view->importUrl(); - link_view->show(); -} - -void MainWindow::slotImportUrl(const QString &url) -{ - KGetLinkView *link_view = new KGetLinkView(this); - link_view->importUrl(url); - link_view->show(); -} - -/** widget events **/ -void MainWindow::closeEvent( QCloseEvent * e ) -{ - // if the event comes from out the application (close event) we decide between close or hide - // if the event comes from the application (system shutdown) we say goodbye - if(e->spontaneous()) { - e->ignore(); - if(!Settings::enableSystemTray()) - slotQuit(); - else - hide(); - } -} - -void MainWindow::hideEvent(QHideEvent *) -{ - Settings::setShowMain(false); -} - -void MainWindow::showEvent(QShowEvent *) -{ - Settings::setShowMain(true); -} - -void MainWindow::dragEnterEvent(QDragEnterEvent * event) -{ - event->setAccepted(KUrl::List::canDecode(event->mimeData()) - || event->mimeData()->hasText()); -} - -void MainWindow::dropEvent(QDropEvent * event) -{ - KUrl::List list = KUrl::List::fromMimeData(event->mimeData()); - - if (!list.isEmpty()) - { - if (list.count() == 1 && list.first().url().endsWith(QLatin1String(".kgt"))) - { - int msgBoxResult = KMessageBox::questionYesNoCancel(this, i18n("The dropped file is a KGet Transfer List"), "KGet", - KGuiItem(i18n("&Download"), KIcon("document-save")), - KGuiItem(i18n("&Load transfer list"), KIcon("list-add")), KStandardGuiItem::cancel()); - - if (msgBoxResult == 3) //Download - NewTransferDialogHandler::showNewTransferDialog(list.first().url()); - if (msgBoxResult == 4) //Load - KGet::load(list.first().url()); - } - else - { - if (list.count() == 1) - NewTransferDialogHandler::showNewTransferDialog(list.first().url()); - else - NewTransferDialogHandler::showNewTransferDialog(list); - } - } - else - { - NewTransferDialogHandler::showNewTransferDialog(KUrl()); - } -} - -#include "moc_mainwindow.cpp" diff --git a/kget/mainwindow.h b/kget/mainwindow.h deleted file mode 100644 index c5fdaa5c..00000000 --- a/kget/mainwindow.h +++ /dev/null @@ -1,155 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 by Patrick Charbonnier - Based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - Copyright (C) 2006 Dario Massarin - Copyright (C) 2009 - 2010 Matthias Fuchs - - 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. -*/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include -#include -#include - -#include -#include "ui/tray.h" -#include "core/transfer.h" -#include "core/transfergroup.h" - -#include - -class ViewsContainer; -class DropTarget; -class DBusKgetWrapper; -class HttpServer; -class KGet; - -/** - * The main window of KGet. - * - * Can be collapsed or expanded. - */ -class MainWindow : public KXmlGuiWindow -{ - friend class DBusKGetWrapper; - friend class DlgWebinterface; - -Q_OBJECT -public: - explicit MainWindow(bool showMainwindow = true, bool startWithoutAnimation = false, bool doTesting = false, QWidget *parent = 0); - ~MainWindow(); - - virtual void setSystemTrayDownloading(bool running); - - //no slot, to make sure that MainWindow is correctly initialized before any transfers get added - void init(); - -public slots: - void slotQuit(); - void slotImportUrl(const QString &url); - void slotUpdateTitlePercent(); - -protected: - // ignore/accept quit events - virtual void closeEvent(QCloseEvent *); - virtual void hideEvent(QHideEvent *); - virtual void showEvent(QShowEvent *); - - // drag and drop - virtual void dragEnterEvent(QDragEnterEvent *); - virtual void dropEvent(QDropEvent *); - - // set sensitive initial size - virtual QSize sizeHint() const; - -private slots: - // slots connected to actions - void slotToggleDropTarget(); - void slotNewTransfer(); - void slotImportTransfers(); - void slotExportTransfers(); - void slotPreferences(); - void slotDeleteGroup(); - void slotRenameGroup(); - void slotSetIconGroup(); - void slotStartDownload(); - void slotStopDownload(); - void slotConfigureNotifications(); - void slotToggleAutoPaste(); - void slotShowMenubar(); - void slotTransferGroupSettings(); - void slotTransferSettings(); - void slotPriorityTop(); - void slotPriorityBottom(); - void slotPriorityUp(); - void slotPriorityDown(); - void slotDownloadFinishedActions(); - - // transfers slots - void slotStopAllDownload(); - void slotStopSelectedDownload(); - void slotStartAllDownload(); - void slotStartSelectedDownload(); - void slotDeleteSelected(); - void slotDeleteSelectedIncludingFiles(); - void slotRedownloadSelected(); - void slotTransfersOpenDest(); - void slotTransfersOpenFile(); - void slotTransfersShowDetails(); - void slotTransfersCopySourceUrl(); - void slotDeleteFinished(); - - // misc slots - void slotNewToolbarConfig(); - void slotNewConfig(); - void slotCheckClipboard(); - void slotTransferHistory(); - - // import links slots - void slotShowListLinks(); - - //Model changes - void slotTransfersChanged(QMap transfers); - void slotGroupsChanged(QMap groups); - -private: - /** - * Returns the completed percents of all active transfers - */ - int transfersPercent(); - - // one-time functions - void setupActions(); - - KGet * m_kget; - - // internal widgets - ViewsContainer * m_viewsContainer; - - // separated widgets - DropTarget * m_drop; - Tray * m_dock; - - // actions - KToggleAction * m_autoPasteAction; - KToggleAction * m_menubarAction; - - // for autopaste function - QString lastClipboard; - // timer for checking clipboard - autopaste function - QTimer *clipboardTimer; - - bool m_startWithoutAnimation; - bool m_doTesting; // UnitTest flag - - HttpServer *m_webinterface; -}; - -#endif diff --git a/kget/plasma/CMakeLists.txt b/kget/plasma/CMakeLists.txt deleted file mode 100644 index 73963074..00000000 --- a/kget/plasma/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_subdirectory(applet) -add_subdirectory(engine) -add_subdirectory(runner) diff --git a/kget/plasma/applet/CMakeLists.txt b/kget/plasma/applet/CMakeLists.txt deleted file mode 100644 index d21f0e9f..00000000 --- a/kget/plasma/applet/CMakeLists.txt +++ /dev/null @@ -1,53 +0,0 @@ -set(kgetcommonapplet_SRCS - common/kgetappletutils.cpp - common/kgetapplet.cpp -) - -qt4_add_dbus_interface(kgetcommonapplet_SRCS - ../../dbus/org.kde.kget.transfer.xml - transfer_interface -) - -set(kgetbarapplet_SRCS - barapplet/kgetbarapplet.cpp - ${kgetcommonapplet_SRCS} -) - -qt4_add_dbus_interface(kgetbarapplet_SRCS - ../../dbus/org.kde.kget.main.xml - kget_interface -) - -kde4_add_plugin(plasma_kget_barapplet ${kgetbarapplet_SRCS}) -target_link_libraries(plasma_kget_barapplet KDE4::plasma KDE4::kdeui) - -install( - TARGETS plasma_kget_barapplet - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) -install( - FILES barapplet/kgetbarapplet-default.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) - -set(kgetpiechart_SRCS - piechart/kgetpiechart.cpp - ${kgetcommonapplet_SRCS} -) - -qt4_add_dbus_interface(kgetpiechart_SRCS - ../../dbus/org.kde.kget.main.xml - kget_interface -) - -kde4_add_plugin(plasma_kget_piechart ${kgetpiechart_SRCS}) -target_link_libraries(plasma_kget_piechart KDE4::plasma KDE4::kdeui) - -install( - TARGETS plasma_kget_piechart - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) -install( - FILES piechart/kgetpiechartapplet-default.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) diff --git a/kget/plasma/applet/Messages.sh b/kget/plasma/applet/Messages.sh deleted file mode 100755 index 77bf9f73..00000000 --- a/kget/plasma/applet/Messages.sh +++ /dev/null @@ -1,2 +0,0 @@ -#! /usr/bin/env bash -$XGETTEXT */*.cpp -o $podir/plasma_applet_kget.pot diff --git a/kget/plasma/applet/barapplet/kgetbarapplet-default.desktop b/kget/plasma/applet/barapplet/kgetbarapplet-default.desktop deleted file mode 100644 index c5864c26..00000000 --- a/kget/plasma/applet/barapplet/kgetbarapplet-default.desktop +++ /dev/null @@ -1,124 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Name=KGet Barchart Applet -Name[ast]=Miniaplicación gráfica de barres de KGet -Name[bs]=trakasti grafikon KGeta -Name[ca]=Miniaplicació de diagrama de barres del KGet -Name[ca@valencia]=Miniaplicació de diagrama de barres del KGet -Name[cs]=Applet pro sloupcový graf v KGet -Name[da]=KGet søjlediagram-applet -Name[de]=KGet Balkengrafik-Modul -Name[el]=Μικροεφαρμογή ραβδογραφήματος KGet -Name[en_GB]=KGet Barchart Applet -Name[es]=Miniaplicación de gráfica de barras de KGet -Name[et]=KGeti tulpdiagrammi aplett -Name[eu]=KGet-eko barra-diagramen miniaplikazioa -Name[fi]=KGetin pylväskaaviosovelma -Name[fr]=Composant graphique d'histogramme pour KGet -Name[ga]=Feidhmchláirín barrachairte KGet -Name[gl]=Applet de diagrama de barras de KGet -Name[hr]=Applet za stupčasti dijagram za KGet -Name[hu]=KGet oszlopdiagram -Name[ia]=Applet Barchart de KGet (carta a barras) -Name[it]=Grafici a barre per KGet -Name[ja]=KGet 棒グラフアプレット -Name[kk]=KGet гистограмма апплеті -Name[km]=អាប់ភ្លេត​គំនូស​តាង​របស់ KGet -Name[ko]=KGet 막대 그래프 애플릿 -Name[lt]=KGet stulpelinės diagramos programėlė -Name[lv]=KGet stabiņu tabulas sīkrīks -Name[nb]=Miniprogram for KGet-stolpediagram -Name[nds]=KGet-Balkengrafik-Lüttprogramm -Name[nl]=Balkgrafiekapplet voor KGet -Name[nn]=KGet-søylediagram -Name[pa]=ਕੇ-ਗਿੱਟ ਬਾਰਚਾਰਟ ਐਪਲਿਟ -Name[pl]=Wykres słupkowy w KGet -Name[pt]='Applet' de Gráfico de Barras do KGet -Name[pt_BR]=Miniaplicativo de gráfico de barras do KGet -Name[ro]=Miniaplicație KGet DiagramăBară -Name[ru]=KGet: ход загрузки -Name[si]=KGet තීරු ප්‍රස්ථාර යෙදුම -Name[sk]=Stĺpcový graf pre KGet -Name[sl]=KGet (stolpični graf) -Name[sr]=тракасти графикон К‑гета -Name[sr@ijekavian]=тракасти графикон К‑гета -Name[sr@ijekavianlatin]=trakasti grafikon KGeta -Name[sr@latin]=trakasti grafikon KGeta -Name[sv]=Stapeldiagram-miniprogram för Kget -Name[tr]=KGet Sütun Grafiği Programcığı -Name[ug]=KGet بالداق دىئاگرامما ئەپچە -Name[uk]=Аплет гістограми KGet -Name[x-test]=xxKGet Barchart Appletxx -Name[zh_CN]=KGet 柱形图小程序 -Name[zh_TW]=KGet 圖表小程式 -Comment=KGet barchart applet -Comment[ar]=بريمج KGet عمود خُطاطة -Comment[ast]=Miniaplicación gráfica de barres de KGet -Comment[bs]=Aplet trakastog grafikona za KGet -Comment[ca]=Miniaplicació de diagrama de barres del KGet -Comment[ca@valencia]=Miniaplicació de diagrama de barres del KGet -Comment[cs]=Applet pro sloupcový graf v KGet -Comment[da]=KGet søjlediagram-applet -Comment[de]=KGet Balkengrafik-Modul -Comment[el]=Μικροεφαρμογή ραβδογραφήματος KGet -Comment[en_GB]=KGet barchart applet -Comment[es]=Miniaplicación de gráfica de barras de KGet -Comment[et]=KGeti tulpdiagrammi aplett -Comment[eu]=KGet-eko barra-diagramen miniaplikazioa -Comment[fi]=KGetin pylväskaaviosovelma -Comment[fr]=Composant graphique d'histogramme pour KGet -Comment[ga]=Feidhmchláirín barrachairte KGet -Comment[gl]=Applet de diagrama de barras de KGet -Comment[hne]=केगेट बारचार्ट ऐप्लेट -Comment[hr]=Applet za stupčasti dijagram za KGet -Comment[hu]=KGet oszlopdiagram -Comment[ia]=Applet Barchart de KGet (carta a barras) -Comment[it]=Grafici a barre per KGet -Comment[ja]=KGet 棒グラフアプレット -Comment[kk]=KGet гистограммасының апплеті -Comment[km]=អាប់ភ្លេត​គំនូស​តាង​របារ​របស់ KGet -Comment[ko]=KGet 막대 그래프 애플릿 -Comment[lt]=KGet stulpelinės diagramos programėlė -Comment[lv]=KGet stabiņu tabulas sīkrīks -Comment[ml]=കെഗെറ്റ് ബാര്‍ചാര്‍ട്ട് എന്ന ലഘുപ്രയോഗം -Comment[nb]=Miniprogram for KGet-stolpediagram -Comment[nds]=Balkengrafik-Lüttprogramm för KGet -Comment[nl]=Balkgrafiekapplet voor KGet -Comment[nn]=KGet-søylediagram -Comment[pa]=ਕੇ-ਗਿੱਟ ਬਾਰਚਾਰਟ ਐਪਲਿਟ -Comment[pl]=Aplet KGet pokazujący wykres słupkowy -Comment[pt]='Applet' de gráfico de barras do KGet -Comment[pt_BR]=Miniaplicativo de gráfico de barras do KGet -Comment[ro]=Miniaplicație KGet DiagramăBară -Comment[ru]=Показывает загрузки KGet в линейных диаграммах -Comment[si]=KGet තීරු ප්‍රස්ථාර යෙදුම -Comment[sk]=Stĺpcový graf pre KGet -Comment[sl]=Stolpični graf za KGet -Comment[sq]=KGet barchart applet -Comment[sr]=Аплет тракастог графикона за К‑гет -Comment[sr@ijekavian]=Аплет тракастог графикона за К‑гет -Comment[sr@ijekavianlatin]=Aplet trakastog grafikona za KGet -Comment[sr@latin]=Aplet trakastog grafikona za KGet -Comment[sv]=Stapeldiagram-miniprogram för Kget -Comment[tr]=KGet sütun grafiği programcığı -Comment[ug]=KGet بالداق دىئاگرامما ئەپچە -Comment[uk]=Аплет гістограми KGet -Comment[x-test]=xxKGet barchart appletxx -Comment[zh_CN]=KGet 柱形图小程序 -Comment[zh_TW]=KGet 圖表小程式 -Icon=kget -Type=Service -ServiceTypes=Plasma/Applet - -X-KDE-Library=plasma_kget_barapplet - -X-KDE-PluginInfo-Author=Javier Goday -X-KDE-PluginInfo-Email= -X-KDE-PluginInfo-Name=barapplet -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-Category=Online Services -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true - diff --git a/kget/plasma/applet/barapplet/kgetbarapplet.cpp b/kget/plasma/applet/barapplet/kgetbarapplet.cpp deleted file mode 100644 index 66847bfd..00000000 --- a/kget/plasma/applet/barapplet/kgetbarapplet.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 "barapplet/kgetbarapplet.h" -#include "barapplet/kgetbarapplet_p.h" - -#include "../../../core/transferhandler.h" - -#include -#include -#include - -#include - -#include - - -KGetBarApplet::Private::Private(QGraphicsWidget *parent) - : QGraphicsWidget(parent) -{ - QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical, this); - - m_scrollWidget = new Plasma::ScrollWidget(); - m_containerWidget = new QGraphicsWidget(m_scrollWidget); - m_scrollWidget->setWidget(m_containerWidget); - m_containerLayout = new QGraphicsLinearLayout(Qt::Vertical, m_containerWidget); - - layout->addItem(m_scrollWidget); - - setLayout(layout); -} - -KGetBarApplet::Private::~Private() -{ -} - -void KGetBarApplet::Private::addTransfers(const QList &transfers) -{ - foreach (OrgKdeKgetTransferInterface *transfer, transfers) { - if (m_items.contains(transfer)) { - continue; - } - - connect(transfer, SIGNAL(transferChangedEvent(int)), this, SLOT(slotUpdateTransfer(int))); - - QString fileName = KUrl(transfer->dest().value()).fileName(); - kDebug() << fileName; - - Item *item = new Item; - item->proxy = new QGraphicsProxyWidget(); - item->progressBar = new QProgressBar(); - item->proxy->setWidget(item->progressBar); - item->progressBar->setFormat(fileName + " %v%"); - m_items[transfer] = item; - - //running downloads are prepended, others appended - if (transfer->percent() == 100) { - m_containerLayout->addItem(item->proxy); - } else { - m_containerLayout->insertItem(0, item->proxy); - } - - item->progressBar->setValue(transfer->percent().value()); - } -} - -void KGetBarApplet::Private::removeTransfers(const QList &transfers) -{ - // remove the progressbars for the deleted transfers - QHash::iterator it; - for (it = m_items.begin(); it != m_items.end(); ) { - OrgKdeKgetTransferInterface *transfer = it.key(); - if (transfers.contains(transfer)) { - Item *item = it.value(); - it = m_items.erase(it); - - m_containerLayout->removeItem(item->proxy); - item->proxy->deleteLater(); - item->progressBar->deleteLater(); - delete item; - } else { - ++it; - } - } -} - -void KGetBarApplet::Private::slotUpdateTransfer(int transferChange) -{ - OrgKdeKgetTransferInterface *transfer = qobject_cast(QObject::sender()); - - if (transfer && m_items.contains(transfer)) { - Item *item = m_items[transfer]; - - if (transferChange & Transfer::Tc_Percent) { - item->progressBar->setValue(transfer->percent()); - } - if (transferChange & Transfer::Tc_FileName) { - const QString fileName = KUrl(transfer->dest().value()).fileName(); - item->progressBar->setFormat(fileName + " %v%"); - item->progressBar->setValue(transfer->percent()); - } - } -} - -KGetBarApplet::KGetBarApplet(QObject *parent, const QVariantList &args) - : KGetApplet(parent, args) -{ -} - -KGetBarApplet::~KGetBarApplet() -{ -} - -void KGetBarApplet::init() -{ - d = new KGetBarApplet::Private(this); - setDataWidget(d); - connect(this, SIGNAL(transfersAdded(QList)), d, SLOT(addTransfers(QList))); - connect(this, SIGNAL(transfersRemoved(QList)), d, SLOT(removeTransfers(QList))); - - KGetApplet::init(); -} - -#include "moc_kgetbarapplet.cpp" -#include "moc_kgetbarapplet_p.cpp" diff --git a/kget/plasma/applet/barapplet/kgetbarapplet.h b/kget/plasma/applet/barapplet/kgetbarapplet.h deleted file mode 100644 index 8a84694e..00000000 --- a/kget/plasma/applet/barapplet/kgetbarapplet.h +++ /dev/null @@ -1,49 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * - * Copyright (C) 2007 by Javier Goday - * * - * 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 KGETBARAPPLET_H -#define KGETBARAPPLET_H - -#include "common/kgetapplet.h" -#include - -namespace Plasma { - class Svg; -} - -#include -#include - -class KGetBarApplet : public KGetApplet -{ - Q_OBJECT -public: - KGetBarApplet(QObject *parent, const QVariantList &args); - ~KGetBarApplet(); - - void init(); - -private: - class Private; - Private *d; -}; - -K_EXPORT_PLASMA_APPLET(barapplet, KGetBarApplet) - -#endif diff --git a/kget/plasma/applet/barapplet/kgetbarapplet_p.h b/kget/plasma/applet/barapplet/kgetbarapplet_p.h deleted file mode 100644 index 93e873f9..00000000 --- a/kget/plasma/applet/barapplet/kgetbarapplet_p.h +++ /dev/null @@ -1,63 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 KGETBARAPPLET_P_H -#define KGETBARAPPLET_P_H - -#include -#include - -namespace Plasma -{ - class ScrollWidget; -} - -#include -#include - -class KGetBarApplet::Private : public QGraphicsWidget -{ - Q_OBJECT - - public: - Private(QGraphicsWidget *parent = 0); - ~Private(); - - public slots: - void addTransfers(const QList &transfers); - void removeTransfers(const QList &transfers); - - private slots: - void slotUpdateTransfer(int transferChange); - - private: - struct Item - { - QGraphicsProxyWidget *proxy; - QProgressBar *progressBar; - }; - - Plasma::ScrollWidget *m_scrollWidget; - QGraphicsWidget *m_containerWidget; - QGraphicsLinearLayout *m_containerLayout; - QHash m_items; -}; - -#endif diff --git a/kget/plasma/applet/common/kgetapplet.cpp b/kget/plasma/applet/common/kgetapplet.cpp deleted file mode 100644 index e46ef331..00000000 --- a/kget/plasma/applet/common/kgetapplet.cpp +++ /dev/null @@ -1,398 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * - * Copyright (C) 2008 - 2009 by Lukas Appelhans - * * - * 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 "kgetapplet.h" -#include "kget_interface.h" -#include "kgetappletutils.h" -#include "../../../core/transferhandler.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -const int ProxyWidget::MARGIN = 20; -const int ProxyWidget::TOP_MARGIN = 55; -const int ProxyWidget::LEFT_MARGIN = 15; -const int ProxyWidget::SPACING = 4; - -const QString KGetApplet::KGET_DBUS_SERVICE = "org.kde.kget"; -const QString KGetApplet::KGET_DBUS_PATH = "/KGet"; -const int KGetApplet::POLL_INTERVAL = 1500; - -ProxyWidget::ProxyWidget(QGraphicsWidget * parent) - : QGraphicsWidget(parent), - m_layout(0), - m_dataWidget(0) -{ - m_layout = new QGraphicsLinearLayout(Qt::Vertical, this); - m_layout->setSpacing(SPACING); - //m_layout->setContentsMargins(MARGIN, TOP_MARGIN, MARGIN, MARGIN); - - themeChanged(); - - connect(Plasma::Theme::defaultTheme(), SIGNAL(themeChanged()), SLOT(themeChanged())); -} - -ProxyWidget::~ProxyWidget() -{ -} - -void ProxyWidget::paint(QPainter * p, const QStyleOptionGraphicsItem * option, QWidget * widget) -{ - const QRect rect = option->rect; - - p->setRenderHint(QPainter::SmoothPixmapTransform); - - p->setFont(m_font); - p->setPen(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor)); - - QRect iconRect(QPoint(rect.x() + SPACING + 10, rect.y() + SPACING + 10), QSize(m_textHeight, m_textHeight)); - - KIcon("kget").paint(p, iconRect); - p->drawText(QRectF(rect.x() + SPACING * 2 + 10 + iconRect.width(), rect.y() + SPACING + 10, - m_textWidth, m_textHeight), i18n("KGet")); - p->drawLine(QPointF(rect.x() + SPACING + 10, rect.y() + SPACING * 2 + 10 + m_textHeight), - QPointF(rect.width() - SPACING - 10, rect.y() + SPACING * 2 + 10 + m_textHeight)); - - QGraphicsWidget::paint(p, option, widget); -} - -void ProxyWidget::themeChanged() -{ - m_font = Plasma::Theme::defaultTheme()->font(Plasma::Theme::DefaultFont); - m_font.setBold(true); - m_font.setPointSize(15); - - QFontMetrics metrics(m_font); - m_textWidth = metrics.width(i18n("KGet")); - m_textHeight = metrics.height(); - - m_layout->setContentsMargins(MARGIN, MARGIN + m_textHeight + SPACING + 10, MARGIN, MARGIN); -} - -void ProxyWidget::setDataWidget(QGraphicsWidget *widget) -{ - if (m_layout->count()) - m_layout->removeAt(0); - m_layout->addItem(widget); - m_dataWidget = widget; -} - -QGraphicsWidget *ProxyWidget::dataWidget() -{ - return m_dataWidget; -} - -KGetApplet::KGetApplet(QObject *parent, const QVariantList &args) - : Plasma::PopupApplet(parent, args), - m_proxyWidget(0), - m_errorWidget(0), - m_dataWidget(0), - m_globalProgress(0), - m_icon(0), - m_engine(0), - m_totalSize(0), - m_downloadedSize(0) -{ - setAspectRatioMode(Plasma::IgnoreAspectRatio); - setBackgroundHints(Applet::DefaultBackground); - setAcceptDrops(true); - m_proxyWidget = new ProxyWidget(this); -} - -KGetApplet::~KGetApplet() -{ -} - -void KGetApplet::init() -{ - KGlobal::locale()->insertCatalog("plasma_applet_kget"); - - setPopupIcon("kget"); - m_engine = dataEngine("kget"); - if (m_engine) { - m_engine->connectSource("KGet", this, POLL_INTERVAL); - } else { - kDebug() << "KGet Engine could not be loaded"; - } - m_globalProgress = new Plasma::Meter(this); - m_globalProgress->setMeterType(Plasma::Meter::BarMeterHorizontal); - m_globalProgress->setMinimumSize(QSize(0, 0)); - setGraphicsWidget(m_proxyWidget); -} - -void KGetApplet::slotKgetStarted() -{ - m_engine->query("KGet"); -} - -void KGetApplet::dataUpdated(const QString &name, const Plasma::DataEngine::Data &data) -{ - Q_UNUSED(name) - kDebug() << layout()->count(); - if (data["error"].toBool()) { - if (!m_errorWidget) { - m_errorWidget = new ErrorWidget(data["errorMessage"].toString(), this); - connect(m_errorWidget, SIGNAL(kgetStarted()), this, SLOT(slotKgetStarted())); - } - if (m_proxyWidget->dataWidget() != m_errorWidget) { - m_proxyWidget->setDataWidget(m_errorWidget); - m_errorWidget->show(); - m_dataWidget->hide(); - } - } else if (!data["error"].toBool()) { - if (m_errorWidget && m_errorWidget->isVisible()) - m_errorWidget->hide(); - if (m_proxyWidget->dataWidget() != m_dataWidget) { - m_proxyWidget->setDataWidget(m_dataWidget); - m_dataWidget->show(); - } - if (m_transfers.isEmpty()) { - transferAdded(data["transfers"].toMap()); - } else { - if (data.contains("transferAdded")) { - transferAdded(data["transferAdded"].toMap()); - } - if (data.contains("transferRemoved")) { - transferRemoved(data["transferRemoved"].toMap()); - } - } - } -} - -void KGetApplet::transferAdded(const QVariantMap &transfer) -{ - QList added; - QVariantMap::const_iterator it; - QVariantMap::const_iterator itEnd = transfer.constEnd(); - for (it = transfer.constBegin(); it != itEnd; ++it) { - OrgKdeKgetTransferInterface *newTransfer = new OrgKdeKgetTransferInterface("org.kde.kget", it.value().toString(), QDBusConnection::sessionBus(), this); - connect(newTransfer, SIGNAL(transferChangedEvent(int)), this, SLOT(slotUpdateTransfer(int))); - - added.append(newTransfer); - - m_transfers[newTransfer].size = newTransfer->totalSize(); - m_transfers[newTransfer].downloadedSize = newTransfer->downloadedSize(); - m_transfers[newTransfer].source = newTransfer->source(); - m_downloadedSize += m_transfers[newTransfer].downloadedSize; - m_totalSize += m_transfers[newTransfer].size; - } - - if (!added.isEmpty()) { - emit transfersAdded(added); - emit update(); - updateGlobalProgress(); - } -} - -void KGetApplet::transferRemoved(const QVariantMap &transfer) -{ - QList removed; - - foreach (const QVariant &it, transfer.keys()) { - foreach (const Data &it2, m_transfers.values()) { - OrgKdeKgetTransferInterface* iface = m_transfers.key(it2); - if (it.toString() == it2.source) { - removed.append(iface); - - m_downloadedSize -= m_transfers[iface].downloadedSize; - m_totalSize -= m_transfers[iface].size; - - m_transfers.remove(iface); - } - } - } - - if (!removed.isEmpty()) { - emit transfersRemoved(removed); - emit update(); - updateGlobalProgress(); - } -} - -void KGetApplet::slotUpdateTransfer(int transferChange) -{ - OrgKdeKgetTransferInterface *transfer = qobject_cast(QObject::sender()); - - if (transfer && m_transfers.contains(transfer)) { - if (transferChange & Transfer::Tc_TotalSize) { - m_totalSize -= m_transfers[transfer].size; - m_downloadedSize -= m_transfers[transfer].downloadedSize; - - m_transfers[transfer].size = transfer->totalSize(); - m_transfers[transfer].downloadedSize = transfer->downloadedSize(); - m_transfers[transfer].source = transfer->source(); - m_totalSize += m_transfers[transfer].size; - m_downloadedSize += m_transfers[transfer].downloadedSize; - - updateGlobalProgress(); - return; - } - if (transferChange & Transfer::Tc_DownloadedSize) { - m_downloadedSize -= m_transfers[transfer].downloadedSize; - - m_transfers[transfer].downloadedSize = transfer->downloadedSize(); - m_downloadedSize += m_transfers[transfer].downloadedSize; - - updateGlobalProgress(); - return; - } - } -} - -void KGetApplet::updateGlobalProgress() -{ - if (m_globalProgress && m_totalSize) { - m_globalProgress->setValue((m_downloadedSize * 100) / m_totalSize); - } -} - -void KGetApplet::setDataWidget(QGraphicsWidget * widget) -{ - m_dataWidget = widget; - if (m_proxyWidget->dataWidget() != m_errorWidget) - m_proxyWidget->setDataWidget(widget); -} - -void KGetApplet::constraintsEvent(Plasma::Constraints constraints) -{ - if (constraints & Plasma::SizeConstraint) { - QGraphicsLayoutItem *widget = layout()->itemAt(0); - Plasma::IconWidget *icon = 0; - if (!m_icon && (icon = dynamic_cast(widget))) { - m_icon = icon; - } - if (widget == m_proxyWidget && m_globalProgress->isVisible()) { - kDebug() << "remove progressbar"; - m_globalProgress->hide(); - dynamic_cast(layout())->removeItem(m_globalProgress); - } else if (m_icon && m_icon->isVisible()) { - QGraphicsLinearLayout *lay = dynamic_cast(layout()); - kDebug() << "switch to progressbar"; - m_globalProgress->show(); - m_icon->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - m_icon->setPreferredSize(size().height(), size().height()); - m_globalProgress->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - for (int i = 0; i != 2; i++) { - if (lay->count()) - lay->removeAt(0); - } - lay->addItem(m_icon); - lay->addItem(m_globalProgress); - } - /*if (layout()->count() && dynamic_cast(layout()->itemAt(0)) && !m_progressProxy.isVisible()) { - qobject_cast(layout())->addItem(m_progressProxy); - m_progressProxy->show(); - } else if (m_progressProxy.isVisible() && layout->count() == 1) { - kDebug(); - layout()->removeAt(0); - m_progressProxy->hide(); - }*/ - } -} - -bool KGetApplet::sceneEventFilter(QGraphicsItem * watched, QEvent * event) -{ - Q_UNUSED(watched) - switch (event->type()) - { - case QEvent::GraphicsSceneDrop: - dropEvent(static_cast(event)); - break; - case QEvent::Drop: - dropEvent(static_cast(event)); - break; - default: - break; - } - return Plasma::Applet::sceneEventFilter(watched, event); - //This is not 100% kosher, I think we should just return false, but otherwise the plasma resize buttons etc don't show u -} - -void KGetApplet::dropEvent(QGraphicsSceneDragDropEvent * event) -{ - QStringList urls; - if (event->mimeData()->hasUrls()) - { - foreach (const KUrl &url, event->mimeData()->urls()) - urls.append(url.url()); - } - else - { - event->ignore(); - return; - } - - if (QDBusConnection::sessionBus().interface()->isServiceRegistered(KGET_DBUS_SERVICE)) - { - OrgKdeKgetMainInterface kget_interface(KGET_DBUS_SERVICE, KGET_DBUS_PATH, - QDBusConnection::sessionBus()); - - kget_interface.showNewTransferDialog(urls); - } - else - { - QProcess::startDetached("kget", urls); - } - event->accept(); -} - -void KGetApplet::dropEvent(QDropEvent * event) -{ - QStringList urls; - if (event->mimeData()->hasUrls()) - { - foreach (const KUrl &url, event->mimeData()->urls()) - urls.append(url.url()); - } - else - { - event->ignore(); - return; - } - - if (QDBusConnection::sessionBus().interface()->isServiceRegistered(KGET_DBUS_SERVICE)) - { - OrgKdeKgetMainInterface kget_interface(KGET_DBUS_SERVICE, KGET_DBUS_PATH, - QDBusConnection::sessionBus()); - - kget_interface.showNewTransferDialog(urls); - event->accept(); - } - else - { - QProcess::startDetached("kget", urls); - } - event->accept(); -} - -#include "moc_kgetapplet.cpp" diff --git a/kget/plasma/applet/common/kgetapplet.h b/kget/plasma/applet/common/kgetapplet.h deleted file mode 100644 index 83af064a..00000000 --- a/kget/plasma/applet/common/kgetapplet.h +++ /dev/null @@ -1,129 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * - * Copyright (C) 2008 by Lukas Appelhans - * * - * 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 KGETAPPLET_H -#define KGETAPPLET_H - -#include -#include -#include "transfer_interface.h" - -#include - -#include -#include -#include -class ErrorWidget; - -namespace Plasma -{ - class Theme; - class IconWidget; - class Meter; -} - -class ProxyWidget : public QGraphicsWidget -{ - Q_OBJECT - public: - ProxyWidget(QGraphicsWidget * parent); - ~ProxyWidget(); - - void paint(QPainter * p, const QStyleOptionGraphicsItem * option, QWidget * widget); - - void setDataWidget(QGraphicsWidget *widget); - - QGraphicsWidget * dataWidget(); - - private slots: - void themeChanged(); - - private: - QGraphicsLinearLayout * m_layout; - QGraphicsWidget * m_dataWidget; - QFont m_font; - int m_textWidth; - int m_textHeight; - static const int MARGIN; - static const int TOP_MARGIN; - static const int LEFT_MARGIN; - static const int SPACING; -}; - -class KGetApplet : public Plasma::PopupApplet -{ - Q_OBJECT -public: - KGetApplet(QObject *parent, const QVariantList &args); - ~KGetApplet(); - - void init(); - void setDataWidget(QGraphicsWidget * widget); - -public slots: - void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data); - -private slots: - virtual void slotKgetStarted(); - void slotUpdateTransfer(int transferChange); - -signals: - void transfersAdded(const QList &transfers); - void transfersRemoved(const QList &transfers); - void update(); - -private: - void updateGlobalProgress(); - void transferAdded(const QVariantMap &transfer); - void transferRemoved(const QVariantMap &transfer); - -protected: - virtual bool sceneEventFilter(QGraphicsItem * watched, QEvent * event); - virtual void dropEvent(QGraphicsSceneDragDropEvent * event); - virtual void dropEvent(QDropEvent * event); - virtual void constraintsEvent(Plasma::Constraints constraints); - - struct Data - { - KIO::filesize_t size; - KIO::filesize_t downloadedSize; - // source cannot be retrieved once transfer is gone from the D-Bus interface - QString source; - - // required by QHash - inline bool operator==(const Data& other) const { - return (size == other.size && downloadedSize == other.downloadedSize && source == other.source); - } - }; - - ProxyWidget *m_proxyWidget; - ErrorWidget *m_errorWidget; - QGraphicsWidget *m_dataWidget; - Plasma::Meter *m_globalProgress; - Plasma::IconWidget *m_icon; - Plasma::DataEngine *m_engine; - KIO::filesize_t m_totalSize; - KIO::filesize_t m_downloadedSize; - QHash m_transfers; - static const QString KGET_DBUS_SERVICE; - static const QString KGET_DBUS_PATH; - static const int POLL_INTERVAL; -}; - -#endif diff --git a/kget/plasma/applet/common/kgetappletutils.cpp b/kget/plasma/applet/common/kgetappletutils.cpp deleted file mode 100644 index e100dcb8..00000000 --- a/kget/plasma/applet/common/kgetappletutils.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 "kgetappletutils.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -/** Error widget **/ - -ErrorWidget::ErrorWidget(const QString &message, QGraphicsWidget *parent) - : QGraphicsProxyWidget(parent) -{ - m_interface = QDBusConnection::sessionBus().interface(); - - m_layout = new QGraphicsLinearLayout(this); - m_layout->setOrientation(Qt::Vertical); - - m_errorLabel = new Plasma::Label(this); - m_errorLabel->setText(message); - m_errorLabel->nativeWidget()->setAlignment(Qt::AlignCenter); - - m_icon = new Plasma::IconWidget(KIcon("dialog-warning"),"", this); - - m_launchButton = new Plasma::PushButton(this); - m_launchButton->setText(i18n("Launch KGet")); - m_launchButton->nativeWidget()->setIcon(KIcon("kget")); - - m_layout->addItem(m_errorLabel); - m_layout->addItem(m_icon); - m_layout->addItem(m_launchButton); - - setLayout(m_layout); - - connect(m_launchButton, SIGNAL(clicked()), SLOT(launchKGet())); -} - -ErrorWidget::~ErrorWidget() -{ - delete m_errorLabel; - delete m_icon; - delete m_launchButton; -} - -void ErrorWidget::launchKGet() -{ - QProcess::startDetached("kget"); - checkKGetStatus(); -} - -void ErrorWidget::checkKGetStatus() -{ - if (m_interface->isServiceRegistered("org.kde.kget")) { - emit kgetStarted(); - } else { - QTimer::singleShot(1000, this, SLOT(checkKGetStatus())); - } -} - -#include "moc_kgetappletutils.cpp" diff --git a/kget/plasma/applet/common/kgetappletutils.h b/kget/plasma/applet/common/kgetappletutils.h deleted file mode 100644 index 6d36271b..00000000 --- a/kget/plasma/applet/common/kgetappletutils.h +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 KGETAPPLETUTILS_H -#define KGETAPPLETUTILS_H - -#include -#include -#include -#include - -namespace Plasma { - class Label; - class IconWidget; - class PushButton; -} - -class ErrorWidget : public QGraphicsProxyWidget -{ - Q_OBJECT -public: - explicit ErrorWidget(const QString &message, QGraphicsWidget *parent = 0); - ~ErrorWidget(); - -private slots: - void launchKGet(); - void checkKGetStatus(); - -signals: - void kgetStarted(); - -private: - QGraphicsLinearLayout *m_layout; - Plasma::Label *m_errorLabel; - Plasma::IconWidget *m_icon; - Plasma::PushButton *m_launchButton; - QDBusConnectionInterface *m_interface; -}; - -#endif diff --git a/kget/plasma/applet/piechart/kgetpiechart.cpp b/kget/plasma/applet/piechart/kgetpiechart.cpp deleted file mode 100644 index 553a6ddc..00000000 --- a/kget/plasma/applet/piechart/kgetpiechart.cpp +++ /dev/null @@ -1,360 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 "piechart/kgetpiechart.h" -#include "piechart/kgetpiechart_p.h" -#include "common/kgetappletutils.h" - -#include "../../../core/transferhandler.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -const float KGetPieChart::PieChart::PIE_OPACITY = 0.67f; -const float KGetPieChart::PieChart::ACTIVE_PIE_OPACITY = 0.84f; - -KGetPieChart::PieChart::PieChart(QHash *data, KIO::filesize_t totalSize, QGraphicsWidget *parent) - : QGraphicsWidget(parent), - m_data(data), - m_totalSize(totalSize) -{ - setMinimumSize(QSizeF(80, 80)); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - setCacheMode(QGraphicsItem::DeviceCoordinateCache); - - m_totalPen.setWidth(1); - m_totalPen.setColor(Qt::darkGray); - m_totalPen.setStyle(Qt::SolidLine); - - m_activePen.setWidth(1); - m_activePen.setColor(Qt::white); - m_activePen.setStyle(Qt::SolidLine); -} - -KGetPieChart::PieChart::~PieChart() -{ -} - -void KGetPieChart::PieChart::setTotalSize(KIO::filesize_t totalSize) -{ - m_totalSize = totalSize; - m_angles.clear(); - update(); -} - -void KGetPieChart::PieChart::createAngles() -{ - m_angles.clear(); - - if (m_totalSize) { - QHash::const_iterator it; - QHash::const_iterator itEnd = m_data->constEnd(); - int startAngle = 90 * 16; - for (it = m_data->constBegin(); it != itEnd; ++it) { - const int span = (-1 * ((it.value().size * 360 * 16) / m_totalSize)); - m_angles[it.key()] = qMakePair(startAngle, span); - - startAngle += span; - } - } -} - -void KGetPieChart::PieChart::paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - Q_UNUSED(widget) - - kDebug() << "Repaint"; - - if (m_totalSize && (m_angles.count() != m_data->count())) { - createAngles(); - } - - p->setRenderHint(QPainter::Antialiasing); - p->setRenderHint(QPainter::SmoothPixmapTransform); - p->setRenderHint(QPainter::TextAntialiasing); - - int size = option->rect.height(); - if (option->rect.width() < size) { - size = option->rect.width(); - } - const QRect rect = QRect(option->rect.x() + option->rect.width() / 2 - size / 2, - option->rect.y(), - size, - size); - - QHash::const_iterator it; - QHash::const_iterator itEnd = m_data->constEnd(); - for (it = m_data->constBegin(); it != itEnd; ++it) { - OrgKdeKgetTransferInterface *transfer = it.key(); - const Data data = it.value(); - QPair angles = m_angles[transfer]; - const QBrush brush(data.color); - - p->setBrush(brush); - - if (data.isFinished) { - p->setPen(m_totalPen); - } else { - p->setPen(m_activePen); - } - - p->setOpacity(PIE_OPACITY); - p->drawPie(rect, angles.first, angles.second); - - p->setOpacity(ACTIVE_PIE_OPACITY); - if (m_totalSize && !data.isFinished) { - angles.second = (-1 * ((data.downloadedSize * 360 * 16) / m_totalSize)); - } - p->drawPie(QRect(rect.x() + 15, rect.y() + 15, rect.width() - 30, rect.height() - 30), angles.first, angles.second); - } -} - -KGetPieChart::Item::Item(QGraphicsWidget *parent) - : QGraphicsWidget(parent) -{ - m_colorLabel = new Plasma::Label(); - m_colorLabel->nativeWidget()->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - m_name = new Plasma::Label(); - m_name->nativeWidget()->setWordWrap(false); - m_name->nativeWidget()->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred)); - m_sizeLabel = new Plasma::Label(); - m_sizeLabel->nativeWidget()->setWordWrap(false); - - QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal); - layout->addItem(m_colorLabel); - layout->addItem(m_name); - layout->addItem(m_sizeLabel); - - setLayout(layout); -} - -KGetPieChart::Item::~Item() -{ -} - -void KGetPieChart::Item::setSize(KIO::filesize_t size) -{ - m_sizeLabel->setText(KGlobal::locale()->formatByteSize(size)); -} - -void KGetPieChart::Item::setName(const QString &name) -{ - m_name->setText(name); -} - -void KGetPieChart::Item::setColor(const QColor &color) -{ - QPixmap pixmap(10, 10); - pixmap.fill(QColor(color)); - m_colorLabel->nativeWidget()->setPixmap(pixmap); -} - -KGetPieChart::Private::Private(QGraphicsWidget *parent) : QGraphicsWidget(parent), - m_colors("Oxygen.colors"), - m_totalSize(0), - m_piechart(0) -{ - QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical, this); - - m_piechart = new KGetPieChart::PieChart(&m_data, m_totalSize); - layout->insertItem(0, m_piechart); - m_scrollWidget = new Plasma::ScrollWidget(); - m_scrollWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - m_containerWidget = new QGraphicsWidget(m_scrollWidget); - m_scrollWidget->setWidget(m_containerWidget); - m_containerLayout = new QGraphicsLinearLayout(Qt::Vertical, m_containerWidget); - - layout->addItem(m_scrollWidget); - - setLayout(layout); -} - -KGetPieChart::Private::~Private() -{ -} - -void KGetPieChart::Private::addTransfers(const QList &transfers) -{ - foreach (OrgKdeKgetTransferInterface *transfer, transfers) { - if (m_items.contains(transfer)) { - continue; - } - - connect(transfer, SIGNAL(transferChangedEvent(int)), this, SLOT(slotUpdateTransfer(int))); - - QString fileName = KUrl(transfer->dest().value()).fileName(); - kDebug() << fileName; - - Data data; - data.name = fileName; - data.isFinished = (transfer->status() == Transfer::Finished); - data.size = transfer->totalSize(); - data.downloadedSize = transfer->downloadedSize(); - m_data[transfer] = data; - - Item *item = new Item; - item->setName(data.name); - item->setSize(data.size); - m_items[transfer] = item; - - m_totalSize += data.size; - - //running downloads are prepended, others appended - if (data.isFinished) { - m_containerLayout->addItem(item); - } else { - m_containerLayout->insertItem(0, item); - } - } - - updateTransfers(); -} - -void KGetPieChart::Private::removeTransfers(const QList &transfers) -{ - // remove the progressbars for the deleted transfers - QHash::iterator it; - for (it = m_items.begin(); it != m_items.end(); ) { - OrgKdeKgetTransferInterface *transfer = it.key(); - if (transfers.contains(transfer)) { - Item *item = it.value(); - it = m_items.erase(it); - - m_totalSize -= m_data[transfer].size; - m_data.remove(transfer); - - m_containerLayout->removeItem(item); - item->deleteLater(); - } else { - ++it; - } - } - - updateTransfers(); -} - -void KGetPieChart::Private::slotUpdateTransfer(int transferChange) -{ - OrgKdeKgetTransferInterface *transfer = qobject_cast(QObject::sender()); - - bool updatePieSize = false; - bool updatePie = false; - if (transfer && m_items.contains(transfer)) { - Item *item = m_items[transfer]; - - if (transferChange & Transfer::Tc_Status) { - m_data[transfer].isFinished = (transfer->status() == Transfer::Finished); - updatePie = true; - } - if (transferChange & Transfer::Tc_FileName) { - m_data[transfer].name = KUrl(transfer->dest().value()).fileName(); - item->setName(m_data[transfer].name); - } - if (transferChange & Transfer::Tc_TotalSize) { - m_totalSize -= m_data[transfer].size; - KIO::filesize_t newSize = transfer->totalSize(); - m_totalSize += newSize; - m_data[transfer].size = newSize; - - item->setSize(m_data[transfer].size); - - updatePieSize = true; - } - if (transferChange & Transfer::Tc_DownloadedSize) { - m_data[transfer].downloadedSize = transfer->downloadedSize(); - updatePie = true; - } - } - - if (updatePieSize) { - m_piechart->setTotalSize(m_totalSize); - } else if (updatePie) { - m_piechart->update(); - } -} -void KGetPieChart::Private::updateTransfers() -{ - if (m_items.isEmpty()) { - return; - } - - int step = m_colors.count() / m_items.count(); - //there are more items than colors - if (!step) { - step = 1; - } - - int i = 0; - QHash::const_iterator it; - QHash::const_iterator itEnd = m_items.constEnd(); - for (it = m_items.constBegin(); it != itEnd; ++it) { - m_data[it.key()].color = m_colors.color(i * 6 + 4); - it.value()->setColor(m_data[it.key()].color); - ++i; - } - - m_piechart->setTotalSize(m_totalSize); -} - - -KGetPieChart::KGetPieChart(QObject *parent, const QVariantList &args) - : KGetApplet(parent, args) -{ -} - -KGetPieChart::~KGetPieChart() -{ - delete d; -} - -void KGetPieChart::init() -{ - d = new KGetPieChart::Private(this); - setDataWidget(d); - connect(this, SIGNAL(transfersAdded(QList)), d, SLOT(addTransfers(QList))); - connect(this, SIGNAL(transfersRemoved(QList)), d, SLOT(removeTransfers(QList))); - - KGetApplet::init(); -} - -#include "moc_kgetpiechart.cpp" -#include "moc_kgetpiechart_p.cpp" diff --git a/kget/plasma/applet/piechart/kgetpiechart.h b/kget/plasma/applet/piechart/kgetpiechart.h deleted file mode 100644 index 096a00e7..00000000 --- a/kget/plasma/applet/piechart/kgetpiechart.h +++ /dev/null @@ -1,53 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * - * Copyright (C) 2007 by Javier Goday - * * - * 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 KGETPIECHART_H -#define KGETPIECHART_H - -#include "common/kgetapplet.h" -#include - -#include -#include - -namespace Plasma { - class Svg; -} - -class KGetPieChart : public KGetApplet -{ - Q_OBJECT -public: - KGetPieChart(QObject *parent, const QVariantList &args); - ~KGetPieChart(); - - void init(); - -private: - class Data; - class Item; - class PieChart; - class PrivateData; - class Private; - Private *d; -}; - -K_EXPORT_PLASMA_APPLET(kgetpiechart, KGetPieChart) - -#endif diff --git a/kget/plasma/applet/piechart/kgetpiechart_p.h b/kget/plasma/applet/piechart/kgetpiechart_p.h deleted file mode 100644 index ba847786..00000000 --- a/kget/plasma/applet/piechart/kgetpiechart_p.h +++ /dev/null @@ -1,118 +0,0 @@ -/*************************************************************************** - * * - * 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. * - * * - * Copyright (C) 2007 by Javier Goday * - * Copyright (C) 2009 by Matthias Fuchs * - * * - * 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 KGETPIECHART_P_H -#define KGETPIECHART_P_H - -#include -#include -#include - -#include -#include - -#include - -namespace Plasma -{ - class Label; - class ScrollWidget; -} - -class KGetPieChart::Data -{ - public: - QString name; - bool isFinished; - KIO::filesize_t size; - KIO::filesize_t downloadedSize; - QColor color; -}; - -class KGetPieChart::PieChart : public QGraphicsWidget -{ - Q_OBJECT - - public: - PieChart(QHash *data, KIO::filesize_t totalSize, QGraphicsWidget *parent = 0); - ~PieChart(); - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); - void setTotalSize(KIO::filesize_t totalSize); - void createAngles(); - - private: - QHash *m_data; - KIO::filesize_t m_totalSize; - QHash > m_angles; - QPen m_totalPen; - QPen m_activePen; - - static const float PIE_OPACITY; - static const float ACTIVE_PIE_OPACITY; -}; - -class KGetPieChart::Item : public QGraphicsWidget -{ - Q_OBJECT - - public: - Item(QGraphicsWidget *parent = 0); - ~Item(); - - void setSize(KIO::filesize_t size); - void setName(const QString &name); - void setColor(const QColor &color); - - private: - Plasma::Label *m_name; - Plasma::Label *m_sizeLabel; - Plasma::Label *m_colorLabel; -}; - -class KGetPieChart::Private : public QGraphicsWidget -{ -Q_OBJECT -public: - Private(QGraphicsWidget *parent = 0); - ~Private(); - - public slots: - void addTransfers(const QList &transfers); - void removeTransfers(const QList &transfers); - - private slots: - void slotUpdateTransfer(int transferChange); - - private: - void updateTransfers(); - - private: - KColorCollection m_colors; - KIO::filesize_t m_totalSize; - Plasma::ScrollWidget *m_scrollWidget; - QGraphicsWidget *m_containerWidget; - QGraphicsLinearLayout *m_containerLayout; - QHash m_data; - QHash m_items; - PieChart *m_piechart; -}; - -#endif diff --git a/kget/plasma/applet/piechart/kgetpiechartapplet-default.desktop b/kget/plasma/applet/piechart/kgetpiechartapplet-default.desktop deleted file mode 100644 index c5c0ea35..00000000 --- a/kget/plasma/applet/piechart/kgetpiechartapplet-default.desktop +++ /dev/null @@ -1,123 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Name=KGet Piechart Applet -Name[ast]=Miniaplicación gráfica circular -Name[bs]=Torta grafikon KGeta -Name[ca]=Miniaplicació de diagrama de sectors del KGet -Name[ca@valencia]=Miniaplicació de diagrama de sectors del KGet -Name[cs]=Applet pro koláčový graf v KGet -Name[da]=KGet cirkeldiagram-applet -Name[de]=KGet Tortengrafik-Modul -Name[el]=Μικροεφαρμογή γραφήματος πίτας KGet -Name[en_GB]=KGet Piechart Applet -Name[es]=Miniaplicación de gráficas circulares -Name[et]=KGeti sektordiagrammi aplett -Name[eu]=KGet-eko tarta-diagramaren miniaplikazioa -Name[fi]=KGetin piirakkakaaviosovelma -Name[fr]=Composant graphique en camembert pour KGet -Name[ga]=Feidhmchláirín píchairte KGet -Name[gl]=Applet de diagrama de sectores de KGet -Name[hr]=Applet za tortni dijagram za KGet -Name[hu]=KGet kördiagram -Name[ia]=Applet Piechart de KGet (carta a torta) -Name[it]=Grafici a torta per KGet -Name[ja]=KGet 円グラフアプレット -Name[kk]=KGet үлес диаграмма апплеті -Name[km]=អាប់ភ្លេត​គំនូស​តាង​ចំណិច​របស់ KGet -Name[ko]=KGet 원 그래프 애플릿 -Name[lt]=KGet skritulinės diagramos programėlė -Name[lv]=KGet rinķa grafika sīkrīks -Name[nb]=Miniprogram for KGet-kakediagram -Name[nds]=KGet-Kokengrafik-Lüttprogramm -Name[nl]=Taartpuntapplet voor KGet -Name[nn]=KGet-kakediagram -Name[pa]=ਕੇ-ਗਿੱਟ ਪਾਈਚਾਰਟ ਐਪਲਿਟ -Name[pl]=Wykres kołowy w KGet -Name[pt]='Applet' de Gráfico Circular do KGet -Name[pt_BR]=Miniaplicativo de gráfico de setores do KGet -Name[ro]=Miniaplicație KGet DiagramăDisc -Name[ru]=KGet: круговая диаграмма -Name[si]=KGet වෘතප්‍රස්ථාර යෙදුම -Name[sk]=Koláčový graf pre KGet -Name[sl]=KGet (tortni graf) -Name[sr]=питасти графикон К‑гета -Name[sr@ijekavian]=питасти графикон К‑гета -Name[sr@ijekavianlatin]=pitasti grafikon KGeta -Name[sr@latin]=pitasti grafikon KGeta -Name[sv]=Cirkeldiagram-miniprogram för Kget -Name[tr]=KGet Pasta Grafiği Programcığı -Name[ug]=KGet دۈگىلەك دىئاگرامما ئەپچە -Name[uk]=Аплет кругової діаграми KGet -Name[x-test]=xxKGet Piechart Appletxx -Name[zh_CN]=KGet 饼状图小程序 -Name[zh_TW]=KGet 圓餅圖小程式 -Comment=KGet piechart applet -Comment[ar]=بريمج KGet piechart -Comment[ast]=Miniaplicación gráfica circular -Comment[bs]=Aplet torta grafikona za KGet -Comment[ca]=Miniaplicació de diagrama de sectors del KGet -Comment[ca@valencia]=Miniaplicació de diagrama de sectors del KGet -Comment[cs]=Applet pro koláčový graf v KGet -Comment[da]=KGet cirkeldiagram-applet -Comment[de]=KGet Tortengrafik-Modul -Comment[el]=Μικροεφαρμογή γραφήματος πίτας KGet -Comment[en_GB]=KGet piechart applet -Comment[es]=Miniaplicación de gráfica circular -Comment[et]=KGeti sektordiagrammi aplett -Comment[eu]=KGet-eko tarta-diagramaren miniaplikazioa -Comment[fi]=KGetin piirakkakaaviosovelma -Comment[fr]=Composant graphique en camembert pour KGet -Comment[ga]=Feidhmchláirín píchairte KGet -Comment[gl]=Applet de diagrama de sectores de KGet -Comment[hne]=केगेट पाईचार्ट ऐप्लेट -Comment[hr]=Applet za tortni dijagram za KGet -Comment[hu]=KGet kördiagram -Comment[ia]=Applet Piechart de KGet (carta a torta) -Comment[it]=Grafici a torta per KGet -Comment[ja]=KGet 円グラフアプレット -Comment[kk]=KGet үлес диаграммасының апплеті -Comment[km]=អាប់ភ្លេត​គំនូស​តាង​ចំណិត​របស់ KGet -Comment[ko]=KGet 원 그래프 애플릿 -Comment[lt]=KGet skritulinės diagramos programėlė -Comment[lv]=KGet rinķa grafika sīkrīks -Comment[ml]=കെഗെറ്റ് പൈചാര്‍ട്ട് എന്ന ലഘുപ്രയോഗം -Comment[nb]=Miniprogram for KGet-kakediagram -Comment[nds]=Kokengrafik-Lüttprogramm för KGet -Comment[nl]=Taartpuntgrafiek voor KGet -Comment[nn]=KGet-kakediagram -Comment[pa]=ਕੇ-ਗਿੱਟ ਪਾਈਚਾਰਟ ਐਪਲਿਟ -Comment[pl]=Aplet pokazujący wykres kołowy w KGet -Comment[pt]='Applet' de gráfico circular do KGet -Comment[pt_BR]=Miniaplicativo de gráfico de setores do KGet -Comment[ro]=Miniaplicație KGet DiagramăDisc -Comment[ru]=Показывает загрузки KGet в круговой диаграмме -Comment[si]=KGet වෘතප්‍රස්ථාර යෙදුම -Comment[sk]=Koláčový graf pre KGet -Comment[sl]=Tortni graf za KGet -Comment[sr]=Аплет питастог графикона за К‑гет -Comment[sr@ijekavian]=Аплет питастог графикона за К‑гет -Comment[sr@ijekavianlatin]=Aplet pitastog grafikona za KGet -Comment[sr@latin]=Aplet pitastog grafikona za KGet -Comment[sv]=Cirkeldiagram-miniprogram för Kget -Comment[tr]=KGet pasta grafiği programcığı -Comment[ug]=KGet دۈگىلەك دىئاگرامما ئەپچە -Comment[uk]=Аплет кругової діаграми KGet -Comment[x-test]=xxKGet piechart appletxx -Comment[zh_CN]=KGet 饼图小程序 -Comment[zh_TW]=KGet 圓餅圖小程式 -Icon=kget -Type=Service -ServiceTypes=Plasma/Applet - -X-KDE-Library=plasma_kget_piechart - -X-KDE-PluginInfo-Author=Javier Goday -X-KDE-PluginInfo-Email= -X-KDE-PluginInfo-Name=kgetpiechart -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-Category=Online Services -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true - diff --git a/kget/plasma/engine/CMakeLists.txt b/kget/plasma/engine/CMakeLists.txt deleted file mode 100644 index 1bd2e76b..00000000 --- a/kget/plasma/engine/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -include_directories( ../../) - -set(kget_engine_SRCS - kgetengine.cpp -) - -qt4_add_dbus_interface(kget_engine_SRCS ../../dbus/org.kde.kget.main.xml kget_interface) - -kde4_add_plugin(plasma_engine_kget ${kget_engine_SRCS}) -target_link_libraries(plasma_engine_kget KDE4::kdecore KDE4::plasma) - -install(TARGETS plasma_engine_kget DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) -install(FILES plasma-engine-kget.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) diff --git a/kget/plasma/engine/kgetengine.cpp b/kget/plasma/engine/kgetengine.cpp deleted file mode 100644 index 0bc13898..00000000 --- a/kget/plasma/engine/kgetengine.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License version 2 as - * published by the Free Software Foundation - * - * Copyright (C) 2007 by Javier Goday - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "kgetengine.h" -#include "kget_interface.h" - -#include -#include - -#include "plasma/datacontainer.h" - -const quint16 KGetEngine::MINIMUM_UPDATE_INTERVAL = 1000; -const QString KGetEngine::KGET_DBUS_SERVICE = "org.kde.kget"; -const QString KGetEngine::KGET_DBUS_PATH = "/KGet"; - -KGetEngine::KGetEngine(QObject* parent, const QVariantList& args) - : Plasma::DataEngine(parent), - m_kget(0) -{ - Q_UNUSED(args) - - interface = QDBusConnection::sessionBus().interface(); - setMinimumPollingInterval(MINIMUM_UPDATE_INTERVAL); -} - -KGetEngine::~KGetEngine() -{ -} - -QStringList KGetEngine::sources() const -{ - QStringList sources; - sources << "KGet"; - - return sources; -} - -bool KGetEngine::sourceRequestEvent(const QString &name) -{ - return updateSourceEvent(name); -} - -bool KGetEngine::updateSourceEvent(const QString &name) -{ - kDebug(); - if (name == "KGet") { - getKGetData(name); - } - return true; -} - -void KGetEngine::updateData() -{ - updateSourceEvent("KGet"); -} - -void KGetEngine::getKGetData(const QString &name) -{ - removeAllData(name); - - if (isDBusServiceRegistered()) { - if (!m_kget) { - m_kget = new OrgKdeKgetMainInterface(KGET_DBUS_SERVICE, KGET_DBUS_PATH, QDBusConnection::sessionBus(), this); - connect(m_kget, SIGNAL(transfersAdded(QStringList,QStringList)), this, SLOT(slotTransfersAdded(QStringList,QStringList))); - connect(m_kget, SIGNAL(transfersRemoved(QStringList,QStringList)), this, SLOT(slotTransfersRemoved(QStringList,QStringList))); - } - - setData(name, "error", false); - setData(name, "transfers", m_kget->transfers().value()); - } else { - setData(name, "error", true); - setData(name, "errorMessage", i18n("Is KGet up and running?")); - } -} - -void KGetEngine::transferAdded(const QString &url, const QString &dBusObjectPath) -{ - const QString name = "KGet"; - removeAllData(name); - - QVariantMap added; - added.insert(url, dBusObjectPath); - - setData(name, "error", false); - setData(name, "transfers", m_kget->transfers().value()); - setData(name, "transferAdded", added); -} - -//TODO investigate if this should be improved for speed reasons -void KGetEngine::slotTransfersAdded(const QStringList &urls, const QStringList &dBusObjectPaths) -{ - for (int i = 0; i < urls.count(); ++i) { - transferAdded(urls[i], dBusObjectPaths[i]); - } -} - -void KGetEngine::transferRemoved(const QString &url, const QString &dBusObjectPath) -{ - const QString name = "KGet"; - removeAllData(name); - - QVariantMap removed; - removed.insert(url, dBusObjectPath); - - setData(name, "error", false); - setData(name, "transfers", m_kget->transfers().value()); - setData(name, "transferRemoved", removed); -} - -//TODO investigate if this should be improved for speed reasons -void KGetEngine::slotTransfersRemoved(const QStringList &urls, const QStringList &dBusObjectPaths) -{ - for (int i = 0; i < urls.count(); ++i) { - transferRemoved(urls[i], dBusObjectPaths[i]); - } -} - -bool KGetEngine::isDBusServiceRegistered() -{ - return interface->isServiceRegistered(KGET_DBUS_SERVICE); -} - -#include "moc_kgetengine.cpp" diff --git a/kget/plasma/engine/kgetengine.h b/kget/plasma/engine/kgetengine.h deleted file mode 100644 index 7d57669b..00000000 --- a/kget/plasma/engine/kgetengine.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License version 2 as - * published by the Free Software Foundation - * - * Copyright (C) 2007 by Javier Goday - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KGETENGINE_H -#define KGETENGINE_H - -#include - -#include - -class OrgKdeKgetMainInterface; - -class KGetEngine : public Plasma::DataEngine -{ - Q_OBJECT - - public: - KGetEngine(QObject* parent, const QVariantList& args); - ~KGetEngine(); - - QStringList sources() const; - - protected: - bool sourceRequestEvent(const QString &name); - bool updateSourceEvent(const QString& source); - - private slots: - void getKGetData(const QString &name); - void updateData(); - void slotTransfersAdded(const QStringList &urls, const QStringList &dBusObjectPaths); - void slotTransfersRemoved(const QStringList &urls, const QStringList &dBusObjectPaths); - - private: - void transferAdded(const QString &url, const QString &dBusObjectPath); - void transferRemoved(const QString &url, const QString &dBusObjectPath); - bool isDBusServiceRegistered(); - - private: - QDBusConnectionInterface *interface; - OrgKdeKgetMainInterface *m_kget; - static const quint16 MINIMUM_UPDATE_INTERVAL; - static const QString KGET_DBUS_SERVICE; - static const QString KGET_DBUS_PATH; -}; - -K_EXPORT_PLASMA_DATAENGINE(kget, KGetEngine) - -#endif diff --git a/kget/plasma/engine/plasma-engine-kget.desktop b/kget/plasma/engine/plasma-engine-kget.desktop deleted file mode 100644 index f353758d..00000000 --- a/kget/plasma/engine/plasma-engine-kget.desktop +++ /dev/null @@ -1,64 +0,0 @@ -[Desktop Entry] -Name=KGet Data Engine -Name[ar]=KGet البيانات المحرك -Name[ast]=Motor de KGet Data -Name[bg]=Ядро за данни на KGet -Name[bs]=Pogon podataka za KGet -Name[ca]=Motor de dades del KGet -Name[ca@valencia]=Motor de dades del KGet -Name[cs]=Datový nástroj KGet -Name[da]=KGet datamotor -Name[de]=KGet-Datenmodul -Name[el]=Μηχανή δεδομένων του KGet -Name[en_GB]=KGet Data Engine -Name[eo]=KGet datuma motoro -Name[es]=Motor de KGet Data -Name[et]=KGeti andmete mootor -Name[eu]=KGet-eko datuen motorra -Name[fi]=KGet-moottori -Name[fr]=Moteur de données KGet -Name[ga]=Inneall Sonraí KGet -Name[gl]=Motor de datos de KGet -Name[hi]=केगेट डाटा इंजिन -Name[hne]=केगेट डाटा इंजिन -Name[hr]=Podatkovni mehanizam za KGet -Name[hu]=KGet feldolgozómodul -Name[ia]=Motor de datos de KGet -Name[is]=KGet gagnavél -Name[it]=Sorgente di dati di KGet -Name[ja]=KGet データエンジン -Name[kk]=KGet дерек тетігі -Name[km]=ម៉ាស៊ីន​ទិន្នន័យ KGet -Name[ko]=KGet 데이터 엔진 -Name[lt]=KGet duomenų sistema -Name[lv]=KGet datu dzinējs -Name[ml]=കെഗെറ്റ് ഡാറ്റാ യന്ത്രം -Name[nb]=KGet datamotor -Name[nds]=KGet-Datenkarn -Name[nl]=KGet (gegevensengine) -Name[nn]=KGet-datamotor -Name[pa]=KGet ਡਾਟਾ ਇੰਜਣ -Name[pl]=Silnik danych KGet -Name[pt]=Motor de Dados do KGet -Name[pt_BR]=Mecanismo de dados do KGet -Name[ro]=Motor de date KGet -Name[ru]=Движок данных KGet -Name[si]=KGet දත්ත එළවුම -Name[sk]=Dátový nástroj KGet -Name[sl]=Podatkovni pogon KGet -Name[sr]=датомотор К‑гета -Name[sr@ijekavian]=датомотор К‑гета -Name[sr@ijekavianlatin]=datomotor KGeta -Name[sr@latin]=datomotor KGeta -Name[sv]=Datagränssnitt för Kget -Name[tr]=KGet Veri Motoru -Name[ug]=KGet سانلىق مەلۇمات موتورى -Name[uk]=Рушій даних KGet -Name[x-test]=xxKGet Data Enginexx -Name[zh_CN]=KGet 数据引擎 -Name[zh_TW]=KGet 資料引擎 -X-KDE-ServiceTypes=Plasma/DataEngine -Type=Service -Icon=kget -X-KDE-Library=plasma_engine_kget -X-KDE-PluginInfo-Name=kget diff --git a/kget/plasma/runner/CMakeLists.txt b/kget/plasma/runner/CMakeLists.txt deleted file mode 100644 index e9dd7dde..00000000 --- a/kget/plasma/runner/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -set(krunner_kget_SRCS - kgetrunner.cpp - ) - -qt4_add_dbus_interface(krunner_kget_SRCS ../../dbus/org.kde.kget.main.xml kget_interface) - -kde4_add_plugin(krunner_kget - ${krunner_kget_SRCS} -) -target_link_libraries(krunner_kget - KDE4::plasma -) - -install(TARGETS - krunner_kget - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) -install(FILES - plasma-runner-kget.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) diff --git a/kget/plasma/runner/Messages.sh b/kget/plasma/runner/Messages.sh deleted file mode 100644 index 1bc99096..00000000 --- a/kget/plasma/runner/Messages.sh +++ /dev/null @@ -1,2 +0,0 @@ -#! /usr/bin/env bash -$XGETTEXT *.cpp -o $podir/plasma_runner_kget.pot diff --git a/kget/plasma/runner/kgetrunner.cpp b/kget/plasma/runner/kgetrunner.cpp deleted file mode 100644 index ba8248ff..00000000 --- a/kget/plasma/runner/kgetrunner.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * This file is part of the KDE project. - * - * Copyright (C) 2009 Tomas Van Verrewegen - * Copyright (C) 2009 Lukas Appelhans - * Copyright (C) 2010 Matthias Fuchs - * - * 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. - */ - -#include "kgetrunner.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -const QString KGET_DBUS_SERVICE = "org.kde.kget"; -const QString KGET_DBUS_PATH = "/KGet"; - -KGetRunner::KGetRunner(QObject* parent, const QVariantList& args) - : Plasma::AbstractRunner(parent, args), m_icon("kget") -{ - setObjectName("KGet"); - addSyntax(Plasma::RunnerSyntax(":q:", i18n("Find all links in :q: and download them with KGet."))); -} - - -KGetRunner::~KGetRunner() -{ -} - -void KGetRunner::init() -{ - m_kget = new OrgKdeKgetMainInterface(KGET_DBUS_SERVICE, KGET_DBUS_PATH, QDBusConnection::sessionBus(), this); - m_interface = QDBusConnection::sessionBus().interface(); -} - -void KGetRunner::match(Plasma::RunnerContext& context) -{ - QString query = context.query(); - m_urls = parseUrls(context.query()); - if (!m_urls.isEmpty()) { - Plasma::QueryMatch match(this); - match.setType(Plasma::QueryMatch::PossibleMatch); - match.setRelevance(0.9); - match.setIcon(m_icon); - if(m_urls.size() == 1) { - match.setText(i18n("Download %1 with KGet.", KUrl(m_urls.first()).prettyUrl())); - } - else { - match.setText(i18np("Download %1 link with KGet.", "Download %1 links with KGet.", m_urls.size())); - } - context.addMatch(query, match); - } -} - - -void KGetRunner::run(const Plasma::RunnerContext& /*context*/, const Plasma::QueryMatch& /*match*/) -{ - QDBusConnectionInterface* connection = QDBusConnection::sessionBus().interface(); - if(connection->isServiceRegistered(KGET_DBUS_SERVICE)) { - // KGet is running. Make the call immediately. - showNewTransferDialog(); - return; - } - - // KGet is not running. Ask DBus to start it. - connection->startService(KGET_DBUS_SERVICE); - if(connection->lastError().type() != QDBusError::NoError) { - KNotification::event( - "kget/error", - i18n("KGet Runner"), - i18n("Could not communicate with KGet, response from DBus:

%1

", connection->lastError().message()), - "dialog-warning" - ); - return; - } - - // Set a timer to make the call when KGet has been started. - // This might still fail if it takes too long to start KGet. - // For me, the 1000ms delay is mooooore than sufficient. - QTimer::singleShot(1000, this, SLOT(showNewTransferDialog())); -} - -void KGetRunner::showNewTransferDialog() -{ - QDBusPendingCall call = m_kget->asyncCall("showNewTransferDialog", m_urls); - QDBusPendingCallWatcher* watcher = new QDBusPendingCallWatcher(call, this); - QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(callFinished(QDBusPendingCallWatcher*))); - - m_urls.clear(); -} - -void KGetRunner::callFinished(QDBusPendingCallWatcher* call) -{ - QDBusPendingReply<> reply = *call; - - // TODO Remove the check for QDBusError::NoReply when NewTransferDialog is fixed to show asynchronously. - if(!reply.isValid() && (reply.error().type() != QDBusError::NoReply)) { - // Send a notification about the error to the user. - KNotification::event( - "kget/error", - i18n("KGet Runner"), - i18n("Could not communicate with KGet, response from DBus:

%1

", reply.error().message()), - "dialog-warning" - ); - } -} - -QStringList KGetRunner::parseUrls(const QString& text) const -{ - QStringList urls; - // We could use QString::split() or similar, but a simple split on whitespace will - // keep us from finding many possible matches (eg: "http://... or =http://...). - // So, for now, let's traverse the query with a simple regexp. - QRegExp re("\\b\\S+"); - int i = re.indexIn(text); - while(i != -1) { - // We check if the match is a valid URL, if the protocol is handled by KGet, - // and if the host is not empty, otherwise "http://" would also be matched. - KUrl url(re.cap()); - if (m_interface->isServiceRegistered(KGET_DBUS_SERVICE) - ? m_kget->isSupported(url.url()).value() - : (url.isValid() && url.hasHost())) { - urls << url.url(); - - // continue searching after last match... - i = re.indexIn(text, i + re.matchedLength()); - } else { - // if the match is not a URL, continue searching from next character... - i = re.indexIn(text, i + 1); - } - } - return urls; -} - - -#include "moc_kgetrunner.cpp" diff --git a/kget/plasma/runner/kgetrunner.h b/kget/plasma/runner/kgetrunner.h deleted file mode 100644 index da5103b6..00000000 --- a/kget/plasma/runner/kgetrunner.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of the KDE project. - * - * Copyright (C) 2009 Tomas Van Verrewegen - * Copyright (C) 2009 Lukas Appelhans - * Copyright (C) 2010 Matthias Fuchs - * - * 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. - */ - -#ifndef KGETRUNNER_H -#define KGETRUNNER_H - -#include "kget_interface.h" - -#include -#include - -#include -#include - - -class KGetRunner - : public Plasma::AbstractRunner -{ - Q_OBJECT - - public: - KGetRunner(QObject* parent, const QVariantList& args); - ~KGetRunner(); - - void match(Plasma::RunnerContext& context); - void run(const Plasma::RunnerContext& context, const Plasma::QueryMatch& match); - - protected slots: - void init(); - - private slots: - void showNewTransferDialog(); - void callFinished(QDBusPendingCallWatcher* call); - - private: - QStringList parseUrls(const QString& text) const; - - private: - QDBusConnectionInterface *m_interface; - OrgKdeKgetMainInterface *m_kget; - KIcon m_icon; - QStringList m_urls; -}; - - -K_EXPORT_PLASMA_RUNNER(kget, KGetRunner) - - -#endif diff --git a/kget/plasma/runner/plasma-runner-kget.desktop b/kget/plasma/runner/plasma-runner-kget.desktop deleted file mode 100644 index bfddbb4a..00000000 --- a/kget/plasma/runner/plasma-runner-kget.desktop +++ /dev/null @@ -1,143 +0,0 @@ -[Desktop Entry] -Name=KGet -Name[ar]=KGet -Name[ast]=KGet -Name[be]=KGet -Name[bg]=KGet -Name[bn]=কে-গেট -Name[br]=KGet -Name[bs]=KGet -Name[ca]=KGet -Name[ca@valencia]=KGet -Name[cs]=KGet -Name[cy]=KNôl -Name[da]=KGet -Name[de]=KGet -Name[el]=KGet -Name[en_GB]=KGet -Name[eo]=KGet -Name[es]=KGet -Name[et]=KGet -Name[eu]=KGet -Name[fi]=KGet -Name[fr]=KGet -Name[ga]=KGet -Name[gl]=KGet -Name[he]=KGet -Name[hi]=के-गेट -Name[hne]=के-गेट -Name[hr]=KGet -Name[hu]=KGet -Name[ia]=KGet -Name[is]=KGet -Name[it]=KGet -Name[ja]=KGet -Name[kk]=KGet -Name[km]=KGet -Name[ko]=KGet -Name[lt]=KGet -Name[lv]=KGet -Name[mk]=KGet -Name[ml]=കെഗെറ്റ് -Name[mr]=के-गेट -Name[ms]=KGet -Name[nb]=KGet -Name[nds]=KGet -Name[ne]=केडीई गेट -Name[nl]=KGet -Name[nn]=KGet -Name[pa]=ਕੇ-ਗੈੱਟ -Name[pl]=KGet -Name[pt]=KGet -Name[pt_BR]=KGet -Name[ro]=KGet -Name[ru]=KGet -Name[se]=KGet -Name[si]=KGet -Name[sk]=KGet -Name[sl]=KGet -Name[sq]=KGet -Name[sr]=К‑гет -Name[sr@ijekavian]=К‑гет -Name[sr@ijekavianlatin]=KGet -Name[sr@latin]=KGet -Name[sv]=Kget -Name[ta]=கேகெட் -Name[tg]=KGet -Name[th]=ดาวน์โหลด-K -Name[tr]=KGet -Name[ug]=KGet -Name[uk]=KGet -Name[vi]=KGet -Name[wa]=KGet -Name[xh]=KGet -Name[x-test]=xxKGetxx -Name[zh_CN]=KGet -Name[zh_HK]=KGet -Name[zh_TW]=檔案傳輸_KGet -Comment=Download links with KGet -Comment[ast]=Baxada d'enllaces con KGet -Comment[bg]=Изтегляне на препратки с KGet -Comment[bs]=Preuzmite vezu KGetom -Comment[ca]=Baixa els enllaços amb el KGet -Comment[ca@valencia]=Baixa els enllaços amb el KGet -Comment[cs]=Stáhnout odkazy pomocí KGet -Comment[da]=Download links med KGet -Comment[de]=Verknüpfungen mit KGet herunterladen -Comment[el]=Λήψη συνδέσμων με το KGet -Comment[en_GB]=Download links with KGet -Comment[es]=Descargar enlaces con KGet -Comment[et]=Linkide allalaadimine KGeti abil -Comment[eu]=Deskargatu estekak KGet-ekin -Comment[fi]=Hae linkit KGet-ohjelmalla -Comment[fr]=Télécharger des liens avec KGet -Comment[ga]=Íosluchtaigh naisc le KGet -Comment[gl]=Obter ligazóns co KGet -Comment[hr]=Preuzima linkove KGetom -Comment[hu]=Hivatkozások letöltése a KGettel -Comment[ia]=Discarga ligamines con KGet -Comment[is]=Sækja tengla með KGet -Comment[it]=Scarica collegamenti con KGet -Comment[ja]=KGet でリンクをダウンロード -Comment[kk]=Сілтемелерден KGet көмегімен жүктеп алу -Comment[km]=ទាញយក​តំណ​ដោយ​ប្រើ KGet -Comment[ko]=KGet으로 링크 다운로드 -Comment[lt]=Atsisiųsti nuorodas su KGet -Comment[lv]=Lejupielādēt saites ar KGet -Comment[mr]=के-गेटने लिंक्स डाउनलोड करा -Comment[nb]=Last ned lenker med KGet -Comment[nds]=Links mit KGet daalladen -Comment[nl]=Koppelingen met KGet downloaden -Comment[nn]=Last ned med KGet -Comment[pa]=ਲਿੰਕ KGet ਨਾਲ ਡਾਊਨਲੋਡ -Comment[pl]=Pobierz odnośniki przy pomocy KGet -Comment[pt]=Obter as ligações com o KGet -Comment[pt_BR]=Baixa links com o KGet -Comment[ro]=Descarcă legături cu KGet -Comment[ru]=Загрузить ссылки с помощью KGet -Comment[si]=KGet සමඟ බාගැනීම් සබඳතා -Comment[sk]=Stiahnuť odkazy pomocou KGet -Comment[sl]=Prejmi povezave s KGet -Comment[sr]=Преузмите везу К‑гетом -Comment[sr@ijekavian]=Преузмите везу К‑гетом -Comment[sr@ijekavianlatin]=Preuzmite vezu KGetom -Comment[sr@latin]=Preuzmite vezu KGetom -Comment[sv]=Ladda ner länkar med Kget -Comment[th]=ดาวน์โหลดส่วนเชื่อมโยงด้วย 'ดาวน์โหลด-K' -Comment[tr]=Bağlantıları KGet ile İndir -Comment[ug]=KGet بىلەن چۈشۈرىدىغان ئۇلانمىلار -Comment[uk]=Звантажити посилання за допомогою KGet -Comment[wa]=Hårdêyes d' aberwetaedje avou KGet -Comment[x-test]=xxDownload links with KGetxx -Comment[zh_CN]=用 KGet 下载链接 -Comment[zh_TW]=用 KGet 下載連結 -X-KDE-ServiceTypes=Plasma/Runner -Type=Service -Icon=kget -X-KDE-Library=krunner_kget -X-KDE-PluginInfo-Author=Tomas Van Verrewegen -X-KDE-PluginInfo-Email=tomasvanverrewegen@telenet.be -X-KDE-PluginInfo-Name=krunner_kget -X-KDE-PluginInfo-Version=0.1.5 -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true diff --git a/kget/tests/CMakeLists.txt b/kget/tests/CMakeLists.txt deleted file mode 100644 index 8e10dda7..00000000 --- a/kget/tests/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -include_directories( - ../ -) - -set(kget_test_transfers_SRCS - testkget.cpp - testtransfers.cpp -) - -qt4_add_dbus_interface(kget_test_transfers_SRCS ../dbus/org.kde.kget.main.xml kget_interface) -qt4_add_dbus_interface(kget_test_transfers_SRCS ../dbus/org.kde.kget.transfer.xml transfer_interface) -qt4_add_dbus_interface(kget_test_transfers_SRCS ../dbus/org.kde.kget.verifier.xml verifier_interface) - -kde4_add_test(kget-test_transfers ${kget_test_transfers_SRCS}) - -target_link_libraries(kget-test_transfers ${QT_QTTEST_LIBRARY} KDE4::kio kgetcore) - - -#===========Verifier=========== -kde4_add_test(kget-verifiertest verifiertest.cpp) - -target_link_libraries(kget-verifiertest ${QT_QTTEST_LIBRARY} KDE4::kdecore kgetcore) - - -#===========Scheduler=========== -kde4_add_test(kget-schedulertest schedulertest.cpp) - -target_link_libraries(kget-schedulertest ${QT_QTTEST_LIBRARY} ${QT_QTGUI_LIBRARY} KDE4::kdecore kgetcore) - -#===========FileDeleter=========== -set(filedeletertest_SRCS - filedeletertest.cpp - ../core/filedeleter.cpp -) - -kde4_add_test(kget-filedeletertest ${filedeletertest_SRCS}) - -target_link_libraries(kget-filedeletertest KDE4::kio ${QT_QTTEST_LIBRARY}) diff --git a/kget/tests/filedeletertest.cpp b/kget/tests/filedeletertest.cpp deleted file mode 100644 index 79c516f5..00000000 --- a/kget/tests/filedeletertest.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* Code mostly from email from Will Stephenson * -* * -* 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 "filedeletertest.h" -#include "../core/filedeleter.h" - -#include -#include -#include - -#include -#include -#include - -void FileDeleterTest::fileDeleterTest() -{ - //nothing started to delete yet - QVERIFY(!FileDeleter::isFileBeingDeleted(KUrl())); - QVERIFY(!FileDeleter::isFileBeingDeleted(KUrl("/tmp/aFile"))); - - //create file that is going to be deleted - KTemporaryFile file1; - file1.setAutoRemove(false); - QVERIFY(file1.open()); - const QString fileUrl1 = file1.fileName(); - QVERIFY(QFile::exists(fileUrl1)); - - //nothing started to delete yet - QVERIFY(!FileDeleter::isFileBeingDeleted(KUrl(fileUrl1))); - - //create two QObjects that will receive the result signal - SignalReceiver receiver1; - QSignalSpy spy1(&receiver1, SIGNAL(result())); - QVERIFY(spy1.isEmpty()); - - SignalReceiver receiver2; - QSignalSpy spy2(&receiver1, SIGNAL(result())); - QVERIFY(spy2.isEmpty()); - - //delete the file - FileDeleter::deleteFile(KUrl(fileUrl1), &receiver1, SIGNAL(result())); - QVERIFY(FileDeleter::isFileBeingDeleted(KUrl(fileUrl1))); - - //deleting twice with the same receiver, still the method should only be called once - FileDeleter::deleteFile(KUrl(fileUrl1), &receiver1, SIGNAL(result())); - - KJob *job = FileDeleter::deleteFile(KUrl(fileUrl1)); - connect(job, SIGNAL(result(KJob*)), &receiver2, SIGNAL(result())); - - //removal should be done by now - QTest::qWait(5000); - - QVERIFY(!FileDeleter::isFileBeingDeleted(KUrl(fileUrl1))); - QVERIFY(!QFile::exists(fileUrl1)); - - QCOMPARE(spy1.count(), 1); - QCOMPARE(spy2.count(), 1); -} - -QTEST_MAIN(FileDeleterTest) - -#include "moc_filedeletertest.cpp" diff --git a/kget/tests/filedeletertest.h b/kget/tests/filedeletertest.h deleted file mode 100644 index ffa8b40a..00000000 --- a/kget/tests/filedeletertest.h +++ /dev/null @@ -1,42 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* Code mostly from email from Will Stephenson * -* * -* 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 KGET_FILE_DELETER_TEST -#define KGET_FILE_DELETER_TEST - -#include - -class SignalReceiver : public QObject -{ - Q_OBJECT - - signals: - void result(); -}; - -class FileDeleterTest : public QObject -{ - Q_OBJECT - - private slots: - void fileDeleterTest(); -}; - -#endif diff --git a/kget/tests/kget-test.xml b/kget/tests/kget-test.xml deleted file mode 100644 index 11e422ba..00000000 --- a/kget/tests/kget-test.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - - sha256 - notworking3edf1df576ee82b2ecb8ba85c343644e48ee62e68290e71e6084b00d6ba2622e - - - - Tc_Percent - 70 - - - - 10000 - - - - false - - - sha256 - 3edf1df576ee82b2ecb8ba85c343644e48ee62e68290e71e6084b00d6ba2622e - - - true - - - true - - - true - - - - - sha256 - 0551459c85cd3da3d58ddc9016fd28be5af503f5e1615a71ba5b512ac945806f - - - - Tc_Percent - 50 - - - ${DIR}/downloads2 - true - - - true - - - true - - - - - - Tc_Percent - 20 - - - true - 3000 - - - Tc_Status - 4 - - - false - - - false - - - sha256 - d7bef0d4c4e7a62e08efb8e5f252a01357007b9588a87ff2b463a3857011f79d - - - true - - - - true - - - - - sha256 - 78d599a133dba7fe2036dfa8db8fb6131ab9642783fc9578b07a20995252d2de - - - true - 2000 - - - Tc_Percent - 10 - - - ${DIR}/downloads2 - true - - - true - - - true - - - 10000 - - - false - - - - - sha1 - borked6306cfb137241b6c87f5944e6bf91870fe - - - sha1 - 512000 - borked37a13b2fc07fdf9ed95e42b6168e9d7ceb - 1d886ba863f9e3d608f995b8095312fe513a3313 - 02297cdc86ecb701a74c2425083678140538430b - borkedf60aaabe9df367150b3cdbd5735f21ee66 - b930b4ad9f9caed3d558c47ffef1558fe2ff9bbb - fe97d2ebe3bd1813f4dadfebed4764c52fad9b6f - - - - false - - - - - 0 - 3 - - - sha1 - c092cfbb46719d89a5718735dc81ca75c0176e45 - - - true - - - true - - - - - sha256 - 069cf7e51cd261eb163aaf06c8d1754c6835f31252180aff5814e5afc7757fbc - - - - true - - - diff --git a/kget/tests/schedulertest.cpp b/kget/tests/schedulertest.cpp deleted file mode 100644 index 81c003b9..00000000 --- a/kget/tests/schedulertest.cpp +++ /dev/null @@ -1,546 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 "schedulertest.h" -#include "../core/scheduler.h" -#include "../settings.h" - -#include -#include - -Q_DECLARE_METATYPE(Job::ErrorType) -Q_DECLARE_METATYPE(Job::Status) -Q_DECLARE_METATYPE(Job::Policy) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) - -const int SchedulerTest::NO_LIMIT = 0; - -SettingsHelper::SettingsHelper(int limit) - : m_oldLimit(Settings::maxConnections()) -{ - Settings::setMaxConnections(limit); -} - -SettingsHelper::~SettingsHelper() -{ - Settings::setMaxConnections(m_oldLimit); -} - -TestJob::TestJob(Scheduler *scheduler, JobQueue *parent) - : Job(scheduler, parent) -{ -} - -void TestJob::start() -{ - if (status() == Aborted || status() == Stopped) { - setStatus(Running); - } -} - -void TestJob::stop() -{ - if ((status() == Running) || (status() == Aborted) || (status() == Moving) || (status() == Finished)) { - setStatus(Stopped); - } -} - -int TestJob::elapsedTime() const -{ - return 0; -} - -int TestJob::remainingTime() const -{ - return 0; -} - -bool TestJob::isStalled() const -{ - return false; -} - -bool TestJob::isWorking() const -{ - return true; -} - -TestQueue::TestQueue(Scheduler *scheduler) - : JobQueue(scheduler) -{ -} - -void TestQueue::appendPub(Job *job) -{ - append(job); -} - -void SchedulerTest::testAppendJobs() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(QList, finalStatus); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - QList jobs; - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - queue->appendPub(job); - jobs << job; - } - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), finalStatus[i]); - } -} - -void SchedulerTest::testAppendJobs_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn >("finalStatus"); - - QTest::newRow("limit 2, two finished, will third be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("limit 2, two finished, will third aborted be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Aborted) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("limit 2, will first two start while last will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("limit 2, will first two start while last will be stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Running) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running); - QTest::newRow("no limit, will all three be started and one remain running?") << NO_LIMIT << (QList() << Job::Stopped << Job::Running << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running << Job::Running); -} - -void SchedulerTest::testCountRunningJobs() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(int, numRunningJobs); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - queue->appendPub(job); - } - - QCOMPARE(scheduler.countRunningJobs(), numRunningJobs); - - const bool hasRunningJobs = numRunningJobs; - QCOMPARE(scheduler.hasRunningJobs(), hasRunningJobs); -} - -void SchedulerTest::testCountRunningJobs_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn("numRunningJobs"); - - QTest::newRow("limit 2, two finished, will third be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << 1; - QTest::newRow("limit 2, two finished, will none be started?") << 2 << (QList() << Job::Finished << Job::Finished) << 0; - QTest::newRow("limit 2, will first two start while last will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << 2; - QTest::newRow("limit 2, will first two start while last will be stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Running) << 2; - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << 1; - QTest::newRow("no limit, two finished, will third be started and fourth stay running?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped << Job::Running) << 2; - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << 3; -} - -void SchedulerTest::testStopScheduler() -{ - QFETCH(int, limit); - QFETCH(QList, status); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - queue->appendPub(job); - } - - scheduler.stop(); - - QCOMPARE(scheduler.countRunningJobs(), 0); - -} - -void SchedulerTest::testStopScheduler_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - - QTest::newRow("limit 2, two finished one stopped") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped); - QTest::newRow("limit 2, two finished one running") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped); - QTest::newRow("limit 2, three stopped") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped); - QTest::newRow("limit 2, two stopped one running") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Running); - QTest::newRow("no limit, two finished one stopped") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped); - QTest::newRow("no limit, three stopped") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped); - QTest::newRow("no limit, one running, three stopped") << NO_LIMIT << (QList() << Job::Running << Job::Stopped << Job::Stopped << Job::Stopped); -} - -void SchedulerTest::testSchedulerStopStart() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(QList, finalStatus); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - QList jobs; - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - queue->appendPub(job); - jobs << job; - } - - scheduler.stop(); - scheduler.start(); - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), finalStatus[i]); - } -} - -void SchedulerTest::testSchedulerStopStart_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn >("finalStatus"); - - QTest::newRow("limit 2, two finished, will third be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("limit 2, will first two start while last will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("limit 2, will first two start while last will be stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Running) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running); - QTest::newRow("limit 2, two finished, will third stay running?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Running) << (QList() << Job::Finished << Job::Finished << Job::Running); -} - - -void SchedulerTest::testSuspendScheduler() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(QList, finalStatus); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - scheduler.setIsSuspended(true); - - //uses an own list instead of the iterators to make sure that the order stays the same - QList jobs; - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - queue->appendPub(job); - jobs << job; - } - - //scheduler is suspended thus the status has to be same as start status - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), status[i]); - } - scheduler.setIsSuspended(false); - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), finalStatus[i]); - } -} - -void SchedulerTest::testSuspendScheduler_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn >("finalStatus"); - - //NOTE Scheduler does not stop jobs, it just prevents new ones from being started - QTest::newRow("limit 2, two finished, will third be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("limit 2, will first two start while last will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("limit 2, will first start and second not while last will stay running?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Running) << (QList() << Job::Running << Job::Running << Job::Stopped); - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running); - QTest::newRow("limit 2, two finished, will third stay running?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Running) << (QList() << Job::Finished << Job::Finished << Job::Running); - -} - -void SchedulerTest::testJobQueueStopPolicy() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(QList, finalStatus); - QFETCH(QList, policy); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - queue->setStatus(JobQueue::Stopped); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - QList jobs; - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - job->setPolicy(policy[i]); - queue->appendPub(job); - jobs << job; - } - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), finalStatus[i]); - } -} - -void SchedulerTest::testJobQueueStopPolicy_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn >("finalStatus"); - QTest::addColumn >("policy"); - - QTest::newRow("limit 2, two finished, will third not be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::None << Job::None << Job::None); - QTest::newRow("limit 2, will first start while rest will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Stopped << Job::Stopped) << (QList() << Job::Start << Job::Stop << Job::None); - QTest::newRow("limit 2, will first and third start while rest will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Stopped << Job::Running << Job::Stopped) << (QList() << Job::Start << Job::Stop << Job::Start << Job::None); - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running) << (QList() << Job::Start << Job::None << Job::Start); - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running) << (QList() << Job::Start << Job::Start << Job::Start); -} - -void SchedulerTest::testJobQueueStopStartPolicy() -{ - QFETCH(int, limit); - QFETCH(QList, status); - QFETCH(QList, intermediateStatus); - QFETCH(QList, policy); - QFETCH(QList, finalStatus); - - SettingsHelper helper(limit); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - queue->setStatus(JobQueue::Stopped); - scheduler.addQueue(queue); - - //uses an own list instead of the iterators to make sure that the order stays the same - QList jobs; - for (int i = 0; i < status.size(); ++i) { - TestJob *job = new TestJob(&scheduler, queue); - job->setStatus(status[i]); - job->setPolicy(policy[i]); - queue->appendPub(job); - jobs << job; - } - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), intermediateStatus[i]); - } - - queue->setStatus(JobQueue::Running); - - for (int i = 0; i < status.size(); ++i) { - QCOMPARE(jobs[i]->status(), finalStatus[i]); - - } -} - -void SchedulerTest::testJobQueueStopStartPolicy_data() -{ - QTest::addColumn("limit"); - QTest::addColumn >("status"); - QTest::addColumn >("intermediateStatus"); - QTest::addColumn >("policy"); - QTest::addColumn >("finalStatus"); - - QTest::newRow("limit 2, two finished, will third be started?") << 2 << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::None << Job::None << Job::None) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("limit 2, will first and last start while rest will stay stopped?") << 2 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Stopped << Job::Stopped) << (QList() << Job::Start << Job::Stop << Job::None) << (QList() << Job::Running << Job::Stopped << Job::Running); - QTest::newRow("limit 3, will first, third and last start while rest will stay stopped?") << 3 << (QList() << Job::Stopped << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Stopped << Job::Running << Job::Stopped) << (QList() << Job::Start << Job::Stop << Job::Start << Job::None) << (QList() << Job::Running << Job::Stopped << Job::Running << Job::Running); - QTest::newRow("no limit, two finished, will third be started?") << NO_LIMIT << (QList() << Job::Finished << Job::Finished << Job::Stopped) << (QList() << Job::Finished << Job::Finished << Job::Running) << (QList() << Job::Start << Job::Start << Job::Start) << (QList() << Job::Finished << Job::Finished << Job::Running); - QTest::newRow("no limit, will all three be started?") << NO_LIMIT << (QList() << Job::Stopped << Job::Stopped << Job::Stopped) << (QList() << Job::Running << Job::Running << Job::Running) << (QList() << Job::Start << Job::Start << Job::Start) << (QList() << Job::Running << Job::Running << Job::Running); -} - -void SchedulerTest::testJobErrorType() -{ - QFETCH(bool, jobQueueRunning); - QFETCH(Job::Policy, policy); - QFETCH(Job::ErrorType, errorType); - QFETCH(Job::Status, finalStatus); - - SettingsHelper helper(NO_LIMIT); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - queue->setStatus(jobQueueRunning ? JobQueue::Running : JobQueue::Stopped); - scheduler.addQueue(queue); - - TestJob *job = new TestJob(&scheduler, queue); - job->setPolicy(policy); - job->setError(QString(), QPixmap(), errorType); - queue->appendPub(job); - - QCOMPARE(job->status(), finalStatus); -} - -void SchedulerTest::testJobErrorType_data() -{ - QTest::addColumn("jobQueueRunning"); - QTest::addColumn("policy"); - QTest::addColumn("errorType"); - QTest::addColumn("finalStatus"); - - QTest::newRow("queue running, job::none, autoretry, running") << true << Job::None << Job::AutomaticRetry << Job::Running; - QTest::newRow("queue running, job::start, autoretry, running") << true << Job::Start << Job::AutomaticRetry << Job::Running; - QTest::newRow("queue running, job::stop, autoretry, aborted") << true << Job::Stop << Job::AutomaticRetry << Job::Aborted; - QTest::newRow("queue running, job::none, manualsolve, aborted") << true << Job::None << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue running, job::start, manualsolve, aborted") << true << Job::Start << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue running, job::stop, manualsolve, aborted") << true << Job::Stop << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue running, job::none, notsolveable, aborted") << true << Job::None << Job::NotSolveable << Job::Aborted; - QTest::newRow("queue running, job::start, notsolveable, aborted") << true << Job::Start << Job::NotSolveable << Job::Aborted; - QTest::newRow("queue running, job::stop, notsolveable, aborted") << true << Job::Stop << Job::NotSolveable << Job::Aborted; - QTest::newRow("queue stopped, job::none, autoretry, aborted") << false << Job::None << Job::AutomaticRetry << Job::Aborted; - QTest::newRow("queue stopped, job::start, autoretry, running") << false << Job::Start << Job::AutomaticRetry << Job::Running; - QTest::newRow("queue stopped, job::stop, autoretry, aborted") << false << Job::Stop << Job::AutomaticRetry << Job::Aborted; - QTest::newRow("queue stopped, job::none, manualsolve, aborted") << false << Job::None << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue stopped, job::start, manualsolve, aborted") << false << Job::Start << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue stopped, job::stop, manualsolve, aborted") << false << Job::Stop << Job::ManualSolve << Job::Aborted; - QTest::newRow("queue stopped, job::none, notsolveable, aborted") << false << Job::None << Job::NotSolveable << Job::Aborted; - QTest::newRow("queue stopped, job::start, notsolveable, aborted") << false << Job::Start << Job::NotSolveable << Job::Aborted; - QTest::newRow("queue stopped, job::stop, notsolveable, aborted") << false << Job::Stop << Job::NotSolveable << Job::Aborted; -} - -void SchedulerTest::testGettingNetworkConnection() -{ - QFETCH(Job::Policy, policy); - QFETCH(Job::Status, finalStatus); - - SettingsHelper helper(NO_LIMIT); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - scheduler.setHasNetworkConnection(false); - - TestJob *job = new TestJob(&scheduler, queue); - job->setPolicy(policy); - queue->appendPub(job); - - scheduler.setHasNetworkConnection(true); - - QCOMPARE(job->policy(), policy);//the policy should remain unchanged - QCOMPARE(job->status(), finalStatus); -} - -void SchedulerTest::testGettingNetworkConnection_data() -{ - QTest::addColumn("policy"); - QTest::addColumn("finalStatus"); - - QTest::newRow("Start, Running") << Job::Start << Job::Running; - QTest::newRow("Stop, Stopped") << Job::Stop << Job::Stopped; - QTest::newRow("None, Running") << Job::None << Job::Running; -} - -void SchedulerTest::testLosingNetworkConnection() -{ - QFETCH(Job::Policy, policy); - - SettingsHelper helper(NO_LIMIT); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - scheduler.setHasNetworkConnection(true); - - TestJob *job = new TestJob(&scheduler, queue); - job->setPolicy(policy); - queue->appendPub(job); - - scheduler.setHasNetworkConnection(false); - - QCOMPARE(job->policy(), policy);//the policy should remain unchanged - QCOMPARE(job->status(), Job::Stopped); -} - -void SchedulerTest::testLosingNetworkConnection_data() -{ - QTest::addColumn("policy"); - - QTest::newRow("Start") << Job::Start; - QTest::newRow("Stop") << Job::Stop; - QTest::newRow("None") << Job::None; -} - -void SchedulerTest::testShouldUpdate() -{ - QFETCH(bool, isSuspended); - QFETCH(bool, hasNetworkConnection); - QFETCH(bool, shouldUpdate); - - SettingsHelper helper(NO_LIMIT); - - Scheduler scheduler; - TestQueue *queue = new TestQueue(&scheduler); - scheduler.addQueue(queue); - - QVERIFY(scheduler.shouldUpdate());//should be true by default - - scheduler.setIsSuspended(isSuspended); - scheduler.setHasNetworkConnection(hasNetworkConnection); - - QCOMPARE(scheduler.shouldUpdate(), shouldUpdate); -} - -void SchedulerTest::testShouldUpdate_data() -{ - QTest::addColumn("isSuspended"); - QTest::addColumn("hasNetworkConnection"); - QTest::addColumn("shouldUpdate"); - - QTest::newRow("false, true, true") << false << true << true; - QTest::newRow("true, true, false") << true << true << false; - QTest::newRow("false, false, false") << false << false << false; -} - -QTEST_MAIN(SchedulerTest) - -#include "moc_schedulertest.cpp" diff --git a/kget/tests/schedulertest.h b/kget/tests/schedulertest.h deleted file mode 100644 index 8ef37109..00000000 --- a/kget/tests/schedulertest.h +++ /dev/null @@ -1,154 +0,0 @@ -/************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 KGET_SCHEDULER_TEST_H -#define KGET_SCHEDULER_TEST_H - -#include "../core/job.h" -#include "../core/jobqueue.h" - -class Scheduler; - -//TODO how should Job::Moving and Job::FinishedKeepAlive be tested? they clearly depend on the Transfer implementation -//though TestJob itself already does what Transfers ought to do - -/** - * Makes sure settings are changed on construction and then restored - * once the destructor is called - */ -class SettingsHelper //TODO better name -{ - public: - SettingsHelper(int limit); - ~SettingsHelper(); - - private: - int m_oldLimit; -}; - -/** - * There to make it easy to create jobs with which to fill the test schedule queue - */ -class TestJob : public Job -{ - Q_OBJECT - - public: - TestJob(Scheduler *scheduler, JobQueue *parent); - - virtual void start(); - virtual void stop(); - virtual int elapsedTime() const; - virtual int remainingTime() const; - virtual bool isStalled() const; - virtual bool isWorking() const; - - signals: - void statusChanged(); -}; - -/** - * Adds a public append method - */ -class TestQueue : public JobQueue -{ - Q_OBJECT - - public: - TestQueue(Scheduler *scheduler); - void appendPub(Job *job); -}; - -class SchedulerTest : public QObject -{ - Q_OBJECT - - private slots: - /** - * Tests if the scheduler reacts correctly on appending jobs, i.e. - * start/stop them - */ - void testAppendJobs(); - void testAppendJobs_data(); - - /** - * Tests Scheduler::countRunningJobs and Scheduler::hasRunningJobs - */ - void testCountRunningJobs(); - void testCountRunningJobs_data(); - - /** - * Tests if after stopping the scheduler all jobs are not running - */ - void testStopScheduler(); - void testStopScheduler_data(); - - /** - * Stops the scheduler and then starts it again to see if jobs - * are correctly started - */ - void testSchedulerStopStart(); - void testSchedulerStopStart_data(); - - void testSuspendScheduler(); - void testSuspendScheduler_data(); - - /** - * Tests the case where the JobQueuePolicy is set to stop - * (this also happens on Scheduler::stop()) by default it is set to start. - * Jobs with a Start policy might be started depending on their - * other settings - */ - void testJobQueueStopPolicy(); - void testJobQueueStopPolicy_data(); - - /** - * Tests the case where the JobQueuePolicy is set to stop, - * and then set to start again. By default it is set to start. - * Jobs with a Start policy might be started depending on their - * other settings - */ - void testJobQueueStopStartPolicy(); - void testJobQueueStopStartPolicy_data(); - - void testJobErrorType(); - void testJobErrorType_data(); - - /** - * There is no connection and transfers are added. - * Then connection is retrieved. - */ - void testGettingNetworkConnection(); - void testGettingNetworkConnection_data(); - - /** - * There is a connection and transfers are added. - * Then connection is lost. - */ - void testLosingNetworkConnection(); - void testLosingNetworkConnection_data(); - - void testShouldUpdate(); - void testShouldUpdate_data(); - - private: - static const int NO_LIMIT; -}; - -#endif diff --git a/kget/tests/testkget.cpp b/kget/tests/testkget.cpp deleted file mode 100644 index 4b375775..00000000 --- a/kget/tests/testkget.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Dario Massarin - - 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. -*/ - -#include "testkget.h" -#include "core/transfergrouphandler.h" -#include "core/kget.h" -#include "core/transfertreemodel.h" - -TestKGet::TestKGet() - : QObject(0), - m_addedGH(0) -{ - connect(KGet::model(), SIGNAL(groupAddedEvent(TransferGroupHandler*)), SLOT(addedTransferGroupEvent(TransferGroupHandler*))); - connect(KGet::model(), SIGNAL(groupRemovedEvent(TransferGroupHandler*)), SLOT(removedTransferGroupEvent(TransferGroupHandler*))); -} - -void TestKGet::addedTransferGroupEvent(TransferGroupHandler * group) -{ - m_addedGH = group; -} - -void TestKGet::removedTransferGroupEvent(TransferGroupHandler * group) -{ - m_removedGH = group; -} - -void TestKGet::simpleTest() -{ - QVERIFY(1 == 1); -} - -void TestKGet::transferGroupTest() -{ - KGet::delGroup(KGet::findGroup("testGroup")); // In case you already have one - - m_addedGH = 0; - m_removedGH = 0; - - // Add Group - QVERIFY(KGet::addGroup("testGroup")); - QVERIFY(m_addedGH != 0); // Should already have received the added group notification - - // Verify default Group parameters - QVERIFY(m_addedGH->name() == "testGroup"); - QVERIFY(m_addedGH->status() == JobQueue::Running); - QVERIFY(m_addedGH->size() == 0); - QVERIFY(m_addedGH->totalSize() == 0); - QVERIFY(m_addedGH->downloadedSize() == 0); - QVERIFY(m_addedGH->uploadedSize() == 0); - QVERIFY(m_addedGH->percent() == 0); - QVERIFY(m_addedGH->downloadSpeed() == 0); - QVERIFY(m_addedGH->uploadSpeed() == 0); - - // Delete newly added Group - KGet::delGroup(KGet::findGroup("testGroup"), false); - QVERIFY(m_removedGH != 0); // Should already have received the removed group notification - - QVERIFY(m_removedGH->name() == "testGroup"); -} - -void TestKGet::transferGroupRepetitiveAddTest() -{ - for(int i=0; i < 100; i++) - { - // Adding... - QVERIFY(KGet::addGroup("testGroup" + QString::number(i))); - QVERIFY(m_addedGH != 0); // Should already have received the added group notification - QVERIFY(m_addedGH->name() == "testGroup" + QString::number(i)); - } - - for(int i=0; i < 100; i++) - { - // Removing... - KGet::delGroup(KGet::findGroup("testGroup" + QString::number(i)), false); - QVERIFY(m_removedGH != 0); // Should already have received the removed group notification - QVERIFY(m_removedGH->name() == "testGroup" + QString::number(i)); - } -} - -#include "moc_testkget.cpp" diff --git a/kget/tests/testkget.h b/kget/tests/testkget.h deleted file mode 100644 index 8e5bb761..00000000 --- a/kget/tests/testkget.h +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Dario Massarin - - 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. -*/ - -#ifndef _TESTKGET_H -#define _TESTKGET_H - -#include - -class TransferGroupHandler; - -class TestKGet : public QObject -{ -Q_OBJECT -public: - TestKGet(); - -private slots: - void simpleTest(); - void transferGroupTest(); - void transferGroupRepetitiveAddTest(); - - void addedTransferGroupEvent(TransferGroupHandler * group); - void removedTransferGroupEvent(TransferGroupHandler * group); - -private: - TransferGroupHandler * m_addedGH; - TransferGroupHandler * m_removedGH; -}; - -#endif diff --git a/kget/tests/testtransfers.cpp b/kget/tests/testtransfers.cpp deleted file mode 100644 index 53732b95..00000000 --- a/kget/tests/testtransfers.cpp +++ /dev/null @@ -1,675 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Dario Massarin - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "testtransfers.h" -#include "core/transfergrouphandler.h" -#include "core/transferhandler.h" -#include "core/kget.h" - -#include "kget_interface.h" -#include "transfer_interface.h" -#include "verifier_interface.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -//FIXME not working fine if files or transfers are existing already -QHash Commands::s_stringCommands; -QHash Commands::s_transferChangeEvents; - -Commands::Commands(const QString &source, QObject *parent) - : QObject(parent), - m_timerId(-1), - m_source(source), - m_transfer(0), - m_verifier(0) -{ - static int instance = 0; - if (!instance++) { - s_stringCommands["start"] = Start; - s_stringCommands["stop"] = Stop; - s_stringCommands["addchecksum"] = AddChecksum; - s_stringCommands["addpartialchecksums"] = AddPartialChecksums; - s_stringCommands["isverifyable"] = IsVerifyable; - s_stringCommands["verify"] = Verify; - s_stringCommands["findbrokenpieces"] = FindBrokenPieces; - s_stringCommands["repair"] = Repair; - s_stringCommands["setdirectory"] = SetDirectory; - s_stringCommands["wait"] = Wait; - s_stringCommands["randomaction"] = RandomAction; - s_stringCommands["verified"] = Verified; - s_stringCommands["changedevent"] = ChangedEvent; - s_stringCommands["brokenpieces"] = BrokenPieces; - - s_transferChangeEvents["tc_filename"] = Transfer::Tc_FileName; - s_transferChangeEvents["tc_status"] = Transfer::Tc_Status; - s_transferChangeEvents["tc_totalsize"] = Transfer::Tc_TotalSize; - s_transferChangeEvents["tc_percent"] = Transfer::Tc_Percent; - s_transferChangeEvents["tc_downloadspeed"] = Transfer::Tc_DownloadSpeed; - s_transferChangeEvents["tc_remainingtime"] = Transfer::Tc_RemainingTime; - s_transferChangeEvents["tc_uploadspeed"] = Transfer::Tc_UploadSpeed; - s_transferChangeEvents["tc_uploadlimit"] = Transfer::Tc_UploadLimit; - s_transferChangeEvents["tc_downloadlimit"] = Transfer::Tc_DownloadLimit; - s_transferChangeEvents["tc_canresume"] = Transfer::Tc_CanResume; - s_transferChangeEvents["tc_downloadedsize"] = Transfer::Tc_DownloadedSize; - s_transferChangeEvents["tc_uploadedsize"] = Transfer::Tc_UploadedSize; - s_transferChangeEvents["tc_log"] = Transfer::Tc_Log; - s_transferChangeEvents["tc_group"] = Transfer::Tc_Group; - s_transferChangeEvents["tc_selection"] = Transfer::Tc_Selection; - } -} - -QList > Commands::parseCommands(const QDomElement& e, TestTransfers *transfer) -{ - QList > commands; - - for (QDomElement elem = e.firstChildElement("command"); !elem.isNull(); elem = elem.nextSiblingElement("command")) { - const QString typeString = elem.attribute("type").toLower(); - - if (!s_stringCommands.contains(typeString)) { - kDebug() << "Error while parsing, type" << typeString << "not supported."; - QWARN("Problem while parsing."); - return commands; - } - const int type = s_stringCommands[typeString]; - - QVariant data; - QStringList args; - for (QDomElement arg = elem.firstChildElement("arg"); !arg.isNull(); arg = arg.nextSiblingElement("arg")) { - args << arg.text(); - } - - switch (type) { - case Verify: - case FindBrokenPieces: - case Start: - case Stop: - commands.append(QPair(type, data)); - break; - case IsVerifyable: - case Verified: - case Repair: - if (args.count() == 1) { - data = args.first(); - if (data.canConvert(QVariant::Bool)) { - commands.append(QPair(type, data)); - break; - } - } - kDebug() << "Parsing IsVerifyable/Verified/Repair failed."; - QWARN("Problem while parsing."); - break; - case AddChecksum: - if (args.count() == 2) { - data = args; - commands.append(QPair(type, data)); - } else { - kDebug() << "Parsing setHash failed."; - QWARN("Problem while parsing."); - } - break; - case AddPartialChecksums: { - if (args.count() >= 3) { - bool worked; - QList list; - list << args[0];//Type - const qulonglong length = args[1].toULongLong(&worked); - if (worked) { - list << length; - for (int i = 2; i < args.count(); ++i) { - list << args[i]; - } - data = list; - commands.append(QPair(type, data)); - break; - } - } - kDebug() << "Parsing AddPartialChecksums failed."; - QWARN("Problem while parsing."); - break; - } - case BrokenPieces: { - QList list; - bool worked = true; - foreach (const QString &arg, args) { - const int value = arg.toInt(&worked); - if (!worked) { - break; - } - list << value; - } - if (worked) { - data = list; - commands.append(QPair(type, data)); - break; - } - kDebug() << "Parsing BrokenPieces failed."; - QWARN("Problem while parsing."); - break; - } - case RandomAction: { - QList list; - if (args.count() == 1) { - data = args.takeFirst(); - if (data.canConvert(QVariant::Bool) && !data.toBool()) { - list << data.toBool(); - data = list; - commands.append(QPair(type, data)); - break; - } - } else if (args.count() == 2) { - data = args.takeFirst(); - if (data.canConvert(QVariant::Bool) && data.toBool()) { - list << data.toBool(); - bool worked; - list << args.takeFirst().toInt(&worked); - if (worked) { - data = list; - commands.append(QPair(type, data)); - break; - } - } - } - kDebug() << "Parsing RandomAction failed."; - QWARN("Problem while parsing."); - break; - } - case SetDirectory: - if (args.count() == 2) { - data = args.last(); - QString newDirectory = args.first(); - if (transfer) { - newDirectory.replace("${DIR}/", transfer->tempDir()); - } - if (!newDirectory.isEmpty() && data.canConvert(QVariant::Bool)) { - const bool shouldWork = data.toBool(); - QList list; - list << newDirectory << shouldWork; - data = list; - commands.append(QPair(type, data)); - break; - } - } - kDebug() << "Parsing SetDirectory failed."; - QWARN("Problem while parsing."); - break; - case Wait: - if (args.count() == 1) { - bool worked; - data = args.first().toInt(&worked); - if (worked) { - commands.append(QPair(type, data)); - break; - } - } - kDebug() << "Parsing Wait failed."; - QWARN("Problem while parsing."); - break; - case ChangedEvent: - if (!args.isEmpty() && (args.count() <= 2)) { - QList list; - const QString typeString = args.first().toLower(); - if (s_transferChangeEvents.contains(typeString)) { - int value = s_transferChangeEvents[typeString]; - list << value; - if (args.count() == 2) { - bool worked; - value = args.last().toInt(&worked); - if (worked) { - list << value; - data = list; - commands.append(QPair(type, data)); - break; - } - } else { - data = list; - commands.append(QPair(type, data)); - break; - } - } - } - kDebug() << "Parsing ChangedEvent failed" << args; - QWARN("Problem while parsing."); - break; - default: - QWARN("Default should never happen."); - break; - } - } - - return commands; -} - -QString Commands::source() const -{ - return m_source; -} - -void Commands::associateTransfer(OrgKdeKgetTransferInterface *transfer) -{ - if (m_transfer) { - disconnect(m_transfer, 0, this, 0); - } - if (m_verifier) { - disconnect(m_verifier, 0, this, 0); - delete m_verifier; - } - - m_transfer = transfer; - kDebug() << this << "associated with" << m_transfer << m_source; - - QDBusPendingReply reply = m_transfer->dest(); - const QString dest = reply.value(); - - reply = m_transfer->verifier(dest); - m_verifier = new OrgKdeKgetVerifierInterface("org.kde.kget", reply.value(), QDBusConnection::sessionBus(), this); - - connect(m_verifier, SIGNAL(verified(bool)), this, SLOT(slotVerified(bool))); - connect(m_verifier, SIGNAL(brokenPieces(QStringList,qulonglong)), this, SLOT(slotBrokenPieces(QStringList,qulonglong))); - connect(m_transfer, SIGNAL(transferChangedEvent(int)), this, SLOT(slotChangedEvent(int))); -} - -bool Commands::hasCommands() const -{ - return !m_commands.isEmpty(); -} - -void Commands::setCommands(const QList > &commands) -{ - m_commands = commands; -} - -void Commands::timerEvent(QTimerEvent *event) -{ - Q_UNUSED(event) - - const int value = KRandom::randomMax(10); - //70% of the cases start, in 30% stop - if (value > 2) { - kDebug() << this << "is randomly started."; - m_transfer->start(); - } else { - kDebug() << this << "is randomly stopped"; - m_transfer->stop(); - } -} - -void Commands::slotWaitEvent() -{ - //wait is over so continue with executing commands - if (!m_commands.isEmpty()) { - m_commands.takeFirst(); - executeCommands(); - } -} - -void Commands::executeCommands() -{ - if (!m_transfer) { - QFAIL("Calling executeCommands when no transfer is set."); - } - - //NOTE no checks are being done if the commands are correct, this is to ensure that KGet crashes - //on faulty commands making sure that those are found - while (!m_commands.isEmpty()) { - const QPair operation = m_commands.first(); - const int type = operation.first; - - if (type >= CustomEvent) { - return; - } - const QVariant command = operation.second; - - switch (type) { - case Start: - m_transfer->start(); - kDebug() << this << "is started."; - break; - case Stop: - m_transfer->stop(); - kDebug() << this << "is stopped."; - break; - case AddChecksum: { - QStringList hash = command.toStringList(); - kDebug() << this << "adding hash" << hash; - QDBusPendingReply reply = m_verifier->addChecksum(hash.takeFirst(), hash.takeLast()); - break; - } - case AddPartialChecksums: { - QList list = command.toList(); - kDebug() << this << "adding partial hash" << list; - const QString type = list.takeFirst().toString(); - const qulonglong length = list.takeFirst().toULongLong(); - QStringList checksums; - foreach (const QVariant &value, list) { - checksums << value.toString(); - } - m_verifier->addPartialChecksums(type, length, checksums); - break; - } - case IsVerifyable: { - const bool shouldWork = command.toBool(); - QDBusPendingReply reply = m_verifier->isVerifyable(); - kDebug() << this << "isVerifyable" << reply.value(); - QVERIFY(reply.value() == shouldWork); - break; - } - case Verify: { - kDebug() << this << "verification started."; - m_verifier->verify(); - break; - } - case FindBrokenPieces: - kDebug() << this << "find broken pieces."; - m_verifier->brokenPieces(); - break; - case Repair: { - const bool shouldWork = command.toBool(); - QDBusPendingReply dest = m_transfer->dest(); - QDBusPendingReply reply = m_transfer->repair(dest.value()); - - const bool isRepairable = reply.value(); - kDebug() << this << "repair started" << isRepairable; - QVERIFY(isRepairable == shouldWork); - break; - } - case SetDirectory: { - QList commands = command.toList(); - const QString newDirectory = commands.takeFirst().toString(); - const bool shouldWork = commands.takeFirst().toBool(); - QDBusPendingReply reply = m_transfer->setDirectory(newDirectory); - - const bool moveStarted = reply.value(); - kDebug() << this << "set changing directory started" << moveStarted; - QVERIFY(moveStarted == shouldWork); - break; - } - case Wait: { - const int time = command.toInt(); - kDebug() << this << "waiting for" << time << "msecs" << m_transfer; - QTimer::singleShot(time, this, SLOT(slotWaitEvent())); - return; - break; - } - case RandomAction: { - QList commands = command.toList(); - const bool turnOn = commands.takeFirst().toBool(); - if (m_timerId == -1) { - if (turnOn) { - kDebug() << this << "starting random timer."; - m_timerId = startTimer(commands.takeFirst().toInt()); - } - } else { - kDebug() << this << "killing random timer."; - killTimer(m_timerId); - m_timerId = -1; - if (turnOn) { - kDebug() << this << "starting random timer."; - m_timerId = startTimer(commands.takeFirst().toInt()); - } - } - break; - } - } - - m_commands.takeFirst(); - } -} -void Commands::slotChangedEvent(int event) -{ - if (!m_transfer || m_commands.isEmpty()) { - return; - } - - const QPair operation = m_commands.first(); - const int type = operation.first; - - if (type != ChangedEvent) { - return; - } - - const QList commands = operation.second.toList(); - - //at least one and maximum two commands allowed; - if (commands.isEmpty() || commands.count() > 2) { - return; - } - - bool worked; - const int eventType = commands.first().toInt(&worked); - if (!worked || !(eventType & event)) { - return; - } - - if (commands.count() == 2) { - const int compareValue = commands.last().toInt(&worked); - if (!worked) { - return; - } - - switch (eventType) { - case Transfer::Tc_Status: { - QDBusPendingReply reply = m_transfer->status(); - if (reply.value() == compareValue) { - m_commands.takeFirst(); - executeCommands(); - } - break; - } - case Transfer::Tc_Percent: { - QDBusPendingReply reply = m_transfer->percent(); - if (reply.value() >= compareValue) { - kDebug() << this << "ChangedEvent percent."; - m_commands.takeFirst(); - executeCommands(); - } - break; - } - default: - break; - } - } else { - m_commands.takeFirst(); - executeCommands(); - } -} - -void Commands::slotVerified(bool verified) -{ - if (!m_commands.isEmpty()) { - const QPair operation = m_commands.first(); - const int type = operation.first; - - if (type == Verified) { - const QVariant command = operation.second; - m_commands.takeFirst(); - if (command.canConvert(QVariant::Bool)) { - const bool shouldWork = command.toBool(); - kDebug() << this << "is verified" << verified; - QVERIFY(verified == shouldWork); - } - - executeCommands(); - return; - } - } - - kDebug() << this << "is verified" << verified; - QVERIFY(verified); -} - -void Commands::slotBrokenPieces(const QStringList &offsets, qulonglong length) -{ - if (m_commands.isEmpty()) { - return; - } - - const QPair operation = m_commands.first(); - const int type = operation.first; - if (type != BrokenPieces) { - return; - } - -// QList list = brokenPieces.variant().toList();//FIXME - QList compareList = operation.second.toList(); - if (offsets.count() != compareList.count()) { - QFAIL("Emitted brokenPieces list does not match."); - } - for (int i = 0; i < offsets.count(); ++i) { - QVERIFY(static_cast(offsets[i].toULongLong() / length) == compareList[i].toInt()); - } - - m_commands.takeFirst(); - executeCommands(); -} - -TestTransfers::TestTransfers() -{ - if(!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kget")) { - KRun::runCommand("kget --showDropTarget --hideMainWindow", "kget", "kget", 0); - } - - m_dir.reset(new KTempDir()); - kDebug() << "Using temp dir:" << tempDir(); - -//TODO add a signal to check if the move worked!! - -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdeedu-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdegames-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdegraphics-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdelibs-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdelibs-experimental-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdemultimedia-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdenetwork-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdepim-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdepim-runtime-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdepimlibs-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdeplasma-addons-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdesdk-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdetoys-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/kdewebdev-4.3.1.tar.bz2" -// << "http://mirrors.isc.org/pub/kde/stable/4.3.1/src/oxygen-icons-4.3.1.tar.bz2"; - -// << "6326cff7779dfadc1b18a3a6bbe7b0750fb7ceaf" -// << "576255ce66a0c089e0840bd90ea89d5705872bc8" -// << "d57d9007b95607c0ee925cc963d7e14798fc69f9" -// << "511532852caca9302c643fded4013ef1f57d5433" -// << "7d560817a186c4b7099d321ee4a58705962a59d3" -// << "ef50f869f1a6cdf91fe7808f095fccbd9463a7dd" -// << "57194b5f89b37329e562951c491fa18029c0b431" -// << "6fd0309dbd911e2667ec1c08d1f10f2626a54534" -// << "c39b0fc1d3721fb8c6074ba6a174ad8716c6c604" -// << "f4b04b21a6aa3accc530bc6c32cf0d820c611265" -// << "83421181dd3a80c4ac0ff5bab111b7f71f6a1192" -// << "ded236a12002b824f97856ce5dc882161ed437d2" -// << "31a60deafef34a02fb7de5339eed1c750a456d3b" -// << "28580c6f283fa7a6405f6a4415ebe9a4167f0992" -// << "75a82d2e80d946333f63e32db56767c3ed17ba33"; -} - -QString TestTransfers::tempDir() const -{ - return m_dir->name(); -} - -void TestTransfers::parseFile() -{ - QFile file(QString::fromLocal8Bit(KDESRCDIR) + "/kget-test.xml"); - if (!file.open(QIODevice::ReadOnly)) { - QFAIL("XML file not found."); - } - - QDomDocument doc; - if (!doc.setContent(&file)) { - file.close(); - QFAIL("Not able to set content."); - } - file.close(); - - for (QDomElement elem = doc.firstChildElement("tests").firstChildElement("transfer"); !elem.isNull(); elem = elem.nextSiblingElement("transfer")) { - const QString source = elem.attribute("source"); - if (source.isEmpty()) { - QFAIL("One transfer does not have an source attribute."); - return; - } - Commands *transfer = new Commands(source, this); - transfer->setCommands(Commands::parseCommands(elem, this)); - m_commands.append(transfer); - } -} - -void TestTransfers::createTransfer() -{ - if (m_commands.isEmpty()) { - QFAIL("No commands set."); - } - - - if (!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kget")) { - kDebug() << "Service not registered yet, retrying."; - QTimer::singleShot(500, this, SLOT(createTransfer())); - return; - } - QVERIFY(QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kget")); - - OrgKdeKgetMainInterface kgetInterface("org.kde.kget", "/KGet", QDBusConnection::sessionBus()); - - foreach (Commands *command, m_commands) { - QDBusPendingReply reply = kgetInterface.addTransfer(command->source(), tempDir() + KUrl(command->source()).fileName(), false); - reply.waitForFinished(); - - if (reply.value().size()) { - kDebug() << "TestTransfers::createTransfer -> transfer = " << reply.value(); - OrgKdeKgetTransferInterface *transfer = new OrgKdeKgetTransferInterface("org.kde.kget", reply.value().first(), QDBusConnection::sessionBus(), this); - - command->associateTransfer(transfer); - command->executeCommands(); - } else { - QFAIL("Reply NOT VALID!!!"); - } - } -} - -void TestTransfers::simpleTest() -{ - QVERIFY(1 == 1); - - parseFile(); - createTransfer(); - - //execute as long as there are still commands left - forever { - bool abort = true; - foreach (Commands *commands, m_commands) { - if (commands->hasCommands()) { - abort = false; - break; - } - } - - if (abort) { - break; - } - QTest::qWait(3000); - } -} - -QTEST_KDEMAIN(TestTransfers, GUI) - -#include "moc_testtransfers.cpp" - diff --git a/kget/tests/testtransfers.h b/kget/tests/testtransfers.h deleted file mode 100644 index 5843548f..00000000 --- a/kget/tests/testtransfers.h +++ /dev/null @@ -1,109 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 Dario Massarin - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef _TESTTRANSFERS_H -#define _TESTTRANSFERS_H - -#include -#include -#include -#include - -class KTempDir; -class OrgKdeKgetTransferInterface; -class OrgKdeKgetVerifierInterface; -class TestTransfers; - -class Commands : public QObject -{ - Q_OBJECT - - public: - Commands(const QString &source, QObject *parent); - - QString source() const; - bool hasCommands() const; - void setCommands(const QList > &commands); - void executeCommands(); - void associateTransfer(OrgKdeKgetTransferInterface *transfer); - - static QList > parseCommands(const QDomElement &e, TestTransfers *transfer); - - enum Action { - Start, - Stop, - AddChecksum, //QStringList() << type << hash - AddPartialChecksums, //QList() << QString typ << qulonglong length << QStringList checksums - IsVerifyable, //bool if verifyable - Verify, - FindBrokenPieces, - Repair, //bool if it works - SetDirectory, - Wait, //int time; waits until time is over and then proceeds to executeCommands - RandomAction, //QList << bool false OR QList << bool true << int timeBetweenActions; chooses automatically periodially Start or Stop - CustomEvent = 100 - }; - - /** - * Event is a list of Events, events are blocking, so every command after an event - * is blocked, unless the event happens, that way one can start a Repair when Verified returns false - */ - enum Event { - Verified = CustomEvent + 1, //bool verified - ChangedEvent = CustomEvent + 2, //QList() << int TransferChange << int triggerValue = optional; when the event and the triggervalue match then executing continues; e.g. QList() << Transfer::Tc_Percent << 50; //goes on when more than 50% have been downloaded - BrokenPieces = CustomEvent + 3 - }; - - protected: - void timerEvent(QTimerEvent *event); - - private slots: - void slotVerified(bool verified); - void slotBrokenPieces(const QStringList &offsets, qulonglong length); - void slotChangedEvent(int event); - void slotWaitEvent(); - - private: - int m_timerId; - const QString m_source; - QList > m_commands; - OrgKdeKgetTransferInterface *m_transfer; - OrgKdeKgetVerifierInterface *m_verifier; - - static QHash s_stringCommands; - static QHash s_transferChangeEvents; -}; - -class TestTransfers: public QObject -{ - Q_OBJECT - - public: - TestTransfers(); - - QString tempDir() const; - - public slots: - void createTransfer(); - - private slots: - void simpleTest(); - - private: - void parseFile(); - - private: - QList m_transferIfaces; - QList m_commands; - QScopedPointer m_dir; -}; - -#endif diff --git a/kget/tests/verifiertest.cpp b/kget/tests/verifiertest.cpp deleted file mode 100644 index 6d2525da..00000000 --- a/kget/tests/verifiertest.cpp +++ /dev/null @@ -1,352 +0,0 @@ - -#include "verifiertest.h" -#include "../settings.h" -#include "../core/verifier.h" - -#include - -#include -#include -#include - -typedef QPair Checksum; -typedef QPair Checksums; -Q_DECLARE_METATYPE(Checksum) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(Checksums) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(Verifier::ChecksumStrength) -Q_DECLARE_METATYPE(QList) - -VerfierTest::VerfierTest(QObject *parent) - : QObject(parent), - m_supported(Verifier::supportedVerficationTypes()) -{ - //create a file which will used in the test - m_tempDir.reset(new KTempDir(KStandardDirs::locateLocal("tmp", "kget_test"))); - QString path = m_tempDir->name(); - path.append("test.txt"); - QFile file(path); - if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - kFatal() << "Creating file failed:" << path; - } - m_file = KUrl(path); - - const QByteArray data("This is a test for the KGet Verifier class.\n"); - const qint64 size = data.size(); - for (int i = 0; i < 50000; ++i) { - if (file.write(data) != size) { - kFatal() << "Creating file failed:" << path; - } - } - - kDebug() << "Supported types:" << m_supported; - - //Otherwise testVerify fails - qRegisterMetaType("KUrl"); -} - -void VerfierTest::testChecksum() -{ - QFETCH(QString, type); - QFETCH(QString, checksum); - - if (!m_supported.contains(type)) { - return; - } - - QCOMPARE(Verifier::checksum(m_file, type), checksum); -} - -void VerfierTest::testChecksum_data() -{ - QTest::addColumn("type"); - QTest::addColumn("checksum"); - - QTest::newRow("md5 checksum") << "md5" << "1c3b1b627e4f236fdac8f6ab3ee160d1"; - QTest::newRow("sha1 checksum") << "sha1" << "0a4886f5c6e45c5a879b0093a43cb06fc5568bc5"; - QTest::newRow("sha256 checksum") << "sha256" << "9cf2cfe941569d8627dc3ede2897dea1c3949eb6bd124d3bca06a888492f955b"; - QTest::newRow("sha384 checksum") << "sha384" << "a27d95917b3d3ff9145fd9a66cc9852f3a15e7ebac9e7112d4260e2747d45c89a949fe53d110ecc260e246f959ca30e9"; - QTest::newRow("sha512 checksum") << "sha512" << "4c6d2020482ddb1c6f7275f40fb35084805f06a23e433420e46b794ef7ad9770d527c4a7f5dc50bdf7acbd3f2e0a34f00a1b7283a1b222da6835f93505db6641"; -} - -void VerfierTest::testPartialChecksums() -{ - QFETCH(QString, type); - QFETCH(KIO::filesize_t, length); - QFETCH(QStringList, checksums); - QFETCH(bool, result); - - const PartialChecksums partial = Verifier::partialChecksums(m_file, type, length); - QCOMPARE((partial.checksums() == checksums), result); -} - -void VerfierTest::testPartialChecksums_data() -{ - QTest::addColumn("type"); - QTest::addColumn("length"); - QTest::addColumn("checksums"); - QTest::addColumn("result"); - - QTest::newRow("md5, empty checksums") << "md5" << KIO::filesize_t(512 * 1000) << QStringList() << expectedResult(false, "md5"); - QTest::newRow("md5, one checksum is too long, 500 KiB") << "md5" << KIO::filesize_t(500 * 1024) << (QStringList() << "AAAAA8c53d0109e5222e2c57d187eec33ab71" << "f13b7c9978ac7edac8b1c2b9be55abb0" <<"643086ed0d7e733629c848e94e29cdc4" << "6c349ee55737d9bc45ef1b1e75ec7bdf" << "40363ab59bbfa39f6faa4aa18ee75a6c") << expectedResult(false, "md5"); - QTest::newRow("valid md5 checksums, 500 KiB") << "md5" << KIO::filesize_t(500 * 1024) << (QStringList() << "8c53d0109e5222e2c57d187eec33ab71" << "f13b7c9978ac7edac8b1c2b9be55abb0" <<"643086ed0d7e733629c848e94e29cdc4" << "6c349ee55737d9bc45ef1b1e75ec7bdf" << "40363ab59bbfa39f6faa4aa18ee75a6c") << expectedResult(true, "md5"); - QTest::newRow("valid md5 checksums, 400 KiB") << "md5" << KIO::filesize_t(400 * 1024) << (QStringList() << "ce7d795bd0b1499f18d2ba8f338302d3" << "e6681cc0049c6cae347039578eaf1117" << "e66499f43f930fb013092a2d66ecdfaf" << "b2930c55fea65c11813dff09447fbe92" << "77b79bd53b62accec6367c7d7b2fc85b" << "40363ab59bbfa39f6faa4aa18ee75a6c") << expectedResult(true, "md5"); - QTest::newRow("valid md5 checksums, one part with file size") << "md5" << KIO::filesize_t(2200000) << (QStringList() << "1c3b1b627e4f236fdac8f6ab3ee160d1") << expectedResult(true, "md5"); - QTest::newRow("valid sha1 checksums, 1000 KiB") << "sha1" << KIO::filesize_t(1000 * 1024) << (QStringList() << "5d76447e7655fd1d4dfba458c33340757d81eb95" << "0bc9428e3b39fc34ab457d58d62f1973a1183ac2" << "48a313a958ea1c55eb9527b0141ae30742fedfdb") << expectedResult(true, "sha1"); -} - -void VerfierTest::testIsChecksum() -{ - QFETCH(QString, type); - QFETCH(QString, checksum); - QFETCH(bool, result); - - QCOMPARE(Verifier::isChecksum(type, checksum), result); -} - -void VerfierTest::testIsChecksum_data() -{ - QTest::addColumn("type"); - QTest::addColumn("checksum"); - QTest::addColumn("result"); - - const QStringList supported = Verifier::supportedVerficationTypes(); - - QTest::newRow("md5, too many chars") << "md5" << "1c3b1b627e4f236fdac8f6ab3ee160d1a" << expectedResult(false, "md5"); - QTest::newRow("md5, correct length, one wrong char") << "md5" << "1c b1b627e4f236fdac8f6ab3ee160d1" << expectedResult(false, "md5"); - QTest::newRow("md5, correct length, many wrong chars") << "md5" << "1c[b1b627e4f236fd)c8f6ab3_e160d1" << expectedResult(false, "md5"); - QTest::newRow("valid md5 checksum") << "md5" << "1C3B1b627e4F236fdac8f6ab3ee160d1" << expectedResult(true, "md5"); - QTest::newRow("valid sha1 checksum") << "sha1" << "0a4886f5c6e45c5a879b0093a43cb06fc5568bc5" << expectedResult(true, "sha1"); - QTest::newRow("valid sha256 checksum") << "sha256" << "9cf2cfe941569d8627dc3ede2897dea1c3949eb6bd124d3bca06a888492f955b" << expectedResult(true, "sha256"); - QTest::newRow("valid sha384 checksum") << "sha384" << "a27d95917b3d3ff9145fd9a66cc9852f3a15e7ebac9e7112d4260e2747d45c89a949fe53d110ecc260e246f959ca30e9" << expectedResult(true, "sha384"); - QTest::newRow("valid sha512 checksum") << "sha512" << "4c6d2020482ddb1c6f7275f40fb35084805f06a23e433420e46b794ef7ad9770d527c4a7f5dc50bdf7acbd3f2e0a34f00a1b7283a1b222da6835f93505db6641" << expectedResult(true, "sha512"); -} - -void VerfierTest::testAvailableChecksum() -{ - QFETCH(QList, checksums); - QFETCH(Verifier::ChecksumStrength, strength); - QFETCH(Checksum, result); - - Verifier verifier(m_file); - for (int i = 0; i < checksums.size(); ++i) { - verifier.addChecksum(checksums[i].first, checksums[i].second); - } - - const Checksum returned = verifier.availableChecksum(strength); - QCOMPARE(returned, result); -} - -void VerfierTest::testAvailableChecksum_data() -{ - QTest::addColumn >("checksums"); - QTest::addColumn("strength"); - QTest::addColumn("result"); - - const Checksum md5sum("md5", "1c3b1b627e4f236fdac8f6ab3ee160d1"); - const Checksum md5sumInvalid("md5", "1c b1b627e4f236fdac8f6ab3ee160d1"); - const Checksum sha1sum("sha1", "0a4886f5c6e45c5a879b0093a43cb06fc5568bc5"); - const Checksum sha1sumInvalid("sha1", "0a4886f5c6e45c5a879b0093a43cb06fc5568bc"); - const Checksum emptysum; - - QTest::newRow("weak (md5), md5 should be returned") << (QList() << md5sum) << Verifier::Weak << md5sum; - QTest::newRow("strong (md5), md5 should be returned") << (QList() << md5sum) << Verifier::Strong << md5sum; - QTest::newRow("strongest (md5), md5 should be returned") << (QList() << md5sum) << Verifier::Strongest << md5sum; - QTest::newRow("weak (md5), nothing should be returned (md5 invalid)") << (QList() << md5sumInvalid) << Verifier::Weak << emptysum; - QTest::newRow("strong (md5), nothing should be returned (md5 invalid)") << (QList() << md5sumInvalid) << Verifier::Strong << emptysum; - QTest::newRow("strongest (md5), nothing should be returned (md5 invalid)") << (QList() << md5sumInvalid) << Verifier::Strongest << emptysum; - if (m_supported.contains("sha1")) { - QTest::newRow("weak (md5, sha1), sha1 should be returned (md5 invalid)") << (QList() << md5sumInvalid << sha1sum) << Verifier::Weak << sha1sum; - QTest::newRow("strong (md5, sha1), md5 should be returned (sha1 invalid)") << (QList() << md5sum << sha1sumInvalid) << Verifier::Strong << md5sum; - QTest::newRow("strongest (md5, sha1), md5 should be returned (sha1 invalid)") << (QList() << md5sum << sha1sumInvalid) << Verifier::Strongest << md5sum; - QTest::newRow("strong (md5, sha1), sha1 should be returned") << (QList() << md5sum << sha1sum) << Verifier::Strong << sha1sum; - QTest::newRow("strong (md5, sha1), sha1 should be returned") << (QList() << md5sum << sha1sum) << Verifier::Strongest << sha1sum; - QTest::newRow("strongest (md5, sha1), nothing should be returned (md5, sha1 invalid)") << (QList() << md5sumInvalid << sha1sumInvalid) << Verifier::Strongest << emptysum; - } -} - -void VerfierTest::testAvailablePartialChecksum() -{ - QFETCH(QList, data); - QFETCH(Verifier::ChecksumStrength, strength); - QFETCH(Checksums, result); - - Verifier verifier(m_file); - for (int i = 0; i < data.size(); ++i) { - verifier.addPartialChecksums(data[i].first, data[i].second.length(), data[i].second.checksums()); - } - - const QPair returned = verifier.availablePartialChecksum(strength); - QVERIFY(!returned.first.isEmpty()); - QVERIFY(returned.second); - - if (returned.second) { - QCOMPARE(returned.first, result.first); - QCOMPARE(returned.second->checksums(), result.second.checksums()); - QCOMPARE(returned.second->length(), result.second.length()); - } -} - -void VerfierTest::testAvailablePartialChecksum_data() -{ - QTest::addColumn >("data"); - QTest::addColumn("strength"); - QTest::addColumn("result"); - - const Checksums md5Sums("md5", PartialChecksums(400 * 1024, (QStringList() << "ce7d795bd0b1499f18d2ba8f338302d3" << "e6681cc0049c6cae347039578eaf1117" << "e66499f43f930fb013092a2d66ecdfaf" << "b2930c55fea65c11813dff09447fbe92" << "77b79bd53b62accec6367c7d7b2fc85b" << "40363ab59bbfa39f6faa4aa18ee75a6c"))); - const Checksums sha1Sums("sha1", PartialChecksums(1000 * 1024, (QStringList() << "5d76447e7655fd1d4dfba458c33340757d81eb95" << "0bc9428e3b39fc34ab457d58d62f1973a1183ac2" << "48a313a958ea1c55eb9527b0141ae30742fedfdb"))); - const Checksums sha512Sums("sha512", PartialChecksums(2000 * 1024, (QStringList() << "ba9c09d26d7ec7ff60671bc72ec9fed10dee851ae951fbb9e41061490fc10019076982b4c25723870bb5ff17401fdd6d21db43f6018a0604177197db384122d3" << "a63af512c40951216f20c01f5d5623af4c24b907f9a78ded98c14ab550e23764cd131961cbf45df7dfcb17b3cca7443db12de1e0540ed421579d15ccfc7863d0"))); - - QTest::newRow("weak (md5), md5 should be returned") << (QList() << md5Sums) << Verifier::Weak << md5Sums; - QTest::newRow("strong (md5), md5 should be returned") << (QList() << md5Sums) << Verifier::Strong << md5Sums; - QTest::newRow("strongest (md5), md5 should be returned") << (QList() << md5Sums) << Verifier::Strongest << md5Sums; - if (m_supported.contains("sha1")) { - QTest::newRow("weak (md5, sha1), md5 should be returned") << (QList() << md5Sums << sha1Sums) << Verifier::Weak << md5Sums; - QTest::newRow("strong (md5, sha1), sha1 should be returned") << (QList() << md5Sums << sha1Sums) << Verifier::Strong << sha1Sums; - QTest::newRow("strongest (md5, sha1), sha1 should be returned") << (QList() << md5Sums << sha1Sums) << Verifier::Strongest << sha1Sums; - if (m_supported.contains("sha512")) { - QTest::newRow("weak (md5, sha1, sha512), md5 should be returned") << (QList() << md5Sums << sha1Sums << sha512Sums) << Verifier::Weak << md5Sums; - QTest::newRow("strong (md5, sha1, sha512), sha1 should be returned") << (QList() << md5Sums << sha1Sums << sha512Sums) << Verifier::Strong << sha1Sums; - QTest::newRow("strongest (md5, sha1, sha512), sha512 should be returned") << (QList() << md5Sums << sha1Sums << sha512Sums) << Verifier::Strongest << sha512Sums; - } - } -} - -bool VerfierTest::expectedResult(bool expected, const QString& type) -{ - return (expected && m_supported.contains(type)); -} - -void VerfierTest::testVerify() -{ - QFETCH(QList, checksums); - QFETCH(Verifier::ChecksumStrength, strength); - QFETCH(bool, result); - - const Verifier::ChecksumStrength tempStrength = static_cast(Settings::checksumStrength()); - Settings::setChecksumStrength(strength); - Verifier verifier(m_file); - for (int i = 0; i < checksums.size(); ++i) { - verifier.addChecksum(checksums[i].first, checksums[i].second); - } - - QSignalSpy stateSpy(&verifier, SIGNAL(verified(bool))); - QVERIFY(stateSpy.isValid()); - QCOMPARE(stateSpy.count(), 0); - - verifier.verify(); - - //wait for a maximum of 5 seconds, the slowest computer should be done by then - for (int i = 0; !stateSpy.count() && (i < 50); ++i) { - QTest::qWait(100); - } - - QCOMPARE(stateSpy.count(), 1); - const QList argument = stateSpy.takeFirst(); - QCOMPARE(argument.count(), 1); - QCOMPARE(argument.first().toBool(), result); - - Settings::setChecksumStrength(tempStrength); -} - -void VerfierTest::testVerify_data() -{ - QTest::addColumn >("checksums"); - QTest::addColumn("strength"); - QTest::addColumn("result"); - - const Checksum md5sumCorrect("md5", "1c3b1b627e4f236fdac8f6ab3ee160d1"); - const Checksum md5sumWrong("md5", "ac3b1b627e4f236fdac8f6ab3ee160d1"); - const Checksum md5sumInvalid("md5", "1c b1b627e4f236fdac8f6ab3ee160d1"); - const Checksum sha1sumCorrect("sha1", "0a4886f5c6e45c5a879b0093a43cb06fc5568bc5"); - const Checksum sha1sumWrong("sha1", "aa4886f5c6e45c5a879b0093a43cb06fc5568bc5"); - const Checksum sha1sumInvalid("sha1", "0a4886f5c6e45c5a879b0093a43cb0"); - - QTest::newRow("weak (md5), should be verified") << (QList() << md5sumCorrect) << Verifier::Weak << true; - QTest::newRow("strong (md5), should be verified") << (QList() << md5sumCorrect) << Verifier::Strong << true; - QTest::newRow("strongest (md5), should be verified") << (QList() << md5sumCorrect) << Verifier::Strongest << true; - QTest::newRow("weak (md5), should not be verified (md5 wrong)") << (QList() << md5sumWrong) << Verifier::Weak << false; - if (m_supported.contains("sha1")) { - QTest::newRow("weak (md5, sha1), should not be verified (md5 wrong)") << (QList() << md5sumWrong << sha1sumCorrect) << Verifier::Weak << false; - QTest::newRow("weak (md5, sha1), should be verified (md5 invalid)") << (QList() << md5sumInvalid << sha1sumCorrect) << Verifier::Weak << true; - QTest::newRow("strong (md5, sha1), should not be verified (sha1 wrong)") << (QList() << md5sumCorrect << sha1sumWrong) << Verifier::Strong << false; - QTest::newRow("strong (md5, sha1), should be verified (sha1 invalid)") << (QList() << md5sumCorrect << sha1sumInvalid) << Verifier::Strong << true; - QTest::newRow("strong (md5, sha1), should be verified") << (QList() << md5sumCorrect << sha1sumCorrect) << Verifier::Strong << true; - QTest::newRow("strongest (md5, sha1), should be verified (sha1 invalid)") << (QList() << md5sumCorrect << sha1sumInvalid) << Verifier::Strongest << true; - } -} - -void VerfierTest::testBrokenPieces() -{ - QFETCH(QList, data); - QFETCH(Verifier::ChecksumStrength, strength); - QFETCH(QList, offsets); - QFETCH(KIO::filesize_t, length); - - const Verifier::ChecksumStrength tempStrength = static_cast(Settings::checksumStrength()); - Settings::setChecksumStrength(strength); - Verifier verifier(m_file); - for (int i = 0; i < data.size(); ++i) { - verifier.addPartialChecksums(data[i].first, data[i].second.length(), data[i].second.checksums()); - } - - QSignalSpy stateSpy(&verifier, SIGNAL(brokenPieces(QList,KIO::filesize_t))); - QVERIFY(stateSpy.isValid()); - QCOMPARE(stateSpy.count(), 0); - - verifier.brokenPieces(); - - //wait for a maximum of 5 seconds, the slowest computer should be done by then - for (int i = 0; !stateSpy.count() && (i < 50); ++i) { - QTest::qWait(100); - } - - QCOMPARE(stateSpy.count(), 1); - const QList argument = stateSpy.takeFirst(); - QCOMPARE(argument.count(), 2); - const QList returnedOffsets = qvariant_cast >(argument[0]); - QCOMPARE(returnedOffsets, offsets); - const KIO::filesize_t returnedLength = qvariant_cast(argument[1]); - QCOMPARE(returnedLength, length); - - Settings::setChecksumStrength(tempStrength); -} - -void VerfierTest::testBrokenPieces_data() -{ - QTest::addColumn >("data"); - QTest::addColumn("strength"); - QTest::addColumn >("offsets"); - QTest::addColumn("length"); - - const QList emptyOffsets; - - const KIO::filesize_t md5Length = 400 * 1024; - const Checksums md5sumsCorrect("md5", PartialChecksums(md5Length, (QStringList() << "ce7d795bd0b1499f18d2ba8f338302d3" << "e6681cc0049c6cae347039578eaf1117" << "e66499f43f930fb013092a2d66ecdfaf" << "b2930c55fea65c11813dff09447fbe92" << "77b79bd53b62accec6367c7d7b2fc85b" << "40363ab59bbfa39f6faa4aa18ee75a6c"))); - const Checksums md5sumsWrong1("md5", PartialChecksums(md5Length, (QStringList() << "ae7d795bd0b1499f18d2ba8f338302d3" << "e6681cc0049c6cae347039578eaf1117" << "e66499f43f930fb013092a2d66ecdfaf" << "b2930c55fea65c11813dff09447fbe92" << "77b79bd53b62accec6367c7d7b2fc85b" << "40363ab59bbfa39f6faa4aa18ee75a6c"))); - QList md5sumsWrong1Offsets1 = (QList() << 0); - const Checksums md5sumsWrong2("md5", PartialChecksums(md5Length, (QStringList() << "ce7d795bd0b1499f18d2ba8f338302d3" << "e6681cc0049c6cae347039578eaf1117" << "d66499f43f930fb013092a2d66ecdfaf" << "b2930c55fea65c11813dff09447fbe92" << "77b79bd53b62accec6367c7d7b2fc85b" << "d0363ab59bbfa39f6faa4aa18ee75a6c"))); - QList md5sumsWrong1Offsets2 = (QList() << 2 * md5Length << 5 * md5Length); - - const KIO::filesize_t sha1Length = 1000 * 1024; - const Checksums sha1sumsCorrect("sha1", PartialChecksums(sha1Length, (QStringList() << "5d76447e7655fd1d4dfba458c33340757d81eb95" << "0bc9428e3b39fc34ab457d58d62f1973a1183ac2" << "48a313a958ea1c55eb9527b0141ae30742fedfdb"))); - const Checksums sha1sumsWrong1("sha1", PartialChecksums(sha1Length, (QStringList() << "5d76447e7655fd1d4dfba458c33340757d81eb95" << "abc9428e3b39fc34ab457d58d62f1973a1183ac2" << "48a313a958ea1c55eb9527b0141ae30742fedfdb"))); - QList sha1sumsWrong1Offsets1 = (QList() << sha1Length); - const Checksums sha1sumsWrong2("sha1", PartialChecksums(sha1Length, (QStringList() << "ad76447e7655fd1d4dfba458c33340757d81eb95" << "abc9428e3b39fc34ab457d58d62f1973a1183ac2" << "a8a313a958ea1c55eb9527b0141ae30742fedfdb"))); - QList sha1sumsWrong1Offsets2 = (QList() << 0 << sha1Length << 2 * sha1Length); - - QTest::newRow("weak (md5), no broken pieces") << (QList() << md5sumsCorrect) << Verifier::Weak << emptyOffsets << md5Length; - QTest::newRow("weak (md5), 1 broken piece (first)") << (QList() << md5sumsWrong1) << Verifier::Weak << md5sumsWrong1Offsets1 << md5Length; - QTest::newRow("weak (md5), 2 broken piece (third, sixth)") << (QList() << md5sumsWrong2) << Verifier::Weak << md5sumsWrong1Offsets2 << md5Length; - if (m_supported.contains("sha1")) { - QTest::newRow("weak (md5, sha1), no broken pieces (sha1 wrong)") << (QList() << md5sumsCorrect << sha1sumsWrong1) << Verifier::Weak << emptyOffsets << md5Length; - QTest::newRow("strong (md5, sha1), no broken pieces (md5 wrong)") << (QList() << md5sumsWrong1 << sha1sumsCorrect) << Verifier::Strong << emptyOffsets << sha1Length; - QTest::newRow("strong (md5, sha1), 3 broken pieces (first, second, third)") << (QList() << md5sumsCorrect << sha1sumsWrong2) << Verifier::Strong << sha1sumsWrong1Offsets2 << sha1Length; - QTest::newRow("strongest (md5, sha1), 1 broken piece (second)") << (QList() << md5sumsCorrect << sha1sumsWrong1) << Verifier::Strongest << sha1sumsWrong1Offsets1 << sha1Length; - } -} - -QTEST_MAIN(VerfierTest) - -#include "moc_verifiertest.cpp" diff --git a/kget/tests/verifiertest.h b/kget/tests/verifiertest.h deleted file mode 100644 index b7bfed20..00000000 --- a/kget/tests/verifiertest.h +++ /dev/null @@ -1,64 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2011 Matthias Fuchs * -* * -* 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 KGET_VERIFIER_TEST_H -#define KGET_VERIFIER_TEST_H - -#include -#include -#include - -class KTempDir; - -class VerfierTest : public QObject -{ - Q_OBJECT - - public: - explicit VerfierTest(QObject *parent = 0); - - private slots: - void testChecksum(); - void testChecksum_data(); - void testPartialChecksums(); - void testPartialChecksums_data(); - void testIsChecksum(); - void testIsChecksum_data(); - void testAvailableChecksum(); - void testAvailableChecksum_data(); - void testAvailablePartialChecksum(); - void testAvailablePartialChecksum_data(); - void testVerify(); - void testVerify_data(); - void testBrokenPieces(); - void testBrokenPieces_data(); - - private: - /** - * @returns (expected && Verifier::supportedVerficationTypes().contains(type)) - */ - bool expectedResult(bool expected, const QString &type); - - private: - QScopedPointer m_tempDir; - KUrl m_file; - const QStringList m_supported; -}; - -#endif diff --git a/kget/transfer-plugins/CMakeLists.txt b/kget/transfer-plugins/CMakeLists.txt deleted file mode 100644 index 4b0119d2..00000000 --- a/kget/transfer-plugins/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -add_subdirectory(kio) -if (LIBTORRENT_FOUND) - add_subdirectory(torrent) -endif (LIBTORRENT_FOUND) - -add_subdirectory(checksumsearch) - -SET(SUPPORTED_KGET_MIMETYPES "${SUPPORTED_KGET_MIMETYPES}" PARENT_SCOPE) diff --git a/kget/transfer-plugins/checksumsearch/CMakeLists.txt b/kget/transfer-plugins/checksumsearch/CMakeLists.txt deleted file mode 100644 index 791bd7a8..00000000 --- a/kget/transfer-plugins/checksumsearch/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -include_directories( - ../../ -) - -set(kget_checksumsearchfactory_PART_SRCS - checksumsearch.cpp - checksumsearchtransferdatasource.cpp - checksumsearchfactory.cpp -) - -kde4_add_kcfg_files(kget_checksumsearchfactory_PART_SRCS checksumsearchsettings.kcfgc) - -kde4_add_plugin(kget_checksumsearchfactory ${kget_checksumsearchfactory_PART_SRCS}) - -target_link_libraries(kget_checksumsearchfactory KDE4::kio kgetcore) - -install(TARGETS kget_checksumsearchfactory DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) -install(FILES kget_checksumsearchfactory.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - -###Build KCM-Module -set(kcm_kget_checksumsearchfactory_PART_SRCS - checksumsearch.cpp - dlgchecksumsearch.cpp - checksumsearch.ui - checksumsearchadddlg.ui -) - -kde4_add_kcfg_files(kcm_kget_checksumsearchfactory_PART_SRCS checksumsearchsettings.kcfgc) -kde4_add_plugin(kcm_kget_checksumsearchfactory ${kcm_kget_checksumsearchfactory_PART_SRCS}) -target_link_libraries(kcm_kget_checksumsearchfactory KDE4::kdeui KDE4::kio kgetcore) -install(TARGETS kcm_kget_checksumsearchfactory DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - -install(FILES kget_checksumsearchfactory_config.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) diff --git a/kget/transfer-plugins/checksumsearch/checksumsearch.cpp b/kget/transfer-plugins/checksumsearch/checksumsearch.cpp deleted file mode 100644 index 131dce2d..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearch.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "checksumsearch.h" - -#include "core/verifier.h" - -#include -#include - -#include -#include - -const QStringList ChecksumSearch::URLCHANGEMODES = (QStringList() << i18n("Append") << i18n("Replace file") << i18n("Replace file-ending")); - -ChecksumSearch::ChecksumSearch(const QList &srcs, const QString &fileName, const QStringList &types, QObject *parent) - : QObject(parent), - m_copyJob(0), - m_srcs(srcs), - m_fileName(fileName), - m_types(types) -{ - createDownload(); -} - -ChecksumSearch::~ChecksumSearch() -{ - if (m_copyJob) - { - m_copyJob->kill(KJob::Quietly); - } -} - -void ChecksumSearch::createDownload() -{ - if (m_srcs.isEmpty() || m_types.isEmpty()) { - deleteLater(); - } else { - m_src = m_srcs.takeFirst(); - m_type = m_types.takeFirst(); - m_isEmpty = m_type.isEmpty(); - - m_copyJob = KIO::get(m_src, KIO::Reload, KIO::HideProgressInfo); - connect(m_copyJob, SIGNAL(data(KIO::Job*,QByteArray)), SLOT(slotData(KIO::Job*,QByteArray))); - connect(m_copyJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*))); - } -} - -void ChecksumSearch::slotData(KIO::Job *job, const QByteArray &data) -{ - Q_UNUSED(job) - - if (m_dataBA.size() > 5 * 1024) { - m_copyJob->kill(KJob::EmitResult); - } else { - m_dataBA.append(data); - } -} - -void ChecksumSearch::slotResult(KJob *job) -{ - m_data.clear(); - - switch (job->error()) - { - case 0://The download has finished - { - kDebug() << "Correctly downloaded" << m_src.pathOrUrl(); - m_data = QString(m_dataBA); - break; - } - - default: - kDebug() << "There was error" << job->error() << "while downloading" << m_src.pathOrUrl(); - break; - } - - m_copyJob = 0; - m_dataBA.clear(); - - parseDownload(); -} - -void ChecksumSearch::parseDownload() -{ - if (!m_data.isEmpty()) { - kDebug() << "*******Parse*******\n" << m_data << "*******************"; - } - - //no type has been specified - if (m_type.isEmpty()) { - parseDownloadEmpty(); - return; - } - - const int length = Verifier::diggestLength(m_type); - - const QString patternChecksum = QString("\\w{%1}").arg(length); - QRegExp rxChecksum(patternChecksum); - QString hash; - - //find the correct line - const QStringList lines = m_data.split('\n'); - foreach (const QString &line, lines) { - if (line.contains(m_fileName, Qt::CaseInsensitive)) { - if (rxChecksum.indexIn(line) > -1) { - hash = rxChecksum.cap(0).toLower(); - if (!m_fileName.contains(hash, Qt::CaseInsensitive)) { - kDebug() << "Found hash: " << hash; - emit data(m_type, hash); - } - } - } - } - - //nothing found yet, so simply search for a word in the whole data that has the correct length - if (hash.isEmpty() && (rxChecksum.indexIn(m_data) > -1)) { - QString hash = rxChecksum.cap(0); - if (!m_fileName.contains(hash, Qt::CaseInsensitive)) { - kDebug() << "Found hash:" << hash; - emit data(m_type, hash); - } - } - - //only create a download here if type was specified, otherwise parseDownloadEmpty has to handle this - if (!m_isEmpty) { - createDownload(); - } -} - -void ChecksumSearch::parseDownloadEmpty() -{ - const QStringList lines = m_data.split('\n'); - const QStringList supportedTypes = Verifier::supportedVerficationTypes(); - foreach (const QString &type, supportedTypes) - { - if (m_data.contains(type, Qt::CaseInsensitive)) - { - m_type = type; - parseDownload(); - } - } - - createDownload(); -} - -KUrl ChecksumSearch::createUrl(const KUrl &src, const QString &change, ChecksumSearch::UrlChangeMode mode) -{ - if (!src.isValid() || change.isEmpty()) - { - return KUrl(); - } - - KUrl url; - if (mode == kg_Append) - { - url = KUrl(src.pathOrUrl() + change); - } - else if (mode == kg_ReplaceFile) - { - KUrl temp = src.upUrl(); - temp.addPath(change); - url = temp; - } - else if (mode == kg_ReplaceEnding) - { - QString fileName = src.fileName(); - - int index = fileName.lastIndexOf('.'); - if (index > -1) - { - fileName = fileName.left(index); - index = fileName.lastIndexOf('.'); - // FIXME: for anything other than *.tar.* this would be wrong as it could be version, - // e.g. foo-1.2.3.gz. have to probe for two cases here - if (index > -1) - { - fileName = fileName.left(index); - } - } - KUrl temp = src.upUrl(); - temp.addPath(fileName + change); - url = temp; - } - - return url; -} - -#include "moc_checksumsearch.cpp" diff --git a/kget/transfer-plugins/checksumsearch/checksumsearch.h b/kget/transfer-plugins/checksumsearch/checksumsearch.h deleted file mode 100644 index 92ec60ce..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearch.h +++ /dev/null @@ -1,96 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 CHECKSUMSEARCH_H -#define CHECKSUMSEARCH_H - -#include - -#include -#include - -class ChecksumSearch : public QObject -{ - Q_OBJECT - - public: - ChecksumSearch(const QList &srcs, const QString &fileName, const QStringList &types, QObject *parent = 0); - ~ChecksumSearch(); - - /** - * Used to define in which way the url should be changed to try and find - * Checksums - */ - enum UrlChangeMode - { - kg_Append, ///Appends the QString to the Url --> "http://test.com/aFile.zip"; ".md5" "http://test.com/aFile.zip.md5" - kg_ReplaceFile, ///Replaces the file of the Url with QString --> "http://test.com/aFile.zip"; "MD5SUMS" "http://test.com/MD5SUMS" - kg_ReplaceEnding ///Only replaces the file ending of the Url with QString --> "http://test.com/aFile.zip"; "-CHECKSUM" "http://test.com/aFile-CHECKSUM" - }; - - /** - * Returns the available mode-names. The order of the Stringlist is the same as in the enum - */ - static QStringList urlChangeModes() {return URLCHANGEMODES;} - - /** - * Returns a modified url according to the parameters - * @param src the url to modify - * @param change the string containing the change e.g. ".md5" - * @param mode the mode of the change e.g. Append - */ - static KUrl createUrl(const KUrl &src, const QString &change, UrlChangeMode mode); - - Q_SIGNALS: - void data(QString type, QString checksum); - - private slots: - void slotResult(KJob *job); - void slotData(KIO::Job *job, const QByteArray &data); - - private: - /** - * Creates a download - */ - void createDownload(); - - /** - * Parses the download - */ - void parseDownload(); - - /** - * Parses the download when no type has been specified - */ - void parseDownloadEmpty(); - - private: - KIO::TransferJob *m_copyJob; - KUrl m_src; - QList m_srcs; - QString m_fileName; - QString m_type; - QStringList m_types; - QByteArray m_dataBA; - QString m_data; - bool m_isEmpty; - static const QStringList URLCHANGEMODES; -}; - -#endif diff --git a/kget/transfer-plugins/checksumsearch/checksumsearch.ui b/kget/transfer-plugins/checksumsearch/checksumsearch.ui deleted file mode 100644 index 09ce5506..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearch.ui +++ /dev/null @@ -1,62 +0,0 @@ - - - ChecksumSearch - - - - 0 - 0 - 400 - 300 - - - - - - - QAbstractItemView::ExtendedSelection - - - false - - - true - - - false - - - true - - - - - - - - - - - - - Qt::Vertical - - - - 84 - 128 - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- -
diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchadddlg.ui b/kget/transfer-plugins/checksumsearch/checksumsearchadddlg.ui deleted file mode 100644 index 2847feac..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchadddlg.ui +++ /dev/null @@ -1,119 +0,0 @@ - - - ChecksumSearchAddDlg - - - - 0 - 0 - 356 - 223 - - - - - - - - - Change string: - - - - - - - true - - - - - - - Mode: - - - - - - - - - - Checksum type: - - - - - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 5 - - - - - - - - - 75 - true - - - - Result: - - - - - - - label - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
-
- -
diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchfactory.cpp b/kget/transfer-plugins/checksumsearch/checksumsearchfactory.cpp deleted file mode 100644 index 636e2ada..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchfactory.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Manolo Valdes - - 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. -*/ - -#include "checksumsearchfactory.h" -#include "checksumsearchtransferdatasource.h" - -#include "core/scheduler.h" -#include "core/transfergroup.h" - -#include - -#include - -KGET_EXPORT_PLUGIN( ChecksumSearchFactory ) - -ChecksumSearchFactory::ChecksumSearchFactory(QObject *parent, const QVariantList &args) - : TransferFactory(parent, args) -{ -} - -ChecksumSearchFactory::~ChecksumSearchFactory() -{ -} - -TransferDataSource *ChecksumSearchFactory::createTransferDataSource(const KUrl &srcUrl, const QDomElement &type, QObject *parent) -{ - if (type.attribute("type") == "checksumsearch") { - return new ChecksumSearchTransferDataSource(srcUrl, parent); - } - return 0; -} diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchfactory.h b/kget/transfer-plugins/checksumsearch/checksumsearchfactory.h deleted file mode 100644 index 713ee777..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchfactory.h +++ /dev/null @@ -1,31 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Manolo Valdes - - 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. -*/ - -#ifndef CHECKSUMSEARCH_FACTORY_H -#define CHECKSUMSEARCH_FACTORY_H - -#include "core/plugin/transferfactory.h" - -class Transfer; -class TransferGroup; -class Scheduler; -class TransferDataSource; - -class ChecksumSearchFactory : public TransferFactory -{ - Q_OBJECT - public: - ChecksumSearchFactory(QObject *parent, const QVariantList &args); - ~ChecksumSearchFactory(); - - TransferDataSource * createTransferDataSource(const KUrl &srcUrl, const QDomElement &type, QObject *parent); -}; - -#endif diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchsettings.kcfgc b/kget/transfer-plugins/checksumsearch/checksumsearchsettings.kcfgc deleted file mode 100644 index 8037361c..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchsettings.kcfgc +++ /dev/null @@ -1,5 +0,0 @@ -ClassName=ChecksumSearchSettings -File=kget_checksumsearchfactory.kcfg -Mutators=true -Singleton=true -Visibility=KDE_EXPORT diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.cpp b/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.cpp deleted file mode 100644 index b1c28572..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "checksumsearchtransferdatasource.h" -#include "checksumsearch.h" -#include "checksumsearchsettings.h" - -#include -#include - -ChecksumSearchTransferDataSource::ChecksumSearchTransferDataSource(const KUrl &srcUrl, QObject *parent) - : TransferDataSource(srcUrl, parent) -{ -} - -ChecksumSearchTransferDataSource::~ChecksumSearchTransferDataSource() -{ -} - -void ChecksumSearchTransferDataSource::start() -{ - QStringList changes = ChecksumSearchSettings::self()->searchStrings(); - QList modes = ChecksumSearchSettings::self()->urlChangeModeList(); - QStringList types = ChecksumSearchSettings::self()->checksumTypeList(); - - QList urls; - - for (int i = 0, k = 0; i < changes.size(); ++i) { - const ChecksumSearch::UrlChangeMode mode = static_cast(modes.at(i)); - const KUrl source = ChecksumSearch::createUrl(m_sourceUrl, changes.at(i), mode); - KIO::Job* job = KIO::stat(source, KIO::HideProgressInfo); - const bool success = KIO::NetAccess::synchronousRun(job, nullptr); - // qDebug() << Q_FUNC_INFO << "get" << source << success << KIO::NetAccess::lastErrorString(); - if (success) { - urls.append(source); - ++k; - } else { - types.removeAt(k); - } - } - - kDebug() << "Creating Checksumsearch for" << urls.count() << "urls."; - - if (urls.count() && types.count()) { - ChecksumSearch *search = new ChecksumSearch(urls, m_sourceUrl.fileName(), types); - - connect(search, SIGNAL(data(QString,QString)), this, SIGNAL(data(QString,QString))); - } -} - -void ChecksumSearchTransferDataSource::stop() -{ -} - -void ChecksumSearchTransferDataSource::addSegments(const QPair &segmentSize, const QPair &segmentRange) -{ - Q_UNUSED(segmentSize) - Q_UNUSED(segmentRange) -} - -#include "moc_checksumsearchtransferdatasource.cpp" diff --git a/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.h b/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.h deleted file mode 100644 index 2a69ac04..00000000 --- a/kget/transfer-plugins/checksumsearch/checksumsearchtransferdatasource.h +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 CHECKSUMSEARCHTRANSFERDATASOURCE_H -#define CHECKSUMSEARCHTRANSFERDATASOURCE_H - -#include "core/transferdatasource.h" - -#include - -class ChecksumSearch; -class ChecksumSearchTransferDataSource; - -class ChecksumSearchTransferDataSource : public TransferDataSource -{ - Q_OBJECT - public: - ChecksumSearchTransferDataSource(const KUrl &srcUrl, QObject *parent); - virtual ~ChecksumSearchTransferDataSource(); - - void start(); - void stop(); - void addSegments(const QPair &segmentSize, const QPair &segmentRange); - - private: - KUrl m_src; - - friend class ChecksumSearchController; -}; - -#endif diff --git a/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.cpp b/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.cpp deleted file mode 100644 index d5824245..00000000 --- a/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "dlgchecksumsearch.h" - -#include "kget_export.h" - -#include "core/verifier.h" - -#include "checksumsearch.h" -#include "checksumsearchsettings.h" - -#include -#include -#include -#include - -KGET_EXPORT_PLUGIN_CONFIG(DlgChecksumSettingsWidget) - -const KUrl ChecksumSearchAddDlg::URL = KUrl("http://www.example.com/file.zip"); - -ChecksumSearchAddDlg::ChecksumSearchAddDlg(QStringListModel *modesModel, QStringListModel *typesModel, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_modesModel(modesModel), - m_typesModel(typesModel) -{ - setCaption(i18n("Add item")); - showButtonSeparator(true); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - - if (m_modesModel) - { - ui.mode->setModel(m_modesModel); - } - if (m_typesModel) - { - ui.type->setModel(m_typesModel); - } - - slotUpdate(); - - connect(ui.change, SIGNAL(textChanged(QString)), this, SLOT(slotUpdate())); - connect(ui.mode, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdate())); - connect(this, SIGNAL(accepted()), this, SLOT(slotAccpeted())); -} - -void ChecksumSearchAddDlg::slotUpdate() -{ - enableButtonOk(!ui.change->text().isEmpty()); - - const ChecksumSearch::UrlChangeMode mode = static_cast(ui.mode->currentIndex()); - const KUrl modifiedUrl = ChecksumSearch::createUrl(URL, ui.change->text(), mode); - const QString text = i18n("%1 would become %2", URL.prettyUrl(), modifiedUrl.prettyUrl()); - ui.label->setText(text); -} - -void ChecksumSearchAddDlg::slotAccpeted() -{ - emit addItem(ui.change->text(), ui.mode->currentIndex(), ui.type->currentText()); -} - -ChecksumDelegate::ChecksumDelegate(QObject *parent) - : QStyledItemDelegate(parent), - m_modesModel(0), - m_typesModel(0) -{ -} - -ChecksumDelegate::ChecksumDelegate(QStringListModel *modesModel, QStringListModel *typesModel, QObject *parent) - : QStyledItemDelegate(parent), - m_modesModel(modesModel), - m_typesModel(typesModel) -{ -} - -QWidget *ChecksumDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - - if (index.isValid()) - { - if (index.column() == 0l) - { - KLineEdit *line = new KLineEdit(parent); - - return line; - } - else if (index.column() == 1) - { - if (m_modesModel) - { - KComboBox *modesBox = new KComboBox(parent); - modesBox->setModel(m_modesModel); - - return modesBox; - } - } - else if (index.column() == 2) - { - if (m_typesModel) - { - KComboBox *typesBox = new KComboBox(parent); - typesBox->setModel(m_typesModel); - - return typesBox; - } - } - } - - return 0; -} - -void ChecksumDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (index.isValid() && editor) { - if (index.column() == 0) { - KLineEdit *line = static_cast(editor); - line->setText(index.data(Qt::EditRole).toString()); - } else if (index.column() == 1) { - KComboBox *modesBox = static_cast(editor); - const QString mode = index.data(Qt::EditRole).toString(); - modesBox->setCurrentIndex(modesBox->findText(mode)); - } else if (index.column() == 2) { - KComboBox *typesBox = static_cast(editor); - const QString type = index.data(Qt::EditRole).toString(); - typesBox->setCurrentIndex(typesBox->findText(type)); - } - } -} - -void ChecksumDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (index.isValid() && editor && model) - { - if (index.column() == 0) - { - KLineEdit *line = static_cast(editor); - if (!line->text().isEmpty()) - { - model->setData(index, line->text()); - } - } - else if (index.column() == 1) - { - KComboBox *modesBox = static_cast(editor); - model->setData(index, modesBox->currentText()); - model->setData(index, modesBox->currentIndex(), Qt::UserRole); - } - else if (index.column() == 2) - { - KComboBox *typesBox = static_cast(editor); - model->setData(index, typesBox->currentText()); - } - } -} - -void ChecksumDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(index) - editor->setGeometry(option.rect); -} - -DlgChecksumSettingsWidget::DlgChecksumSettingsWidget(QWidget *parent, const QVariantList &args) - : KCModule(KGetFactory::componentData(), parent, args) -{ - ui.setupUi(this); - - m_modes = ChecksumSearch::urlChangeModes(); - m_modesModel = new QStringListModel(m_modes, this); - QStringList types = Verifier::supportedVerficationTypes(); - types.insert(0, QString()); - m_typesModel = new QStringListModel(types, this); - - m_model = new QStandardItemModel(0, 3, this); - m_model->setHeaderData(0, Qt::Horizontal, i18nc("the string that is used to modify an url", "Change string")); - m_model->setHeaderData(1, Qt::Horizontal, i18nc("the mode defines how the url should be changed", "Change mode")); - m_model->setHeaderData(2, Qt::Horizontal, i18nc("the type of the checksum e.g. md5", "Checksum type")); - - m_proxy = new QSortFilterProxyModel(this); - m_proxy->setSourceModel(m_model); - m_proxy->setSortCaseSensitivity(Qt::CaseInsensitive); - - ui.treeView->setModel(m_proxy); - ChecksumDelegate *delegate = new ChecksumDelegate(m_modesModel, m_typesModel, this); - ui.treeView->setItemDelegate(delegate); - ui.treeView->sortByColumn(2, Qt::AscendingOrder); - ui.add->setGuiItem(KStandardGuiItem::add()); - ui.remove->setGuiItem(KStandardGuiItem::remove()); - slotUpdate(); - - connect(ui.add, SIGNAL(clicked()), this, SLOT(slotAdd())); - connect(ui.remove, SIGNAL(clicked()), this, SLOT(slotRemove())); - connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(slotUpdate())); - connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(changed())); - connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(changed())); - connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(changed())); -} - -DlgChecksumSettingsWidget::~DlgChecksumSettingsWidget() -{ -} - -void DlgChecksumSettingsWidget::slotAdd() -{ - ChecksumSearchAddDlg *dialog = new ChecksumSearchAddDlg(m_modesModel, m_typesModel, this); - connect(dialog, SIGNAL(addItem(QString,int,QString)), this, SLOT(slotAddItem(QString,int,QString))); - - dialog->show(); -} - -void DlgChecksumSettingsWidget::slotRemove() -{ - while (ui.treeView->selectionModel()->hasSelection()) { - const QModelIndex index = ui.treeView->selectionModel()->selectedRows().first(); - m_model->removeRow(m_proxy->mapToSource(index).row()); - } -} - -void DlgChecksumSettingsWidget::slotAddItem(const QString &change, int mode, const QString &type) -{ - QStandardItem *item = new QStandardItem(m_modes.value(mode)); - item->setData(QVariant(mode), Qt::UserRole); - - QList items; - items << new QStandardItem(change); - items << item; - items << new QStandardItem(type); - m_model->insertRow(m_model->rowCount(), items); -} - -void DlgChecksumSettingsWidget::slotUpdate() -{ - ui.remove->setEnabled(ui.treeView->selectionModel()->hasSelection()); -} - -void DlgChecksumSettingsWidget::load() -{ - QStringList changes = ChecksumSearchSettings::self()->searchStrings(); - QList modes = ChecksumSearchSettings::self()->urlChangeModeList(); - QStringList types = ChecksumSearchSettings::self()->checksumTypeList(); - - for(int i = 0; i < changes.size(); ++i) - { - slotAddItem(changes.at(i), modes.at(i), types.at(i)); - } -} - -void DlgChecksumSettingsWidget::save() -{ - QStringList changes; - QList modes; - QStringList types; - - for (int row = 0; row < m_model->rowCount(); ++row) - { - changes.append(m_model->data(m_model->index(row, 0)).toString()); - modes.append(m_model->data(m_model->index(row, 1), Qt::UserRole).toInt()); - types.append(m_model->data(m_model->index(row, 2)).toString()); - } - - ChecksumSearchSettings::self()->setSearchStrings(changes); - ChecksumSearchSettings::self()->setUrlChangeModeList(modes); - ChecksumSearchSettings::self()->setChecksumTypeList(types); - - ChecksumSearchSettings::self()->writeConfig(); -} - -#include "moc_dlgchecksumsearch.cpp" diff --git a/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.h b/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.h deleted file mode 100644 index 51637666..00000000 --- a/kget/transfer-plugins/checksumsearch/dlgchecksumsearch.h +++ /dev/null @@ -1,136 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 DLGCHECKSUMSEARCH_H -#define DLGCHECKSUMSEARCH_H - -#include "ui_checksumsearch.h" -#include "ui_checksumsearchadddlg.h" - -#include "checksumsearchtransferdatasource.h" - -#include - -#include -#include - -#include -#include -#include - -class ChecksumSearchAddDlg : public KDialog -{ - Q_OBJECT - - public: - ChecksumSearchAddDlg(QStringListModel *modesModel, QStringListModel *typesModel, QWidget *parent = 0, Qt::WFlags flags = 0); - - signals: - /** - * Emitted when the dialog gets accepted - * @param change the string that should change the source url by mode - * @param mode the change mode - * @param type the checksum type, can be an empty string - */ - void addItem(const QString &change, int mode, const QString &type); - - private slots: - /** - * Enables or disables buttons depending on if the user entered text or not, also changes - * the label etc. - */ - void slotUpdate(); - - void slotAccpeted(); - - private: - Ui::ChecksumSearchAddDlg ui; - - QStringListModel *m_modesModel; - QStringListModel *m_typesModel; - - static const KUrl URL; -}; - -class ChecksumDelegate : public QStyledItemDelegate -{ - Q_OBJECT - - public: - ChecksumDelegate(QObject *parent = 0); - ChecksumDelegate(QStringListModel *modesModel, QStringListModel *typesModel, QObject *parent = 0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; - - private: - QStringListModel *m_modesModel; - QStringListModel *m_typesModel; -}; - -class DlgChecksumSettingsWidget : public KCModule -{ - Q_OBJECT - - public: - explicit DlgChecksumSettingsWidget(QWidget *parent = 0, const QVariantList &args = QVariantList()); - ~DlgChecksumSettingsWidget(); - - public slots: - void save(); - void load(); - - private slots: - /** - * Oppens the AddDlg - */ - void slotAdd(); - - /** - * Remove the selected indexes - */ - void slotRemove(); - - /** - * Enables or disables buttons depending on if the user entered text or not, also changes - * the label etc. - */ - void slotUpdate(); - - /** - * Adds a new item defining how to proceed a search for checksums to the model - * @param change the string that should change the source url by mode - * @param mode the change mode, defined in verifier.h, using int instead of enum as convenience - * @param type the checksum type, like e.g. "md5", empty if you do not know that - * e.g. if change is "CHECKSUMS" you cannot know which checksums are present - */ - void slotAddItem(const QString &change, int mode, const QString &type = QString()); - - private: - Ui::ChecksumSearch ui; - QStandardItemModel *m_model; - QSortFilterProxyModel *m_proxy; - QStringList m_modes; - QStringListModel *m_modesModel; - QStringListModel *m_typesModel; -}; - -#endif // DLGCHECKSUMSEARCH_H diff --git a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.desktop b/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.desktop deleted file mode 100644 index b7d43a06..00000000 --- a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.desktop +++ /dev/null @@ -1,127 +0,0 @@ -[Desktop Entry] -# service definition -Type=Service -X-KDE-ServiceTypes=KGet/Plugin -Icon=kget - -# standard fields -Name=Checksum Search -Name[ast]=Guetar comprabación de suma -Name[bg]=Търсене на контролна сума -Name[bs]=Traženje kontrolnih suma -Name[ca]=Cerca de suma de verificació -Name[ca@valencia]=Cerca de suma de verificació -Name[cs]=Hledání kontrolního součtu -Name[da]=Tjeksum-søgning -Name[de]=Prüfsummen-Suche -Name[el]=Αναζήτηση αθροίσματος ελέγχου -Name[en_GB]=Checksum Search -Name[es]=Buscar comprabación de suma -Name[et]=Kontrollsumma otsing -Name[eu]=Kontrol-baturaren bilaketa -Name[fi]=Tarkistussummaetsintä -Name[fr]=Recherche d'une somme de contrôle -Name[ga]=Cuardach ar suimeanna seiceála -Name[gl]=Procura de suma de comprobación -Name[hr]=Pretraživač kontrolnih suma -Name[hu]=Ellenőrzőösszeg-kereső -Name[ia]=Cerca de Checksum -Name[is]=Leitar að gátsummum -Name[it]=Ricerca per codice di controllo -Name[ja]=チェックサム検索 -Name[kk]=Бақылау қосындысын іздеу -Name[km]=ស្វែងរក​ឆេក​សាំ -Name[ko]=체크섬 검색 -Name[lt]=Tikrinimo sumos paieška -Name[lv]=Kontrolsummu meklēšana -Name[nb]=Sjekksum-søk -Name[nds]=Pröövsumm-Söök -Name[nl]=Controlesom zoeken -Name[nn]=Sjekksum-søk -Name[pa]=ਚੈਕਸਮ ਖੋਜ -Name[pl]=Znajdywanie sumy kontrolnej -Name[pt]=Pesquisa por Código de Validação -Name[pt_BR]=Pesquisa de soma de verificação -Name[ro]=Căutare sumă de control -Name[ru]=Поиск контрольных сумм -Name[si]=පිරික්සුම් සෙවුම -Name[sk]=Hľadanie kontrolného súčtu -Name[sl]=Iskanje nadzornih vsot -Name[sr]=Тражење контролних сума -Name[sr@ijekavian]=Тражење контролних сума -Name[sr@ijekavianlatin]=Traženje kontrolnih suma -Name[sr@latin]=Traženje kontrolnih suma -Name[sv]=Checksummesökning -Name[tr]=Sağlama Araması -Name[ug]=تەكشۈرۈش ئىزدەش -Name[uk]=Пошук контрольної суми -Name[x-test]=xxChecksum Searchxx -Name[zh_CN]=校验和搜索 -Name[zh_TW]=驗證碼搜尋 - -Comment=Tries to find checksums for a specified URL -Comment[ast]=Intenta alcontrar comprobación de suma pa una direición URL especificada -Comment[bg]=Търсене на контролни суми за указания URL-адрес -Comment[bs]=Pokušava da nađe kontrolne sume za navedeni URL -Comment[ca]=Intenta cercar sumes de verificació per a un URL especificat -Comment[ca@valencia]=Intenta cercar sumes de verificació per a un URL especificat -Comment[cs]=Pokusí se najít kontrolní součty pro zadanou URL -Comment[da]=Forsøger at finde tjeksummer for en angivet URL -Comment[de]=Versucht Prüfsummen für eine angegebene Adresse zu finden -Comment[el]=Προσπαθεί να βρει αθροίσματα ελέγχου για ένα ορισμένο URL -Comment[en_GB]=Tries to find checksums for a specified URL -Comment[es]=Intenta encontrar sumas de verificación para la dirección URL especificada -Comment[et]=Kontrollsumma otsimine määratud URL-ilt -Comment[eu]=Zehaztutako URLaren kontrol-batura bilatzen saiatzen da -Comment[fi]=Yrittää löytää tarkistussummat määritellylle verkko-osoitteelle -Comment[fr]=Tente de trouver une somme de contrôle pour une URL donnée -Comment[ga]=Déan iarracht ar shuim sheiceála a aimsiú a fhreagraíonn d'URL ar leith -Comment[gl]=Tenta atopar sumas de comprobación para un url que se especifique -Comment[hr]=Pokušava pronaći kontrolnu sumu za navedeni URL -Comment[hu]=Ellenőrzőösszegek keresése egy megadott URL-hez -Comment[ia]=Il tenta de trovar checksums pro un URL specificate -Comment[is]=Reynir að finna gátsummu á tilgreindri slóð (URL) -Comment[it]=Cerca di trovare dei codici di controllo per un URL specifico -Comment[ja]=指定された URL のチェックサムを探します -Comment[kk]=Келтірілген URL-дегі файлдың бақылау қосындысын іздеу -Comment[km]=ព្យាយាម​រក​ឆេកសាំ​សម្រាប់ URL ដែល​បាន​បញ្ជាក់ -Comment[ko]=지정한 URL의 체크섬을 검색합니다 -Comment[lt]=Bando rasti tikrinimo sumas nurodytam URL -Comment[lv]=Mēģina atrast kontrolsummas norādītajam URL -Comment[nb]=Forsøker å finne sjekksummer for en gitt URL -Comment[nds]=Söcht na en Pröövsumm för en angeven URL -Comment[nl]=Probeert controlesommen voor een gespecificeerde URL te vinden -Comment[nn]=Prøver å finna sjekksummar for oppgjevne adresser -Comment[pl]=Próbuje znaleźć sumy kontrolne dla podanego adresu URL -Comment[pt]=Tenta pesquisar os códigos de validação ('checksums') para um dado URL -Comment[pt_BR]=Tenta encontrar as somas de verificação para uma URL especificada -Comment[ro]=Încearcă să găsească sume de control pentru un anumit URL -Comment[ru]=Поиск контрольных сумм для указанного адреса URL -Comment[si]=දෙනලද URL හි පිරික්සුමක් උත්සාහ කරයි -Comment[sk]=Pokúsi sa nájsť kontrolné súčty pre zadanú URL -Comment[sl]=Za podan naslov poskuša najti nadzorno vsoto -Comment[sr]=Покушава да нађе контролне суме за наведени УРЛ -Comment[sr@ijekavian]=Покушава да нађе контролне суме за наведени УРЛ -Comment[sr@ijekavianlatin]=Pokušava da nađe kontrolne sume za navedeni URL -Comment[sr@latin]=Pokušava da nađe kontrolne sume za navedeni URL -Comment[sv]=Försöker hitta checksummor för en specifik webbadress -Comment[tr]=Belirtilen bir adres için sağlamaları bulmaya çalışır -Comment[ug]=بەلگىلەنگەن URL نىڭ تەكشۈرۈشىنى ئىزدەيدۇ -Comment[uk]=Намагається знайти контрольні суми файла за вказаною адресою -Comment[x-test]=xxTries to find checksums for a specified URLxx -Comment[zh_CN]=尝试查找指定 URL 的数据校验和 -Comment[zh_TW]=試著尋找指定網址的驗證碼 - -# options for library loader -X-KDE-Library=kget_checksumsearchfactory -X-KDE-KGet-plugintype=TransferFactory -X-KDE-KGet-rank=30 -X-KDE-KGet-framework-version=1 - -X-KDE-PluginInfo-Author=Matthias Fuchs -X-KDE-PluginInfo-Email=mat69@gmx.net -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-PluginInfo-Name=kget_checksumsearch_plugin diff --git a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.kcfg b/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.kcfg deleted file mode 100644 index c02ff6cf..00000000 --- a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory.kcfg +++ /dev/null @@ -1,22 +0,0 @@ - - - kdemacros.h - - - - - .md5,.md5sum,MD5SUMS,.sha1,.sha1sum,SHA1SUMS,.sha256,.sha256sum,SHA256SUMS,.sha512,.sha512sum,SHA512SUMS,-CHECKSUM - - - - 0,2,1,0,2,1,0,2,1,0,2,1,2 - - - - md5,md5,md5,sha1,sha1,sha1,sha256,sha256,sha256,sha512,sha512,sha512, - - - diff --git a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory_config.desktop b/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory_config.desktop deleted file mode 100644 index 9c4ca766..00000000 --- a/kget/transfer-plugins/checksumsearch/kget_checksumsearchfactory_config.desktop +++ /dev/null @@ -1,59 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule - -X-KDE-Library=kcm_kget_checksumsearchfactory -X-KDE-ParentComponents=kget_checksumsearch_plugin - -Name=ChecksumSearch -Name[ast]=Guetador de comprobación de sumes -Name[bg]=ТърсенеКонтролнаСума -Name[bs]=ChecksumSearch -Name[ca]=Cerca la suma de verificació -Name[ca@valencia]=Cerca de suma de verificació -Name[cs]=Hledání kontrolního součtu -Name[da]=ChecksumSearch -Name[de]=Prüfsummen-Suche -Name[el]=ChecksumSearch -Name[en_GB]=ChecksumSearch -Name[es]=Buscador de sumas de verificación -Name[et]=Kontrollsumma otsing -Name[eu]=Kontrol-baturaren bilaketa -Name[fi]=Tarkistussummahaku -Name[fr]=ChecksumSearch -Name[ga]=ChecksumSearch -Name[gl]=Procura de suma de comprobación -Name[hr]=Pretraživač kontrolnih suma -Name[hu]=Ellenőrzőösszeg-kereső -Name[ia]=ChecksumSearch (Cerca de Checksum) -Name[is]=LeitGátsummu -Name[it]=Ricerca per codice di controllo -Name[ja]=チェックサム検索 -Name[kk]=Бақылау қосындысын іздеу -Name[km]=ChecksumSearch -Name[ko]=ChecksumSearch -Name[lt]=Tikrinimo sumos paieška -Name[lv]=ChecksumSearch -Name[nb]=Sjekksumsøk -Name[nds]=Pröövsumm-Söök -Name[nl]=ChecksumSearch -Name[nn]=Sjekksum-søk -Name[pa]=ChecksumSearch -Name[pl]=Znajdywanie sumy kontrolnej -Name[pt]=Pesquisa por Código de Validação -Name[pt_BR]=Pesquisa de soma de verificação -Name[ru]=Поиск контрольных сумм -Name[si]=පිරික්සුම් සෙවුම -Name[sk]=ChecksumSearch -Name[sl]=ChecksumSearch -Name[sr]=Тражење контролних сума -Name[sr@ijekavian]=Тражење контролних сума -Name[sr@ijekavianlatin]=Traženje kontrolnih suma -Name[sr@latin]=Traženje kontrolnih suma -Name[sv]=Checksummesökning -Name[tr]=Sağlama Araması -Name[ug]=تەكشۈرۈش ئىزدەش -Name[uk]=Пошук контрольної суми -Name[x-test]=xxChecksumSearchxx -Name[zh_CN]=校验和搜索 -Name[zh_TW]=驗證碼搜尋 diff --git a/kget/transfer-plugins/kio/CMakeLists.txt b/kget/transfer-plugins/kio/CMakeLists.txt deleted file mode 100644 index 93b4075c..00000000 --- a/kget/transfer-plugins/kio/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -include_directories( - ../../ - ${CMAKE_CURRENT_BINARY_DIR}/../../ -) - -set(kget_kiofactory_PART_SRCS - transferKio.cpp - transferKioFactory.cpp -) - -kde4_add_plugin(kget_kiofactory ${kget_kiofactory_PART_SRCS}) - -target_link_libraries(kget_kiofactory KDE4::kio kgetcore) - -install(TARGETS kget_kiofactory DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) -install(FILES kget_kiofactory.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) diff --git a/kget/transfer-plugins/kio/kget_kiofactory.desktop b/kget/transfer-plugins/kio/kget_kiofactory.desktop deleted file mode 100644 index 44beade0..00000000 --- a/kget/transfer-plugins/kio/kget_kiofactory.desktop +++ /dev/null @@ -1,135 +0,0 @@ -[Desktop Entry] -# service definition -Type=Service -X-KDE-ServiceTypes=KGet/Plugin -Icon=kget - -# standard fields -Name=KIO -Name[ar]=KIO -Name[ast]=KIO -Name[bg]=KIO -Name[bs]=KIO -Name[ca]=KIO -Name[ca@valencia]=KIO -Name[cs]=KIO -Name[da]=KIO -Name[de]=KIO -Name[el]=KIO -Name[en_GB]=KIO -Name[eo]=KIO -Name[es]=KIO -Name[et]=KIO -Name[eu]=KIO -Name[fi]=KIO -Name[fr]=KIO -Name[ga]=KIO -Name[gl]=KIO -Name[hne]=केआईओ -Name[hr]=KIO -Name[hu]=KIO -Name[ia]=KIO -Name[is]=KIO -Name[it]=KIO -Name[ja]=KIO -Name[kk]=KIO -Name[km]=KIO -Name[ko]=KIO -Name[lt]=KIO -Name[lv]=KIO -Name[ml]=കിയോ -Name[nb]=KIO -Name[nds]=KIO-Moduul -Name[nl]=KIO -Name[nn]=KIO -Name[pa]=KIO -Name[pl]=KIO -Name[pt]=KIO -Name[pt_BR]=KIO -Name[ro]=KIO -Name[ru]=Обычная загрузка файлов -Name[si]=KIO -Name[sk]=KIO -Name[sl]=KIO -Name[sq]=KIO -Name[sr]=К‑У/И -Name[sr@ijekavian]=К‑У/И -Name[sr@ijekavianlatin]=K‑U/I -Name[sr@latin]=K‑U/I -Name[sv]=KIO -Name[tr]=KIO -Name[ug]=KIO -Name[uk]=KIO -Name[x-test]=xxKIOxx -Name[zh_CN]=KIO -Name[zh_TW]=KIO -Comment=Classic file downloader plugin -Comment[ar]=ملحق تنزيل الملف الكلاسيكي -Comment[ast]=Complementu de baxada de ficheros clásicu -Comment[bg]=Класическа приставка за изтегляне на файлове -Comment[bs]=Klasični priključak za preuzimanje datoteka -Comment[ca]=Connector del baixador de fitxers clàssic -Comment[ca@valencia]=Connector de descarregador clàssic de fitxers -Comment[cs]=Modul pro klasické stahování souborů -Comment[da]=Plugin til klassisk fildownload -Comment[de]=Klassisches Datei-Übertragungs-Modul -Comment[el]=Κλασικό πρόσθετο λήψης αρχείων -Comment[en_GB]=Classic file downloader plugin -Comment[es]=Complemento de descarga de archivos clásico -Comment[et]=Klassikaline failide allalaadimise plugin -Comment[eu]=Fitxategien deskargatzaile klasikoaren plugina -Comment[fi]=Perinteinen tiedostonlatausliitännäinen -Comment[fr]=Module externe de téléchargement classique de fichiers -Comment[ga]=Breiseán clasaiceach íosluchtaithe comhad -Comment[gl]=Engadido de transferencia clásica de ficheiros -Comment[hr]=Uobičajeni priključak za preuzimanje datoteka -Comment[hu]=Klasszikus fájlletöltő modul -Comment[ia]=Plug-in de discargator classic de file -Comment[is]=Klassískt íforrit til niðurhals -Comment[it]=Estensione classica del scaricatore di file -Comment[ja]=従来のファイルダウンロード用プラグイン -Comment[kk]=Классикалық файл жүктегіш плагині -Comment[km]=កម្មវិធី​ជំនួយ​របស់​កម្មវិធីទាញយក​ឯកសារ​បុរាណ -Comment[ko]=고전 파일 다운로더 플러그인 -Comment[lt]=Klasikinis failų atsiuntimo įskiepis -Comment[lv]=Klasiskās failu lejupielādes sparudnis -Comment[ml]=നിത്യഹരിതമായ ഫയലുകള്‍ ഇറക്കിവെക്കാനുള്ള സംയോജകം -Comment[nb]=Klassisk programtillegg for filnedlasting -Comment[nds]=Klass'sch Dateidaallaad-Moduul -Comment[nl]=Klassieke plugin voor bestand downloaden -Comment[nn]=Klassisk programtillegg for filnedlasting -Comment[pa]=ਕਲਾਸਿਕ ਫਾਇਲ ਡਾਊਨਲੋਡਰ ਪਲੱਗਇਨ -Comment[pl]=Klasyczna wtyczka do pobierania plików -Comment[pt]='Plugin' de transferência de ficheiros clássico -Comment[pt_BR]=Plugin de download de arquivos clássico -Comment[ro]=Modul de descărcare clasică -Comment[ru]=Классический модуль загрузки файлов -Comment[si]=සම්ප්‍රධායික ගොනු බාගැනීම් ප්ලගිනය -Comment[sk]=Modul pre klasické sťahovanie súborov -Comment[sl]=Vstavek za klasično prejemanje datotek -Comment[sr]=Класични прикључак за преузимање фајлова -Comment[sr@ijekavian]=Класични прикључак за преузимање фајлова -Comment[sr@ijekavianlatin]=Klasični priključak za preuzimanje fajlova -Comment[sr@latin]=Klasični priključak za preuzimanje fajlova -Comment[sv]=Klassiskt insticksprogram för filnerladdning -Comment[tr]=Klasik dosya indirme eklentisi -Comment[ug]=كلاسسىك ھۆججەت چۈشۈرۈش قىستۇرمىسى -Comment[uk]=Додаток класичного звантаження файлів -Comment[x-test]=xxClassic file downloader pluginxx -Comment[zh_CN]=传统的文件下载插件 -Comment[zh_TW]=傳統檔案下載外掛程式 - -# options for library loader -X-KDE-Library=kget_kiofactory -X-KDE-KGet-plugintype=TransferFactory -X-KDE-KGet-rank=50 -X-KDE-KGet-framework-version=1 - -X-KDE-PluginInfo-Author=Dario Massarin -X-KDE-PluginInfo-Email=nekkar@libero.it -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-PluginInfo-Name=kget_kio_plugin - diff --git a/kget/transfer-plugins/kio/transferKio.cpp b/kget/transfer-plugins/kio/transferKio.cpp deleted file mode 100644 index 4c150fd7..00000000 --- a/kget/transfer-plugins/kio/transferKio.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ - -#include "transferKio.h" -#include "core/kget.h" -#include "core/transferdatasource.h" -#include "settings.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -TransferKio::TransferKio(TransferGroup * parent, TransferFactory * factory, - Scheduler * scheduler, const KUrl & source, const KUrl & dest) - : Transfer(parent, factory, scheduler, source, dest), - m_copyjob(nullptr), - m_verifier(nullptr), - m_filemodel(nullptr) -{ - if (KProtocolManager::autoResume()) { - setCapabilities(Transfer::Cap_Resuming); - } -} - -void TransferKio::start() -{ - if (status() != Job::Finished) { - kDebug() << "TransferKio::start"; - setStatus(Job::Running); - setTransferChange(Transfer::Tc_Status, true); - - if (Settings::checksumAutomaticVerification()) { - QDomDocument doc; - QDomElement element = doc.createElement("TransferDataSource"); - element.setAttribute("type", "checksumsearch"); - doc.appendChild(element); - - TransferDataSource *checksumSearch = KGet::createTransferDataSource(m_source, element, this); - if (checksumSearch) { - connect(checksumSearch, SIGNAL(data(QString,QString)), this, SLOT(slotChecksumFound(QString,QString))); - checksumSearch->start(); - } - } - - createJob(); - } -} - -void TransferKio::stop() -{ - if (status() == Job::Stopped || status() == Job::Finished) { - return; - } - - if (m_copyjob) { - m_copyjob->kill(KJob::EmitResult); - m_copyjob = nullptr; - } - - kDebug() << "Stop"; - setStatus(Job::Stopped); - m_downloadSpeed = 0; - setTransferChange(Transfer::Tc_Status | Transfer::Tc_DownloadSpeed, true); -} - -void TransferKio::deinit(Transfer::DeleteOptions options) -{ - if (options & Transfer::DeleteFiles) { - KIO::Job *del = KIO::del(m_dest, KIO::HideProgressInfo); - KIO::NetAccess::synchronousRun(del, 0); - } - - if (options & Transfer::DeleteTemporaryFiles) { - KIO::Job *del = KIO::del(m_dest.path() + ".part", KIO::HideProgressInfo); - KIO::NetAccess::synchronousRun(del, 0); - } -} - -bool TransferKio::repair(const KUrl &file) -{ - Q_UNUSED(file); - - if (verifier()->status() == Verifier::NotVerified) { - m_downloadedSize = 0; - m_percent = 0; - if (m_copyjob) { - m_copyjob->kill(KJob::Quietly); - m_copyjob = nullptr; - } - setTransferChange(Transfer::Tc_DownloadedSize | Transfer::Tc_Percent, true); - - start(); - - return true; - } - - return false; -} - -Verifier *TransferKio::verifier(const KUrl &file) -{ - Q_UNUSED(file); - - if (!m_verifier) { - m_verifier = new Verifier(m_dest, this); - connect(m_verifier, SIGNAL(verified(bool)), this, SLOT(slotVerified(bool))); - } - - foreach (const QString &checksumtype, m_checksums.keys()) { - const QString checksumvalue = m_checksums.value(checksumtype); - m_verifier->addChecksum(checksumtype, checksumvalue); - } - - return m_verifier; -} - -FileModel *TransferKio::fileModel() -{ - if (!m_filemodel) { - m_filemodel = new FileModel(files(), directory(), this); - } - - const KUrl fileurl = m_dest; - - QModelIndex fileindex = m_filemodel->index(fileurl, FileItem::File); - m_filemodel->setData(fileindex, Qt::Checked, Qt::CheckStateRole); - - QModelIndex statusindex = m_filemodel->index(fileurl, FileItem::Status); - m_filemodel->setData(statusindex, status()); - - QModelIndex sizeindex = m_filemodel->index(fileurl, FileItem::Size); - m_filemodel->setData(sizeindex, m_totalSize); - - QModelIndex checksumindex = m_filemodel->index(fileurl, FileItem::ChecksumVerified); - m_filemodel->setData(checksumindex, verifier()->status()); - - return m_filemodel; -} - -void TransferKio::save(const QDomElement &element) -{ - QDomElement elementcopy = element; - QString checksumsstring; - bool firstappend = true; - foreach (const QString &checksumtype, m_checksums.keys()) { - const QString checksumvalue = m_checksums.value(checksumtype); - if (firstappend) { - checksumsstring.append(QString::fromLatin1("%1,%2").arg(checksumtype).arg(checksumvalue)); - firstappend = false; - } else { - checksumsstring.append(QString::fromLatin1(";%1,%2").arg(checksumtype).arg(checksumvalue)); - } - } - elementcopy.setAttribute("Checksums", checksumsstring); - - Transfer::save(elementcopy); -} - -void TransferKio::load(const QDomElement *element) -{ - Transfer::load(element); - - m_checksums.clear(); - if (element) { - const QStringList checksums = element->attribute("Checksums").split(";"); - foreach (const QString &checksum, checksums) { - const QStringList splitchecksum = checksum.split(","); - if (splitchecksum.size() != 2) { - kDebug() << "invalid checksum" << checksum; - continue; - } - m_checksums.insert(splitchecksum.at(0), splitchecksum.at(1)); - } - } -} - -// NOTE: INTERNAL METHODS -void TransferKio::createJob() -{ - if (!m_copyjob) { - m_copyjob = KIO::file_copy(m_source, m_dest, -1, KIO::HideProgressInfo); - - connect(m_copyjob, SIGNAL(result(KJob*)), - this, SLOT(slotResult(KJob*))); - connect(m_copyjob, SIGNAL(infoMessage(KJob*,QString)), - this, SLOT(slotInfoMessage(KJob*,QString))); - connect(m_copyjob, SIGNAL(percent(KJob*,ulong)), - this, SLOT(slotPercent(KJob*,ulong))); - connect(m_copyjob, SIGNAL(totalSize(KJob*,qulonglong)), - this, SLOT(slotTotalSize(KJob*,qulonglong))); - connect(m_copyjob, SIGNAL(processedSize(KJob*,qulonglong)), - this, SLOT(slotProcessedSize(KJob*,qulonglong))); - connect(m_copyjob, SIGNAL(speed(KJob*,ulong)), - this, SLOT(slotSpeed(KJob*,ulong))); - } -} - -void TransferKio::slotResult( KJob * kioJob ) -{ - kDebug() << "slotResult" << kioJob->error() << kioJob->errorString(); - - m_downloadSpeed = 0; - setTransferChange(Transfer::Tc_DownloadSpeed, true); - - switch (kioJob->error()) { - case 0: // The download has finished - case KIO::ERR_FILE_ALREADY_EXIST: { // The file has already been downloaded. - setStatus(Job::Finished); - m_percent = 100; - m_downloadedSize = m_totalSize = QFile(m_dest.path()).size(); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Percent | Transfer::Tc_DownloadedSize | Transfer::Tc_TotalSize, true); - break; - } - default: { - // There has been an error - setError(kioJob->errorString(), SmallIcon("dialog-error"), Job::ManualSolve); - setStatus(Job::Aborted); - setLog(kioJob->errorString(), Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - break; - } - } - // when slotResult gets called, the m_copyjob has already been deleted! - m_copyjob = nullptr; - - if (status() == Job::Finished) { - if (m_verifier && Settings::checksumAutomaticVerification()) { - m_verifier->verify(); - } - } -} - -void TransferKio::slotInfoMessage( KJob * kioJob, const QString & msg ) -{ - kDebug() << "slotInfoMessage"; - Q_UNUSED(kioJob); - - setLog(msg, Transfer::Log_Info); - setTransferChange(Transfer::Tc_Log, true); -} - -void TransferKio::slotPercent( KJob * kioJob, unsigned long percent ) -{ - kDebug() << "slotPercent"; - Q_UNUSED(kioJob); - - m_percent = percent; - setTransferChange(Transfer::Tc_Percent, true); -} - -void TransferKio::slotTotalSize( KJob * kioJob, qulonglong size ) -{ - kDebug() << "slotTotalSize"; - Q_UNUSED(kioJob); - - m_totalSize = size; - setTransferChange(Transfer::Tc_TotalSize, true); -} - -void TransferKio::slotProcessedSize( KJob * kioJob, qulonglong size ) -{ - kDebug() << "slotProcessedSize"; - Q_UNUSED(kioJob); - - m_downloadedSize = size; - setTransferChange(Transfer::Tc_DownloadedSize, true); -} - -void TransferKio::slotSpeed( KJob * kioJob, unsigned long bytes_per_second ) -{ - kDebug() << "slotSpeed"; - Q_UNUSED(kioJob) - - m_downloadSpeed = bytes_per_second; - setTransferChange(Transfer::Tc_DownloadSpeed, true); -} - -void TransferKio::slotVerified(bool isVerified) -{ - if (!isVerified) { - QString text = i18n("The download (%1) could not be verified. Do you want to repair it?", m_dest.fileName()); - - if (!verifier()->partialChunkLength()) { - text = i18n("The download (%1) could not be verified. Do you want to redownload it?", m_dest.fileName()); - } - if (KMessageBox::warningYesNo(0, - text, - i18n("Verification failed.")) == KMessageBox::Yes) { - repair(); - } - } -} - -void TransferKio::slotChecksumFound(QString type, QString checksum) -{ - verifier()->addChecksum(type, checksum); - m_checksums.insert(type, checksum); -} - -#include "moc_transferKio.cpp" diff --git a/kget/transfer-plugins/kio/transferKio.h b/kget/transfer-plugins/kio/transferKio.h deleted file mode 100644 index 483cac0a..00000000 --- a/kget/transfer-plugins/kio/transferKio.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ - - -#ifndef TRANSFER_KIO_H -#define TRANSFER_KIO_H - -#include - -#include "core/transfer.h" -#include "core/verifier.h" -#include "core/filemodel.h" - -/** - * This transfer uses the KIO class to download files - */ - -class TransferKio : public Transfer -{ - Q_OBJECT -public: - TransferKio(TransferGroup * parent, TransferFactory * factory, - Scheduler * scheduler, const KUrl & src, const KUrl & dest); - - // --- Job virtual functions --- - void start() final; - void stop() final; - - // --- Transfer virtual functions --- - void deinit(Transfer::DeleteOptions options) final; - - bool repair(const KUrl &file = KUrl()) final; - - Verifier *verifier(const KUrl &file = KUrl()) final; - - FileModel *fileModel() final; - - void save(const QDomElement &element) final; - void load(const QDomElement *element) final; - -private slots: - void slotResult( KJob * kioJob ); - void slotInfoMessage( KJob * kioJob, const QString & msg ); - void slotPercent( KJob * kioJob, unsigned long percent ); - void slotTotalSize( KJob * kioJob, qulonglong size ); - void slotProcessedSize( KJob * kioJob, qulonglong size ); - void slotSpeed( KJob * kioJob, unsigned long bytes_per_second ); - void slotVerified(bool isVerified); - void slotChecksumFound(QString type, QString checksum); - -private: - void createJob(); - - KIO::FileCopyJob * m_copyjob; - Verifier *m_verifier; - FileModel *m_filemodel; - QMap m_checksums; -}; - -#endif diff --git a/kget/transfer-plugins/kio/transferKioFactory.cpp b/kget/transfer-plugins/kio/transferKioFactory.cpp deleted file mode 100644 index 061dc9d5..00000000 --- a/kget/transfer-plugins/kio/transferKioFactory.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - - 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. -*/ - -#include "transferKioFactory.h" - -#include "core/scheduler.h" -#include "core/transfergroup.h" -#include "transferKio.h" - -#include -#include - -KGET_EXPORT_PLUGIN( TransferKioFactory ) - -TransferKioFactory::TransferKioFactory(QObject *parent, const QVariantList &args) - : TransferFactory(parent, args) -{ -} - -TransferKioFactory::~TransferKioFactory() -{ -} - -Transfer * TransferKioFactory::createTransfer( const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup * parent, - Scheduler * scheduler) -{ - kDebug() << "TransferKioFactory::createTransfer"; - - if (isSupported(srcUrl)) { - return new TransferKio(parent, this, scheduler, srcUrl, destUrl); - } - return 0; -} - -bool TransferKioFactory::isSupported(const KUrl &url) const -{ - QString prot = url.protocol(); - kDebug() << "Protocol = " << prot; - return addsProtocols().contains(prot); -} - -QStringList TransferKioFactory::addsProtocols() const -{ - QStringList protocols = QStringList() << "http" << "https" << "ftp"; - if (KProtocolInfo::isKnownProtocol("sftp")) { - protocols << "sftp"; - } - return protocols; -} diff --git a/kget/transfer-plugins/kio/transferKioFactory.h b/kget/transfer-plugins/kio/transferKioFactory.h deleted file mode 100644 index d541b09e..00000000 --- a/kget/transfer-plugins/kio/transferKioFactory.h +++ /dev/null @@ -1,34 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - - 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. -*/ - -#ifndef KIO_FACTORY_H -#define KIO_FACTORY_H - -#include "core/plugin/transferfactory.h" - -class Transfer; -class TransferGroup; -class Scheduler; - -class TransferKioFactory : public TransferFactory -{ - Q_OBJECT - public: - TransferKioFactory(QObject *parent, const QVariantList &args); - ~TransferKioFactory(); - - Transfer * createTransfer( const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup * parent, Scheduler * scheduler); - - bool isSupported(const KUrl &url) const; - QStringList addsProtocols() const; -}; - -#endif diff --git a/kget/transfer-plugins/torrent/CMakeLists.txt b/kget/transfer-plugins/torrent/CMakeLists.txt deleted file mode 100644 index 6326e462..00000000 --- a/kget/transfer-plugins/torrent/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -# Set supported mime type -SET(SUPPORTED_KGET_MIMETYPES "${SUPPORTED_KGET_MIMETYPES}application/x-bittorrent;" PARENT_SCOPE) - -include_directories( - ../../ - ${CMAKE_CURRENT_BINARY_DIR}/../../ - ${LIBTORRENT_INCLUDES} -) - -set(kget_torrentfactory_PART_SRCS - transferTorrent.cpp - transferTorrentFactory.cpp -) - -kde4_add_plugin(kget_torrentfactory ${kget_torrentfactory_PART_SRCS}) - -target_link_libraries(kget_torrentfactory - KDE4::kdecore - ${LIBTORRENT_LIBRARIES} - kgetcore -) - -set_target_properties(kget_torrentfactory PROPERTIES - COMPILE_FLAGS "${KDE4_ENABLE_EXCEPTIONS}" -) - -install( - TARGETS kget_torrentfactory - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) -install( - FILES kget_torrentfactory.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) - -# KCM module -set(kcm_kget_torrentfactory_PART_SRCS - dlgtorrent.cpp - dlgtorrent.ui -) - -kde4_add_plugin(kcm_kget_torrentfactory ${kcm_kget_torrentfactory_PART_SRCS}) -target_link_libraries(kcm_kget_torrentfactory - KDE4::kdeui - ${LIBTORRENT_LIBRARIES} -) - -install( - TARGETS kcm_kget_torrentfactory - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) - -install( - FILES kget_torrentfactory_config.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) diff --git a/kget/transfer-plugins/torrent/dlgtorrent.cpp b/kget/transfer-plugins/torrent/dlgtorrent.cpp deleted file mode 100644 index 7b87dff6..00000000 --- a/kget/transfer-plugins/torrent/dlgtorrent.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2022 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "dlgtorrent.h" - -#include "kget_export.h" - -#include -#include -#include -#include -#include -#include - -KGET_EXPORT_PLUGIN_CONFIG(DlgTorrentSettings) - -static const int tableindexrole = 1234; -static const int tabletyperole = 4321; - -static const int ltstringsettingscount = lt::settings_pack::num_string_settings; -static const int ltintsettingscount = lt::settings_pack::num_int_settings; -static const int ltboolsettingscount = lt::settings_pack::num_bool_settings; - -DlgTorrentSettings::DlgTorrentSettings(QWidget *parent, const QVariantList &args) - : KCModule(KGetFactory::componentData(), parent, args) -{ - m_ui.setupUi(this); - - load(); - - connect( - m_ui.settingsTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), - this, SLOT(slotItemChanged(QTableWidgetItem*)) - ); -} - -DlgTorrentSettings::~DlgTorrentSettings() -{ -} - -void DlgTorrentSettings::load() -{ - QFile settingsfile(KStandardDirs::locateLocal("appdata", "torrentsettings.json")); - QJsonDocument settingsjson; - if (settingsfile.open(QFile::ReadOnly)) { - settingsjson = QJsonDocument::fromJson(settingsfile.readAll()); - } - - const QVariantMap settingsmap = settingsjson.toVariant().toMap(); - lt::settings_pack ltsettings = lt::default_settings(); - foreach (const QString &key, settingsmap.keys()) { - const int settingskey = key.toInt(); - const QVariant settingsvalue = settingsmap.value(key); - switch (settingsvalue.type()) { - case QVariant::ByteArray: - case QVariant::String: { - const QString settingsstring = settingsvalue.toString(); - ltsettings.set_str(settingskey, settingsstring.toStdString()); - break; - } - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: { - const int settingsint = settingsvalue.toInt(); - ltsettings.set_int(settingskey, settingsint); - break; - } - case QVariant::Bool: { - const bool settingsbool = settingsvalue.toBool(); - ltsettings.set_bool(settingskey, settingsbool); - break; - } - default: { - kWarning() << "invalid setting type"; - break; - } - } - } - - loadSettings(ltsettings); - emit changed(false); -} - -void DlgTorrentSettings::save() -{ - QVariantMap settingsmap; - for (int i = 0; i < m_ui.settingsTableWidget->rowCount(); i++) { - const QTableWidgetItem* tablewidget0 = m_ui.settingsTableWidget->item(i, 0); - const int settingsindex = tablewidget0->data(tableindexrole).toInt(); - const int settingstype = tablewidget0->data(tabletyperole).toInt(); - const QString settingskey = QString::number(settingsindex); - - // qDebug() << Q_FUNC_INFO << settingsindex << settingstype; - - switch (settingstype) { - case QVariant::String: { - const QTableWidgetItem* tablewidget1 = m_ui.settingsTableWidget->item(i, 1); - settingsmap.insert(settingskey, tablewidget1->text()); - break; - } - case QVariant::Int: { - const QSpinBox* tablecellwidget = qobject_cast(m_ui.settingsTableWidget->cellWidget(i, 1)); - settingsmap.insert(settingskey, tablecellwidget->value()); - break; - } - case QVariant::Bool: { - const QTableWidgetItem* tablewidget1 = m_ui.settingsTableWidget->item(i, 1); - settingsmap.insert(settingskey, tablewidget1->checkState() == Qt::Checked ? true : false); - break; - } - default: { - kWarning() << "invalid setting type" << settingstype; - break; - } - } - } - - QJsonDocument settingsjson = QJsonDocument::fromVariant(settingsmap); - if (settingsjson.isNull()) { - kWarning() << "could not parse settings map"; - return; - } - - QFile settingsfile(KStandardDirs::locateLocal("appdata", "torrentsettings.json")); - if (!settingsfile.open(QFile::WriteOnly)) { - kWarning() << "could not open settings file"; - return; - } - - const QByteArray settingsdata = settingsjson.toJson(); - if (settingsfile.write(settingsdata) != settingsdata.size()) { - kWarning() << "could not write settings file"; - return; - } - - emit changed(false); -} - -void DlgTorrentSettings::defaults() -{ - const lt::settings_pack ltsettings = lt::default_settings(); - loadSettings(ltsettings); - emit changed(true); -} - -void DlgTorrentSettings::slotItemChanged(QTableWidgetItem* tablewidget) -{ - Q_UNUSED(tablewidget); - emit changed(true); -} - -void DlgTorrentSettings::slotSpinBoxChanged(const int value) -{ - Q_UNUSED(value); - emit changed(true); -} - -void DlgTorrentSettings::loadSettings(const lt::settings_pack <settings) -{ - m_ui.settingsTableWidget->clearContents(); - - int tablerowcount = 0; - // qDebug() << Q_FUNC_INFO << "string settings"; - for (int i = 0; i < ltstringsettingscount; i++) { - const int settingindex = (lt::settings_pack::string_type_base + i); - // qDebug() << Q_FUNC_INFO << lt::name_for_setting(settingindex) << ltsettings.get_str(settingindex).c_str(); - - m_ui.settingsTableWidget->setRowCount(tablerowcount + 1); - - QTableWidgetItem* tablewidget = new QTableWidgetItem(); - tablewidget->setData(tableindexrole, QVariant(settingindex)); - tablewidget->setData(tabletyperole, QVariant(int(QVariant::String))); - tablewidget->setFlags(Qt::ItemIsEnabled); - tablewidget->setText(QString::fromStdString(lt::name_for_setting(settingindex))); - m_ui.settingsTableWidget->setItem(tablerowcount, 0, tablewidget); - - tablewidget = new QTableWidgetItem(); - tablewidget->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable); - tablewidget->setText(QString::fromStdString(ltsettings.get_str(settingindex))); - m_ui.settingsTableWidget->setItem(tablerowcount, 1, tablewidget); - - tablerowcount++; - } - - // qDebug() << Q_FUNC_INFO << "int settings"; - for (int i = 0; i < ltintsettingscount; i++) { - const int settingindex = (lt::settings_pack::int_type_base + i); - // qDebug() << Q_FUNC_INFO << lt::name_for_setting(settingindex) << ltsettings.get_int(settingindex); - - if (settingindex == lt::settings_pack::alert_mask) { - continue; - } - - m_ui.settingsTableWidget->setRowCount(tablerowcount + 1); - - QTableWidgetItem* tablewidget = new QTableWidgetItem(); - tablewidget->setData(tableindexrole, QVariant(settingindex)); - tablewidget->setData(tabletyperole, QVariant(int(QVariant::Int))); - tablewidget->setFlags(Qt::ItemIsEnabled); - tablewidget->setText(QString::fromStdString(lt::name_for_setting(settingindex))); - m_ui.settingsTableWidget->setItem(tablerowcount, 0, tablewidget); - - QSpinBox* tablecellwidget = new QSpinBox(); - tablecellwidget->setRange(INT_MIN, INT_MAX); - tablecellwidget->setValue(ltsettings.get_int(settingindex)); - connect( - tablecellwidget, SIGNAL(valueChanged(int)), - this, SLOT(slotSpinBoxChanged(int)) - ); - m_ui.settingsTableWidget->setCellWidget(tablerowcount, 1, tablecellwidget); - - tablerowcount++; - } - - // qDebug() << Q_FUNC_INFO << "bool settings"; - for (int i = 0; i < ltboolsettingscount; i++) { - const int settingindex = (lt::settings_pack::bool_type_base + i); - // qDebug() << Q_FUNC_INFO << lt::name_for_setting(settingindex) << ltsettings.get_bool(settingindex); - - m_ui.settingsTableWidget->setRowCount(tablerowcount + 1); - - QTableWidgetItem* tablewidget = new QTableWidgetItem();; - tablewidget->setData(tableindexrole, QVariant(settingindex)); - tablewidget->setData(tabletyperole, QVariant(int(QVariant::Bool))); - tablewidget->setFlags(Qt::ItemIsEnabled); - tablewidget->setText(QString::fromStdString(lt::name_for_setting(settingindex))); - m_ui.settingsTableWidget->setItem(tablerowcount, 0, tablewidget); - - tablewidget = new QTableWidgetItem(); - tablewidget->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); - tablewidget->setCheckState(ltsettings.get_bool(settingindex) ? Qt::Checked : Qt::Unchecked); - m_ui.settingsTableWidget->setItem(tablerowcount, 1, tablewidget); - - tablerowcount++; - } - - m_ui.settingsTableWidget->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); -} - -#include "moc_dlgtorrent.cpp" diff --git a/kget/transfer-plugins/torrent/dlgtorrent.h b/kget/transfer-plugins/torrent/dlgtorrent.h deleted file mode 100644 index d3f6cab2..00000000 --- a/kget/transfer-plugins/torrent/dlgtorrent.h +++ /dev/null @@ -1,53 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2022 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef DLGTORRENT_H -#define DLGTORRENT_H - -#include "ui_dlgtorrent.h" - -#include -#include - -#include - -class DlgTorrentSettings : public KCModule -{ - Q_OBJECT - // KCModule reimplementations -public: - explicit DlgTorrentSettings(QWidget *parent = 0, const QVariantList &args = QVariantList()); - ~DlgTorrentSettings(); - -public Q_SLOTS: - void save() final; - void load() final; - void defaults() final; - -private Q_SLOTS: - void slotItemChanged(QTableWidgetItem* tablewidget); - void slotSpinBoxChanged(const int value); - -private: - void loadSettings(const lt::settings_pack <settings); - - Ui::DlgTorrent m_ui; -}; - -#endif // DLGTORRENT_H diff --git a/kget/transfer-plugins/torrent/dlgtorrent.ui b/kget/transfer-plugins/torrent/dlgtorrent.ui deleted file mode 100644 index ad78a9ec..00000000 --- a/kget/transfer-plugins/torrent/dlgtorrent.ui +++ /dev/null @@ -1,64 +0,0 @@ - - - DlgTorrent - - - - 0 - 0 - 459 - 413 - - - - - - - Torrent Settings - - - - - - - true - - - false - - - - Setting - - - - - Value - - - - - - - - <html><head/><body><p>For description of the settings visit:</p><p><a href="https://www.libtorrent.org/reference-Settings.html#settings_pack"><span style=" text-decoration: underline; color:#0057ae;">https://www.libtorrent.org/reference-Settings.html#settings_pack</span></a></p></body></html> - - - Qt::AlignCenter - - - true - - - - - - - - KTitleWidget - -
ktitlewidget.h
-
-
- -
diff --git a/kget/transfer-plugins/torrent/kget_torrentfactory.desktop b/kget/transfer-plugins/torrent/kget_torrentfactory.desktop deleted file mode 100644 index ac04cbc0..00000000 --- a/kget/transfer-plugins/torrent/kget_torrentfactory.desktop +++ /dev/null @@ -1,24 +0,0 @@ -[Desktop Entry] -# service definition -Type=Service -X-KDE-ServiceTypes=KGet/Plugin -Icon=application-x-bittorrent - -# standard fields -Name=Torrent -Comment=Torrent downloader plugin - -# options for library loader -X-KDE-Library=kget_torrentfactory -X-KDE-KGet-plugintype=TransferFactory -X-KDE-KGet-rank=200 -X-KDE-KGet-framework-version=1 - -X-KDE-PluginInfo-Author=Ivailo Monev -X-KDE-PluginInfo-Email=xakepa10@gmail.com -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-PluginInfo-Name=kget_torrent_plugin - diff --git a/kget/transfer-plugins/torrent/kget_torrentfactory_config.desktop b/kget/transfer-plugins/torrent/kget_torrentfactory_config.desktop deleted file mode 100644 index bf05b678..00000000 --- a/kget/transfer-plugins/torrent/kget_torrentfactory_config.desktop +++ /dev/null @@ -1,8 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule - -X-KDE-Library=kcm_kget_torrentfactory -X-KDE-ParentComponents=kget_torrent_plugin - -Name=Torrent diff --git a/kget/transfer-plugins/torrent/transferTorrent.cpp b/kget/transfer-plugins/torrent/transferTorrent.cpp deleted file mode 100644 index 95f150ea..00000000 --- a/kget/transfer-plugins/torrent/transferTorrent.cpp +++ /dev/null @@ -1,932 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "transferTorrent.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if LIBTORRENT_VERSION_NUM >= 10200 -# include -#endif - -// NOTE: error_code comparison is bogus and breaks translatelterror() too, -// possibly silently fixed via: -// https://github.com/boostorg/system/commit/2fa0a00583a3a791092568d2ade793314181926e -#define BOOST_ERROR_EQUAL_OPERATOR_IS_BORKED - -static const int LTPollInterval = 1000; -static const int LTResumeInterval = 10000; - -enum LTPriorities { - Disabled = 0, - LowPriority = 1, - NormalPriority = 4, - HighPriority = 7, -}; - -static QString translatelterror(lt::error_code lterror) -{ - if (lterror == lt::errors::no_error) { - return i18n("Not an error"); - } else if (lterror == lt::errors::file_collision) { - return i18n("Two torrents has files which end up overwriting each other"); - } else if (lterror == lt::errors::failed_hash_check) { - return i18n("A piece did not match its piece hash"); - } else if (lterror == lt::errors::torrent_is_no_dict) { - return i18n("The .torrent file does not contain a bencoded dictionary at its top level"); - } else if (lterror == lt::errors::torrent_missing_info) { - return i18n("The .torrent file does not have an ``info`` dictionary"); - } else if (lterror == lt::errors::torrent_info_no_dict) { - return i18n("The .torrent file's ``info`` entry is not a dictionary"); - } else if (lterror == lt::errors::torrent_missing_piece_length) { - return i18n("The .torrent file does not have a ``piece length`` entry"); - } else if (lterror == lt::errors::torrent_missing_name) { - return i18n("The .torrent file does not have a ``name`` entry"); - } else if (lterror == lt::errors::torrent_invalid_name) { - return i18n("The .torrent file's name entry is invalid"); - } else if (lterror == lt::errors::torrent_invalid_length) { - return i18n("The length of a file, or of the whole .torrent file is invalid"); - } else if (lterror == lt::errors::torrent_file_parse_failed) { - return i18n("Failed to parse a file entry in the .torrent"); - } else if (lterror == lt::errors::torrent_missing_pieces) { - return i18n("The ``pieces`` field is missing or invalid in the .torrent file"); - } else if (lterror == lt::errors::torrent_invalid_hashes) { - return i18n("The ``pieces`` string has incorrect length"); - } else if (lterror == lt::errors::too_many_pieces_in_torrent) { - return i18n("The .torrent file has more pieces than is supported by libtorrent"); - } else if (lterror == lt::errors::invalid_swarm_metadata) { - return i18n("The metadata (.torrent file) that was received from the swarm matched the info-hash, but failed to be parsed"); - } else if (lterror == lt::errors::invalid_bencoding) { - return i18n("The file or buffer is not correctly bencoded"); - } else if (lterror == lt::errors::no_files_in_torrent) { - return i18n("The .torrent file does not contain any files"); - } else if (lterror == lt::errors::invalid_escaped_string) { - return i18n("The string was not properly url-encoded as expected"); - } else if (lterror == lt::errors::session_is_closing) { - return i18n("Operation is not permitted since the session is shutting down"); - } else if (lterror == lt::errors::duplicate_torrent) { - return i18n("There's already a torrent with that info-hash added to the session"); - } else if (lterror == lt::errors::invalid_torrent_handle) { - return i18n("The supplied torrent_handle is not referring to a valid torrent"); - } else if (lterror == lt::errors::invalid_entry_type) { - return i18n("The type requested from the entry did not match its type"); - } else if (lterror == lt::errors::missing_info_hash_in_uri) { - return i18n("The specified URI does not contain a valid info-hash"); - } else if (lterror == lt::errors::file_too_short) { - return i18n("One of the files in the torrent was unexpectedly small"); - } else if (lterror == lt::errors::unsupported_url_protocol) { - return i18n("The URL used an unknown protocol"); - } else if (lterror == lt::errors::url_parse_error) { - return i18n("The URL did not conform to URL syntax and failed to be parsed"); - } else if (lterror == lt::errors::peer_sent_empty_piece) { - return i18n("The peer sent a 'piece' message of length 0"); - } else if (lterror == lt::errors::invalid_file_tag) { - return i18n("A bencoded structure was corrupt and failed to be parsed parse_failed"); - } else if (lterror == lt::errors::missing_info_hash) { - return i18n("The fast resume file was missing or had an invalid info-hash"); - } else if (lterror == lt::errors::mismatching_info_hash) { - return i18n("The info-hash did not match the torrent"); - } else if (lterror == lt::errors::invalid_hostname) { - return i18n("The URL contained an invalid hostname"); - } else if (lterror == lt::errors::invalid_port) { - return i18n("The URL had an invalid port"); - } else if (lterror == lt::errors::port_blocked) { - return i18n("The port is blocked by the port-filter"); - } else if (lterror == lt::errors::expected_close_bracket_in_address) { - return i18n("The IPv6 address was expected to end with ']'"); - } else if (lterror == lt::errors::destructing_torrent) { - return i18n("The torrent is being destructed"); - } else if (lterror == lt::errors::timed_out) { - return i18n("The connection timed out"); - } else if (lterror == lt::errors::upload_upload_connection) { - return i18n("The peer is upload only, and we are upload only"); - } else if (lterror == lt::errors::uninteresting_upload_peer) { - return i18n("The peer is upload only, and we're not interested in it"); - } else if (lterror == lt::errors::invalid_info_hash) { - return i18n("The peer sent an unknown info-hash"); - } else if (lterror == lt::errors::torrent_paused) { - return i18n("The torrent is paused, preventing the operation from succeeding"); - } else if (lterror == lt::errors::invalid_have) { - return i18n("The peer sent an invalid have message, either wrong size or referring to a piece that doesn't exist in the torrent"); - } else if (lterror == lt::errors::invalid_bitfield_size) { - return i18n("The bitfield message had the incorrect size"); - } else if (lterror == lt::errors::too_many_requests_when_choked) { - return i18n("The peer kept requesting pieces after it was choked, possible abuse attempt"); - } else if (lterror == lt::errors::invalid_piece) { - return i18n("The peer sent a piece message that does not correspond to a piece request sent by the client"); - } else if (lterror == lt::errors::no_memory) { - return i18n("memory allocation failed"); - } else if (lterror == lt::errors::torrent_aborted) { - return i18n("The torrent is aborted, preventing the operation to succeed"); - } else if (lterror == lt::errors::self_connection) { - return i18n("The peer is a connection to ourself, no point in keeping it"); - } else if (lterror == lt::errors::invalid_piece_size) { - return i18n("The peer sent a piece message with invalid size"); - } else if (lterror == lt::errors::timed_out_no_interest) { - return i18n("The peer has not been interesting or interested in us for too long"); - } else if (lterror == lt::errors::timed_out_inactivity) { - return i18n("The peer has not said anything in a long time"); - } else if (lterror == lt::errors::timed_out_no_handshake) { - return i18n("The peer did not send a handshake within a reasonable amount of time"); - } else if (lterror == lt::errors::timed_out_no_request) { - return i18n("The peer has been unchoked for too long without requesting any data"); - } else if (lterror == lt::errors::invalid_choke) { - return i18n("The peer sent an invalid choke message"); - } else if (lterror == lt::errors::invalid_unchoke) { - return i18n("The peer send an invalid unchoke message"); - } else if (lterror == lt::errors::invalid_interested) { - return i18n("The peer sent an invalid interested message"); - } else if (lterror == lt::errors::invalid_not_interested) { - return i18n("The peer sent an invalid not-interested message"); - } else if (lterror == lt::errors::invalid_request) { - return i18n("The peer sent an invalid piece request message"); - } else if (lterror == lt::errors::invalid_hash_list) { - return i18n("The peer sent an invalid hash-list message"); - } else if (lterror == lt::errors::invalid_hash_piece) { - return i18n("The peer sent an invalid hash-piece message"); - } else if (lterror == lt::errors::invalid_cancel) { - return i18n("The peer sent an invalid cancel message"); - } else if (lterror == lt::errors::invalid_dht_port) { - return i18n("The peer sent an invalid DHT port-message"); - } else if (lterror == lt::errors::invalid_suggest) { - return i18n("The peer sent an invalid suggest piece-message"); - } else if (lterror == lt::errors::invalid_have_all) { - return i18n("The peer sent an invalid have all-message"); - } else if (lterror == lt::errors::invalid_have_none) { - return i18n("The peer sent an invalid have none-message"); - } else if (lterror == lt::errors::invalid_reject) { - return i18n("The peer sent an invalid reject message"); - } else if (lterror == lt::errors::invalid_allow_fast) { - return i18n("The peer sent an invalid allow fast-message"); - } else if (lterror == lt::errors::invalid_extended) { - return i18n("The peer sent an invalid extension message ID"); - } else if (lterror == lt::errors::invalid_message) { - return i18n("The peer sent an invalid message ID"); - } else if (lterror == lt::errors::sync_hash_not_found) { - return i18n("The synchronization hash was not found in the encrypted handshake"); - } else if (lterror == lt::errors::invalid_encryption_constant) { - return i18n("The encryption constant in the handshake is invalid"); - } else if (lterror == lt::errors::no_plaintext_mode) { - return i18n("The peer does not support plaintext, which is the selected mode"); - } else if (lterror == lt::errors::no_rc4_mode) { - return i18n("The peer does not support rc4, which is the selected mode"); - } else if (lterror == lt::errors::unsupported_encryption_mode) { - return i18n("The peer does not support any of the encryption modes that the client supports"); - } else if (lterror == lt::errors::unsupported_encryption_mode_selected) { - return i18n("The peer selected an encryption mode that the client did not advertise and does not support"); - } else if (lterror == lt::errors::invalid_pad_size) { - return i18n("The pad size used in the encryption handshake is of invalid size"); - } else if (lterror == lt::errors::invalid_encrypt_handshake) { - return i18n("The encryption handshake is invalid"); - } else if (lterror == lt::errors::no_incoming_encrypted) { - return i18n("The client is set to not support incoming encrypted connections and this is an encrypted connection"); - } else if (lterror == lt::errors::no_incoming_regular) { - return i18n("The client is set to not support incoming regular bittorrent connections"); - } else if (lterror == lt::errors::duplicate_peer_id) { - return i18n("The client is already connected to this peer-ID"); - } else if (lterror == lt::errors::torrent_removed) { - return i18n("Torrent was removed"); - } else if (lterror == lt::errors::packet_too_large) { - return i18n("The packet size exceeded the upper sanity check-limit"); - } else if (lterror == lt::errors::http_error) { - return i18n("The web server responded with an error"); - } else if (lterror == lt::errors::missing_location) { - return i18n("The web server response is missing a location header"); - } else if (lterror == lt::errors::invalid_redirection) { - return i18n("The web seed redirected to a path that no longer matches the .torrent directory structure"); - } else if (lterror == lt::errors::redirecting) { - return i18n("The connection was closed because it redirected to a different URL"); - } else if (lterror == lt::errors::invalid_range) { - return i18n("The HTTP range header is invalid"); - } else if (lterror == lt::errors::no_content_length) { - return i18n("The HTTP response did not have a content length"); - } else if (lterror == lt::errors::banned_by_ip_filter) { - return i18n("The IP is blocked by the IP filter"); - } else if (lterror == lt::errors::too_many_connections) { - return i18n("At the connection limit"); - } else if (lterror == lt::errors::peer_banned) { - return i18n("The peer is marked as banned"); - } else if (lterror == lt::errors::stopping_torrent) { - return i18n("The torrent is stopping, causing the operation to fail"); - } else if (lterror == lt::errors::too_many_corrupt_pieces) { - return i18n("The peer has sent too many corrupt pieces and is banned"); - } else if (lterror == lt::errors::torrent_not_ready) { - return i18n("The torrent is not ready to receive peers"); - } else if (lterror == lt::errors::peer_not_constructed) { - return i18n("The peer is not completely constructed yet"); - } else if (lterror == lt::errors::session_closing) { - return i18n("The session is closing, causing the operation to fail"); - } else if (lterror == lt::errors::optimistic_disconnect) { - return i18n("The peer was disconnected in order to leave room for a potentially better peer"); - } else if (lterror == lt::errors::torrent_finished) { - return i18n("The torrent is finished"); - } else if (lterror == lt::errors::no_router) { - return i18n("No UPnP router found"); - } else if (lterror == lt::errors::metadata_too_large) { - return i18n("The metadata message says the metadata exceeds the limit"); - } else if (lterror == lt::errors::invalid_metadata_request) { - return i18n("The peer sent an invalid metadata request message"); - } else if (lterror == lt::errors::invalid_metadata_size) { - return i18n("The peer advertised an invalid metadata size"); - } else if (lterror == lt::errors::invalid_metadata_offset) { - return i18n("The peer sent a message with an invalid metadata offset"); - } else if (lterror == lt::errors::invalid_metadata_message) { - return i18n("The peer sent an invalid metadata message"); - } else if (lterror == lt::errors::pex_message_too_large) { - return i18n("The peer sent a peer exchange message that was too large"); - } else if (lterror == lt::errors::invalid_pex_message) { - return i18n("The peer sent an invalid peer exchange message"); - } else if (lterror == lt::errors::invalid_lt_tracker_message) { - return i18n("The peer sent an invalid tracker exchange message"); - } else if (lterror == lt::errors::too_frequent_pex) { - return i18n("The peer sent an pex messages too often"); - } else if (lterror == lt::errors::no_metadata) { - return i18n("The operation failed because it requires the torrent to have the metadata (.torrent file) and it doesn't have it yet"); - } else if (lterror == lt::errors::invalid_dont_have) { - return i18n("The peer sent an invalid ``dont_have`` message"); - } else if (lterror == lt::errors::requires_ssl_connection) { - return i18n("The peer tried to connect to an SSL torrent without connecting over SSL"); - } else if (lterror == lt::errors::invalid_ssl_cert) { - return i18n("The peer tried to connect to a torrent with a certificate for a different torrent"); - } else if (lterror == lt::errors::not_an_ssl_torrent) { - return i18n("The torrent is not an SSL torrent, and the operation requires an SSL torrent"); - } else if (lterror == lt::errors::banned_by_port_filter) { - return i18n("Peer was banned because its listen port is within a banned port range"); - } else if (lterror == lt::errors::unsupported_protocol_version) { - return i18n("The NAT-PMP router responded with an unsupported protocol version"); - } else if (lterror == lt::errors::natpmp_not_authorized) { - return i18n("You are not authorized to map ports on this NAT-PMP router"); - } else if (lterror == lt::errors::network_failure) { - return i18n("The NAT-PMP router failed because of a network failure"); - } else if (lterror == lt::errors::no_resources) { - return i18n("The NAT-PMP router failed because of lack of resources"); - } else if (lterror == lt::errors::unsupported_opcode) { - return i18n("The NAT-PMP router failed because an unsupported opcode was sent"); - } else if (lterror == lt::errors::missing_file_sizes) { - return i18n("The resume data file is missing the 'file sizes' entry"); - } else if (lterror == lt::errors::no_files_in_resume_data) { - return i18n("The resume data file 'file sizes' entry is empty"); - } else if (lterror == lt::errors::missing_pieces) { - return i18n("The resume data file is missing the 'pieces' and 'slots' entry"); - } else if (lterror == lt::errors::mismatching_number_of_files) { - return i18n("The number of files in the resume data does not match the number of files in the torrent"); - } else if (lterror == lt::errors::mismatching_file_size) { - return i18n("One of the files on disk has a different size than in the fast resume file"); - } else if (lterror == lt::errors::mismatching_file_timestamp) { - return i18n("One of the files on disk has a different timestamp than in the fast resume file"); - } else if (lterror == lt::errors::not_a_dictionary) { - return i18n("The resume data file is not a dictionary"); - } else if (lterror == lt::errors::invalid_blocks_per_piece) { - return i18n("The 'blocks per piece' entry is invalid in the resume data file"); - } else if (lterror == lt::errors::missing_slots) { - return i18n("The resume file is missing the 'slots' entry"); - } else if (lterror == lt::errors::too_many_slots) { - return i18n("The resume file contains more slots than the torrent"); - } else if (lterror == lt::errors::invalid_slot_list) { - return i18n("The 'slot' entry is invalid in the resume data"); - } else if (lterror == lt::errors::invalid_piece_index) { - return i18n("One index in the 'slot' list is invalid"); - } else if (lterror == lt::errors::pieces_need_reorder) { - return i18n("The pieces on disk needs to be re-ordered for the specified allocation mode"); - } else if (lterror == lt::errors::resume_data_not_modified) { - return i18n("The resume data is not modified"); - } else if (lterror == lt::errors::http_parse_error) { - return i18n("The HTTP header was not correctly formatted"); - } else if (lterror == lt::errors::http_missing_location) { - return i18n("The HTTP response was in the 300-399 range but lacked a location header"); - } else if (lterror == lt::errors::http_failed_decompress) { - return i18n("The HTTP response was encoded with gzip or deflate but decompressing it failed"); - } else if (lterror == lt::errors::no_i2p_router) { - return i18n("The URL specified an i2p address, but no i2p router is configured"); - } else if (lterror == lt::errors::no_i2p_endpoint) { - return i18n("i2p acceptor is not available yet, can't announce without endpoint"); - } else if (lterror == lt::errors::scrape_not_available) { - return i18n("The tracker URL doesn't support transforming it into a scrape URL"); - } else if (lterror == lt::errors::invalid_tracker_response) { - return i18n("Invalid tracker response"); - } else if (lterror == lt::errors::invalid_peer_dict) { - return i18n("Invalid peer dictionary entry"); - } else if (lterror == lt::errors::tracker_failure) { - return i18n("Tracker sent a failure message"); - } else if (lterror == lt::errors::invalid_files_entry) { - return i18n("Missing or invalid 'files' entry"); - } else if (lterror == lt::errors::invalid_hash_entry) { - return i18n("Missing or invalid 'hash' entry"); - } else if (lterror == lt::errors::invalid_peers_entry) { - return i18n("Missing or invalid 'peers' and 'peers6' entry"); - } else if (lterror == lt::errors::invalid_tracker_response_length) { - return i18n("udp tracker response packet has invalid size"); - } else if (lterror == lt::errors::invalid_tracker_transaction_id) { - return i18n("Invalid transaction id in udp tracker response"); - } else if (lterror == lt::errors::invalid_tracker_action) { - return i18n("Invalid action field in udp tracker response"); - } - return i18n("Unknown error"); -} - -class TorrentFileModel : public FileModel -{ -public: - TorrentFileModel(const QList &files, const KUrl &destDirectory, QObject *parent); - Qt::ItemFlags flags(const QModelIndex &index) const final; - - Job::Status transferstatus; -}; - -TorrentFileModel::TorrentFileModel(const QList &files, const KUrl &destDirectory, QObject *parent) - : FileModel(files, destDirectory, parent) -{ -} - -Qt::ItemFlags TorrentFileModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) { - return 0; - } - - if (index.column() == FileItem::File) { - // TODO: this really should be done for other transfer plugins too, it does not make sense - // to disable file transfer once it is already finished - // TODO: this does not (and cannot) account for parent item (directory) flags - if (transferstatus == Job::Finished || transferstatus == Job::FinishedKeepAlive) { - return Qt::ItemIsSelectable; - } - } - - return FileModel::flags(index); -} - -TransferTorrent::TransferTorrent(TransferGroup* parent, TransferFactory* factory, - Scheduler* scheduler, const KUrl &source, const KUrl &dest) - : Transfer(parent, factory, scheduler, source, dest), - m_startonload(false), m_polltimerid(0), m_resumetimerid(0), m_ltsession(nullptr), - m_filemodel(nullptr), m_dirwatch(nullptr) -{ - setCapabilities(Transfer::Cap_SpeedLimit | Transfer::Cap_Resuming | Transfer::Cap_MultipleMirrors); - - lt::settings_pack ltsettings = lt::default_settings(); - ltsettings.set_int(lt::settings_pack::alert_mask, - lt::alert::status_notification - | lt::alert::error_notification - | lt::alert::progress_notification - | lt::alert::stats_notification); - - m_ltsession = new lt::session(ltsettings); - - m_dirwatch = new KDirWatch(this); - m_dirwatch->addFile(KStandardDirs::locateLocal("appdata", "torrentsettings.json")); - connect(m_dirwatch, SIGNAL(dirty(QString)), this, SLOT(slotSettingsDirty(QString))); - - applySettings(); -} - -TransferTorrent::~TransferTorrent() -{ - if (m_resumetimerid != 0) { - killTimer(m_resumetimerid); - m_resumetimerid = 0; - } - if (m_polltimerid != 0) { - killTimer(m_polltimerid); - m_polltimerid = 0; - } - - delete m_ltsession; -} - -void TransferTorrent::setSpeedLimits(int uploadLimit, int downloadLimit) -{ - if (m_lthandle.is_valid()) { - m_lthandle.set_upload_limit(uploadLimit * 1024); - m_lthandle.set_download_limit(downloadLimit * 1024); - } else { - kDebug() << "torrent handle is not valid"; - } -} - -QHash > TransferTorrent::availableMirrors(const KUrl &file) const -{ - Q_UNUSED(file); - - QHash > result; - - if (m_lthandle.is_valid()) { - const std::vector lttrackers = m_lthandle.trackers(); - foreach (const lt::announce_entry <tracker, lttrackers) { - result.insert(KUrl(lttracker.url.c_str()), QPair(true, 1)); - } - } else { - kDebug() << "torrent handle is not valid"; - } - - return result; -} - -void TransferTorrent::setAvailableMirrors(const KUrl &file, const QHash > &mirrors) -{ - Q_UNUSED(file); - - std::vector lttrackers; - foreach (const KUrl &fileurl, mirrors.keys()) { - const QPair mirrorpair = mirrors.value(fileurl); - if (mirrorpair.first == true) { - const QByteArray filestring = fileurl.prettyUrl().toLocal8Bit(); - lttrackers.push_back(lt::announce_entry(filestring.constData())); - } - } - - if (m_lthandle.is_valid()) { - m_lthandle.replace_trackers(lttrackers); - } else { - kDebug() << "torrent handle is not valid"; - } -} - -void TransferTorrent::start() -{ - if (status() == Job::Running) { - return; - } - - const KUrl sourceurl = source(); - const QString sourcestring = sourceurl.url(); - const QByteArray destination = directory().toLocalFile().toLocal8Bit(); - - kDebug() << "source" << sourceurl << "destination" << destination; - - try { - lt::add_torrent_params ltparams; - if (sourcestring.startsWith("magnet:")) { - const QByteArray source = sourcestring.toLocal8Bit(); - - lt::error_code lterror = lt::errors::no_error; - lt::parse_magnet_uri(source.constData(), ltparams, lterror); - -#ifdef BOOST_ERROR_EQUAL_OPERATOR_IS_BORKED - if (lterror) { -#else - if (lterror != lt::errors::no_error) { -#endif - kError() << lterror.message().c_str(); - - const QString errormesssage = translatelterror(lterror); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } - } else if (sourcestring.endsWith(".torrent")) { - const QByteArray source = sourceurl.toLocalFile().toLocal8Bit(); - -#if LIBTORRENT_VERSION_NUM >= 10200 - ltparams.ti = std::make_shared(std::string(source.constData())); -#else - ltparams.ti = boost::make_shared(source.constData()); -#endif - if (!ltparams.ti->is_valid()) { - kError() << "invalid torrent file"; - - const QString errormesssage = i18n("Invalid torrent file"); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } - m_totalSize = ltparams.ti->total_size(); - setTransferChange(Transfer::Tc_TotalSize, true); - } else { - kError() << "invalid source" << sourceurl; - - const QString errormesssage = i18n("Invalid source URL"); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } - - ltparams.save_path = destination.constData(); -#if LIBTORRENT_VERSION_NUM >= 10200 - std::vector priorities; - foreach (const boost::uint8_t priority, m_priorities) { - priorities.push_back(lt::download_priority_t(priority)); - } - ltparams.file_priorities = priorities; -#else - ltparams.file_priorities = m_priorities; -#endif - ltparams.resume_data = m_ltresumedata; - ltparams.upload_limit = (m_uploadLimit * 1024); - ltparams.download_limit = (m_downloadLimit * 1024); - m_lthandle = m_ltsession->add_torrent(ltparams); -#if LIBTORRENT_VERSION_NUM >= 10200 - } catch(boost::system::system_error &err) { -#else - } catch(lt::libtorrent_exception &err) { -#endif - const QString errormesssage = QString::fromStdString(err.what()); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } catch(std::exception &err) { - const QString errormesssage = QString::fromStdString(err.what()); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } catch (...) { - const QString errormesssage = i18n("Exception raised"); - setError(errormesssage, SmallIcon("dialog-error"), Job::NotSolveable); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - return; - } - - setStatus(Job::Running); - setTransferChange(Transfer::Tc_Status, true); - - Q_ASSERT(m_polltimerid == 0); - m_polltimerid = startTimer(LTPollInterval); - Q_ASSERT(m_resumetimerid == 0); - m_resumetimerid = startTimer(LTResumeInterval); -} - -void TransferTorrent::stop() -{ - if (status() == Job::Stopped) { - return; - } - - if (m_resumetimerid != 0) { - killTimer(m_resumetimerid); - m_resumetimerid = 0; - } - if (m_polltimerid != 0) { - killTimer(m_polltimerid); - m_polltimerid = 0; - } - - m_downloadSpeed = 0; - m_uploadSpeed = 0; - setStatus(Job::Stopped); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_DownloadSpeed | Transfer::Tc_UploadSpeed, true); -} - -void TransferTorrent::deinit(Transfer::DeleteOptions options) -{ - Q_ASSERT(m_ltsession); - if (options & Transfer::DeleteFiles && m_lthandle.is_valid()) { - m_ltsession->remove_torrent(m_lthandle, lt::session_handle::delete_files); - } - - if (options & Transfer::DeleteTemporaryFiles && m_lthandle.is_valid()) { - m_ltsession->remove_torrent(m_lthandle, lt::session_handle::delete_partfile); - } -} - -bool TransferTorrent::isStalled() const -{ - if (!m_lthandle.is_valid()) { - kDebug() << "torrent handle is not valid"; - return true; - } - const lt::torrent_status ltstatus = m_lthandle.status(); - return (status() == Job::Running && downloadSpeed() == 0 && ltstatus.state == lt::torrent_status::finished); -} - -bool TransferTorrent::isWorking() const -{ - return (m_polltimerid != 0); -} - -QList TransferTorrent::files() const -{ - QList result; - - if (m_lthandle.is_valid() && m_lthandle.torrent_file()) { - const lt::file_storage ltstorage = m_lthandle.torrent_file()->files(); - if (ltstorage.is_valid()) { - for (int i = 0; i < ltstorage.num_files(); i++) { - result.append(KUrl(ltstorage.file_path(i).c_str())); - } - } - } - - return result; -} - -FileModel* TransferTorrent::fileModel() -{ - if (!m_filemodel) { - m_filemodel = new TorrentFileModel(files(), directory(), this); - connect(m_filemodel, SIGNAL(checkStateChanged()), this, SLOT(slotCheckStateChanged())); - } - - const Job::Status transferstatus = status(); - m_filemodel->transferstatus = transferstatus; - if (m_lthandle.is_valid() && m_lthandle.torrent_file()) { - const lt::file_storage ltstorage = m_lthandle.torrent_file()->files(); - if (ltstorage.is_valid()) { - for (int i = 0; i < ltstorage.num_files(); i++) { - const KUrl fileurl = KUrl(ltstorage.file_path(i).c_str()); - - Job::Status filestatus = transferstatus; - // priority has no effect on finished/seeded torrents - const int ltpriority = (m_priorities.size() > i ? m_priorities.at(i) : LTPriorities::NormalPriority); - const lt::torrent_status ltstatus = m_lthandle.status(); - if (ltstatus.state == lt::torrent_status::seeding || ltstatus.state == lt::torrent_status::finished) { - filestatus = Job::Finished; - } - if (ltpriority == LTPriorities::Disabled) { - filestatus = Job::Stopped; - } - - const Qt::CheckState filestate = (ltpriority == LTPriorities::Disabled ? Qt::Unchecked : Qt::Checked); - QModelIndex fileindex = m_filemodel->index(fileurl, FileItem::File); - m_filemodel->setData(fileindex, filestate, Qt::CheckStateRole); - - QModelIndex statusindex = m_filemodel->index(fileurl, FileItem::Status); - m_filemodel->setData(statusindex, filestatus); - - const qlonglong filesize = ltstorage.file_size(i); - QModelIndex sizeindex = m_filemodel->index(fileurl, FileItem::Size); - m_filemodel->setData(sizeindex, filesize); - } - } - } - - return m_filemodel; -} - -void TransferTorrent::slotCheckStateChanged() -{ - Q_ASSERT(m_filemodel); - - int counter = 0; - m_priorities.clear(); - m_ltresumedata.clear(); - m_ltresumedata.shrink_to_fit(); - foreach (const KUrl &url, files()) { - const QModelIndex fileindex = m_filemodel->index(url, FileItem::File); - const int checkstate = m_filemodel->data(fileindex, Qt::CheckStateRole).toInt(); - if (checkstate != int(Qt::Unchecked)) { - kDebug() << "will downloand" << url; - - m_priorities.push_back(LTPriorities::NormalPriority); - m_lthandle.file_priority(counter, LTPriorities::NormalPriority); - } else { - kDebug() << "will not downloand" << url; - - m_lthandle.file_priority(counter, LTPriorities::Disabled); - m_priorities.push_back(LTPriorities::Disabled); - } - counter++; - } -} - -void TransferTorrent::slotSettingsDirty(const QString &settings) -{ - kDebug() << "torrent settings are dirty"; - Q_UNUSED(settings); - applySettings(); -} - -void TransferTorrent::applySettings() -{ - if (!m_ltsession) { - kDebug() << "null torrent session pointer"; - return; - } - - QFile settingsfile(KStandardDirs::locateLocal("appdata", "torrentsettings.json")); - QJsonDocument settingsjson; - if (settingsfile.open(QFile::ReadOnly)) { - settingsjson = QJsonDocument::fromJson(settingsfile.readAll()); - } - - const QVariantMap settingsmap = settingsjson.toVariant().toMap(); - lt::settings_pack ltsettings = lt::default_settings(); - foreach (const QString &key, settingsmap.keys()) { - const int settingskey = key.toInt(); - if (settingskey == lt::settings_pack::alert_mask) { - continue; - } - const QVariant settingsvalue = settingsmap.value(key); - switch (settingsvalue.type()) { - case QVariant::ByteArray: - case QVariant::String: { - const QString settingsstring = settingsvalue.toString(); - ltsettings.set_str(settingskey, settingsstring.toStdString()); - break; - } - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: { - const int settingsint = settingsvalue.toInt(); - ltsettings.set_int(settingskey, settingsint); - break; - } - case QVariant::Bool: { - const bool settingsbool = settingsvalue.toBool(); - ltsettings.set_bool(settingskey, settingsbool); - break; - } - default: { - kWarning() << "invalid setting type"; - break; - } - } - } - - ltsettings.set_int(lt::settings_pack::alert_mask, - lt::alert::status_notification - | lt::alert::error_notification - | lt::alert::progress_notification - | lt::alert::stats_notification); - - m_ltsession->apply_settings(ltsettings); -} - -void TransferTorrent::save(const QDomElement &element) -{ - QDomElement elementcopy = element; - QString prioritiesstring; - for (int i = 0; i < m_priorities.size(); i++) { - const boost::uint8_t priority = m_priorities.at(i); - if (i == 0) { - prioritiesstring.append(QString::number(priority)); - } else { - prioritiesstring.append(QString::fromLatin1(",") + QString::number(priority)); - } - } - elementcopy.setAttribute("FilePriorities", prioritiesstring); - - const QByteArray resumedatahex = QByteArray::fromRawData(m_ltresumedata.data(), m_ltresumedata.size()).toHex(); - const QString resumedata = QString::fromLatin1(resumedatahex.data(), resumedatahex.size()); - elementcopy.setAttribute("ResumeData", resumedata); - - Transfer::save(elementcopy); -} - -void TransferTorrent::load(const QDomElement *element) -{ - Transfer::load(element); - - m_priorities.clear(); - m_ltresumedata.clear(); - m_ltresumedata.shrink_to_fit(); - if (element) { - const QStringList priorities = element->attribute("FilePriorities").split(","); - foreach (const QString &priority, priorities) { - m_priorities.push_back(boost::uint8_t(priority.toInt())); - } - - const QByteArray resumedatahex = element->attribute("ResumeData").toLatin1(); - const QByteArray resumedata = QByteArray::fromHex(resumedatahex); - if (!resumedata.isEmpty()) { - m_ltresumedata = std::vector(resumedata.constData(), resumedata.constData() + resumedata.size()); - } - } - - if (m_startonload) { - start(); - } -} - -void TransferTorrent::init() -{ - // start even if transfer is finished so that torrent is seeded - if (policy() != Job::Stop) { - m_startonload = true; - } -} - -void TransferTorrent::timerEvent(QTimerEvent *event) -{ - if (event->timerId() != m_polltimerid && event->timerId() != m_resumetimerid) { - event->ignore(); - return; - } - - if (event->timerId() == m_resumetimerid) { - kDebug() << "posting save resume data alert"; - if (m_lthandle.is_valid()) { - m_lthandle.save_resume_data(); - } - event->accept(); - return; - } - - Q_ASSERT(m_ltsession); - std::vector ltalerts; - m_ltsession->pop_alerts(<alerts); - - foreach (lt::alert const* ltalert, ltalerts) { - if (lt::alert_cast(ltalert)) { - const lt::torrent_status ltstatus = m_lthandle.status(); - - m_percent = (ltstatus.progress * 100.0); - m_downloadedSize = ltstatus.total_done; - m_downloadSpeed = ltstatus.download_rate; - m_uploadedSize = (ltstatus.total_upload + ltstatus.all_time_upload); - m_uploadSpeed = ltstatus.upload_rate; - - switch (ltstatus.state) { - case lt::torrent_status::queued_for_checking: - case lt::torrent_status::checking_files: - case lt::torrent_status::checking_resume_data: { - setStatus(Job::Running, i18n("Checking...")); - setTransferChange(Transfer::Tc_Status, false); - break; - } - case lt::torrent_status::allocating: { - setStatus(Job::Running, i18n("Allocating disk space...")); - setTransferChange(Transfer::Tc_Status, false); - break; - } - case lt::torrent_status::finished: - case lt::torrent_status::seeding: { - setStatus(Job::FinishedKeepAlive, i18n("Seeding...")); - setTransferChange(Transfer::Tc_Status, false); - break; - } - case lt::torrent_status::downloading_metadata: - case lt::torrent_status::downloading: { - setStatus(Job::Running); - setTransferChange(Transfer::Tc_Status, false); - break; - } - } - - setTransferChange( - Transfer::Tc_Percent - | Transfer::Tc_DownloadedSize | Transfer::Tc_DownloadSpeed - | Transfer::Tc_UploadedSize | Transfer::Tc_UploadSpeed - , true - ); - } else if (lt::alert_cast(ltalert)) { - m_lthandle.save_resume_data(); - - setStatus(Job::FinishedKeepAlive); - setTransferChange(Transfer::Tc_Status, true); - } else if (lt::alert_cast(ltalert)) { - kDebug() << "save resume data alert"; - -#if LIBTORRENT_VERSION_NUM >= 10200 - const lt::save_resume_data_alert* ltresumealert = lt::alert_cast(ltalert); - if (ltresumealert) { - m_ltresumedata = lt::write_resume_data_buf(ltresumealert->params); - } -#endif - } else if (lt::alert_cast(ltalert)) { - kError() << ltalert->message().c_str(); - - const lt::torrent_error_alert* lterror = lt::alert_cast(ltalert); - - killTimer(m_resumetimerid); - m_resumetimerid = 0; - killTimer(m_polltimerid); - m_polltimerid = 0; - - const QString errormesssage = translatelterror(lterror->error); - setError(errormesssage, SmallIcon("dialog-error"), Job::ManualSolve); - setLog(errormesssage, Transfer::Log_Error); - setTransferChange(Transfer::Tc_Status | Transfer::Tc_Log, true); - } - } - - m_ltsession->post_torrent_updates(); - - event->accept(); -} - -#include "moc_transferTorrent.cpp" diff --git a/kget/transfer-plugins/torrent/transferTorrent.h b/kget/transfer-plugins/torrent/transferTorrent.h deleted file mode 100644 index 8a51db97..00000000 --- a/kget/transfer-plugins/torrent/transferTorrent.h +++ /dev/null @@ -1,84 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef TRANSFER_TORRENT_H -#define TRANSFER_TORRENT_H - -#include "core/transfer.h" -#include "core/filemodel.h" - -#include -#include - -#include -#include -#include - -class TorrentFileModel; - -class TransferTorrent : public Transfer -{ - Q_OBJECT - // Transfer reimplementations -public: - TransferTorrent(TransferGroup* parent, TransferFactory* factory, - Scheduler* scheduler, const KUrl &src, const KUrl &dest); - ~TransferTorrent(); - -public: - void init() final; - void deinit(Transfer::DeleteOptions options) final; - QList files() const final; - FileModel* fileModel() final; - void save(const QDomElement &element) final; - void load(const QDomElement *element) final; - QHash > availableMirrors(const KUrl &file) const final; - void setAvailableMirrors(const KUrl &file, const QHash > &mirrors) final; - - // Job reimplementations - void start() final; - void stop() final; - bool isStalled() const final; - bool isWorking() const final; - -protected: - // QObject reimplementation - void timerEvent(QTimerEvent *event) final; - // Transfer reimplementation - void setSpeedLimits(int uploadLimit, int downloadLimit) final; - -private Q_SLOTS: - void slotCheckStateChanged(); - void slotSettingsDirty(const QString &settings); - -private: - void applySettings(); - - bool m_startonload; - int m_polltimerid; - int m_resumetimerid; - lt::session* m_ltsession; - lt::torrent_handle m_lthandle; - std::vector m_ltresumedata; - TorrentFileModel* m_filemodel; - std::vector m_priorities; - KDirWatch* m_dirwatch; -}; - -#endif // TRANSFER_TORRENT_H diff --git a/kget/transfer-plugins/torrent/transferTorrentFactory.cpp b/kget/transfer-plugins/torrent/transferTorrentFactory.cpp deleted file mode 100644 index 447f32bf..00000000 --- a/kget/transfer-plugins/torrent/transferTorrentFactory.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "transferTorrentFactory.h" -#include "transferTorrent.h" -#include "core/scheduler.h" -#include "core/transfergroup.h" - -#include - -KGET_EXPORT_PLUGIN(TransferTorrentFactory) - -TransferTorrentFactory::TransferTorrentFactory(QObject *parent, const QVariantList &args) - : TransferFactory(parent, args) -{ -} - -TransferTorrentFactory::~TransferTorrentFactory() -{ -} - -Transfer* TransferTorrentFactory::createTransfer(const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup* parent, - Scheduler* scheduler) -{ - kDebug() << "TransferTorrentFactory::createTransfer"; - if (isSupported(srcUrl)) { - return new TransferTorrent(parent, this, scheduler, srcUrl, destUrl); - } - return nullptr; -} - -bool TransferTorrentFactory::isSupported(const KUrl &url) const -{ - const QString urlstring = url.url(); - return (urlstring.startsWith("magnet:") || urlstring.endsWith(".torrent")); -} - -QStringList TransferTorrentFactory::addsProtocols() const -{ - // magnet is not an actual protocol but register it anyway - return QStringList() << "magnet"; -} \ No newline at end of file diff --git a/kget/transfer-plugins/torrent/transferTorrentFactory.h b/kget/transfer-plugins/torrent/transferTorrentFactory.h deleted file mode 100644 index 92316887..00000000 --- a/kget/transfer-plugins/torrent/transferTorrentFactory.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2021 Ivailo Monev - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2, as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef TRANSFER_TORRENT_FACTORY_H -#define TRANSFER_TORRENT_FACTORY_H - -#include "core/plugin/transferfactory.h" - -class Transfer; -class TransferGroup; -class Scheduler; - -class TransferTorrentFactory : public TransferFactory -{ - Q_OBJECT -public: - TransferTorrentFactory(QObject *parent, const QVariantList &args); - ~TransferTorrentFactory(); - - Transfer* createTransfer(const KUrl &srcUrl, const KUrl &destUrl, - TransferGroup* parent, Scheduler* scheduler); - bool isSupported(const KUrl &url) const; - QStringList addsProtocols() const; -}; - -#endif // TRANSFER_TORRENT_FACTORY_H diff --git a/kget/ui/CMakeLists.txt b/kget/ui/CMakeLists.txt deleted file mode 100644 index 8266aec9..00000000 --- a/kget/ui/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_subdirectory(icons) - -install(FILES kgetui.rc DESTINATION ${KDE4_DATA_INSTALL_DIR}/kget) diff --git a/kget/ui/contextmenu.cpp b/kget/ui/contextmenu.cpp deleted file mode 100644 index e6f78611..00000000 --- a/kget/ui/contextmenu.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ - -#include "contextmenu.h" - - -#include "core/kget.h" -#include "core/plugin/transferfactory.h" -#include "core/transferhandler.h" -#include "core/transfergrouphandler.h" -#include -#include - -#include -#include -#include - -KMenu * ContextMenu::createTransferContextMenu(QList transfers, QWidget *parent) -{ - if (transfers.empty()) - return 0; - - //First check whether all the transfers in the list belong to the same - //transferfactory - //bool sameFactory = true; - - /*QList::iterator it = transfers.begin(); - - for(; (it!=transfers.end()) && (sameFactory) ; ++it) - { - //sameFactory = ( (*it)->m_transfer->factory() == //Port factory() to transferhandler - // transfers.first()->m_transfer->factory() ); - }*/ - - KMenu *popup = new KMenu(parent); - popup->addTitle(transfers.first()->dest().fileName()); - //Get the transfer factory actions - QList actionList = transfers.first()->factoryActions(); -// popup->addTitle( i18np("%1 Download selected", "%1 Downloads selected", transfers.count()) ); - - //Plug all the actions in the popup menu - popup->addActions(transfers.first()->contextActions()); - popup->addSeparator(); - popup->addAction( KGet::actionCollection()->action("transfer_settings") ); - popup->addSeparator(); - - foreach (QAction * it, actionList) - { - //Plug each action in the popup menu - popup->addAction( it ); - } - - if (!actionList.isEmpty()) - popup->addSeparator(); - - - popup->addAction( KGet::actionCollection()->action("transfer_open_dest") ); - //popup->addAction( KGet::actionCollection()->action("transfer_open_file") ); - popup->addAction( KGet::actionCollection()->action("transfer_show_details") ); - popup->addAction( KGet::actionCollection()->action("transfer_copy_source_url") ); - - return popup; -} - -KMenu * ContextMenu::createTransferContextMenu(TransferHandler* handler, QWidget *parent) -{ - KMenu *popup = ContextMenu::createTransferContextMenu(QList() << handler, parent); - - // only shows the open with actions if the transfer is finished - if (handler->status() == Job::Finished || handler->status() == Job::FinishedKeepAlive) { - KFileItemList items; - items << KFileItem(KFileItem::Unknown, KFileItem::Unknown, handler->dest()); - - KFileItemActions menuActions; - - menuActions.setItemListProperties(KFileItemListProperties(items)); - menuActions.setParentWidget(parent); - - menuActions.addServiceActionsTo(popup); - menuActions.addOpenWithActionsTo(popup, "DesktopEntryName != 'kget'"); - - // TODO : seems like the popup menu has to be showed while the KonqMenuActions instance exists ? - popup->exec(QCursor::pos()); - popup->deleteLater(); - - return 0; - } - - return popup; -} - -KMenu * ContextMenu::createTransferGroupContextMenu(TransferGroupHandler *handler, QWidget *parent) -{ - if (!handler) - return 0; - - KMenu * popup = new KMenu(parent); - popup->addTitle(handler->name()); - - popup->addActions(handler->actions()); - popup->addSeparator(); - popup->addAction(KGet::actionCollection()->action("transfer_group_settings")); - popup->addSeparator(); - - QList transferGroups = KGet::selectedTransferGroups(); - if (transferGroups.count() != KGet::allTransferGroups().count()) { - const int numGroups = transferGroups.count(); - QAction *action = KGet::actionCollection()->action("delete_groups"); - action->setText(i18np("Delete Group", "Delete Groups", numGroups)); - popup->addAction(action); - - action = KGet::actionCollection()->action("rename_groups"); - action->setText(i18np("Rename Group...", "Rename Groups...", numGroups)); - popup->addAction(action); - } - popup->addAction( KGet::actionCollection()->action("seticon_groups") ); - return popup; -} diff --git a/kget/ui/contextmenu.h b/kget/ui/contextmenu.h deleted file mode 100644 index c8e8045b..00000000 --- a/kget/ui/contextmenu.h +++ /dev/null @@ -1,29 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2004 Dario Massarin - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ - -#ifndef TRANSFERCONTEXTMENU_H -#define TRANSFERCONTEXTMENU_H - -#include - -class TransferHandler; -class TransferGroupHandler; -class KMenu; -#include - -namespace ContextMenu -{ - KMenu * createTransferContextMenu(QList transfer, QWidget *parent); - KMenu * createTransferContextMenu(TransferHandler* handler, QWidget *parent); - KMenu * createTransferGroupContextMenu(TransferGroupHandler *handler, QWidget *parent); -} - -#endif diff --git a/kget/ui/droptarget.cpp b/kget/ui/droptarget.cpp deleted file mode 100644 index a8ab3b31..00000000 --- a/kget/ui/droptarget.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 Patrick Charbonnier - Based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - Copyright (C) 2008 Urs Wolfer - - 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. -*/ - -#include "ui/droptarget.h" - -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfergrouphandler.h" -#include "core/transfertreemodel.h" -#include "settings.h" -#include "mainwindow.h" -#include "ui/newtransferdialog.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -#define TARGET_SIZE 64 -#define TARGET_ANI_MS 20 -#define TARGET_TOOLTIP_MS 1000 - -DropTarget::DropTarget(MainWindow * mw) - : QWidget(0, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint), - parentWidget(mw), animTimer(0), showInformation(false) -{ - KWindowSystem::setState(winId(), NET::SkipTaskbar); - - QRect screenGeo = qApp->desktop()->screenGeometry(Settings::dropPosition()); - if ((screenGeo.x() + screenGeo.width() >= Settings::dropPosition().x() && - screenGeo.y() + screenGeo.height() >= Settings::dropPosition().y()) && Settings::dropPosition().y() >= 0 && Settings::dropPosition().x() >= 0) - position = QPoint(Settings::dropPosition()); - else - position = QPoint(screenGeo.x() + screenGeo.width() / 2, screenGeo.y() + screenGeo.height() / 2); - setFixedSize(TARGET_SIZE, TARGET_SIZE); - - if(Settings::dropSticky()) - KWindowSystem::setState(winId(), KWindowSystem::Sticky); - - cachedPixmap = DesktopIcon("kget", TARGET_SIZE); - if (!cachedPixmap.mask().isNull()) - { - QBitmap mask(size()); - mask.fill(Qt::color0); - QBitmap pixMask = cachedPixmap.mask(); - QPainter p(&mask); - p.drawPixmap((mask.width() - pixMask.width())/2, (mask.height() - pixMask.height())/2, - pixMask); - setMask(mask); - } - else - setMask(QBitmap()); - - // popup menu for right mouse button - popupMenu = new KMenu(this); - popupMenu->addTitle(mw->windowTitle()); - - QAction * downloadAction = mw->actionCollection()->action("start_all_download"); - popupMenu->addAction( downloadAction ); - connect( downloadAction, SIGNAL(toggled(bool)), this, SLOT(slotStartStopToggled(bool)) ); - popupMenu->addSeparator(); - pop_show = popupMenu->addAction( QString(), this, SLOT(toggleMinimizeRestore()) ); - popupMenu->addAction(parentWidget->actionCollection()->action("show_drop_target")); - pop_sticky = popupMenu->addAction(i18nc("fix position for droptarget", "Sticky"), this, SLOT(toggleSticky())); - pop_sticky->setCheckable(true); - pop_sticky->setChecked(Settings::dropSticky()); - popupMenu->addSeparator(); - popupMenu->addAction( mw->actionCollection()->action("preferences") ); - - QAction *quitAction = new QAction(this); - quitAction->setText(i18n("Quit KGet")); - quitAction->setIcon(KIcon("system-shutdown")); - connect(quitAction, SIGNAL(triggered()), mw, SLOT(slotQuit())); - popupMenu->addAction(quitAction); - - isdragging = false; - - // Enable dropping - setAcceptDrops(true); - - if ( Settings::showDropTarget() && Settings::firstRun() ) { - showInformation = true; - } - - animTimer = new QTimer(this); - popupTimer = new QTimer(this); - - setMouseTracking(true); - - connect(KGet::model(), SIGNAL(transfersChangedEvent(QMap)), - this, SLOT(slotToolTipUpdate())); - - connect(popupTimer, SIGNAL(timeout()), - this, SLOT(slotToolTipTimer())); -} - - -DropTarget::~DropTarget() -{ - Settings::setDropPosition( pos() ); - Settings::setShowDropTarget( !isHidden() ); - Settings::self()->writeConfig(); -// unsigned long state = KWindowSystem::windowInfo(kdrop->winId()).state(); -// // state will be 0L if droptarget is hidden. Sigh. -// config->writeEntry("State", state ? state : DEFAULT_DOCK_STATE ); -} - -void DropTarget::setDropTargetVisible( bool shown, bool internal ) -{ - if (shown == !isHidden()) - return; - - if ( internal ) - Settings::setShowDropTarget( shown ); - - if (!shown) - { - Settings::setDropPosition( pos() ); - position = pos(); - if ( Settings::animateDropTarget() ) - playAnimationHide(); - else - hide(); - } - else - { - if ( Settings::animateDropTarget() ) { - playAnimationShow(); - } else { - move(position); - show(); - } - slotToolTipUpdate(); - } -} - -void DropTarget::playAnimationShow() -{ - if (animTimer->isActive()) - animTimer->stop(); - animTimer->disconnect(); - connect( animTimer, SIGNAL(timeout()), - this, SLOT(slotAnimateShow())); - - move(position.x(), -TARGET_SIZE); - - ani_y = -1; - ani_vy = 0; - show(); - animTimer->start(TARGET_ANI_MS); -} - -void DropTarget::playAnimationHide() -{ - if (animTimer->isActive()) - animTimer->stop(); - - animTimer->disconnect(); - connect( animTimer, SIGNAL(timeout()), - this, SLOT(slotAnimateHide())); - ani_y = (float)y(); - ani_vy = 0; - animTimer->start(TARGET_ANI_MS); -} - -void DropTarget::playAnimationSync() -{ - if (animTimer->isActive()) - animTimer->stop(); - - animTimer->disconnect(); - connect( animTimer, SIGNAL(timeout()), - this, SLOT(slotAnimateSync())); - ani_y = (float)y(); - ani_vy = -1; - animTimer->start(TARGET_ANI_MS); -} - -void DropTarget::slotStartStopToggled( bool started ) -{ - if ( started && Settings::animateDropTarget() ) - playAnimationSync(); -} - - -/** widget events */ - -void DropTarget::dragEnterEvent(QDragEnterEvent * event) -{ - event->setAccepted(KUrl::List::canDecode(event->mimeData()) - || event->mimeData()->hasText()); -} - - -void DropTarget::dropEvent(QDropEvent * event) -{ - KUrl::List list = KUrl::List::fromMimeData(event->mimeData()); - QString str; - - if (!list.isEmpty()) - { - if (list.count() == 1 && list.first().url().endsWith(QLatin1String(".kgt"))) - { - int msgBoxResult = KMessageBox::questionYesNoCancel(this, i18n("The dropped file is a KGet Transfer List"), "KGet", - KGuiItem(i18n("&Download"), KIcon("document-save")), - KGuiItem(i18n("&Load transfer list"), KIcon("list-add")), KStandardGuiItem::cancel()); - - if (msgBoxResult == 3) //Download - NewTransferDialogHandler::showNewTransferDialog(list.first().url()); - if (msgBoxResult == 4) //Load - KGet::load(list.first().url()); - } - else - { - if (list.count() == 1) - { - str = event->mimeData()->text(); - NewTransferDialogHandler::showNewTransferDialog(str); - } - else - NewTransferDialogHandler::showNewTransferDialog(list); - } - } - else - { - NewTransferDialogHandler::showNewTransferDialog(); - } - - if ( Settings::animateDropTarget() ) - playAnimationSync(); -} - - -void DropTarget::closeEvent( QCloseEvent * e ) -{ - if( kapp->sessionSaving() ) - e->ignore(); - else - { - setVisible( false ); - e->accept(); - } -} - -void DropTarget::mousePressEvent(QMouseEvent * e) -{ - // If the user click on the droptarget, stop any animation that is going on - if(animTimer) - { - animTimer->stop(); - } - - if (e->button() == Qt::LeftButton) - { - isdragging = true; - dx = e->globalPos().x() - pos().x(); - dy = e->globalPos().y() - pos().y(); - } - else if (e->button() == Qt::RightButton) - { - pop_show->setText(parentWidget->isHidden() ? - i18n("Show Main Window") : - i18n("Hide Main Window") ); - popupMenu->popup(e->globalPos()); - } - else if (e->button() == Qt::MiddleButton) - { - //Here we paste the transfer - QString newtransfer = QApplication::clipboard()->text(); - newtransfer = newtransfer.trimmed(); - - if(!newtransfer.isEmpty()) - KGet::addTransfer(KUrl(newtransfer), QString(), QString(), true); - } -} - -void DropTarget::mouseReleaseEvent(QMouseEvent *) -{ - isdragging = false; -} - -void DropTarget::mouseDoubleClickEvent(QMouseEvent * e) -{ - if (e->button() == Qt::LeftButton) - toggleMinimizeRestore(); -} - -void DropTarget::mouseMoveEvent(QMouseEvent * e) -{ - Q_UNUSED(e) - if ( isdragging && !Settings::dropSticky() ) - { - move( QCursor::pos().x() - dx, QCursor::pos().y() - dy ); - e->accept(); - } -} - -void DropTarget::enterEvent(QEvent * event) -{ - Q_UNUSED(event) - popupTimer->start(2000); -} - -void DropTarget::leaveEvent(QEvent * event) -{ - Q_UNUSED(event) - popupTimer->stop(); -} - -void DropTarget::paintEvent( QPaintEvent * ) -{ - QPainter p(this); - p.drawPixmap(0, 0, cachedPixmap); -} - -void DropTarget::toggleSticky() -{ - Settings::setDropSticky( !Settings::dropSticky() ); - pop_sticky->setChecked(Settings::dropSticky()); - - if ( Settings::dropSticky() ) - KWindowSystem::setState(winId(), KWindowSystem::SkipTaskbar | KWindowSystem::KeepAbove | KWindowSystem::Sticky); - else - KWindowSystem::clearState(winId(), KWindowSystem::Sticky); -} - -void DropTarget::toggleMinimizeRestore() -{ - bool nextState = parentWidget->isHidden(); - Settings::setShowMain( nextState ); - parentWidget->setVisible( nextState ); - if(nextState) - { - KWindowSystem::activateWindow(static_cast(parentWidget)->winId()); - } -} - -/** widget animations */ -void DropTarget::slotAnimateShow() -{ - static float dT = TARGET_ANI_MS / 1000.0; - - ani_vy -= ani_y * 30 * dT; - ani_vy *= 0.95; - ani_y += ani_vy * dT; - - move(x(), qRound(position.y() * (1 + ani_y))); - - if ( fabs(ani_y) < 0.01 && fabs(ani_vy) < 0.01 && animTimer->isActive() ) - { - animTimer->stop(); - - if (showInformation) - KPassivePopup::message(i18n("Drop Target"), - i18n("You can drag download links into the drop target."), this); - } -} - -void DropTarget::slotAnimateHide() -{ - static float dT = TARGET_ANI_MS / 1000.0; - - ani_vy += -2000 * dT; - float new_y = y() + ani_vy * dT; - - if ( new_y < -height() ) - { - animTimer->stop(); - hide(); - move( x(), qRound(ani_y) ); - } else - move( x(), qRound(new_y) ); -} - -void DropTarget::slotAnimateSync() -{ - static float dT = TARGET_ANI_MS / 1000.0; - - ani_vy += 4 * dT; // from -1 to 1 in 0.5 seconds - float i = 2 * M_PI * ani_vy; // from -2PI to 2PI - float j = (i == 0.0) ? 1 : (sin( i ) / i) * (1 + fabs(ani_vy)); - - if ( ani_vy >= 1 ) - { - animTimer->stop(); - move( x(), qRound(ani_y) ); - } else - move( x(), qRound(ani_y + 6*j) ); -} - -void DropTarget::slotToolTipUpdate() -{ - QStringList dataList; - QString data; - - foreach (TransferHandler *transfer, KGet::allTransfers()) { - data.clear(); - switch (transfer->status()) { - case Job::Finished: - data = i18nc("%1 filename, %2 total size, %3 status", "%1(%2) %3", - transfer->source().fileName(), - KIO::convertSize(transfer->totalSize()), - transfer->statusText()); - break; - case Job::Running: - data = i18nc("%1 filename, %2 percent complete, %3 downloaded out of %4 total size", "%1(%2% %3/%4) Speed:%5/s", - transfer->source().fileName(), - transfer->percent(), - KIO::convertSize(transfer->downloadedSize()), - KIO::convertSize(transfer->totalSize()), - KIO::convertSize(transfer->downloadSpeed())); - break; - default: - data = i18nc("%1 filename, %2 percent complete, %3 downloaded out of %4 total size, %5 status", "%1(%2% %3/%4) %5", - transfer->source().fileName(), - transfer->percent(), - KIO::convertSize(transfer->downloadedSize()), - KIO::convertSize(transfer->totalSize()), - transfer->statusText()); - break; - } - dataList << data; - } - - if (!dataList.empty()) - tooltipText = dataList.join("\n"); - else - tooltipText = i18n("Ready"); -} - -void DropTarget::slotToolTipTimer() -{ - if (!popupMenu->isVisible() && isVisible() && mask().contains(mapFromGlobal(QCursor::pos()))) - QToolTip::showText(QCursor::pos(),tooltipText,this,rect()); -} - -void DropTarget::slotClose() -{ - setVisible( false ); -} - -#include "moc_droptarget.cpp" diff --git a/kget/ui/droptarget.h b/kget/ui/droptarget.h deleted file mode 100644 index e1d35c80..00000000 --- a/kget/ui/droptarget.h +++ /dev/null @@ -1,96 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 Patrick Charbonnier - Based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss - - 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. -*/ - -#ifndef DROPTARGET_H -#define DROPTARGET_H - -#include -#include - - - - -#include "core/transfer.h" - -#include -#include -class KMenu; - -class MainWindow; -class DropTargetModelObserver; -class DropTargetGroupObserver; -class DropTargetTransferObserver; - -class DropTarget : public QWidget -{ -Q_OBJECT - -public: - DropTarget(MainWindow * parent); - ~DropTarget(); - - void playAnimationShow(); - void playAnimationHide(); - void playAnimationSync(); - void setDropTargetVisible( bool shown, bool internal = true ); - -protected: - // drag and drop - void dragEnterEvent(QDragEnterEvent *); - void dropEvent(QDropEvent *); - - // handle quit events as hide events - void closeEvent( QCloseEvent * ); - - void mousePressEvent(QMouseEvent * e); - void mouseReleaseEvent(QMouseEvent * e); - void mouseDoubleClickEvent(QMouseEvent * e); - void mouseMoveEvent(QMouseEvent * e); - void enterEvent(QEvent * event); - void leaveEvent(QEvent * event); - - // paint the drop target - void paintEvent(QPaintEvent*); - -private slots: - void toggleSticky(); - void toggleMinimizeRestore(); - void slotStartStopToggled( bool ); - void slotAnimateShow(); - void slotAnimateHide(); - void slotAnimateSync(); - void slotToolTipUpdate(); - void slotToolTipTimer(); - void slotClose(); - -private: - KMenu * popupMenu; - MainWindow * parentWidget; - QTimer * animTimer; - QTimer * popupTimer; - QPixmap cachedPixmap; - - QAction * pop_sticky; - QAction * pop_show; - - QPoint position; - - QString tooltipText; - - int dx; - int dy; - bool isdragging; - bool showInformation; - - float ani_y, ani_vy; -}; - -#endif // _DROPTARGET_H diff --git a/kget/ui/groupsettingsdialog.cpp b/kget/ui/groupsettingsdialog.cpp deleted file mode 100644 index 18f07bd8..00000000 --- a/kget/ui/groupsettingsdialog.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ -#include "groupsettingsdialog.h" - -#include "core/transfergrouphandler.h" -#include - - -GroupSettingsDialog::GroupSettingsDialog(QWidget *parent, TransferGroupHandler *group) - : KGetSaveSizeDialog("GroupSettingsDialog", parent), - m_group(group) -{ - setCaption(i18n("Group Settings for %1", group->name())); - showButtonSeparator(true); - - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - - setMainWidget(widget); - - ui.downloadBox->setValue(group->downloadLimit(Transfer::VisibleSpeedLimit)); - ui.uploadBox->setValue(group->uploadLimit(Transfer::VisibleSpeedLimit)); - - ui.defaultFolderRequester->setMode(KFile::Directory); - QString path = group->defaultFolder(); - ui.defaultFolderRequester->setUrl(path); - ui.defaultFolderRequester->setStartDir(KUrl(KGet::generalDestDir(true))); - - ui.regExpEdit->setText(group->regExp().pattern()); - - connect(this, SIGNAL(accepted()), SLOT(save())); -} - -GroupSettingsDialog::~GroupSettingsDialog() -{ -} - -QSize GroupSettingsDialog::sizeHint() const -{ - QSize sh = KDialog::sizeHint(); - sh.setWidth(sh.width() * 1.4); - return sh; -} - -void GroupSettingsDialog::save() -{ - //check needed, otherwise "/" would be added as folder if the line was empty! - if (ui.defaultFolderRequester->text().isEmpty()) { - m_group->setDefaultFolder(QString()); - } else { - m_group->setDefaultFolder(ui.defaultFolderRequester->url().toLocalFile(KUrl::AddTrailingSlash)); - } - - m_group->setDownloadLimit(ui.downloadBox->value(), Transfer::VisibleSpeedLimit); - m_group->setUploadLimit(ui.uploadBox->value(), Transfer::VisibleSpeedLimit); - - QRegExp regExp; - regExp.setPattern(ui.regExpEdit->text()); - m_group->setRegExp(regExp); - -} - -#include "moc_groupsettingsdialog.cpp" diff --git a/kget/ui/groupsettingsdialog.h b/kget/ui/groupsettingsdialog.h deleted file mode 100644 index 02c37d67..00000000 --- a/kget/ui/groupsettingsdialog.h +++ /dev/null @@ -1,41 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - - 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. -*/ -#ifndef GROUPSETTINGSDIALOG_H -#define GROUPSETTINGSDIALOG_H - -#include "ui_groupsettingsdialog.h" -#include "../core/basedialog.h" - -#include - - -class TransferGroupHandler; - -class GroupSettingsDialog : public KGetSaveSizeDialog -{ - Q_OBJECT - public: - GroupSettingsDialog(QWidget *parent, TransferGroupHandler *group); - ~GroupSettingsDialog(); - - QSize sizeHint() const; - - private slots: - void save(); - - private: - - private: - TransferGroupHandler* m_group; - Ui::GroupSettingsDialog ui; - -}; - -#endif diff --git a/kget/ui/groupsettingsdialog.ui b/kget/ui/groupsettingsdialog.ui deleted file mode 100644 index 1106ae23..00000000 --- a/kget/ui/groupsettingsdialog.ui +++ /dev/null @@ -1,158 +0,0 @@ - - - GroupSettingsDialog - - - - 0 - 0 - 457 - 150 - - - - - 0 - 0 - - - - Qt::LeftToRight - - - - - - - 0 - 0 - - - - Group Settings - - - - - - - QFormLayout::ExpandingFieldsGrow - - - - - Default &folder: - - - defaultFolderRequester - - - - - - - true - - - - - - - Moves all transfers with the regular expression to this group - - - Regular &expression: - - - regExpEdit - - - - - - - *movies* - - - - - - - - 0 - 0 - - - - Not set - - - KiB/s - - - 10000 - - - - - - - - 0 - 0 - - - - Not set - - - KiB/s - - - 10000 - - - - - - - Maximum &download speed: - - - downloadBox - - - - - - - Maximum &upload speed: - - - uploadBox - - - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
- - KTitleWidget - QWidget -
ktitlewidget.h
-
- - KUrlRequester - QFrame -
kurlrequester.h
-
-
- -
diff --git a/kget/ui/history/rangetreewidget.cpp b/kget/ui/history/rangetreewidget.cpp deleted file mode 100644 index 48877e18..00000000 --- a/kget/ui/history/rangetreewidget.cpp +++ /dev/null @@ -1,341 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ - -#include "rangetreewidget.h" -#include "settings.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class RangeTreeWidget::Range -{ -public: - Range() - { - }; - - bool check(const QVariant &data) const - { - if (data.type() == QVariant::String) { - return (QString::compare(data.toString(), min.toString()) == 0); - } - else if (data.type() == QVariant::Int || data.type() == QVariant::Double) { - if (data.toDouble() >= min.toDouble() && (data.toDouble() <= max.toDouble() || max.toDouble() < 0)) { - // the last range ends with -1 - return true; - } - } - - return false; - } - - int id; - QVariant min; - QVariant max; - QString title; -}; - -RangeSortFilterProxyModel::RangeSortFilterProxyModel(QObject *parent): - QSortFilterProxyModel(parent) -{ -} - -RangeSortFilterProxyModel::~RangeSortFilterProxyModel() -{ -} - -bool RangeSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const -{ - // if the row is a range row, we include in the filter always - if(source_parent.isValid()) { - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - } - - return true; -} - -RangeTreeWidget::RangeTreeWidget(QWidget *parent) : QTreeView(parent), - m_data(), - m_ranges(), - m_rangeDelegate(0) -{ - setDragEnabled(false); - setAlternatingRowColors(true); - setEditTriggers(QAbstractItemView::NoEditTriggers); - header()->setMovable(false); - - // initialize the standard item model of the tree - m_model = new QStandardItemModel(this); - m_proxyModel = new RangeSortFilterProxyModel(this); - - m_proxyModel->setSourceModel(m_model); - setModel(m_proxyModel); - - // delegate for the range title - RangeTreeWidgetItemDelegate *delegate = new RangeTreeWidgetItemDelegate(this); - setItemDelegate(delegate); -} - -RangeTreeWidget::~RangeTreeWidget() -{ - QList list; - for (int i = 0; i < 5; i++) - { - list.append(columnWidth(i)); - } - Settings::setHistoryColumnWidths(list); - Settings::self()->writeConfig(); - clear(); - - delete m_rangeDelegate; -} - -int RangeTreeWidget::addRange(const QVariant &min, const QVariant &max, const QString &title) -{ - int row = m_data.size(); - - Range range; - range.min = min; - range.max = max; - range.title = title; - range.id = row; - m_ranges << range; - - m_data [row] = new QStandardItem(title); - m_model->insertRow(row, m_data [row]); - setFirstColumnSpanned(row, QModelIndex(), true); - // openPersistentEditor(model()->index(row, 0, QModelIndex())); - - // expand the first row - if(row == 0) { - setExpanded(model()->index(row, 0, QModelIndex()), true); - } - - return row; -} - -void RangeTreeWidget::clear() -{ - m_model->clear(); - m_data.clear(); - m_ranges.clear(); -} - -void RangeTreeWidget::add(const QVariant &data, const QString &column) -{ - QVariantList list; - list << QVariant(column); - - add(data, list); -} - -void RangeTreeWidget::add(const QVariant &data, const QVariantList &columns) -{ - QStandardItem *parent = getRange(data); - - QList list; - foreach(const QVariant &item, columns) { - list << new QStandardItem(item.toString()); - } - - parent->appendRow(list); - // TODO: need to find a better way to update rangetitlewidget count from the QStandardItem children count - // closePersistentEditor(parent->index()); - // openPersistentEditor(parent->index()); -} - -void RangeTreeWidget::addLabel(const QString &title) -{ - int index = header()->count(); - m_model->setColumnCount(index + 1); - m_model->setHeaderData(index, Qt::Horizontal, title); -} - -void RangeTreeWidget::setLabels(const QStringList &labels) -{ - m_model->setColumnCount(labels.size()); - - for(int i=0; isetHeaderData(i, Qt::Horizontal, labels.at(i)); - } -} - -void RangeTreeWidget::setRangeDelegate(RangeDelegate *delegate) -{ - delete m_rangeDelegate; - m_rangeDelegate = delegate; -} - -QList RangeTreeWidget::data() -{ - QList list; - foreach(const Range &range, m_ranges) { - QStandardItem *parent = m_model->itemFromIndex(model()->index(range.id, 0, QModelIndex())); - - for(int y=0; yrowCount(); y++) { - QVariantList items; - for(int x=0; xcount(); x++) { - QStandardItem *item = parent->child(y, x); - items << item->data(Qt::DisplayRole); - } - list << items; - } - } - - return list; -} - -QStandardItem *RangeTreeWidget::currentItem(int column) -{ - QStandardItem *item = 0; - if (column >= 0) { - item = m_model->itemFromIndex(m_model->index(m_proxyModel->mapToSource(currentIndex()).row(), - column, - m_proxyModel->mapToSource(currentIndex()).parent())); - } - else { - item = m_model->itemFromIndex(m_proxyModel->mapToSource(currentIndex())); - } - return item; -} - -QStandardItem *RangeTreeWidget::item(const QModelIndex &index, int column) -{ - return m_model->item(m_proxyModel->mapToSource(index).row(), column); -} - -void RangeTreeWidget::removeRow(int row, const QModelIndex &parent) -{ - m_model->removeRow(row, parent); -} - -void RangeTreeWidget::setFilterRegExp(const QString &text) -{ - m_proxyModel->setFilterRegExp(text); -} - -QStandardItem *RangeTreeWidget::getRange(const QVariant &data) -{ - QVariant rangeData = data; - if (m_rangeDelegate) { - rangeData = m_rangeDelegate->getRangeData(data); - } - - foreach (const Range &range, m_ranges) { - if(range.check(rangeData)) { - return m_data [range.id]; - } - } - - if (m_rangeDelegate) { - int id = addRange(rangeData, rangeData, rangeData.toString()); - return m_data [id]; - } - else { - // if no range found, return the last one - return m_data [m_data.size() - 1]; - } -} - -RangeDelegate::RangeDelegate(QObject *parent) : QObject(parent) -{ -} - -RangeDelegate::~RangeDelegate() -{ -} - -HostRangeDelegate::HostRangeDelegate(QObject *parent) : RangeDelegate(parent) -{ -} - -HostRangeDelegate::~HostRangeDelegate() -{ -} - -QVariant HostRangeDelegate::getRangeData(const QVariant &data) -{ - return QUrl(data.toString()).host(); -} - -RangeTreeWidgetItemDelegate::RangeTreeWidgetItemDelegate(QAbstractItemView *parent) : QStyledItemDelegate(parent) -{ -} - -void RangeTreeWidgetItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if(index.parent().isValid()) { - QStyledItemDelegate::paint(painter, option, index); - } - else if(index.isValid()) { - QStyleOptionViewItemV4 opt(option); - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); - - const QSortFilterProxyModel *model = static_cast (index.model()); - const QStandardItemModel *s_model = static_cast (model->sourceModel()); - QStandardItem *item = s_model->itemFromIndex(model->mapToSource(index)); - // draw the range title - painter->save(); - QFont font; - font.setBold(true); - painter->setFont(font); - painter->drawText(option.rect.left() + 10, - option.rect.top() + 5, - option.rect.width() - 20, 15, - Qt::AlignLeft, - item->data(Qt::DisplayRole).toString() + - " (" + QString::number(model->rowCount(index)) + ')'); - painter->restore(); - - // Draw the line under the title - QColor color = option.palette.color(QPalette::Text); - if (option.state & QStyle::State_Selected) { - color = option.palette.color(QPalette::HighlightedText); - } - - QRect lineRect(option.rect.left() + 10, option.rect.bottom() - 2, - 500, 1); - - QLinearGradient gradient(option.rect.left() + 10, option.rect.top(), - 500, option.rect.height()); - gradient.setColorAt(0, color); - gradient.setColorAt(1, Qt::transparent); - - painter->fillRect(lineRect, gradient); - } -} - -QSize RangeTreeWidgetItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - Q_UNUSED(index) - - return QSize(0, 30); -} - -#include "moc_rangetreewidget.cpp" diff --git a/kget/ui/history/rangetreewidget.h b/kget/ui/history/rangetreewidget.h deleted file mode 100644 index bcc82488..00000000 --- a/kget/ui/history/rangetreewidget.h +++ /dev/null @@ -1,131 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ - -#ifndef RANGETREEWIDGET_H -#define RANGETREEWIDGET_H - -#include -#include -#include -#include - -#include -#include -#include -#include -class RangeDelegate; - -/** -* We need to override the qsortfilterproxymodel behavior -* to avoid include the range rows in the search filter -* the range rows are always showed -**/ -class RangeSortFilterProxyModel : public QSortFilterProxyModel -{ -public: - RangeSortFilterProxyModel(QObject *parent = 0); - ~RangeSortFilterProxyModel(); - -protected: - virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; -}; - -class RangeTreeWidget : public QTreeView -{ -Q_OBJECT -public: - - RangeTreeWidget(QWidget *parent = 0); - ~RangeTreeWidget(); - - /** - * Creates a range with a title between two values - */ - int addRange(const QVariant &min, const QVariant &max, const QString &title); - void clear(); - - void add(const QVariant &data, const QString &column); - void add(const QVariant &data, const QVariantList &columns); - void addLabel(const QString &title); - void setLabels(const QStringList &labels); - - /** - * Set a delegate in case you want to create the ranges dinamically - * Ej, the host ranges delegate - */ - void setRangeDelegate(RangeDelegate *delegate); - - QList data(); - QStandardItem *currentItem(int column = -1); - QStandardItem *item(const QModelIndex &index = QModelIndex(), int column = 0); - -public slots: - void removeRow(int row, const QModelIndex &parent = QModelIndex()); - /** - * Filters the data throws the qsortfilterproxymodel - */ - void setFilterRegExp(const QString &text); - -private: - /** - * Returns the selected range for a data. - * If a rangedelegate is set, then gets the range from the delegate - */ - QStandardItem *getRange(const QVariant &data); - -private: - class Range; - - QStandardItemModel *m_model; - RangeSortFilterProxyModel *m_proxyModel; - QMap m_data; - QList m_ranges; - - RangeDelegate *m_rangeDelegate; -}; - -/** -* Creates ranges dinamically, based on the item data -*/ -class RangeDelegate : public QObject -{ -Q_OBJECT - public: - RangeDelegate(QObject *parent = 0); - ~RangeDelegate(); - - /** - * Returns the current range of the incoming data - */ - virtual QVariant getRangeData(const QVariant &data) = 0; -}; - -/** -* Creates a ragen based on the host of the transfer -*/ -class HostRangeDelegate : public RangeDelegate -{ -Q_OBJECT - public: - HostRangeDelegate(QObject *parent = 0); - ~HostRangeDelegate(); - - QVariant getRangeData(const QVariant &data); -}; - -class RangeTreeWidgetItemDelegate : public QStyledItemDelegate -{ -public: - RangeTreeWidgetItemDelegate(QAbstractItemView *parent); - - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint (const QStyleOptionViewItem &option, const QModelIndex &index) const; -}; -#endif diff --git a/kget/ui/history/transferhistory.cpp b/kget/ui/history/transferhistory.cpp deleted file mode 100644 index 932f3170..00000000 --- a/kget/ui/history/transferhistory.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - - 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. -*/ - -#include "transferhistory.h" -#include "ui/newtransferdialog.h" -#include "settings.h" -#include "ui/history/transferhistorycategorizedview.h" -#include "ui/history/transferhistorycategorizeddelegate.h" -#include "ui/history/rangetreewidget.h" -#include "core/transferhistorystore.h" -#include "core/job.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -TransferHistory::TransferHistory(QWidget *parent) - : KGetSaveSizeDialog("TransferHistory", parent), - m_rangeType(TransferHistory::Date), - m_progressBar(new QProgressBar(this)), - m_iconModeEnabled(true) -{ - setAttribute(Qt::WA_DeleteOnClose); - setCaption(i18n("Transfer History")); - setButtons(KDialog::Close); - //Setup Ui-Parts from Designer - QWidget *mainWidget = new QWidget(this); - - Ui::TransferHistory widget; - widget.setupUi(mainWidget); - - m_view = new TransferHistoryCategorizedView(this); - - // list icon view - m_iconView = widget.bt_iconview; - m_listView = widget.bt_listview; - - m_listView->setIcon(KIcon("view-list-details")); - m_iconView->setIcon(KIcon("view-list-icons")); - - connect(m_listView, SIGNAL(clicked()), SLOT(slotSetListMode())); - connect(m_iconView, SIGNAL(clicked()), SLOT(slotSetIconMode())); - - // range type - m_rangeTypeCombobox = widget.rangeType; - - m_verticalLayout = widget.vboxLayout; - m_hboxLayout = widget.hboxLayout; - m_searchBar = widget.searchBar; - //m_searchBar->setTreeWidget(m_treeWidget); - m_clearButton = widget.clearButton; - m_clearButton->setIcon(KIcon("edit-clear-history")); - m_actionDelete_Selected = widget.actionDelete_Selected; - m_actionDelete_Selected->setIcon(KIcon("edit-delete")); - m_actionDownload = widget.actionDownload; - m_actionDownload->setIcon(KIcon("document-new")); - m_openFile = new QAction(KIcon("document-open"), i18n("&Open File"), this); - setMainWidget(mainWidget); - - m_verticalLayout->addWidget(m_view); - m_verticalLayout->addWidget(m_progressBar); - - watcher = new QFileSystemWatcher(); - watcher->addPath(KStandardDirs::locateLocal("appdata", QString())); - kDebug() << watcher->directories(); - - m_store = TransferHistoryStore::getStore(); - - connect(m_actionDelete_Selected, SIGNAL(triggered()), this, SLOT(slotDeleteTransfer())); - connect(m_actionDownload, SIGNAL(triggered()), this, SLOT(slotDownload())); - connect(m_openFile, SIGNAL(triggered()), this, SLOT(slotOpenFile())); - connect(m_clearButton, SIGNAL(clicked()), this, SLOT(slotClear())); - connect(m_rangeTypeCombobox, SIGNAL(activated(int)), this, SLOT(slotLoadRangeType(int))); - connect(m_view, SIGNAL(deletedTransfer(QString,QModelIndex)), - SLOT(slotDeleteTransfer(QString,QModelIndex))); - connect(m_view, SIGNAL(doubleClicked(QModelIndex)), SLOT(slotOpenFile(QModelIndex))); - connect(m_store, SIGNAL(loadFinished()), SLOT(slotLoadFinished())); - connect(m_store, SIGNAL(elementLoaded(int,int,TransferHistoryItem)), - SLOT(slotElementLoaded(int,int,TransferHistoryItem))); - connect(m_searchBar, SIGNAL(textChanged(QString)), m_view, SLOT(setFilterRegExp(QString))); - slotAddTransfers(); -} - -TransferHistory::~TransferHistory() -{ - delete m_store; -} - -QSize TransferHistory::sizeHint() const -{ - QSize sh(800,600); - return sh; -} - -void TransferHistory::slotDeleteTransfer() -{ - if (!m_iconModeEnabled) { - RangeTreeWidget *range_view = qobject_cast (m_view); - - slotDeleteTransfer(range_view->currentItem(0)->text()); - - slotLoadRangeType(m_rangeType); - } -} - -void TransferHistory::slotDeleteTransfer(const QString &transferName, const QModelIndex &index) -{ - Q_UNUSED(index) - - TransferHistoryItem item; - item.setSource(transferName); - m_store->deleteItem(item); - - slotLoadRangeType(m_rangeType); -} - -void TransferHistory::slotAddTransfers() -{ - m_progressBar->show(); - m_store->load(); -} - -void TransferHistory::slotClear() -{ - m_store->clear(); - - slotLoadRangeType(m_rangeType); -} - -void TransferHistory::slotWriteDefault() -{ - // not neded ?? -} - -void TransferHistory::slotDownload() -{ - if (!m_iconModeEnabled) { - NewTransferDialogHandler::showNewTransferDialog(((RangeTreeWidget *) m_view)->currentItem(0)->text()); - } -} - -void TransferHistory::contextMenuEvent(QContextMenuEvent *event) -{ - Q_UNUSED(event) - - if (!m_iconModeEnabled) { - RangeTreeWidget *range_view = qobject_cast (m_view); - if(range_view->currentIndex().parent().isValid()) { - QMenu *contextMenu = new QMenu(this); - contextMenu->addAction(m_actionDownload); - contextMenu->addAction(m_actionDelete_Selected); - - if (range_view->currentItem(4)->data().toInt() == Job::Finished) - contextMenu->addAction(m_openFile); - contextMenu->exec(QCursor::pos()); - } - } -} - -void TransferHistory::slotOpenFile(const QModelIndex &index) -{ - QString file; - - if (!m_iconModeEnabled) { - RangeTreeWidget *range_view = qobject_cast (m_view); - file = range_view->currentItem(1)->text(); - } - else { - TransferHistoryCategorizedView *categorized_view = qobject_cast (m_view); - file = categorized_view->data(index, TransferHistoryCategorizedDelegate::RoleDest).toString(); - } - - kDebug() << "Try to open the file : " << file; - if (!file.isEmpty()) { - new KRun(file, this, true, false); - } -} - -void TransferHistory::hideEvent(QHideEvent *event) -{ - Q_UNUSED(event) - disconnect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(slotAddTransfers()));//Prevent reloading of TransferHistory when saving - deleteLater(); -} - -QString TransferHistory::statusText(int status) const -{ - switch (status) - { - case Job::Running: - return i18nc("The transfer is running", "Running"); - case Job::Stopped: - return i18nc("The transfer is stopped", "Stopped"); - case Job::Aborted: - return i18nc("The transfer is aborted", "Aborted"); - case Job::Finished: - return i18nc("The transfer is finished", "Finished"); - default: - return QString(); - } -} - -void TransferHistory::slotLoadRangeType(int type) -{ - m_rangeType = type; - if (m_iconModeEnabled) { - TransferHistoryCategorizedView *cat_view = qobject_cast (m_view); - cat_view->clear(); - switch(type) - { - case TransferHistory::Size : - cat_view->setCategorizedDelegate(new SizeCategorizedDelegate()); - break; - case TransferHistory::Date : - cat_view->setCategorizedDelegate(new DateCategorizedDelegate()); - break; - default: - cat_view->setCategorizedDelegate(new HostCategorizedDelegate()); - } - } else { - RangeTreeWidget *range_view = qobject_cast (m_view); - QFontMetrics *font = new QFontMetrics(KGlobalSettings::generalFont()); - range_view->clear(); - - range_view->setLabels(QStringList() << i18n("Source File") << i18n("Destination") << i18n("Time") << i18n("File Size") << i18n("Status")); - range_view->setRangeDelegate(0); - - switch(m_rangeType) - { - case TransferHistory::Host : - range_view->setRangeDelegate(new HostRangeDelegate(this)); - break; - case TransferHistory::Size : - range_view->addRange(QVariant(0), QVariant(1024 * 1024), - i18n("Less than 1MiB")); - range_view->addRange(QVariant(1024 * 1024), QVariant(1024 * 1024 * 10), - i18n("Between 1MiB-10MiB")); - range_view->addRange(QVariant(1024 * 1024 * 10), QVariant(1024 * 1024 * 100), - i18n("Between 10MiB-100MiB")); - range_view->addRange(QVariant(1024 * 1024 * 100), QVariant(1024 * 1024 *1024), - i18n("Between 100MiB-1GiB")); - range_view->addRange(QVariant((double) 1024 * 1024 * 1024), QVariant((double) 1024 * 1024 * 1024 * 10), - i18n("More than 1GiB")); - break; - default: - range_view->addRange(QVariant(0), QVariant(1), i18n("Today")); - range_view->addRange(QVariant(1), QVariant(7), i18n("Last week")); - range_view->addRange(QVariant(7), QVariant(30), i18n("Last month")); - range_view->addRange(QVariant(30), QVariant(-1), i18n("A long time ago")); - } - - QList list = Settings::historyColumnWidths(); - - if (!list.isEmpty()) - { - int j = 0; - foreach (int i, list) - { - range_view->setColumnWidth(j, i); - j++; - } - } - else - { - range_view->setColumnWidth(0, 200); - range_view->setColumnWidth(1, 250); - range_view->setColumnWidth(2, font->width(QDate::currentDate().toString())); - range_view->setColumnWidth(3, font->width("1500000 KiB")); - range_view->setColumnWidth(4, font->width(i18nc("the transfer has been finished", "Finished"))); - } - } - - slotAddTransfers(); -} - -void TransferHistory::slotSetListMode() -{ - m_iconModeEnabled = false; - delete m_view; - m_view = new RangeTreeWidget(this); - m_verticalLayout->insertWidget(1, m_view); - slotLoadRangeType(m_rangeType); - - connect(m_searchBar, SIGNAL(textChanged(QString)), m_view, SLOT(setFilterRegExp(QString))); - // we connect the doubleClicked signal over an item to the open file action - connect(m_view, SIGNAL(doubleClicked(QModelIndex)), SLOT(slotOpenFile(QModelIndex))); -} - -void TransferHistory::slotSetIconMode() -{ - m_iconModeEnabled = true; - delete m_view; - m_view = new TransferHistoryCategorizedView(this); - m_verticalLayout->insertWidget(1, m_view); - slotLoadRangeType(m_rangeType); - - connect(m_searchBar, SIGNAL(textChanged(QString)), m_view, SLOT(setFilterRegExp(QString))); - connect(m_view, SIGNAL(deletedTransfer(QString,QModelIndex)), - SLOT(slotDeleteTransfer(QString,QModelIndex))); - connect(m_view, SIGNAL(doubleClicked(QModelIndex)), SLOT(slotOpenFile(QModelIndex))); -} - -void TransferHistory::slotElementLoaded(int number, int total, const TransferHistoryItem &item) -{ - m_progressBar->setValue(number*100/total); - - if (m_iconModeEnabled) { - ((TransferHistoryCategorizedView *) m_view)->addData( - item.dateTime().date(), item.source(), item.dest(), item.size()); - } - else { - QVariantList attributeList; - attributeList.append(item.source()); - attributeList.append(item.dest()); - attributeList.append(item.dateTime().date().toString()); - attributeList.append(KIO::convertSize(item.size())); - attributeList.append(statusText(item.state())); - - QVariant data; - if(m_rangeType == TransferHistory::Date) { - QDate date = item.dateTime().date(); - data = QVariant(date.daysTo(QDate::currentDate())); - } - else if(m_rangeType == TransferHistory::Host) { - data = QVariant(item.source()); - } - else { - data = QVariant(item.size()); - } - ((RangeTreeWidget *) m_view)->add(data, attributeList); - } -} - -void TransferHistory::slotLoadFinished() -{ - m_progressBar->hide(); -} diff --git a/kget/ui/history/transferhistory.h b/kget/ui/history/transferhistory.h deleted file mode 100644 index e278828f..00000000 --- a/kget/ui/history/transferhistory.h +++ /dev/null @@ -1,83 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2007 by Lukas Appelhans - - 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. -*/ - -#ifndef TRANSFERHISTORY_H -#define TRANSFERHISTORY_H - -#include -#include "../../core/basedialog.h" - -#include "ui_transferhistory.h" - -#include -#include -#include -class KLineEdit; -class KPushButton; -class TransferHistoryStore; -class TransferHistoryItem; - -class TransferHistory : public KGetSaveSizeDialog, Ui::TransferHistory -{ - Q_OBJECT - - public: - TransferHistory(QWidget *parent = 0); - ~TransferHistory(); - - virtual QSize sizeHint() const; - - private: - enum RangeType { - Date = 0, - Size = 1, - Host = 2 - }; - void hideEvent(QHideEvent *event); - QString statusText(int status) const; - - bool save; - QFileSystemWatcher *watcher; - int m_rangeType; - QWidget *m_view; - QProgressBar *m_progressBar; - QVBoxLayout *m_verticalLayout; - KComboBox *m_rangeTypeCombobox; - QHBoxLayout *m_hboxLayout; - KLineEdit *m_searchBar; - QAction *m_actionDelete_Selected; - QAction *m_actionClear; - QAction *m_actionDownload; - QAction *m_openFile; - QPushButton *m_clearButton; - KPushButton *m_iconView; - KPushButton *m_listView; - bool m_iconModeEnabled; - TransferHistoryStore *m_store; - - public slots: - void slotDeleteTransfer(const QString &url, const QModelIndex &index = QModelIndex()); - - private slots: - void slotDeleteTransfer(); - void slotAddTransfers(); - void slotClear(); - void slotWriteDefault(); - void slotDownload(); - void slotOpenFile(const QModelIndex &index = QModelIndex()); - void contextMenuEvent(QContextMenuEvent *event); - void slotLoadRangeType(int type); - void slotSetListMode(); - void slotSetIconMode(); - void slotElementLoaded(int number, int total, const TransferHistoryItem &item); - void slotLoadFinished(); -}; - -#endif diff --git a/kget/ui/history/transferhistory.ui b/kget/ui/history/transferhistory.ui deleted file mode 100644 index 7fca1b93..00000000 --- a/kget/ui/history/transferhistory.ui +++ /dev/null @@ -1,147 +0,0 @@ - - - TransferHistory - - - - 0 - 0 - 708 - 41 - - - - - - - - - 0 - - - 0 - - - - - Clear History - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - View Modes: - - - - - - - true - - - true - - - true - - - - - - - true - - - true - - - - - - - Select Ranges: - - - - - - - - Date - - - - - Size - - - - - Host - - - - - - - - - - - Filter history - - - true - - - - - - - - - - - Delete Selected - - - - - Download - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KPushButton - QPushButton -
kpushbutton.h
-
-
- -
diff --git a/kget/ui/history/transferhistorycategorizeddelegate.cpp b/kget/ui/history/transferhistorycategorizeddelegate.cpp deleted file mode 100644 index bb7796af..00000000 --- a/kget/ui/history/transferhistorycategorizeddelegate.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ -#include "transferhistorycategorizeddelegate.h" - -#include - -#include -#include -#include -#include - -#include - -TransferHistoryCategorizedDelegate::TransferHistoryCategorizedDelegate() -{ -} - -TransferHistoryCategorizedDelegate::~TransferHistoryCategorizedDelegate() -{ -} - -DateCategorizedDelegate::DateCategorizedDelegate() : TransferHistoryCategorizedDelegate() -{ -} - -DateCategorizedDelegate::~DateCategorizedDelegate() -{ -} - -void DateCategorizedDelegate::categorizeItem(QStandardItem *item) -{ - int categorySort = 0; - - QDate date = item->data(TransferHistoryCategorizedDelegate::RoleDate).toDate(); - QVariant value; - - if (date == QDate::currentDate()) { - value = QVariant(i18n("Today")); - } - else if (date.daysTo(QDate::currentDate()) <= 7) { - categorySort = 1; - value = QVariant(i18n("Last week")); - } - else if (date.daysTo(QDate::currentDate()) <= 30) { - categorySort = 2; - value = QVariant(i18n("Last Month")); - } - else { - categorySort = 3; - value = QVariant(i18n("A long time ago")); - } - - item->setData(value, KCategorizedSortFilterProxyModel::CategoryDisplayRole); - item->setData(categorySort, KCategorizedSortFilterProxyModel::CategorySortRole); -} - -SizeCategorizedDelegate::SizeCategorizedDelegate() : TransferHistoryCategorizedDelegate() -{} - -SizeCategorizedDelegate::~SizeCategorizedDelegate() -{} - -void SizeCategorizedDelegate::categorizeItem(QStandardItem *item) -{ - int size = item->data(TransferHistoryCategorizedDelegate::RoleSize).toInt(); - int categorySort = 0; - QVariant value; - - if (size < 10 * 1024 * 1024) { - value = QVariant(i18n("Under 10MiB")); - } - else if (size >= 10 * 1024 * 1024 && size < 50 * 1024 * 1024) { - value = QVariant(i18n("Between 10MiB and 50MiB")); - categorySort = 1; - } - else if (size >= 50 * 1024 * 1024 && size < 100 * 1024 * 1024) { - value = QVariant(i18n("Between 50MiB and 100MiB")); - categorySort = 2; - } - else { - categorySort = 3; - value = QVariant(i18n("More than 100MiB")); - } - - item->setData(value, KCategorizedSortFilterProxyModel::CategoryDisplayRole); - item->setData(categorySort, KCategorizedSortFilterProxyModel::CategorySortRole); -} - -HostCategorizedDelegate::HostCategorizedDelegate() : TransferHistoryCategorizedDelegate() -{ -} - -HostCategorizedDelegate::~HostCategorizedDelegate() -{ -} - -void HostCategorizedDelegate::categorizeItem(QStandardItem *item) -{ - QUrl host(item->data(TransferHistoryCategorizedDelegate::RoleUrl).toString()); - - item->setData(host.host(), KCategorizedSortFilterProxyModel::CategoryDisplayRole); - item->setData(host.host(), KCategorizedSortFilterProxyModel::CategorySortRole); -} diff --git a/kget/ui/history/transferhistorycategorizeddelegate.h b/kget/ui/history/transferhistorycategorizeddelegate.h deleted file mode 100644 index 2d52d908..00000000 --- a/kget/ui/history/transferhistorycategorizeddelegate.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ - -#ifndef TRANSFERHISTORYCATEGORIZEDDELEGATE_H -#define TRANSFERHISTORYCATEGORIZEDDELEGATE_H - -#include - -#include - -class TransferHistoryCategorizedDelegate : public QObject -{ -Q_OBJECT -public: - enum AlternativeRoles { - RoleSize = 0xFF, - RoleDate = 0xFE, - RoleUrl = 0xFD, - RoleDest = 0xFA - }; - - TransferHistoryCategorizedDelegate(); - ~TransferHistoryCategorizedDelegate(); - - virtual void categorizeItem(QStandardItem *item) - { - Q_UNUSED(item) - }; -}; - -/** Categorizes the transfers in date ranges **/ -class DateCategorizedDelegate : public TransferHistoryCategorizedDelegate -{ -public: - DateCategorizedDelegate(); - ~DateCategorizedDelegate(); - - void categorizeItem(QStandardItem *item); -}; - -/** Categorzes the transfers in size ranges **/ -class SizeCategorizedDelegate : public TransferHistoryCategorizedDelegate -{ -public: - SizeCategorizedDelegate(); - ~SizeCategorizedDelegate(); - - void categorizeItem(QStandardItem *item); -}; - -/** Categorizes the transfer by source host **/ -class HostCategorizedDelegate : public TransferHistoryCategorizedDelegate -{ -public: - HostCategorizedDelegate(); - ~HostCategorizedDelegate(); - - void categorizeItem(QStandardItem *item); -}; - -#endif diff --git a/kget/ui/history/transferhistorycategorizedview.cpp b/kget/ui/history/transferhistorycategorizedview.cpp deleted file mode 100644 index d8889a76..00000000 --- a/kget/ui/history/transferhistorycategorizedview.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ -#include "transferhistorycategorizedview.h" -#include "ui/history/transferhistoryitemdelegate.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -TransferHistoryCategorizedView::TransferHistoryCategorizedView(QWidget *parent) - : QWidget(parent) -{ - // the widget layout - QGridLayout *layout = new QGridLayout(); - - // initialize the model - m_model = new QStandardItemModel(); - - // the kcategoryizedview list - TransferHistoryItemDelegate *item_delegate = new TransferHistoryItemDelegate(this); - m_drawer = new KCategoryDrawer(); - m_view = new KCategorizedView(this); - m_view->setCategoryDrawer(m_drawer); - m_view->setSelectionMode(QAbstractItemView::SingleSelection); - m_view->setSpacing(KDialog::spacingHint()); - m_view->setViewMode(QListView::IconMode); - m_view->setMouseTracking(true); - m_view->setItemDelegate(item_delegate); - m_view->setEditTriggers(QAbstractItemView::NoEditTriggers); - layout->addWidget(m_view, 0, 0); - - // the proxy sort filter model and the categorized delegate - m_delegate = new DateCategorizedDelegate(); - m_proxyModel = new KCategorizedSortFilterProxyModel(); - m_proxyModel->setCategorizedModel(true); - m_proxyModel->sort(0); - m_proxyModel->setSourceModel(m_model); - m_view->setModel(m_proxyModel); - - connect(item_delegate, SIGNAL(deletedTransfer(QString,QModelIndex)), - SIGNAL(deletedTransfer(QString,QModelIndex))); - connect(m_view, SIGNAL(doubleClicked(QModelIndex)), SIGNAL(doubleClicked(QModelIndex))); - setLayout(layout); -} - -TransferHistoryCategorizedView::~TransferHistoryCategorizedView() -{ -} - -void TransferHistoryCategorizedView::addData(const QDate &date, const QString &url, const QString &dest, int size) -{ - QStandardItem *item = new QStandardItem(url); - item->setData(QVariant(size), TransferHistoryCategorizedDelegate::RoleSize); - item->setData(QVariant(url), TransferHistoryCategorizedDelegate::RoleUrl); - item->setData(QVariant(dest), TransferHistoryCategorizedDelegate::RoleDest); - item->setData(QVariant(date), TransferHistoryCategorizedDelegate::RoleDate); - - m_delegate->categorizeItem(item); - m_model->appendRow(item); -} - -QVariant TransferHistoryCategorizedView::data(const QModelIndex &index, - TransferHistoryCategorizedDelegate::AlternativeRoles role) const -{ - return m_model->itemFromIndex(m_proxyModel->mapToSource(index))->data(role); -} - -void TransferHistoryCategorizedView::clear() -{ - m_model->clear(); -} - -void TransferHistoryCategorizedView::setFilterRegExp(const QString &text) -{ - m_proxyModel->setFilterRegExp(text); -} - -void TransferHistoryCategorizedView::setCategorizedDelegate(TransferHistoryCategorizedDelegate *delegate) -{ - delete m_delegate; - m_delegate = delegate; - - update(); -} - -void TransferHistoryCategorizedView::removeRow(int row, const QModelIndex &parent) -{ - m_model->removeRow(row, parent); -} - -void TransferHistoryCategorizedView::update() -{ - for(int i=0; irowCount(); i++) { - QStandardItem *item = m_model->item(i, 0); - - m_delegate->categorizeItem(item); - } - - m_proxyModel = new KCategorizedSortFilterProxyModel(this); - m_proxyModel->setCategorizedModel(true); - m_proxyModel->sort(0); - m_proxyModel->setSourceModel(m_model); - QAbstractItemModel *oldProxy = m_view->model(); - m_view->setModel(m_proxyModel); - oldProxy->deleteLater(); -} - -#include "moc_transferhistorycategorizedview.cpp" diff --git a/kget/ui/history/transferhistorycategorizedview.h b/kget/ui/history/transferhistorycategorizedview.h deleted file mode 100644 index 7370065b..00000000 --- a/kget/ui/history/transferhistorycategorizedview.h +++ /dev/null @@ -1,56 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Javier Goday - - 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. -*/ - -#ifndef TRANSFERHISTORYCATEGORIZEDVIEW_H -#define TRANSFERHISTORYCATEGORIZEDVIEW_H - -#include "ui/history/transferhistorycategorizeddelegate.h" - -#include -#include - -#include -#include -class KCategorizedView; -class KCategoryDrawer; -class KCategorizedSortFilterProxyModel; - -class TransferHistoryCategorizedView : public QWidget -{ -Q_OBJECT -public: - - TransferHistoryCategorizedView(QWidget *parent = 0); - ~TransferHistoryCategorizedView(); - - void addData(const QDate &date, const QString &url, const QString &dest, int size); - QVariant data(const QModelIndex &index, TransferHistoryCategorizedDelegate::AlternativeRoles role) const; - -signals: - void deletedTransfer(const QString &url, const QModelIndex &index); - void doubleClicked(const QModelIndex &); - -public slots: - void clear(); - void setFilterRegExp(const QString &text); - void setCategorizedDelegate(TransferHistoryCategorizedDelegate *m_delegate); - void removeRow(int row, const QModelIndex &parent = QModelIndex()); - -private slots: - void update(); - -private: - QStandardItemModel *m_model; - KCategorizedView *m_view; - KCategoryDrawer *m_drawer; - KCategorizedSortFilterProxyModel *m_proxyModel; - TransferHistoryCategorizedDelegate *m_delegate; -}; -#endif diff --git a/kget/ui/history/transferhistoryitemdelegate.cpp b/kget/ui/history/transferhistoryitemdelegate.cpp deleted file mode 100644 index 30c6353c..00000000 --- a/kget/ui/history/transferhistoryitemdelegate.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* This file is part of the KDE project - - Based in the kcategorizeditemsviewdelegate from kdebase/workspace/libs/plasma/appletbrowser by Ivan Cukic - Copyright (C) 2008 Javier Goday - - 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. -*/ - -#include "transferhistoryitemdelegate.h" -#include "ui/history/transferhistorycategorizeddelegate.h" -#include "ui/history/transferhistorycategorizedview.h" -#include "ui/newtransferdialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -TransferHistoryItemDelegate::TransferHistoryItemDelegate(QWidget *parent) : QStyledItemDelegate(), - m_selectedIndex() -{ - m_view = parent; - - // Actions - m_actionDownload = new QAction(this); - m_actionDownload->setText(i18n("Download again")); - m_actionDownload->setIcon(KIcon("document-new")); - connect(m_actionDownload, SIGNAL(triggered()), SLOT(slotDownload())); - - m_actionDelete_Selected = new QAction(this); - m_actionDelete_Selected->setText(i18nc("Delete selected history-item", "Delete selected")); - m_actionDelete_Selected->setIcon(KIcon("edit-delete")); - connect(m_actionDelete_Selected, SIGNAL(triggered()), SLOT(slotDeleteTransfer())); - - m_openFile = new QAction(this); - m_openFile->setText(i18n("Open file")); - m_openFile->setIcon(KIcon("document-open")); - connect(m_openFile, SIGNAL(triggered()), SLOT(slotOpenFile())); -} - -TransferHistoryItemDelegate::~TransferHistoryItemDelegate() -{ -} - -void TransferHistoryItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (!option.state.testFlag(QStyle::State_Selected) && !option.state.testFlag(QStyle::State_MouseOver)) { - // draw a separator - painter->save(); - - QRect roundRect(option.rect.left() + 1, option.rect.top() + 1, - option.rect.width() - 2, option.rect.height() - 2); - - QPainterPath path; - path.addRoundRect(roundRect, 2, 2); - QLinearGradient gradient(roundRect.left(), roundRect.top(), - roundRect.left(), roundRect.bottom()); - gradient.setColorAt(0, Qt::transparent); - gradient.setColorAt(0.95, option.palette.color(QPalette::AlternateBase).darker(130)); - QBrush brush(gradient); - - painter->fillPath(path, brush); - - painter->setPen(option.palette.color(QPalette::AlternateBase).darker(190)); - painter->drawRoundRect(roundRect, 2, 2); - painter->restore(); - } - - QStyleOptionViewItemV4 opt(option); - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); - - const QAbstractItemModel *model = static_cast (index.model()); - QUrl url(model->data(index, TransferHistoryCategorizedDelegate::RoleUrl).toString()); - QString name = url.path().mid(url.path().lastIndexOf("/") + 1); - KIcon icon(KIO::pixmapForUrl( - model->data(index, TransferHistoryCategorizedDelegate::RoleDest).toString(), - 0, KIconLoader::Panel)); - QString size = KIO::convertSize(model->data(index, TransferHistoryCategorizedDelegate::RoleSize).toInt()); - QString date = model->data(index, TransferHistoryCategorizedDelegate::RoleDate).toDate().toString("dd.MM.yyyy"); - QString host = url.host(); - - // draw the host - painter->save(); - painter->setPen(option.palette.color(QPalette::Link)); - // draw the host - painter->drawText(option.rect.left() + PADDING, - option.rect.top() + PADDING, - option.rect.width() - PADDING * 2, 15, - Qt::AlignTop | Qt::AlignLeft, host); - painter->restore(); - - // draw the transfer icon - icon.paint(painter, - option.rect.left() + option.rect.width() / 2 - ICON_SIZE / 2, - option.rect.top() + option.rect.height() / 2 - ICON_SIZE / 2 - PADDING * 2, - ICON_SIZE, ICON_SIZE, Qt::AlignCenter, QIcon::Active); - - painter->save(); - QColor subcolor = (option.state.testFlag(QStyle::State_Selected) || (option.state.testFlag(QStyle::State_MouseOver))) ? - option.palette.color(QPalette::Text) : - option.palette.color(QPalette::BrightText); - - // draw a separator line between the file name and his size and date - painter->setPen(option.palette.color(QPalette::AlternateBase).darker(190)); - painter->drawLine(option.rect.left() + 2, option.rect.bottom() + PADDING - 27, - option.rect.right() - 2, option.rect.bottom() + PADDING - 27); - painter->setPen(subcolor); - // draw the size - painter->drawText(option.rect.right() - PADDING - 100, - option.rect.bottom() + PADDING - 25, - 100 - PADDING * 2, 25, - Qt::AlignTop | Qt::AlignRight, size); - - // draw the date - painter->drawText(option.rect.left() + PADDING, - option.rect.bottom() + PADDING - 25, - 100 - PADDING * 2, 25, - Qt::AlignTop | Qt::AlignLeft, date); - - painter->restore(); - - // draw the filenamne - painter->save(); - QColor foregroundColor = (option.state.testFlag(QStyle::State_Selected)) ? - option.palette.color(QPalette::HighlightedText):option.palette.color(QPalette::Text); - painter->setPen(foregroundColor); - painter->setFont(option.font); - painter->drawText(option.rect.left() + PADDING, - option.rect.bottom() - PADDING - 35, - 200 - PADDING * 2, 15, - Qt::AlignBottom | Qt::AlignCenter, name); - painter->restore(); -} - -QSize TransferHistoryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - Q_UNUSED(index) - - return QSize(200, 110); -} - -bool TransferHistoryItemDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, - const QStyleOptionViewItem &option, const QModelIndex & index) -{ - Q_UNUSED(option) - Q_UNUSED(model) - - QMouseEvent * mouseEvent = dynamic_cast(event); - - if(mouseEvent && index.isValid()) { - if(mouseEvent->button() == Qt::RightButton) { - m_selectedIndex = index; - - QMenu *contextMenu = new QMenu(); - contextMenu->addAction(m_actionDownload); - contextMenu->addAction(m_actionDelete_Selected); - contextMenu->addAction(m_openFile); - - contextMenu->exec(QCursor::pos()); - } - } - - return false; -} - - -void TransferHistoryItemDelegate::slotOpenFile() -{ - const QAbstractItemModel *model = static_cast (m_selectedIndex.model()); - - new KRun(model->data(m_selectedIndex, TransferHistoryCategorizedDelegate::RoleDest).toString(), m_view, true, false); -} - -void TransferHistoryItemDelegate::slotDownload() -{ - const QAbstractItemModel *model = static_cast (m_selectedIndex.model()); - - NewTransferDialogHandler::showNewTransferDialog(model->data(m_selectedIndex, - TransferHistoryCategorizedDelegate::RoleUrl).toString()); -} - -void TransferHistoryItemDelegate::slotDeleteTransfer() -{ - const QAbstractItemModel *model = static_cast (m_selectedIndex.model()); - - emit deletedTransfer(model->data(m_selectedIndex, TransferHistoryCategorizedDelegate::RoleUrl).toString(), m_selectedIndex); -} - -#include "moc_transferhistoryitemdelegate.cpp" diff --git a/kget/ui/history/transferhistoryitemdelegate.h b/kget/ui/history/transferhistoryitemdelegate.h deleted file mode 100644 index 74ffd2af..00000000 --- a/kget/ui/history/transferhistoryitemdelegate.h +++ /dev/null @@ -1,52 +0,0 @@ -/* This file is part of the KDE project - - Based in the kcategorizeditemsviewdelegate from kdebase/workspace/libs/plasma/appletbrowser by Ivan Cukic - Copyright (C) 2008 Javier Goday - - 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. -*/ -#ifndef TRANSFERHISTORYITEMDELEGATE_H -#define TRANSFERHISTORYITEMDELEGATE_H - -#include -#include - -#define ICON_SIZE 40 -#define PADDING 5 - -#include -#include - -class TransferHistoryItemDelegate : public QStyledItemDelegate -{ -Q_OBJECT -public: - TransferHistoryItemDelegate(QWidget *parent); - ~TransferHistoryItemDelegate(); - - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - bool editorEvent(QEvent * event, QAbstractItemModel * model, - const QStyleOptionViewItem & option, const QModelIndex & index); - -signals: - void deletedTransfer(const QString &url, const QModelIndex &index); - -private slots: - void slotOpenFile(); - void slotDownload(); - void slotDeleteTransfer(); - -private: - QWidget *m_view; - QAction *m_actionDelete_Selected; - QAction *m_actionDownload; - QAction *m_openFile; - - QModelIndex m_selectedIndex; -}; -#endif diff --git a/kget/ui/icons/CMakeLists.txt b/kget/ui/icons/CMakeLists.txt deleted file mode 100644 index 64266d49..00000000 --- a/kget/ui/icons/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -kde4_install_icons(${KDE4_ICON_INSTALL_DIR}) diff --git a/kget/ui/icons/hi128-apps-kget.png b/kget/ui/icons/hi128-apps-kget.png deleted file mode 100644 index 5b2cc39f..00000000 Binary files a/kget/ui/icons/hi128-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hi16-apps-kget.png b/kget/ui/icons/hi16-apps-kget.png deleted file mode 100644 index 05de9e25..00000000 Binary files a/kget/ui/icons/hi16-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hi22-apps-kget.png b/kget/ui/icons/hi22-apps-kget.png deleted file mode 100644 index 44954d6e..00000000 Binary files a/kget/ui/icons/hi22-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hi32-apps-kget.png b/kget/ui/icons/hi32-apps-kget.png deleted file mode 100644 index b6180137..00000000 Binary files a/kget/ui/icons/hi32-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hi48-apps-kget.png b/kget/ui/icons/hi48-apps-kget.png deleted file mode 100644 index 80debda7..00000000 Binary files a/kget/ui/icons/hi48-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hi64-apps-kget.png b/kget/ui/icons/hi64-apps-kget.png deleted file mode 100644 index 6396fd36..00000000 Binary files a/kget/ui/icons/hi64-apps-kget.png and /dev/null differ diff --git a/kget/ui/icons/hisc-apps-kget.svgz b/kget/ui/icons/hisc-apps-kget.svgz deleted file mode 100644 index a1f9cb9a..00000000 Binary files a/kget/ui/icons/hisc-apps-kget.svgz and /dev/null differ diff --git a/kget/ui/icons/small/hi16-apps-kget.svgz b/kget/ui/icons/small/hi16-apps-kget.svgz deleted file mode 100644 index 7add5d42..00000000 Binary files a/kget/ui/icons/small/hi16-apps-kget.svgz and /dev/null differ diff --git a/kget/ui/icons/small/hi22-apps-kget.svgz b/kget/ui/icons/small/hi22-apps-kget.svgz deleted file mode 100644 index e3b04b43..00000000 Binary files a/kget/ui/icons/small/hi22-apps-kget.svgz and /dev/null differ diff --git a/kget/ui/kgetui.rc b/kget/ui/kgetui.rc deleted file mode 100644 index dc569ec8..00000000 --- a/kget/ui/kgetui.rc +++ /dev/null @@ -1,46 +0,0 @@ - - - - &File - - - - - - - - - - - &Downloads - - - - - - - - - - - - - - - - - &Settings - - - &Help - - -Main Toolbar - - - - - - - - diff --git a/kget/ui/linkview/importlinkdialog.ui b/kget/ui/linkview/importlinkdialog.ui deleted file mode 100644 index 25bd5e4c..00000000 --- a/kget/ui/linkview/importlinkdialog.ui +++ /dev/null @@ -1,269 +0,0 @@ - - - ImportLinkDialog - - - - 0 - 0 - 750 - 407 - - - - - - - - 0 - - - - - - - &File with links to import: - - - urlRequester - - - - - - - - - - false - - - &Import Links - - - - - - - - - - - - - - - - - Show: - - - - - - - - - - Show &web content - - - true - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 25 - 0 - - - - You can use wildcards for filtering. - - - Filter files here.... - - - true - - - - - - - - - - - - QAbstractItemView::NoEditTriggers - - - true - - - QAbstractItemView::ExtendedSelection - - - false - - - true - - - true - - - false - - - - - - - true - - - 0 - - - true - - - - - - - Qt::Horizontal - - - - - - - - - false - - - - 0 - 0 - - - - &Select All - - - - - - - false - - - - 0 - 0 - - - - D&eselect All - - - - - - - false - - - - 0 - 0 - - - - Inver&t Selection - - - - - - - QDialogButtonBox::Cancel - - - - - - - - - - KDialogButtonBox - QDialogButtonBox -
kdialogbuttonbox.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KSeparator - QFrame -
kseparator.h
-
- - KPushButton - QPushButton -
kpushbutton.h
-
- - KUrlRequester - QFrame -
kurlrequester.h
-
-
- - urlRequester - importLinks - textFilter - filterMode - deselectAll - invertSelection - treeView - - -
diff --git a/kget/ui/linkview/kget_linkview.cpp b/kget/ui/linkview/kget_linkview.cpp deleted file mode 100644 index 7f4ff6d8..00000000 --- a/kget/ui/linkview/kget_linkview.cpp +++ /dev/null @@ -1,481 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 Carsten Pfeiffer - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ - -#include "kget_linkview.h" -#include "settings.h" -#include "kget_sortfilterproxymodel.h" -#include "core/kget.h" -#include "core/linkimporter.h" -#include "ui/newtransferdialog.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -KGetLinkView::KGetLinkView(QWidget *parent) - : KGetSaveSizeDialog("KGetLinkView", parent), - m_linkImporter(0), - m_nameAction(0), - m_urlAction(0) -{ - setAttribute(Qt::WA_DeleteOnClose); - setCaption(i18n("Import Links")); - setButtons(0); - - if (parent) { - KWindowInfo info = KWindowSystem::windowInfo(parent->winId(), NET::WMDesktop, NET::WMDesktop); - KWindowSystem::setCurrentDesktop(info.desktop()); - KWindowSystem::forceActiveWindow(parent->winId()); - } - - // proxy model to filter links - m_proxyModel = new KGetSortFilterProxyModel(1, this); - m_proxyModel->setDynamicSortFilter(true); - m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); - - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - - m_proxyModel->setShowWebContent(ui.showWebContent->isChecked()); - - ui.filterMode->addItem(i18n("Contains"), KGetSortFilterProxyModel::Contain); - ui.filterMode->addItem(i18n("Does Not Contain"), KGetSortFilterProxyModel::DoesNotContain); - - // set the Icons - ui.importLinks->setIcon(KIcon("document-import")); - ui.showCombo->addItem(KIcon("view-list-icons"), i18n("All"), KGetSortFilterProxyModel::NoFilter); - ui.showCombo->addItem(KIcon("video-x-generic"), i18n("Videos"), KGetSortFilterProxyModel::VideoFiles); - ui.showCombo->addItem(KIcon("image-x-generic"), i18n("Images"), KGetSortFilterProxyModel::ImageFiles); - ui.showCombo->addItem(KIcon("audio-x-generic"), i18n("Audio"), KGetSortFilterProxyModel::AudioFiles); - ui.showCombo->addItem(KIcon("package-x-generic"), i18n("Archives"), KGetSortFilterProxyModel::CompressedFiles ); - - ui.treeView->setModel(m_proxyModel); - ui.progressBar->hide(); - - //creates pattern syntax menu for the text filter - m_patternSyntaxMenu = new QMenu(i18nc("of a filter, e.g. RegExp or Wildcard", "Pattern Syntax"), this); - QAction *wildcardAction = new QAction(i18n("Escape Sequences"), this); - wildcardAction->setCheckable(true); - wildcardAction->setChecked(Settings::linkViewFilterPatternSyntax() == Wildcard); - QAction *regExpAction = new QAction(i18n("Regular Expression"), this); - regExpAction->setCheckable(true); - regExpAction->setChecked(Settings::linkViewFilterPatternSyntax() == RegExp); - QActionGroup *actionGroup = new QActionGroup(this); - actionGroup->addAction(wildcardAction); - actionGroup->addAction(regExpAction); - m_patternSyntaxMenu->addActions(actionGroup->actions()); - - //Filter for name/url actions - QActionGroup *columnGroup = new QActionGroup(this); - m_nameAction = new KAction(i18nc("name of a file", "Name"), this); - m_nameAction->setCheckable(true); - m_nameAction->setChecked(true); - m_urlAction = new KAction(i18n("URL"), this); - m_urlAction->setCheckable(true); - columnGroup->addAction(m_nameAction); - columnGroup->addAction(m_urlAction); - connect(columnGroup, SIGNAL(triggered(QAction*)), this, SLOT(slotFilterColumn(QAction*))); - - connect(wildcardAction, SIGNAL(toggled(bool)), this, SLOT(wildcardPatternToggled(bool))); - connect(ui.treeView, SIGNAL(doubleClicked(QModelIndex)), - this, SLOT(uncheckItem(QModelIndex))); - connect(ui.textFilter, SIGNAL(textChanged(QString)), SLOT(setTextFilter(QString))); - connect(ui.textFilter, SIGNAL(aboutToShowContextMenu(QMenu*)), this, SLOT(contextMenuDisplayed(QMenu*))); - connect(ui.filterMode, SIGNAL(currentIndexChanged(int)), this, SLOT(slotFilterModeChanged(int))); - connect(ui.showCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotMimeTypeChanged(int))); - connect(ui.showCombo, SIGNAL(currentIndexChanged(int)), SLOT(updateSelectionButtons())); - connect(ui.urlRequester, SIGNAL(textChanged(QString)), SLOT(updateImportButtonStatus(QString))); - connect(ui.urlRequester, SIGNAL(urlSelected(KUrl)), SLOT(slotStartImport())); - connect(ui.selectAll, SIGNAL(clicked()), this, SLOT(checkAll())); - connect(ui.deselectAll, SIGNAL(clicked()), this, SLOT(uncheckAll())); - connect(ui.invertSelection, SIGNAL(clicked()), this, SLOT(slotInvertSelection())); - connect(this, SIGNAL(accepted()), this, SLOT(slotStartLeech())); - connect(ui.showWebContent, SIGNAL(stateChanged(int)), m_proxyModel, SLOT(setShowWebContent(int))); - connect(ui.importLinks, SIGNAL(clicked()), this, SLOT(slotStartImport())); - connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - SLOT(selectionChanged())); - connect(ui.dialogButtonBox, SIGNAL(rejected()), SLOT(reject())); - - setMainWidget(widget); - QPushButton *download = ui.dialogButtonBox->addButton(i18nc("Download the items which have been selected","&Download"), - QDialogButtonBox::AcceptRole, - this, - SLOT(accept())); - download->setIcon(KIcon("kget")); - - checkClipboard(); -} - -KGetLinkView::~KGetLinkView() -{ - delete(m_linkImporter); -} - -void KGetLinkView::checkClipboard() -{ - QString clipboardContent = QApplication::clipboard()->text(QClipboard::Clipboard); - - if (clipboardContent.length() > 0) - { - delete m_linkImporter; - - m_linkImporter = new LinkImporter(this); - - connect(m_linkImporter, SIGNAL(finished()), SLOT(slotImportFinished())); - m_linkImporter->checkClipboard(clipboardContent); - } -} - -void KGetLinkView::setLinks(const QStringList &links) -{ - m_links = links; - showLinks(m_links, false); -} - -void KGetLinkView::showLinks(const QStringList &links, bool urlRequestVisible) -{ - ui.importWidget->setVisible(urlRequestVisible); - - QStandardItemModel *model = new QStandardItemModel(0, 5, this); - - model->setHeaderData(0, Qt::Horizontal, i18n("Auxiliary header")); - model->setHeaderData(1, Qt::Horizontal, i18n("File Name")); - model->setHeaderData(2, Qt::Horizontal, i18n("Description")); - model->setHeaderData(3, Qt::Horizontal, i18nc("list header: type of file", "File Type")); - model->setHeaderData(4, Qt::Horizontal, i18n("Location (URL)")); - - foreach (const QString &linkitem, links) - { - KUrl url; - KMimeType::Ptr mt; - - if (linkitem.contains(QLatin1String("url "), Qt::CaseInsensitive) && - linkitem.contains(QLatin1String("type "), Qt::CaseInsensitive)) { - const QStringList items = linkitem.split(QLatin1Char(' '), QString::SkipEmptyParts); - const int count = items.count(); - int index = items.indexOf(QLatin1String("url")); - if (index > -1 && index+1 < count) - url = items.at(index+1); - index = items.indexOf(QLatin1String("type")); - if (index > -1 && index+1 < count) - mt = KMimeType::mimeType(items.at(index+1)); - } else { - url = linkitem; - mt = KMimeType::findByUrl(linkitem, 0, true, true); - } - - kDebug() << "Adding:" << linkitem; - - QString file = url.fileName(); - if (file.isEmpty()) - file = QString(url.host()); - - QString mimeTypeName, mimeTypeIcon, mimeTypeComment; - if (mt) { - mimeTypeName = mt->name(); - mimeTypeIcon = mt->iconName(); - mimeTypeComment = mt->comment(); - } - - QStandardItem *item = new QStandardItem(file); - item->setIcon(KIcon(mimeTypeIcon)); - item->setCheckable(true); - item->setCheckState(Qt::Checked); - item->setData(QVariant(url.fileName()), Qt::DisplayRole); - item->setData(QVariant(mimeTypeName), Qt::UserRole); // used for filtering DownloadFilterType - - QList items; - QStandardItem *number = new QStandardItem(); - number->setData(model->rowCount(), Qt::DisplayRole);//used for inital sorting - items << number; - items << item; - items << new QStandardItem(); - items << new QStandardItem(mimeTypeComment); - items << new QStandardItem(url.prettyUrl()); - - model->insertRow(model->rowCount(), items); - } - - connect(model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(selectionChanged())); - m_proxyModel->setSourceModel(model); - m_proxyModel->setFilterKeyColumn(1); - m_proxyModel->sort(0); - - ui.treeView->header()->hideSection(0); - ui.treeView->setColumnWidth(1, 200); // make the filename column bigger by default - - selectionChanged(); // adapt buttons to the new situation -} - -void KGetLinkView::slotMimeTypeChanged(int index) -{ - m_proxyModel->setFilterType(ui.showCombo->itemData(index).toInt()); -} - -void KGetLinkView::slotFilterModeChanged(int index) -{ - m_proxyModel->setFilterMode(ui.filterMode->itemData(index).toInt()); -} - -void KGetLinkView::slotFilterColumn(QAction *action) -{ - //FIXME make this not depend on "magic numbers"? - m_proxyModel->setFilterColumn(action == m_urlAction ? 4 : 1); -} - -void KGetLinkView::slotStartLeech() -{ - QStandardItemModel *model = qobject_cast(m_proxyModel->sourceModel()); - if (model) - { - KUrl::List urls; - - for (int row = 0; row < model->rowCount(); row++) - { - QStandardItem *checkeableItem = model->item(row, 1); - - if (checkeableItem->checkState() == Qt::Checked) - { - urls.append(KUrl(model->data(model->index(row, 4)).toString())); - } - } - - NewTransferDialogHandler::showNewTransferDialog(urls); - } -} - -void KGetLinkView::setPageUrl( const QString& url ) -{ - setWindowTitle( i18n( "Links in: %1 - KGet", url ) ); -} - -void KGetLinkView::importUrl(const QString &url) -{ - if (url.isEmpty()) - { - KUrl clipboardUrl = KUrl(QApplication::clipboard()->text(QClipboard::Clipboard).trimmed()); - if (clipboardUrl.isValid() && - ((!clipboardUrl.scheme().isEmpty() && !clipboardUrl.host().isEmpty()) || - (clipboardUrl.isLocalFile()))) - { - ui.urlRequester->setUrl(clipboardUrl); - } - } - else - { - ui.urlRequester->setUrl(KUrl(url)); - slotStartImport(); - } -} - -void KGetLinkView::selectionChanged() -{ - QStandardItemModel *model = qobject_cast(m_proxyModel->sourceModel()); - if (model) - { - const int modelRowCount = model->rowCount(); - bool buttonEnabled = false; - int count = 0; - - for (int row = 0; row < modelRowCount; row++) - { - QStandardItem *checkeableItem = model->item(row, 1); - - if ((checkeableItem->checkState() == Qt::Checked)) - { - buttonEnabled = true; - - // only count the checked files that are currently visible - if (m_proxyModel->mapFromSource(model->index(row, 1)).isValid()) - { - count++; - } - } - } - - ui.selectAll->setEnabled( !(!modelRowCount || count == m_proxyModel->rowCount() ) ); - ui.deselectAll->setEnabled( count > 0 ); - ui.invertSelection->setEnabled( count > 0 ); - - enableButtonOk(buttonEnabled); - } -} - -void KGetLinkView::setTextFilter(const QString &text) -{ - // TODO: escape user input for avoding malicious user input! (FiNEX) - QString temp = text.isEmpty() ? ui.textFilter->text() : text; - if (Settings::linkViewFilterPatternSyntax() == Wildcard) { - m_proxyModel->setFilterWildcard(temp); - } else { - QRegExp rx(temp, Qt::CaseSensitive, QRegExp::RegExp2); - m_proxyModel->setFilterRegExp(rx); - } - - updateSelectionButtons(); -} - -void KGetLinkView::updateSelectionButtons() -{ - const bool isFiltered = !ui.textFilter->text().isEmpty() || (ui.showCombo->currentIndex() != KGetSortFilterProxyModel::NoFilter); - ui.selectAll->setText(isFiltered ? i18n("&Select All Filtered") : i18n("&Select All")); - ui.deselectAll->setText(isFiltered ? i18n("D&eselect All Filtered") : i18n("D&eselect All")); - - selectionChanged(); -} - -void KGetLinkView::checkAll() -{ - QStandardItemModel *itemsModel = qobject_cast(m_proxyModel->sourceModel()); - if (itemsModel) - { - for (int row = 0; row < m_proxyModel->rowCount(); row++) - { - const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(row, 3)); - QStandardItem *item = itemsModel->item(index.row(), 1); - item->setCheckState(Qt::Checked); - } - } -} - -void KGetLinkView::uncheckAll() -{ - QStandardItemModel *itemsModel = qobject_cast(m_proxyModel->sourceModel()); - if (itemsModel) - { - for (int row = 0; row < m_proxyModel->rowCount(); row++) - { - const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(row, 3)); - QStandardItem *item = itemsModel->item(index.row(), 1); - item->setCheckState(Qt::Unchecked); - } - } -} - -void KGetLinkView::uncheckItem(const QModelIndex &index) -{ - QStandardItemModel *model = qobject_cast(m_proxyModel->sourceModel()); - if (model) - { - if (index.column() != 0) - { - QStandardItem *item = model->itemFromIndex(model->index(m_proxyModel->mapToSource(index).row(), 1)); - item->setCheckState(item->checkState() == Qt::Checked ? Qt::Unchecked : Qt::Checked); - } - } -} - -void KGetLinkView::slotCheckSelected() -{ - QStandardItemModel *model = qobject_cast(m_proxyModel->sourceModel()); - if (model) - { - foreach(const QModelIndex &index, ui.treeView->selectionModel()->selectedIndexes()) - { - QModelIndex sourceIndex = m_proxyModel->mapToSource(index); - QStandardItem *item = model->item(sourceIndex.row(), 1); - - item->setCheckState(Qt::Checked); - } - } -} - -void KGetLinkView::slotInvertSelection() -{ - QStandardItemModel *itemsModel = qobject_cast(m_proxyModel->sourceModel()); - if (itemsModel) - { - for (int row = 0; row < m_proxyModel->rowCount(); row++) - { - const QModelIndex index = m_proxyModel->mapToSource(m_proxyModel->index(row, 3)); - QStandardItem *item = itemsModel->item(index.row(), 1); - item->setCheckState((item->checkState() == Qt::Checked) ? Qt::Unchecked : Qt::Checked); - } - } -} - -void KGetLinkView::slotStartImport() -{ - delete m_linkImporter; - - m_linkImporter = new LinkImporter(ui.urlRequester->url(), this); - - connect(m_linkImporter, SIGNAL(progress(int)), SLOT(slotImportProgress(int))); - connect(m_linkImporter, SIGNAL(finished()), SLOT(slotImportFinished())); - - if (!ui.urlRequester->url().isLocalFile()) - { - m_linkImporter->copyRemoteFile(); - } - - m_linkImporter->start(); - ui.progressBar->show(); -} - -void KGetLinkView::slotImportProgress(int progress) -{ - ui.progressBar->setValue(progress); -} - -void KGetLinkView::slotImportFinished() -{ - ui.progressBar->hide(); - m_links = m_linkImporter->links(); - showLinks(m_links, true); -} - -void KGetLinkView::updateImportButtonStatus(const QString &text) -{ - bool enabled = false; - if (!text.isEmpty()) - { - KUrl url(text); - if (url.isValid()) - { - enabled = true; - } - } - ui.importLinks->setEnabled(enabled); -} - -void KGetLinkView::contextMenuDisplayed(QMenu *menu) -{ - menu->addSeparator(); - menu->addMenu(m_patternSyntaxMenu); - menu->addSeparator()->setText(i18n("Filter Column")); - menu->addAction(m_nameAction); - menu->addAction(m_urlAction); -} - - -void KGetLinkView::wildcardPatternToggled(bool enabled) -{ - if (enabled) { - Settings::setLinkViewFilterPatternSyntax(Wildcard); - } else { - Settings::setLinkViewFilterPatternSyntax(RegExp); - } -} - -#include "moc_kget_linkview.cpp" diff --git a/kget/ui/linkview/kget_linkview.h b/kget/ui/linkview/kget_linkview.h deleted file mode 100644 index cf63a9dc..00000000 --- a/kget/ui/linkview/kget_linkview.h +++ /dev/null @@ -1,81 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2002 Carsten Pfeiffer - - 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. -*/ - -#ifndef KGET_LINKVIEW_H -#define KGET_LINKVIEW_H - -#include "../../core/basedialog.h" -#include - -#include "ui_importlinkdialog.h" - -#include -#include -class LinkImporter; -class KGetSortFilterProxyModel; - - -class KGetLinkView : public KGetSaveSizeDialog -{ - Q_OBJECT - -public: - KGetLinkView(QWidget *parent = 0); - ~KGetLinkView(); - - // void setLinks( QList& links ); - void setLinks(const QStringList &links); - void setPageUrl( const QString& url ); - void importUrl(const QString &url = QString()); - -signals: - void leechUrls( const KUrl::List& urls ); - -private slots: - void slotMimeTypeChanged(int index); - void slotFilterModeChanged(int index); - void slotFilterColumn(QAction*); - void slotStartLeech(); - void selectionChanged(); - void setTextFilter(const QString &text = QString()); - void checkAll(); - void uncheckAll(); - void uncheckItem(const QModelIndex &index); - void slotCheckSelected(); - void slotInvertSelection(); - void updateSelectionButtons(); - void contextMenuDisplayed(QMenu *menu); - void wildcardPatternToggled(bool enabled); - - // import links slots - void slotStartImport(); - void slotImportProgress(int progress); - void slotImportFinished(); - void updateImportButtonStatus(const QString &text); - -private: - void checkClipboard(); - void showLinks(const QStringList &links, bool urlRequestVisible); - -private: - enum PatternSyntax { - Wildcard = 0, - RegExp - }; - Ui::ImportLinkDialog ui; - KGetSortFilterProxyModel *m_proxyModel; - QStringList m_links; - LinkImporter *m_linkImporter; - QMenu *m_patternSyntaxMenu; - QAction *m_nameAction; - QAction *m_urlAction; -}; - -#endif // KGET_LINKVIEW_H diff --git a/kget/ui/linkview/kget_sortfilterproxymodel.cpp b/kget/ui/linkview/kget_sortfilterproxymodel.cpp deleted file mode 100644 index 19760a19..00000000 --- a/kget/ui/linkview/kget_sortfilterproxymodel.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "kget_sortfilterproxymodel.h" - -#include - -static const QString ARCHIVES = QString("/x-7z-compressed,/x-ace,/x-archive,/x-arj,/x-bzip,/x-bzip-compressed-tar,/x-compressed-tar,/x-deb/,/x-rar,/x-tar,/x-rpm,/x-tarz,/zip"); -static const QString WEB_CONTENT = QString("/html,/x-asp,/xhtml+xml,/x-php,"); - -KGetSortFilterProxyModel::KGetSortFilterProxyModel(int column, QObject *parent) - : QSortFilterProxyModel(parent), - m_filterType(NoFilter), - m_filterMode(Contain), - m_column(column), - m_showWebContent(false) -{ - m_mimeTypes.insert(NoFilter, ""); - m_mimeTypes.insert(VideoFiles, "video/"); - m_mimeTypes.insert(AudioFiles, "audio/"); - m_mimeTypes.insert(CompressedFiles, "archive/"); - m_mimeTypes.insert(ImageFiles, "image/"); -} - -KGetSortFilterProxyModel::~KGetSortFilterProxyModel() -{ -} - -bool KGetSortFilterProxyModel::showWebContent() const -{ - return m_showWebContent; -} - -void KGetSortFilterProxyModel::setFilterType(int filterType) -{ - m_filterType = filterType; - invalidateFilter(); -} - -void KGetSortFilterProxyModel::setFilterMode(int filterMode) -{ - switch (filterMode) - { - case DoesNotContain: - m_filterMode = DoesNotContain; - break; - case Contain: - default: - m_filterMode = Contain; - } - - invalidateFilter(); -} - -void KGetSortFilterProxyModel::setShowWebContent(bool show) -{ - m_showWebContent = show; - invalidateFilter(); -} - -void KGetSortFilterProxyModel::setShowWebContent(int show) -{ - m_showWebContent = show; - invalidateFilter(); -} - -void KGetSortFilterProxyModel::setFilterColumn(int column) -{ - m_column = column; - invalidateFilter(); -} - -bool KGetSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const -{ - const QModelIndex index = sourceModel()->index(sourceRow, 1, sourceParent); - if (!index.isValid() || index.data(Qt::UserRole).toString().isEmpty()) - { - return false; - } - - const QString meta = index.data(Qt::UserRole).toString(); - const QString text = columnText(sourceRow, sourceParent); - bool show = false; - - - //do not show entries if their text is empty when not using NoFilter and m_showWebContent - if (!text.isEmpty() && (m_filterType != NoFilter)) - { - show = meta.startsWith(m_mimeTypes[m_filterType]); - - if (m_filterType == CompressedFiles) - { - show = ARCHIVES.contains(meta.mid(meta.indexOf('/'))); - } - } - else if (m_filterType == NoFilter) - { - if (m_showWebContent) - { - show = true; - } - else - { - show = !text.isEmpty() && !WEB_CONTENT.contains(meta.mid(meta.indexOf('/'))); - } - } - - if (show) { - show = acceptText(text); - } - - return show; -} - -QString KGetSortFilterProxyModel::columnText(int row, const QModelIndex &sourceParent) const -{ - const QModelIndex index = sourceModel()->index(row, m_column, sourceParent); - return (index.isValid() ? index.data(Qt::DisplayRole).toString() : QString()); -} - -bool KGetSortFilterProxyModel::acceptText(const QString &text) const -{ - //look if the text-filter matches - const QRegExp re = filterRegExp(); - bool accept = (re.indexIn(text) != -1) ? true : false; - if ((m_filterMode == DoesNotContain) && !re.isEmpty()) { - accept = !accept; - } - - return accept; -} diff --git a/kget/ui/linkview/kget_sortfilterproxymodel.h b/kget/ui/linkview/kget_sortfilterproxymodel.h deleted file mode 100644 index a70d35f4..00000000 --- a/kget/ui/linkview/kget_sortfilterproxymodel.h +++ /dev/null @@ -1,78 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 KGET_SORTFILTERPROXYMODEL_H -#define KGET_SORTFILTERPROXYMODEL_H - -#include - -class KGetSortFilterProxyModel : public QSortFilterProxyModel -{ - Q_OBJECT - - public: - explicit KGetSortFilterProxyModel(int sortColumn, QObject *parent = 0); - virtual ~KGetSortFilterProxyModel(); - - enum DownloadFilterType { - NoFilter, - VideoFiles, - AudioFiles, - CompressedFiles, - ImageFiles - }; - - enum FilterMode { - Contain, - DoesNotContain - }; - - void setFilterType(int filterType); - void setFilterMode(int filterMode); - void setFilterColumn(int column); - bool showWebContent() const; - - public slots: - void setShowWebContent(bool show); - void setShowWebContent(int show); - - protected: - virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; - - private: - /** - * Returns true if text should be accepted by the filter - */ - bool acceptText(const QString &text) const; - - /** - * @param row to get the column from - * @return string for the column that is being filtered - */ - QString columnText(int row, const QModelIndex &sourceParent) const; - - private: - int m_filterType; - FilterMode m_filterMode; - int m_column; - bool m_showWebContent; - QHash m_mimeTypes; -}; - -#endif // KGET_SORTFILTERPROXYMODEL_H diff --git a/kget/ui/mirror/mirroradddlg.ui b/kget/ui/mirror/mirroradddlg.ui deleted file mode 100644 index cbd63e94..00000000 --- a/kget/ui/mirror/mirroradddlg.ui +++ /dev/null @@ -1,121 +0,0 @@ - - - MirrorAddDlg - - - - 0 - 0 - 481 - 167 - - - - - - - - - Mirror: - - - - - - - Number of connections: - - - - - - - Enter a URL - - - true - - - - - - - 1 - - - 20 - - - - - - - Priority: - - - - - - - Optional: The priority of the mirror, 1 highest 999999 lowest. - - - 0 - - - 0 - - - 999999 - - - not specified - - - - - - - Location: - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
- - KIntNumInput - QWidget -
knuminput.h
-
-
- -
diff --git a/kget/ui/mirror/mirrormodel.cpp b/kget/ui/mirror/mirrormodel.cpp deleted file mode 100644 index 83583f0e..00000000 --- a/kget/ui/mirror/mirrormodel.cpp +++ /dev/null @@ -1,518 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "mirrormodel.h" - -#include -#include - -#include -#include -#include -#include -#include - -MirrorDelegate::MirrorDelegate(QObject *parent) - : QStyledItemDelegate(parent), - m_countrySort(0) -{ -} - -MirrorDelegate::MirrorDelegate(QSortFilterProxyModel *countrySort, QObject *parent) - : QStyledItemDelegate(parent), - m_countrySort(countrySort) -{ - -} - -QWidget *MirrorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(option) - - if (index.isValid()) - { - if (index.column() == MirrorItem::Url) - { - KLineEdit *line = new KLineEdit(parent); - - return line; - } - else if (index.column() == MirrorItem::Connections) - { - QSpinBox *numConnections = new QSpinBox(parent); - numConnections->setRange(0, 20); - - return numConnections; - } - else if (index.column() == MirrorItem::Priority) - { - QSpinBox *priority = new QSpinBox(parent); - priority->setRange(0, 999999); - - return priority; - } - else if (index.column() == MirrorItem::Country) - { - if (m_countrySort) - { - KComboBox *countrySort = new KComboBox(parent); - countrySort->setModel(m_countrySort); - - return countrySort; - } - } - } - - return 0; -} - -void MirrorDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (index.isValid() && editor) { - if (index.column() == MirrorItem::Url) { - KLineEdit *line = static_cast(editor); - const KUrl url = index.data(Qt::EditRole).toUrl(); - line->setUrl(url); - } else if (index.column() == MirrorItem::Connections) { - QSpinBox *numConnections = static_cast(editor); - const int num = index.data(Qt::EditRole).toInt(); - numConnections->setValue(num); - } else if (index.column() == MirrorItem::Priority) { - QSpinBox *priority = static_cast(editor); - const int num = index.data(Qt::EditRole).toInt(); - priority->setValue(num); - } else if (index.column() == MirrorItem::Country) { - KComboBox *countrySort = static_cast(editor); - const QString countryCode = index.data(Qt::EditRole).toString(); - const int indexCountrySort = countrySort->findData(countryCode); - countrySort->setCurrentIndex(indexCountrySort); - } - } -} - -void MirrorDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (index.isValid() && editor && model) - { - if (index.column() == MirrorItem::Url) - { - KLineEdit *line = static_cast(editor); - if (!line->text().isEmpty()) - { - model->setData(index, line->text()); - } - } - else if (index.column() == MirrorItem::Connections) - { - QSpinBox *numConnections = static_cast(editor); - model->setData(index, numConnections->value()); - } - else if (index.column() == MirrorItem::Priority) - { - QSpinBox *priority = static_cast(editor); - model->setData(index, priority->value()); - } - else if (index.column() == MirrorItem::Country) - { - KComboBox *countrySort = static_cast(editor); - const QString countryCode = countrySort->itemData(countrySort->currentIndex()).toString(); - model->setData(index, countryCode); - } - } -} - -void MirrorDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - Q_UNUSED(index) - editor->setGeometry(option.rect); -} - -QSize MirrorDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - //make the sizeHint a little bit nicer to have more beautiful editors - QSize hint; - hint.setWidth(QStyledItemDelegate::sizeHint(option, index).width()); - hint.setHeight(option.fontMetrics.height() + 7); - return hint; -} - - -MirrorProxyModel::MirrorProxyModel(QObject *parent) - : QSortFilterProxyModel(parent) -{ -} - -bool MirrorProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const -{ - if (left.column() == MirrorItem::Used) { - const int leftData = sourceModel()->data(left, Qt::CheckStateRole).toInt(); - const int rightData = sourceModel()->data(right, Qt::CheckStateRole).toInt(); - return leftData < rightData; - } else if (left.column() == MirrorItem::Priority) { - const int leftData = sourceModel()->data(left, Qt::UserRole).toInt(); - const int rightData = sourceModel()->data(right, Qt::UserRole).toInt(); - return (!leftData ? true : (leftData > rightData) && rightData);//0 is always smallest, otherwise larger is smaller - } - - return QSortFilterProxyModel::lessThan(left, right); -} - - -MirrorItem::MirrorItem() - : m_checked(Qt::Unchecked), - m_numConnections(0), - m_priority(0) -{ -} - -QVariant MirrorItem::data(int column, int role) const -{ - if (column == MirrorItem::Used) - { - if (role == Qt::CheckStateRole) - { - return m_checked; - } - } - else if (column == MirrorItem::Url) - { - if (role == Qt::DisplayRole) - { - return m_url.pathOrUrl(); - } - else if ((role == Qt::UserRole) || (role == Qt::EditRole)) - { - return QVariant(m_url); - } - } - else if (column == MirrorItem::Connections) - { - if (role == Qt::DisplayRole) - { - if (m_numConnections) - { - return m_numConnections; - } - else - { - return i18n("not specified"); - } - } - else if ((role == Qt::EditRole) || (role == Qt::UserRole)) - { - return m_numConnections; - } - } - else if (column == MirrorItem::Priority) - { - if (role == Qt::DisplayRole) - { - if (m_priority) - { - return m_priority; - } - else - { - return i18n("not specified"); - } - } - else if ((role == Qt::EditRole) || (role == Qt::UserRole)) - { - return m_priority; - } - } - else if (column == MirrorItem::Country) - { - if (role == Qt::DisplayRole) - { - return m_countryName; - } - else if (role == Qt::DecorationRole) - { - return m_countryFlag; - } - else if ((role == Qt::UserRole) || (role == Qt::EditRole)) - { - return m_countryCode; - } - } - - return QVariant(); -} - -Qt::ItemFlags MirrorItem::flags(int column) const -{ - Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if (column == MirrorItem::Used) - { - flags |= Qt::ItemIsUserCheckable; - } - else if (column == MirrorItem::Url) - { - flags |= Qt::ItemIsEditable; - } - else if (column == MirrorItem::Connections) - { - flags |= Qt::ItemIsEditable; - } - else if (column == MirrorItem::Priority) - { - flags |= Qt::ItemIsEditable; - } - else if (column == MirrorItem::Country) - { - flags |= Qt::ItemIsEditable; - } - - return flags; -} - -bool MirrorItem::setData(int column, const QVariant &value, int role) -{ - if ((column == MirrorItem::Used) && (role == Qt::CheckStateRole)) - { - m_checked = static_cast(value.toInt()); - return true; - } - else if ((column == MirrorItem::Url) && (role == Qt::EditRole)) - { - KUrl url; - if (value.type() == QVariant::Url) - { - url = KUrl(value.toUrl()); - } - else if (value.type() == QVariant::String) - { - url = KUrl(value.toString()); - } - - if (!url.isEmpty()) - { - m_url = url; - return true; - } - } - else if ((column == MirrorItem::Connections) && (role == Qt::EditRole)) - { - m_numConnections = value.toInt(); - return true; - } - else if ((column == MirrorItem::Priority) && (role == Qt::EditRole)) - { - m_priority = value.toInt(); - return true; - } - else if ((column == MirrorItem::Country) && (role == Qt::EditRole)) - { - m_countryCode = value.toString(); - m_countryName = KGlobal::locale()->countryCodeToName(m_countryCode); - - if (!m_countryName.isEmpty()) - { - QString path = KStandardDirs::locate("locale", QString::fromLatin1("l10n/%1/flag.png").arg(m_countryCode)); - if (path.isEmpty()) - { - m_countryFlag = KIcon(); - } - else - { - m_countryFlag = KIcon(path); - } - } - else - { - m_countryFlag = KIcon(); - } - return true; - } - - return false; -} - - -MirrorModel::MirrorModel(QObject *parent) -: QAbstractTableModel(parent) -{ -} - -MirrorModel::~MirrorModel() -{ - qDeleteAll(m_data); -} - -int MirrorModel::rowCount(const QModelIndex &index) const -{ - if (!index.isValid()) - { - return m_data.count(); - } - else - { - return 0; - } -} - -int MirrorModel::columnCount(const QModelIndex &index) const -{ - if (index.isValid()) - { - return 0; - } - - return 5; -} - -QVariant MirrorModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Vertical) { - return QVariant(); - } - - if ((section == MirrorItem::Url) && (role == Qt::DisplayRole)) { - return i18nc("Mirror as in server, in url", "Mirror"); - } else if (section == MirrorItem::Priority) { - if (role == Qt::DisplayRole) { - return i18nc("The priority of the mirror", "Priority"); - } else if (role == Qt::DecorationRole) { - return KIcon("games-highscores"); - } - } else if ((section == MirrorItem::Connections) && (role == Qt::DisplayRole)) { - return i18nc("Number of paralell connections to the mirror", "Connections"); - } else if ((section == MirrorItem::Country) && (role == Qt::DisplayRole)) { - return i18nc("Location = country", "Location"); - } - - return QVariant(); -} - -QVariant MirrorModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) { - return QVariant(); - } - - return m_data.at(index.row())->data(index.column(), role); -} - -Qt::ItemFlags MirrorModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) { - return 0; - } - - return m_data.at(index.row())->flags(index.column()); -} - -bool MirrorModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (!index.isValid()) { - return false; - } - - const bool changed = m_data.at(index.row())->setData(index.column(), value, role); - if (changed) - { - emit dataChanged(index, index); - } - return changed; -} - -bool MirrorModel::removeRows(int row, int count, const QModelIndex &parent) -{ - if (parent.isValid() || (row < 0) || (count < 1) || (row + count > rowCount())) - { - return false; - } - - beginRemoveRows(parent, row, row + count - 1); - while (count) - { - MirrorItem *item = m_data[row]; - m_data.removeAt(row); - delete item; - --count; - } - endRemoveRows(); - - return true; -} - -void MirrorModel::addMirror(const KUrl &url, int numConnections, int priority, const QString &countryCode) -{ - if (!url.isValid()) - { - return; - } - - for (int i = 0; i < rowCount(); ++i) - { - //exists already, so remove the row - if (KUrl(m_data.at(i)->data(MirrorItem::Url).toString()) == url) - { - removeRow(i); - break; - } - } - - int index = rowCount(); - emit beginInsertRows(QModelIndex(), index, index); - - MirrorItem *item = new MirrorItem; - m_data.append(item); - item->setData(MirrorItem::Used, Qt::Checked, Qt::CheckStateRole);//every newly added mirror is set to checked automatically - item->setData(MirrorItem::Url, QVariant(url)); - item->setData(MirrorItem::Connections, numConnections); - item->setData(MirrorItem::Priority, priority); - item->setData(MirrorItem::Country, countryCode); - - emit endInsertRows(); -} - -void MirrorModel::setMirrors(const QHash > &mirrors) -{ - removeRows(0, rowCount()); - - QHash >::const_iterator it; - QHash >::const_iterator itEnd = mirrors.constEnd(); - for (it = mirrors.constBegin(); it != itEnd; ++it) - { - MirrorItem *item = new MirrorItem; - item->setData(MirrorItem::Url, QVariant(it.key())); - Qt::CheckState state = (*it).first ? Qt::Checked : Qt::Unchecked; - item->setData(MirrorItem::Used, state, Qt::CheckStateRole); - item->setData(MirrorItem::Connections, (*it).second); - m_data.append(item); - } - - emit reset(); -} - -QHash > MirrorModel::availableMirrors() const -{ - QHash > mirrors; - foreach (MirrorItem *item, m_data) - { - bool used = (item->data(MirrorItem::Used, Qt::CheckStateRole).toInt() == Qt::Checked) ? true : false; - const KUrl url = KUrl(item->data(MirrorItem::Url).toString()); - mirrors[url] = QPair(used, item->data(MirrorItem::Connections, Qt::UserRole).toInt()); - } - return mirrors; -} - -#include "moc_mirrormodel.cpp" diff --git a/kget/ui/mirror/mirrormodel.h b/kget/ui/mirror/mirrormodel.h deleted file mode 100644 index 74d47716..00000000 --- a/kget/ui/mirror/mirrormodel.h +++ /dev/null @@ -1,112 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 MIRRORMODEL_H -#define MIRRORMODEL_H - -#include -#include - -#include -#include - -#include - -class MirrorDelegate : public QStyledItemDelegate -{ - Q_OBJECT - - public: - MirrorDelegate(QObject *parent = 0); - explicit MirrorDelegate(QSortFilterProxyModel *countrySort, QObject *parent = 0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - - private: - QSortFilterProxyModel *m_countrySort; -}; - -class MirrorProxyModel : public QSortFilterProxyModel -{ - Q_OBJECT - - public: - MirrorProxyModel(QObject *parent = 0); - - protected: - bool lessThan(const QModelIndex &left, const QModelIndex &right) const; -}; - -class MirrorItem -{ - public: - MirrorItem(); - - enum DataType - { - Used = 0, - Url, - Connections, - Priority, - Country - }; - - QVariant data(int column, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(int column) const; - bool setData(int column, const QVariant &value, int role = Qt::EditRole); - - private: - KUrl m_url; - Qt::CheckState m_checked; - int m_numConnections; - int m_priority; - QString m_countryCode; - QString m_countryName; - KIcon m_countryFlag; -}; - -class MirrorModel : public QAbstractTableModel -{ - Q_OBJECT - - public: - MirrorModel(QObject *parent); - ~MirrorModel(); - - int rowCount(const QModelIndex &index = QModelIndex()) const; - int columnCount(const QModelIndex &index = QModelIndex()) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - - void addMirror(const KUrl &url, int numConnections = 0, int priority = 0, const QString &countryCode = QString()); - void setMirrors(const QHash > &mirrors); - QHash > availableMirrors() const; - - private: - QList m_data; -}; - -#endif diff --git a/kget/ui/mirror/mirrorsettings.cpp b/kget/ui/mirror/mirrorsettings.cpp deleted file mode 100644 index 00d1d1b1..00000000 --- a/kget/ui/mirror/mirrorsettings.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "mirrorsettings.h" -#include "mirrormodel.h" -#include "core/transferhandler.h" - -#include -#include - -MirrorAddDlg::MirrorAddDlg(MirrorModel *model, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_model(model), - m_countryModel(0) -{ - init(); -} - -MirrorAddDlg::MirrorAddDlg(MirrorModel *model, QSortFilterProxyModel *countryModel, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_model(model), - m_countryModel(countryModel) -{ - init(); -} - -QSize MirrorAddDlg::sizeHint() const -{ - QSize sh = KDialog::sizeHint(); - sh.setHeight(minimumSize().height()); - sh.setWidth(sh.width() * 1.5); - return sh; -} - -void MirrorAddDlg::init() -{ - setCaption(i18n("Add mirror")); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - - if (m_countryModel) - { - ui.location->setModel(m_countryModel); - ui.location->setCurrentIndex(-1); - } - - setButtons(KDialog::Yes | KDialog::Cancel); - setButtonGuiItem(KDialog::Yes, KStandardGuiItem::add()); - - updateButton(); - - connect(ui.url, SIGNAL(textChanged(QString)), this, SLOT(updateButton(QString))); - connect(this, SIGNAL(yesClicked()), this, SLOT(addMirror())); -} - -void MirrorAddDlg::showItem(MirrorItem::DataType type, bool show) -{ - switch (type) - { - case MirrorItem::Connections: - ui.labelConnections->setVisible(show); - ui.numConnections->setVisible(show); - break; - - case MirrorItem::Priority: - ui.labelPriority->setVisible(show); - ui.priority->setVisible(show); - break; - - case MirrorItem::Country: - ui.labelLocation->setVisible(show); - ui.location->setVisible(show); - break; - - default: - break; - } - update(); -} - -void MirrorAddDlg::updateButton(const QString &text) -{ - bool enabled = false; - KUrl url(text); - if (url.isValid() && !url.protocol().isEmpty() && url.hasPath()) - { - enabled = true; - } - enableButton(KDialog::Yes, enabled); - enableButton(KDialog::User1, enabled); -} - -void MirrorAddDlg::addMirror() -{ - const int numConnections = ui.numConnections->isVisible() ? ui.numConnections->value() : 0; - const int priority = ui.priority->isVisible() ? ui.priority->value() : 0; - const QString countryCode = ui.location->itemData(ui.location->currentIndex()).toString(); - m_model->addMirror(KUrl(ui.url->text()), numConnections, priority, countryCode); - if (m_countryModel) - { - ui.location->setCurrentIndex(-1); - } -} - -MirrorSettings::MirrorSettings(QWidget *parent, TransferHandler *handler, const KUrl &file) - : KGetSaveSizeDialog("MirrorSettings", parent), - m_transfer(handler), - m_file(file) -{ - m_model = new MirrorModel(this); - m_model->setMirrors(m_transfer->availableMirrors(m_file)); - m_proxy = new MirrorProxyModel(this); - m_proxy->setSourceModel(m_model); - - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - ui.add->setGuiItem(KStandardGuiItem::add()); - ui.remove->setGuiItem(KStandardGuiItem::remove()); - ui.treeView->setModel(m_proxy); - ui.treeView->header()->setResizeMode(QHeaderView::ResizeToContents); - ui.treeView->hideColumn(MirrorItem::Priority); - ui.treeView->hideColumn(MirrorItem::Country); - ui.treeView->setItemDelegate(new MirrorDelegate(this)); - - updateButton(); - - connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(updateButton())); - connect(ui.add, SIGNAL(clicked()), this, SLOT(addClicked())); - connect(ui.remove, SIGNAL(clicked()), this, SLOT(removeMirror())); - connect(this, SIGNAL(finished()), this, SLOT(save())); - - setMainWidget(widget); - setCaption(i18n("Modify the used mirrors")); - setButtons(KDialog::Close); -} - -QSize MirrorSettings::sizeHint() const -{ - return QSize(700, 400); -} - -void MirrorSettings::updateButton() -{ - ui.remove->setEnabled(ui.treeView->selectionModel()->hasSelection()); -} - -void MirrorSettings::addClicked() -{ - MirrorAddDlg *dialog = new MirrorAddDlg(m_model, this); - dialog->showItem(MirrorItem::Priority, false); - dialog->showItem(MirrorItem::Country, false); - dialog->show(); -} - -void MirrorSettings::removeMirror() -{ - while (ui.treeView->selectionModel()->hasSelection()) { - const QModelIndex index = ui.treeView->selectionModel()->selectedRows().first(); - m_model->removeRow(m_proxy->mapToSource(index).row()); - } -} - -void MirrorSettings::save() -{ - m_transfer->setAvailableMirrors(m_file, m_model->availableMirrors()); -} - -#include "moc_mirrorsettings.cpp" diff --git a/kget/ui/mirror/mirrorsettings.h b/kget/ui/mirror/mirrorsettings.h deleted file mode 100644 index 141fd47b..00000000 --- a/kget/ui/mirror/mirrorsettings.h +++ /dev/null @@ -1,86 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 MIRRORSETTINGS_H -#define MIRRORSETTINGS_H - -#include "mirrormodel.h" -#include "../../core/basedialog.h" - -#include "ui_mirrorsettings.h" -#include "ui_mirroradddlg.h" - -#include -class TransferHandler; - -class MirrorAddDlg : public KDialog -{ - Q_OBJECT - - public: - explicit MirrorAddDlg(MirrorModel *model, QWidget *parent = 0, Qt::WFlags flags = 0); - explicit MirrorAddDlg(MirrorModel *model, QSortFilterProxyModel *countryModel, QWidget *parent = 0, Qt::WFlags flags = 0); - - virtual QSize sizeHint() const; - - /** - * Shows or hides elements, by default all (expect MirrorItem::Used) are shown - * @param type the type whose visibility should be modified - * @param show if type should be shown or not - * @note MirrorItem::Used and MirrorItem::Url can not be modified - */ - void showItem(MirrorItem::DataType type, bool show); - - private slots: - void addMirror(); - void updateButton(const QString &text = QString()); - - private: - void init(); - - private: - Ui::MirrorAddDlg ui; - MirrorModel *m_model; - QSortFilterProxyModel *m_countryModel; -}; - -class MirrorSettings : public KGetSaveSizeDialog -{ - Q_OBJECT - - public: - MirrorSettings(QWidget *parent, TransferHandler *handler, const KUrl &file); - - virtual QSize sizeHint() const; - - private slots: - void updateButton(); - void addClicked(); - void removeMirror(); - void save(); - - private: - TransferHandler *m_transfer; - KUrl m_file; - MirrorModel *m_model; - MirrorProxyModel *m_proxy; - Ui::MirrorSettings ui; -}; - -#endif diff --git a/kget/ui/mirror/mirrorsettings.ui b/kget/ui/mirror/mirrorsettings.ui deleted file mode 100644 index 6f82184e..00000000 --- a/kget/ui/mirror/mirrorsettings.ui +++ /dev/null @@ -1,59 +0,0 @@ - - - MirrorSettings - - - - 0 - 0 - 482 - 216 - - - - - - - QAbstractItemView::ExtendedSelection - - - false - - - true - - - true - - - - - - - - - - - - - Qt::Vertical - - - - 65 - 141 - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- -
diff --git a/kget/ui/newtransferdialog.cpp b/kget/ui/newtransferdialog.cpp deleted file mode 100644 index d940015d..00000000 --- a/kget/ui/newtransferdialog.cpp +++ /dev/null @@ -1,791 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 by Javier Goday - Copyright (C) 2008 - 2009 by Lukas Appelhans - Copyright (C) 2010 by Matthias Fuchs - - 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. -*/ - -#include "newtransferdialog.h" - -#include "core/filedeleter.h" -#include "core/kget.h" -#include "mainwindow.h" -#include "core/mostlocalurl.h" -#include "core/transfertreemodel.h" -#include "core/transfergrouphandler.h" -#include "core/plugin/transferfactory.h" -#include "core/urlchecker.h" -#include "settings.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -K_GLOBAL_STATIC(NewTransferDialogHandler, newTransferDialogHandler) - - -NewTransferDialog::NewTransferDialog(QWidget *parent) - : KDialog(parent), - m_window(0), - m_existingTransfer(0), - m_multiple(false), - m_overWriteSingle(false) -{ - setModal(true); - setCaption(i18n("New Download")); - showButtonSeparator(true); - - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - - enableButtonOk(false); - - //timer to avoid constant checking of the input - m_timer = new QTimer(this); - m_timer->setInterval(350); - m_timer->setSingleShot(true); - connect(m_timer, SIGNAL(timeout()), this, SLOT(checkInput())); - - const KColorScheme scheme = KColorScheme(QPalette::Active, KColorScheme::View); - m_existingFileBackground = scheme.background(KColorScheme::NeutralBackground); - m_normalBackground = scheme.background(); - - - // properties of the m_destRequester combobox - ui.destRequester->comboBox()->setDuplicatesEnabled(false); - ui.destRequester->comboBox()->setUrlDropsEnabled(true); - ui.destRequester->comboBox()->setEditable(true); - ui.destRequester->fileDialog()->setKeepLocation(true); - - ui.errorWidget->setCloseButtonVisible(false); - - connect(ui.groupComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setDefaultDestination())); - - connect(ui.urlRequester, SIGNAL(textChanged(QString)), this, SLOT(setDefaultDestination())); - connect(ui.destRequester, SIGNAL(textChanged(QString)), this, SLOT(inputTimer())); - connect(ui.urlRequester, SIGNAL(textChanged(QString)), this, SLOT(inputTimer())); - connect(ui.listWidget, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(inputTimer())); - connect(this, SIGNAL(finished(int)), this, SLOT(slotFinished(int))); -} - -NewTransferDialog::~NewTransferDialog() -{ -} - -void NewTransferDialog::setMultiple(bool useMultiple) -{ - m_multiple = useMultiple; - - const Qt::Alignment alignment = Qt::AlignLeft | (m_multiple ? Qt::AlignTop : Qt::AlignVCenter); - ui.urlLabel->setAlignment(alignment); - ui.urlRequester->setVisible(!m_multiple); - ui.listWidget->setVisible(m_multiple); - ui.destRequester->setMode(m_multiple ? KFile::Directory : KFile::File); -} - -void NewTransferDialog::clear() -{ - ui.urlRequester->clear(); - ui.urlRequester->setFocus(); - ui.listWidget->clear(); - ui.destRequester->comboBox()->clear(); - ui.destRequester->clear(); - m_destination.clear(); - m_sources.clear(); - m_existingTransfer = 0; - m_overWriteSingle = false; - - //add all destinations - QStringList list; - QString downloadPath = KGet::generalDestDir(); - if (!downloadPath.isEmpty()) { - if (!downloadPath.endsWith('/')) { - downloadPath.append('/'); - } - list << downloadPath; - } - foreach (TransferGroupHandler *handler, KGet::allTransferGroups()) { - const QString folder = handler->defaultFolder(); - if (!folder.isEmpty()) { - list << (folder.endsWith('/') ? folder : folder + '/'); - } - } - - list.removeDuplicates(); - ui.destRequester->comboBox()->insertItems(0, list); - - //add all transfer groups - ui.groupComboBox->clear(); - foreach (TransferGroupHandler *group, KGet::allTransferGroups()) { - ui.groupComboBox->addItem(KIcon(group->iconName()), group->name()); - } - ui.groupComboBox->setCurrentItem(Settings::lastGroup()); - if (ui.groupComboBox->currentIndex() == -1) { - ui.groupComboBox->setCurrentIndex(0); - } - - const bool multipleGroups = KGet::transferGroupNames().count(); - ui.groupComboBox->setVisible(multipleGroups); - ui.groupLabel->setVisible(multipleGroups); -} - -void NewTransferDialog::setSource(const KUrl::List &sources) -{ - if (sources.isEmpty()) { - return; - } - - if (sources.count() == 1) { - KUrl m_srcUrl = sources.first().url(); - ui.urlRequester->clear(); - if (m_srcUrl.isEmpty()) { - m_srcUrl = KUrl(QApplication::clipboard()->text(QClipboard::Clipboard).trimmed()); - } - - if (UrlChecker::checkSource(m_srcUrl) == UrlChecker::NoError) { - ui.urlRequester->insert(m_srcUrl.prettyUrl()); - } - } else { - foreach (const KUrl &sourceUrl, sources) { - if (sourceUrl.url() != KUrl(sourceUrl.url()).fileName()) {//TODO simplify, whatfor is this check anyway, shouldn't the sources be checked already and if not add this to UrlChecker - kDebug() << "Insert" << sourceUrl; - QListWidgetItem *newItem = new QListWidgetItem(sourceUrl.pathOrUrl(), ui.listWidget); - newItem->setCheckState(Qt::Checked); - } - } - } - - const QList groups = KGet::groupsFromExceptions(sources.first()); - if (!groups.isEmpty()) { - ui.groupComboBox->setCurrentIndex(ui.groupComboBox->findText(groups.first()->name())); - } -} - -void NewTransferDialog::setDestinationFileName(const QString &filename) -{ - ui.destRequester->setUrl(QString(ui.destRequester->url().path(KUrl::AddTrailingSlash) + filename)); -} - -void NewTransferDialog::setDestination() -{ - //sets destRequester to either display the defaultFolder of group or the generalDestDir - QString group = ui.groupComboBox->currentText(); - TransferGroupHandler * current = 0; - foreach (TransferGroupHandler * handler, KGet::allTransferGroups()) { - if (handler->name() == group) { - current = handler; - break; - } - } - - if (current) { - QString groupFolder = current->defaultFolder(); - if (groupFolder.isEmpty()) { - groupFolder = KGet::generalDestDir(); - } - if (!groupFolder.endsWith('/')) { - groupFolder.append('/'); - } - ui.destRequester->comboBox()->setCurrentItem(groupFolder, true); - } -} - -void NewTransferDialog::showDialog(KUrl::List list, const QString &suggestedFileName) -{ - //TODO handle the case where for some there are suggested file names --> own file name column in multiple setting - //the dialog is already in use, adapt it - if (isVisible()) { - list << m_sources; - } - clear();//Let's clear the old stuff - m_sources << list; - UrlChecker::removeDuplicates(m_sources); - const int size = m_sources.size(); - kDebug() << "SET SOURCES " << m_sources << " MULTIPLE " << (size > 1); - setMultiple(size > 1); - - if (size) { - if (size == 1 && !suggestedFileName.isEmpty()) { - setDestinationFileName(suggestedFileName); - } - - setSource(m_sources); - } - - prepareDialog(); -} - -void NewTransferDialog::setDefaultDestination() -{ - //NOTE if the user enters a file name manually and the changes the group the manually entered file name will be overwritten - setDestination(); - - //set a file name - if (!m_multiple) { - const KUrl url(ui.urlRequester->text().trimmed()); - if ((UrlChecker::checkSource(url) == UrlChecker::NoError) && - QFileInfo(ui.destRequester->url().toLocalFile()).isDir()) { - setDestinationFileName(url.fileName()); - } - } -} - -void NewTransferDialog::prepareDialog() -{ - if (m_window) { - KWindowInfo info = KWindowSystem::windowInfo(m_window->winId(), NET::WMDesktop, NET::WMDesktop); - KWindowSystem::setCurrentDesktop(info.desktop()); - KWindowSystem::forceActiveWindow(m_window->winId()); - } - - kDebug() << "Show the dialog!"; - show(); -} - -bool NewTransferDialog::isEmpty() -{ - return (m_multiple ? !ui.listWidget->count() : ui.urlRequester->text().trimmed().isEmpty()); -} - -void NewTransferDialog::inputTimer() -{ - enableButtonOk(false); - m_timer->start(); -} - -void NewTransferDialog::checkInput() -{ - KUrl source = KUrl(ui.urlRequester->text().trimmed()); - const KUrl dest = ui.destRequester->url(); - - //check the destination folder - UrlChecker::UrlError error = UrlChecker::checkFolder(dest); - const bool folderValid = (error == UrlChecker::NoError); - bool destinationValid = false; - QString infoText; - QString warningText; - if (!folderValid) { - if (m_multiple) { - infoText = UrlChecker::message(KUrl(), UrlChecker::Folder, error); - } else { - //might be a destination instead of a folder - destinationValid = (UrlChecker::checkDestination(dest) == UrlChecker::NoError); - } - } else { - m_destination = dest; - } - - //check the source - if (!m_multiple) { - source = mostLocalUrl(source); - } - error = UrlChecker::checkSource(source); - const bool sourceValid = (error == UrlChecker::NoError); - if (!m_multiple && !sourceValid) { - infoText = UrlChecker::message(KUrl(), UrlChecker::Source, error); - } - - //check if any sources are checked and for existing transfers or destinations - bool filesChecked = false; - if (m_multiple && folderValid) { - KListWidget *list = ui.listWidget; - - //check if some sources have been checked - for (int i = 0; i < list->count(); ++i) { - QListWidgetItem *item = list->item(i); - if (item->checkState() == Qt::Checked) { - filesChecked = true; - break; - } - } - if (!filesChecked) { - infoText = i18n("Select at least one source url."); - } - - //check if there are existing files - if (filesChecked) { - bool existingFile = false; - for (int i = 0; i < list->count(); ++i) { - QListWidgetItem *item = list->item(i); - const KUrl source = KUrl(item->text()); - const KUrl destUrl = UrlChecker::destUrl(dest, source); - if (UrlChecker::wouldOverwrite(source, destUrl)) { - item->setBackground(m_existingFileBackground); - existingFile = true; - } else { - item->setBackground(m_normalBackground); - } - } - if (existingFile) { - warningText = i18n("Files that exist already in the current folder have been marked.");//TODO better message - } - } - } - - //single file - UrlChecker::UrlWarning warning = UrlChecker::NoWarning; - if (!m_multiple && sourceValid && (folderValid || destinationValid)) { - m_destination = UrlChecker::destUrl(dest, source); - //show only one message for existing transfers - m_existingTransfer = UrlChecker::existingTransfer(source, UrlChecker::Source, &warning); - if (m_existingTransfer) { - warningText = UrlChecker::message(KUrl(), UrlChecker::Source, warning); - } else { - m_existingTransfer = UrlChecker::existingTransfer(m_destination, UrlChecker::Destination, &warning); - if (m_existingTransfer) { - warningText = UrlChecker::message(KUrl(), UrlChecker::Destination, warning); - } - } - - if (UrlChecker::wouldOverwrite(KUrl(ui.urlRequester->text().trimmed()), m_destination)) { - m_overWriteSingle = true; - if (!warningText.isEmpty()) { - warningText += '\n'; - } - warningText += UrlChecker::message(KUrl(), UrlChecker::Destination, UrlChecker::ExistingFile); - } else { - m_overWriteSingle = false; - } - } - - if (!infoText.isEmpty()) { - setInformation(infoText); - } else if (!warningText.isEmpty()) { - setWarning(warningText); - } else { - ui.errorWidget->hide(); - } - - //activate the ok button - if (m_multiple) { - enableButtonOk(folderValid && filesChecked); - } else { - enableButtonOk((folderValid || destinationValid) && sourceValid); - } - - kDebug() << source << source.fileName() << dest << dest.fileName(); -} - -void NewTransferDialog::slotFinished(int resultCode) -{ - if (resultCode == KDialog::Accepted) { - dialogAccepted(); - } - clear(); -} - -void NewTransferDialog::dialogAccepted() -{ - kDebug() << "Dialog accepted."; - - //an existing transfer has been specified and since ok was clicked, it was chosen to be overwritten - if (m_existingTransfer) { - kDebug() << "Removing existing transfer:" << m_existingTransfer; - KGet::delTransfer(m_existingTransfer); - } - - //set the last directory - QString dir = m_destination.toLocalFile(); - if (!QFileInfo(dir).isDir()) { - dir = m_destination.directory(); - } - Settings::setLastDirectory(dir); - Settings::self()->writeConfig(); - - const QString group = ui.groupComboBox->currentText(); - - ///add data to create transfers - QList data; - if (!m_multiple) { - if (m_overWriteSingle) { - kDebug() << "Removing existing file:" << m_destination; - //removes m_destination if it exists, do that here so that it is removed no matter if a transfer could be created or not - //as the user decided to throw the file away - FileDeleter::deleteFile(m_destination); - } - - //sourceUrl is valid, has been checked before - const KUrl sourceUrl = KUrl(ui.urlRequester->text().trimmed()); - kDebug() << "Downloading" << sourceUrl << "to" << m_destination; - data << KGet::TransferData(sourceUrl, m_destination, group, true); - } else { - KUrl::List list; - for (int i = 0; i != ui.listWidget->count(); ++i) { - QListWidgetItem *item = ui.listWidget->item(i); - - //find selected sources - if (item->checkState() == Qt::Checked) { - //both sourceUrl and destUrl are valid, they have been tested in checkInput - const KUrl sourceUrl = KUrl(item->text().trimmed()); - const KUrl destUrl = UrlChecker::destUrl(m_destination, sourceUrl); - kDebug() << "Downloading" << sourceUrl << "to" << destUrl; - - //file exists already, remove it - if (item->background() == m_existingFileBackground) { - kDebug() << "Removing existing file:" << destUrl; - //removes destUrl if it exists, do that here so that it is removed no matter if a transfer could be created or not - //as the user decided to throw the file away - FileDeleter::deleteFile(destUrl); - } - - data << KGet::TransferData(sourceUrl, destUrl, group, true); - } - } - } - - if (!data.isEmpty()) { - Settings::setLastGroup(ui.groupComboBox->currentText()); - KGet::createTransfers(data); - } -} - -void NewTransferDialog::setInformation(const QString &information) -{ - ui.errorWidget->setMessageType(KMessageWidget::Information); - ui.errorWidget->setText(information); - ui.errorWidget->setVisible(!information.isEmpty()); -} - -void NewTransferDialog::setWarning(const QString &warning) -{ - ui.errorWidget->setMessageType(KMessageWidget::Warning); - ui.errorWidget->setText(warning); - ui.errorWidget->setVisible(!warning.isEmpty()); -} - - - -/** - * NOTE some checks in this class might seem redundant, though target is to display as few dialogs, and then preferable - * the NewTransferDialog, to the user as possible i.e. if not enough information -- e.g. no destination folder - * determinable, ...-- is present for a url or a group of urls they won't be added as transfer, - * instead the NewTransferDialog will be shown - * - * This also tries to add as many transfers as possible with one run, to ensure a high speed - */ -NewTransferDialogHandler::NewTransferDialogHandler(QObject *parent) - : QObject(parent), - m_nextJobId(0) -{ -} - -NewTransferDialogHandler::~NewTransferDialogHandler() -{ -} - - -void NewTransferDialogHandler::showNewTransferDialog(const KUrl &url) -{ - showNewTransferDialog(url.isEmpty() ? KUrl::List() : KUrl::List() << url); -} - -void NewTransferDialogHandler::showNewTransferDialog(KUrl::List urls) -{ - if (urls.isEmpty()) { - newTransferDialogHandler->createDialog(urls, QString()); - return; - } - - QHash::iterator itUrls = newTransferDialogHandler->m_urls.insert(newTransferDialogHandler->m_nextJobId, UrlData()); - QString folder; - QString suggestedFileName; - - ///Only two urls defined, check if second one is a path or a file name - if (urls.count() == 2) { - const KUrl lastUrl = urls.last(); - QDir dir(lastUrl.toLocalFile()); - - //check if last url is a file path, either absolute or relative - if (lastUrl.isLocalFile()) { - if (QDir::isAbsolutePath(lastUrl.toLocalFile())) { - if (dir.exists()) { - //second url is a folder path - folder = lastUrl.path(KUrl::AddTrailingSlash); - } else { - //second url is a file path, use this one - folder = lastUrl.directory(KUrl::AddTrailingSlash); - suggestedFileName = lastUrl.fileName(); - } - urls.removeLast(); - } else { - //second url is just a file name - suggestedFileName = lastUrl.fileName(KUrl::LeaveTrailingSlash); - urls.removeLast(); - } - } else if (!lastUrl.isValid() || (lastUrl.scheme().isEmpty() && lastUrl.directory().isEmpty())) { - // Sometimes valid filenames are not recognised by KURL::isLocalFile(), they are marked as invalid then - suggestedFileName = lastUrl.url(); - urls.removeLast(); - } - } - - ///More than two urls defined, and last is local and will be used as destination directory - if (urls.count() > 2 && urls.last().isLocalFile()) { - - /** - * FIXME should the code be uncommented again, though then inputing a wrong destination like - * ~/Downloads/folderNotExisting would result in ~/Downloads/ instead of informing the user - * and giving them the possibility to improve their mistake - */ -// if (!QFileInfo(urls.last().toLocalFile()).isDir()) { -// folder = urls.last().directory(KUrl::AddTrailingSlash); -// } else { - folder = urls.last().path(KUrl::AddTrailingSlash);//checks if that folder is correct happen later -// } - urls.removeLast(); - } - - //add a folder or suggestedFileName if they are valid - if (!folder.isEmpty() && KGet::isValidDestDirectory(folder)) { - (*itUrls).folder = folder; - } - if (!suggestedFileName.isEmpty()) { - (*itUrls).suggestedFileName = KUrl(suggestedFileName).pathOrUrl();//pathOrUrl to get a non percent encoded url - } - - newTransferDialogHandler->m_numJobs[newTransferDialogHandler->m_nextJobId] = urls.count(); - foreach (const KUrl &url, urls) { - // see bko:185283 - KIO::Job *job = mostLocalUrlJob(url); - job->setProperty("jobId", (newTransferDialogHandler->m_nextJobId)); - connect(job, SIGNAL(result(KJob*)), newTransferDialogHandler, SLOT(slotMostLocalUrlResult(KJob*))); - job->start(); - } - - ++(newTransferDialogHandler->m_nextJobId); -} - -void NewTransferDialogHandler::slotMostLocalUrlResult(KJob *j) -{ - MostLocalUrlJob *job = static_cast(j); - const int jobId = job->property("jobId").toInt(); - - if (job->error()) { - kWarning() << "An error happened for" << job->url(); - } else { - m_urls[jobId].urls << job->mostLocalUrl(); - } - --m_numJobs[jobId]; - - if (m_numJobs[jobId] <= 0) { - handleUrls(jobId); - } -} - -void NewTransferDialogHandler::handleUrls(const int jobId) -{ - QHash::iterator itUrls = m_urls.find(jobId); - if (itUrls == m_urls.end()) { - kWarning() << "JobId" << jobId << "was not defined, could not handle urls for it."; - return; - } - - KUrl::List urls = (*itUrls).urls; - UrlChecker::removeDuplicates(urls); - - QString folder = (*itUrls).folder; - if (!folder.isEmpty() && (UrlChecker::checkFolder(KUrl(folder), true) != UrlChecker::NoError)) { - folder.clear(); - } - - const QString suggestedFileName = (*itUrls).suggestedFileName; - KUrl newDest; - const KUrl folderUrl = KUrl(folder); - - //check if the sources are correct - UrlChecker check(UrlChecker::Source); - check.addUrls(urls); - check.displayErrorMessages(); - check.existingTransfers(); - urls = check.correctUrls(); - - QList data; - - ///Just one file to download, with a specified suggestedFileName, handle if possible - if (!suggestedFileName.isEmpty() && (urls.count() == 1)) { - const KUrl sourceUrl = urls.first(); - const QList groups = KGet::groupsFromExceptions(sourceUrl); - const QString groupName = (groups.isEmpty() ? QString() : groups.first()->name()); - QString defaultFolder; - if (groups.isEmpty()) { - defaultFolder = (Settings::askForDestination() ? QString() : KGlobalSettings::downloadPath()); - } else { - defaultFolder = groups.first()->defaultFolder(); - } - - if (!folder.isEmpty()) { - const KUrl destUrl = UrlChecker::destUrl(KUrl(folder), sourceUrl, suggestedFileName); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest, groupName); - } - urls.removeFirst(); - } else if (((!groups.isEmpty() && !Settings::directoriesAsSuggestion()) || !Settings::askForDestination()) && - (UrlChecker::checkFolder(KUrl(defaultFolder)) == UrlChecker::NoError)) { - const KUrl destUrl = UrlChecker::destUrl(KUrl(defaultFolder), sourceUrl, suggestedFileName); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest, groupName); - } - urls.removeFirst(); - } - } - - ///A valid folder has been defined, use that for downloading - if (!folder.isEmpty()) { - //find the associated groups first, we just need the first matching group though - const QList groups = KGet::allTransferGroups(); - foreach (TransferGroupHandler *group, groups) { - if (urls.isEmpty()) { - break; - } - - const QString groupName = group->name(); - const QStringList patterns = group->regExp().pattern().split(','); - - //find all urls where a group can be identified - KUrl::List::iterator it = urls.begin(); - while (it != urls.end()) { - const KUrl sourceUrl = *it; - if (KGet::matchesExceptions(sourceUrl, patterns)) { - const KUrl destUrl = UrlChecker::destUrl(folderUrl, sourceUrl); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest, groupName); - } - it = urls.erase(it); - } else { - ++it; - } - } - } - - //there are still some unhandled urls, i.e. for those no group could be found, add them with an empty group - foreach (const KUrl &sourceUrl, urls) { - const KUrl destUrl = UrlChecker::destUrl(folderUrl, sourceUrl); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest); - } - } - - //all urls have been handled - urls.clear(); - } - - ///Now handle default folders/groups - kDebug() << "DIRECTORIES AS SUGGESTION" << Settings::directoriesAsSuggestion(); - if (!Settings::directoriesAsSuggestion() && !urls.isEmpty()) { - kDebug() << "No, Directories not as suggestion"; - - //find the associated groups first, we just need the first matching group though - const QList groups = KGet::allTransferGroups(); - foreach (TransferGroupHandler *group, groups) { - if (urls.isEmpty()) { - break; - } - - const KUrl folderUrl = KUrl(group->defaultFolder()); - if (UrlChecker::checkFolder(folderUrl) != UrlChecker::NoError) { - continue; - } - - const QString groupName = group->name(); - const QStringList patterns = group->regExp().pattern().split(','); - - KUrl::List::iterator it = urls.begin(); - while (it != urls.end()) { - const KUrl sourceUrl = *it; - if (KGet::matchesExceptions(sourceUrl, patterns)) { - const KUrl destUrl = UrlChecker::destUrl(folderUrl, sourceUrl); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest, groupName); - } - - it = urls.erase(it); - } else { - ++it; - } - } - } - } - - ///Download the rest of the urls to KGlobalSettings::downloadPath() if the user is not aksed for a destination - if (!Settings::askForDestination()) { - //the download path will be always used - const QString dir = KGlobalSettings::downloadPath(); - if (!dir.isEmpty()) { - KUrl::List::iterator it = urls.begin(); - while (it != urls.end()) { - const KUrl sourceUrl = *it; - const KUrl destUrl = UrlChecker::destUrl(dir, sourceUrl); - newDest = check.checkExistingFile(sourceUrl, destUrl); - if (!newDest.isEmpty()) { - data << KGet::TransferData(sourceUrl, newDest); - } - - it = urls.erase(it); - } - } - } - - ///Now create transfers for the urls that provided enough data - if (!data.isEmpty()) { - KGet::createTransfers(data); - } - - ///Handle custom newtransferdialogs... - if ((!m_dialog || m_dialog->isEmpty()) && urls.count() == 1) {//FIXME why the m_dialog check? whenever a dialog has been created this would not be shown? - KUrl url = urls.first(); - QPointer dialog; - foreach (TransferFactory * factory, KGet::factories()) { - const QList groups = KGet::groupsFromExceptions(url); - dialog = factory->createNewTransferDialog(url, suggestedFileName, !groups.isEmpty() ? groups.first() : 0); - if (dialog) { - KWindowInfo info = KWindowSystem::windowInfo(KGet::m_mainWindow->winId(), NET::WMDesktop, NET::WMDesktop); - KWindowSystem::setCurrentDesktop(info.desktop()); - KWindowSystem::forceActiveWindow(KGet::m_mainWindow->winId()); - - dialog->exec(); - delete dialog; - } - } - } - - m_numJobs.remove(jobId); - m_urls.erase(itUrls); - - ///Display default NewTransferDialog - if (!urls.isEmpty()) { - createDialog(urls, suggestedFileName); - } -} - -void NewTransferDialogHandler::createDialog(const KUrl::List &urls, const QString &suggestedFileName) -{ - if (!m_dialog) { - m_dialog = new NewTransferDialog(KGet::m_mainWindow); - } - - m_dialog->m_window = KGet::m_mainWindow; - m_dialog->showDialog(urls, suggestedFileName); -} - -#include "moc_newtransferdialog.cpp" diff --git a/kget/ui/newtransferdialog.h b/kget/ui/newtransferdialog.h deleted file mode 100644 index 267f1b96..00000000 --- a/kget/ui/newtransferdialog.h +++ /dev/null @@ -1,165 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 by Javier Goday - Copyright (C) 2008 - 2009 by Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef NEW_TRANSFER_DIALOG_H -#define NEW_TRANSFER_DIALOG_H - -#include -#include -#include - -#include "ui_newtransferwidget.h" - -class KJob; -class TransferHandler; - -/** -* Dialog to allow add one or more transfers to kget. -* If only one transfer is added then the dialog shows a KUrlRequester. -* If a list of transfers are added then the dialog shows a KListWidget (multiple = true) -* with the transfers as checkable items. -* Also display a KUrlComboRequester for the destination file (or folder if multiple = true) -* And a QComboBox with the groups of transfer in case there are more than one -* -* @note this class is private and should be used via NewTransferDialogHandler -*/ -class NewTransferDialog : public KDialog -{ - Q_OBJECT - - friend class NewTransferDialogHandler; - - public: - ~NewTransferDialog(); - - public slots: - /** - * Called when the transfer group or the urlREquester changed, the dialog sets the default destination - * for transfers in the new group - */ - void setDefaultDestination(); - - private slots: - void inputTimer(); - void checkInput(); - void slotFinished(int resultCode); - - private: - explicit NewTransferDialog(QWidget *parent = 0); - - /** - * Shows the dialog adding one url list transfers - */ - void showDialog(KUrl::List list, const QString &suggestedFileName = QString()); - void prepareDialog(); - bool isEmpty(); - - /** - * Determines where is a multiple (listwidget) or single (kurlrequester) transfer - */ - void setMultiple(bool useMultiple); - - /** - * Set sources to the dialog - */ - void setSource(const KUrl::List &sources); - - void setDestinationFileName(const QString &filename); - void setDestination(); - - void setWarning(const QString &warning); - void setInformation(const QString &information); - - void dialogAccepted(); - - void clear(); - - private: - Ui::NewTransferWidget ui; - QWidget *m_window; - QTimer *m_timer; - KUrl::List m_sources; - - //points to a folder if m_multiple otherwise to the destination - KUrl m_destination; - - TransferHandler *m_existingTransfer; - - QBrush m_existingFileBackground; - QBrush m_normalBackground; - - bool m_multiple; - bool m_overWriteSingle; -}; - -class NewTransferDialogHandler : public QObject -{ - Q_OBJECT - - public: - explicit NewTransferDialogHandler(QObject *parent = 0); - ~NewTransferDialogHandler(); - - /** - * @see showNewTransferDialog(KUrl::List) - */ - static void showNewTransferDialog(const KUrl &url = KUrl()); - - /** - * This will show a dialog to the user to input needed information. - * If the last url of the list is a local file or directory, then all files will - * be downloaded to that destination. - * If there are matching groups with default folders and the user set the option to - * use those, then the affected urls will be downloaded without showing them in the dialog - * - * @note MainWindow will always be the parent widget - */ - static void showNewTransferDialog(KUrl::List list); - - private slots: - void slotMostLocalUrlResult(KJob *job); - - private: - void handleUrls(const int jobId); - void createDialog(const KUrl::List &urls, const QString &suggestedFileName); - - private: - struct UrlData { - KUrl::List urls; - QString folder; - QString suggestedFileName; - QWidget *parent; - }; - - /** - * Always points to the next unused jobId - */ - int m_nextJobId; - - /** - * QHash - * Calling addUrls will create jobs for each url with the same id - */ - QHash m_numJobs; - - /** - * QHash - * Urls for which mosLocalUrl has finished already, - * folder and suggestedFileName can be an empty string if there are none - */ - QHash m_urls; - - QPointer m_dialog; -}; - -#endif diff --git a/kget/ui/newtransferwidget.ui b/kget/ui/newtransferwidget.ui deleted file mode 100644 index 95292ff8..00000000 --- a/kget/ui/newtransferwidget.ui +++ /dev/null @@ -1,112 +0,0 @@ - - - NewTransferWidget - - - - 0 - 0 - 400 - 367 - - - - - - - - - - - - - URL: - - - - - - - Destination: - - - - - - - - - - Transfer group: - - - - - - - - - - - - true - - - - - - - - - - - - Qt::Vertical - - - - 247 - 42 - - - - - - - - - - - KUrlRequester - QFrame -
kurlrequester.h
-
- - KListWidget - QListWidget -
klistwidget.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KUrlComboRequester - KUrlRequester -
kurlrequester.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
- - KMessageWidget - QFrame -
KMessageWidget
- 1 -
-
- -
diff --git a/kget/ui/renamefile.cpp b/kget/ui/renamefile.cpp deleted file mode 100644 index c7fa3516..00000000 --- a/kget/ui/renamefile.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "renamefile.h" -#include "core/filemodel.h" - -#include - -#include - -RenameFile::RenameFile(FileModel *model, const QModelIndex &index, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_model(model), - m_index(index) -{ - setCaption(i18n("Rename File")); - showButtonSeparator(true); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - - const QString originalName = m_model->data(m_index, Qt::DisplayRole).toString(); - m_dest = m_model->getUrl(m_index).upUrl(); - - ui.label->setText(i18n("Rename %1 to:", originalName)); - ui.name->setText(originalName); - - setButtonText(KDialog::Ok, i18n("&Rename")); - enableButtonOk(false); - - connect(ui.name, SIGNAL(textEdited(QString)), this, SLOT(updateButton())); - connect(this, SIGNAL(okClicked()), this, SLOT(rename())); -} - -void RenameFile::updateButton() -{ - const QString newName = ui.name->text(); - KUrl dest = m_dest; - dest.addPath(newName); - - const bool enabled = !newName.isEmpty() && !QFile::exists(dest.pathOrUrl()); - enableButtonOk(enabled); -} - -void RenameFile::rename() -{ - const QString newName = ui.name->text(); - m_model->rename(m_index, newName); -} - -#include "moc_renamefile.cpp" diff --git a/kget/ui/renamefile.h b/kget/ui/renamefile.h deleted file mode 100644 index 57901ba6..00000000 --- a/kget/ui/renamefile.h +++ /dev/null @@ -1,50 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 RENAMEFILE_H -#define RENAMEFILE_H - -#include -#include - -#include "ui_renamefile.h" - -class FileModel; - -class RenameFile : public KDialog -{ - Q_OBJECT - - public: - RenameFile(FileModel *model, const QModelIndex &index, QWidget *parent = 0, Qt::WFlags flags = 0); - - void setOriginalName(const QString &originalName); - - private slots: - void updateButton(); - void rename(); - - private: - FileModel *m_model; - QModelIndex m_index; - Ui::RenameFile ui; - KUrl m_dest; -}; - -#endif diff --git a/kget/ui/renamefile.ui b/kget/ui/renamefile.ui deleted file mode 100644 index e11c2f8c..00000000 --- a/kget/ui/renamefile.ui +++ /dev/null @@ -1,37 +0,0 @@ - - - RenameFile - - - - 0 - 0 - 400 - 69 - - - - - - - - - - true - - - - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
-
- -
diff --git a/kget/ui/transferdetails.cpp b/kget/ui/transferdetails.cpp deleted file mode 100644 index 0069841f..00000000 --- a/kget/ui/transferdetails.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - - 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. -*/ - -#include "transferdetails.h" - -#include "core/kget.h" - -#include -#include -#include - -#include - -TransferDetails::TransferDetails(TransferHandler * transfer) - : QWidget(0), - m_transfer(transfer) -{ - m_genericWidget = new QWidget(this); - - frm.setupUi(m_genericWidget); - - m_layout = new QVBoxLayout(this); - m_layout->addWidget(m_genericWidget); - setLayout(m_layout); - - frm.sourceContentEdit->setText(m_transfer->source().pathOrUrl()); - frm.destContentEdit->setText(m_transfer->dest().pathOrUrl()); - - //This updates the widget with the right values - slotTransferChanged(transfer, 0xFFFFFFFF); - - connect(transfer, SIGNAL(transferChangedEvent(TransferHandler*,TransferHandler::ChangesFlags)), - this, SLOT(slotTransferChanged(TransferHandler*,TransferHandler::ChangesFlags))); -} - -TransferDetails::~TransferDetails() -{ -} - -QWidget *TransferDetails::detailsWidget(TransferHandler *handler) -{ - QWidget *details = KGet::factory(handler)->createDetailsWidget(handler); - - if (!details) { // the transfer factory doesn't override the details widget so use the generic one - details = new TransferDetails(handler); - } - - return details; -} - -void TransferDetails::slotTransferChanged(TransferHandler * transfer, TransferHandler::ChangesFlags flags) -{ - kDebug() << "TransferDetails::slotTransferChanged"; - - Q_UNUSED(transfer) - - if(flags & Transfer::Tc_Status) { - frm.statusPixmapContentLabel->setPixmap(m_transfer->statusPixmap()); - frm.statusTextContentLabel->setText(m_transfer->statusText()); - - if (m_transfer->status() == Job::Finished) { - frm.speedContentLabel->setText(i18n("Average speed: %1/s", KIO::convertSize(m_transfer->averageDownloadSped()))); - } - } - - if ((flags & Transfer::Tc_TotalSize) || (flags & Transfer::Tc_DownloadedSize)) { - frm.completedContentLabel->setText(i18n("%1 of %2", KIO::convertSize(m_transfer->downloadedSize()), KIO::convertSize(m_transfer->totalSize()))); - } - - if (flags & Transfer::Tc_Percent) { - frm.progressBar->setValue(m_transfer->percent()); - } - - if ((flags & Transfer::Tc_DownloadSpeed) && (m_transfer->status() != Job::Finished)) { - int speed = m_transfer->downloadSpeed(); - - if (speed == 0) { - if(m_transfer->status() == Job::Running) - frm.speedContentLabel->setText(i18n("Stalled") ); - else - frm.speedContentLabel->setText(QString()); - } else { - frm.speedContentLabel->setText(i18n("%1/s", KIO::convertSize(speed))); - } - } - - if(flags & Transfer::Tc_FileName) { - frm.destContentEdit->setText(m_transfer->dest().pathOrUrl()); - } - - if (flags & Transfer::Tc_Source) { - frm.sourceContentEdit->setText(m_transfer->source().pathOrUrl()); - } - - frm.remainingTimeLabel->setText(KIO::convertSeconds(m_transfer->remainingTime())); -} - -#include "moc_transferdetails.cpp" diff --git a/kget/ui/transferdetails.h b/kget/ui/transferdetails.h deleted file mode 100644 index f6942f8e..00000000 --- a/kget/ui/transferdetails.h +++ /dev/null @@ -1,45 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - - 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. -*/ - -#ifndef TRANSFERDETAILS_H -#define TRANSFERDETAILS_H - -#include - -#include "core/transferhandler.h" -#include "core/plugin/transferfactory.h" -#include "ui_transferdetailsfrm.h" - -#include -#include -#include - -class TransferDetails : public QWidget -{ - Q_OBJECT - public: - TransferDetails(TransferHandler * transfer); - ~TransferDetails(); - - // gets the generic details widget if the transfer factory doesn't override it - static QWidget *detailsWidget(TransferHandler *transfer); - - public slots: - void slotTransferChanged(TransferHandler * transfer, TransferHandler::ChangesFlags flags); - - private: - TransferHandler * m_transfer; - QVBoxLayout * m_layout; - QWidget * m_genericWidget; - - Ui::TransferDetailsFrm frm; -}; - -#endif diff --git a/kget/ui/transferdetailsfrm.ui b/kget/ui/transferdetailsfrm.ui deleted file mode 100644 index c8660bef..00000000 --- a/kget/ui/transferdetailsfrm.ui +++ /dev/null @@ -1,188 +0,0 @@ - - - TransferDetailsFrm - - - - 0 - 0 - 530 - 211 - - - - - 0 - 0 - - - - - 6 - - - 9 - - - - - 0 - - - 6 - - - - - true - - - - - - - Saving to: - - - - - - - Source: - - - - - - - true - - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 10 - - - - - - - - - - - 6 - - - 0 - - - - - <done> MiB of <todo> MiB - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Status: - - - - - - - <icon> - - - - - - - <status> - - - - - - - - - 6 - - - 0 - - - - - <speed> - - - - - - - Qt::Horizontal - - - - 211 - 20 - - - - - - - - Remaining Time: - - - - - - - <remaining time> - - - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
-
- -
diff --git a/kget/ui/transfersettingsdialog.cpp b/kget/ui/transfersettingsdialog.cpp deleted file mode 100644 index 56b92c3f..00000000 --- a/kget/ui/transfersettingsdialog.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ -#include "transfersettingsdialog.h" -#include "mirror/mirrorsettings.h" -#include "renamefile.h" -#include "verificationdialog.h" -#include "settings.h" - -#include "core/transferhandler.h" -#include "core/filemodel.h" -#include "core/verifier.h" - -#include -#include -#include -#include - -TransferSettingsDialog::TransferSettingsDialog(QWidget *parent, TransferHandler *transfer) - : KGetSaveSizeDialog("TransferSettingsDialog", parent), - m_transfer(transfer), - m_model(m_transfer->fileModel()), - m_proxy(0) -{ - setCaption(i18n("Transfer Settings for %1", m_transfer->source().fileName())); - showButtonSeparator(true); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - ui.ktitlewidget->setPixmap(SmallIcon("preferences-other")); - ui.downloadSpin->setValue(m_transfer->downloadLimit(Transfer::VisibleSpeedLimit)); - ui.uploadSpin->setValue(m_transfer->uploadLimit(Transfer::VisibleSpeedLimit)); - ui.ratioSpin->setValue(m_transfer->maximumShareRatio()); - ui.destination->setUrl(m_transfer->directory().pathOrUrl()); - ui.destination->lineEdit()->setReadOnly(true); - ui.rename->setIcon(KIcon("edit-rename")); - ui.mirrors->setIcon(KIcon("download")); - ui.verification->setIcon(KIcon("document-decrypt")); - - if (m_model) - { - m_model->watchCheckState(); - m_proxy = new QSortFilterProxyModel(this); - m_proxy->setSourceModel(m_model); - ui.treeView->setModel(m_proxy); - ui.treeView->sortByColumn(0, Qt::AscendingOrder); - - QByteArray loadedState = QByteArray::fromBase64(Settings::transferSettingsHeaderState().toAscii()); - if (!loadedState.isEmpty()) { - ui.treeView->header()->restoreState(loadedState); - } else { - ui.treeView->header()->resizeSection(0, ui.treeView->header()->defaultSectionSize() * 3); - } - } - - updateCapabilities(); - - connect(m_transfer, SIGNAL(capabilitiesChanged()), this, SLOT(updateCapabilities())); - connect(this, SIGNAL(accepted()), SLOT(save())); - connect(this, SIGNAL(finished()), this, SLOT(slotFinished())); - connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(slotSelectionChanged())); - connect(ui.rename, SIGNAL(clicked(bool)), this, SLOT(slotRename())); - connect(ui.mirrors, SIGNAL(clicked(bool)), this, SLOT(slotMirrors())); - connect(ui.verification, SIGNAL(clicked(bool)), this, SLOT(slotVerification())); -} - -TransferSettingsDialog::~TransferSettingsDialog() -{ - if (m_model) { - Settings::setTransferSettingsHeaderState(ui.treeView->header()->saveState().toBase64()); - } -} - -QSize TransferSettingsDialog::sizeHint() const -{ - QSize sh = KDialog::sizeHint(); - sh.setWidth(sh.width() * 1.7); - return sh; -} - -void TransferSettingsDialog::updateCapabilities() -{ - const int capabilities = m_transfer->capabilities(); - - const bool supportsSpeedLimit = capabilities & Transfer::Cap_SpeedLimit; - ui.labelDownload->setVisible(supportsSpeedLimit); - ui.downloadSpin->setVisible(supportsSpeedLimit); - ui.labelUpload->setVisible(supportsSpeedLimit); - ui.uploadSpin->setVisible(supportsSpeedLimit); - ui.labelShareRatio->setVisible(supportsSpeedLimit); - ui.ratioSpin->setVisible(supportsSpeedLimit); - - ui.destination->setEnabled(capabilities & Transfer::Cap_Moving); - ui.mirrors->setVisible(capabilities & Transfer::Cap_MultipleMirrors); - ui.rename->setVisible(capabilities & Transfer::Cap_Renaming); -} - -void TransferSettingsDialog::slotMirrors() -{ - const QModelIndex index = m_proxy->mapToSource(ui.treeView->selectionModel()->selectedIndexes().first()); - KDialog *mirrors = new MirrorSettings(this, m_transfer, m_model->getUrl(index)); - mirrors->setAttribute(Qt::WA_DeleteOnClose); - mirrors->show(); -} - -void TransferSettingsDialog::slotRename() -{ - const QModelIndex index = m_proxy->mapToSource(ui.treeView->selectionModel()->selectedIndexes().first()); - RenameFile *renameDlg = new RenameFile(m_model, index, this); - renameDlg->setAttribute(Qt::WA_DeleteOnClose); - renameDlg->show(); -} - -void TransferSettingsDialog::slotVerification() -{ - const QModelIndex index = m_proxy->mapToSource(ui.treeView->selectionModel()->selectedIndexes().first()); - KDialog *verification = new VerificationDialog(this, m_transfer, m_model->getUrl(index)); - verification->setAttribute(Qt::WA_DeleteOnClose); - verification->show(); -} - -void TransferSettingsDialog::slotSelectionChanged() -{ - bool enabled = false; - //only enable rename when one item is selected and when this item is a file - if (ui.treeView->selectionModel()->selectedRows().count() == 1) - { - const QModelIndex index = m_proxy->mapToSource(ui.treeView->selectionModel()->selectedIndexes().first()); - if (index.isValid() && !(static_cast(index.internalPointer()))->childCount()) - { - enabled = true; - } - } - ui.mirrors->setEnabled(enabled); - ui.rename->setEnabled(enabled); - ui.verification->setEnabled(enabled); -} - -void TransferSettingsDialog::save() -{//TODO: Set to -1 when no limit - KUrl oldDirectory = m_transfer->directory(); - KUrl newDirectory = ui.destination->url(); - if ((oldDirectory != newDirectory) && !m_transfer->setDirectory(newDirectory)) - { - KMessageBox::error(this, i18n("Changing the destination did not work, the destination stays unmodified."), i18n("Destination unmodified")); - } - - m_transfer->setDownloadLimit(ui.downloadSpin->value(), Transfer::VisibleSpeedLimit); - m_transfer->setUploadLimit(ui.uploadSpin->value(), Transfer::VisibleSpeedLimit); - m_transfer->setMaximumShareRatio(ui.ratioSpin->value()); -} - -void TransferSettingsDialog::slotFinished() -{ - if (m_model) - { - m_model->stopWatchCheckState(); - } -} - -#include "moc_transfersettingsdialog.cpp" diff --git a/kget/ui/transfersettingsdialog.h b/kget/ui/transfersettingsdialog.h deleted file mode 100644 index 4f4dc172..00000000 --- a/kget/ui/transfersettingsdialog.h +++ /dev/null @@ -1,50 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2008 Lukas Appelhans - Copyright (C) 2009 Matthias Fuchs - - 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. -*/ - -#ifndef TRANSFERSETTINGSDIALOG_H -#define TRANSFERSETTINGSDIALOG_H - -#include "ui_transfersettingsdialog.h" -#include "../core/basedialog.h" - -#include - -class FileModel; -class RenameFile; -class TransferHandler; - -class TransferSettingsDialog : public KGetSaveSizeDialog -{ - Q_OBJECT - public: - TransferSettingsDialog(QWidget *parent, TransferHandler *transfer); - ~TransferSettingsDialog(); - - virtual QSize sizeHint() const; - - private slots: - void updateCapabilities(); - void slotMirrors(); - void slotRename(); - void slotVerification(); - void slotSelectionChanged(); - void slotFinished(); - void save(); - - private: - TransferHandler *m_transfer; - FileModel *m_model; - QSortFilterProxyModel *m_proxy; - Ui::TransferSettingsDialog ui; -}; - -#endif - diff --git a/kget/ui/transfersettingsdialog.ui b/kget/ui/transfersettingsdialog.ui deleted file mode 100644 index 10e9c8b9..00000000 --- a/kget/ui/transfersettingsdialog.ui +++ /dev/null @@ -1,207 +0,0 @@ - - - TransferSettingsDialog - - - - 0 - 0 - 626 - 338 - - - - - - - - 0 - 0 - - - - Transfer Settings - - - - - - - QFormLayout::ExpandingFieldsGrow - - - - - Download des&tination: - - - destination - - - - - - - KFile::Directory|KFile::ExistingOnly - - - - - - - true - - - Not set - - - KiB/s - - - 100000 - - - - - - - true - - - Not set - - - KiB/s - - - 100000 - - - - - - - true - - - Not set - - - - - - - &Upload limit: - - - uploadSpin - - - - - - - &Download limit: - - - downloadSpin - - - - - - - Maximum &share ratio: - - - ratioSpin - - - - - - - - - - - true - - - 70 - - - - - - - - - false - - - Modify the mirrors used for downloading. - - - Mirrors - - - - - - - false - - - Rename - - - - - - - false - - - Verification - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
- - KTitleWidget - QWidget -
ktitlewidget.h
-
- - KUrlRequester - QFrame -
kurlrequester.h
-
-
- -
diff --git a/kget/ui/transfersview.cpp b/kget/ui/transfersview.cpp deleted file mode 100644 index 3e29d2cf..00000000 --- a/kget/ui/transfersview.cpp +++ /dev/null @@ -1,334 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - Copyright (C) 2009 Lukas Appelhans - - 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. -*/ - -#include "transfersview.h" -#include "settings.h" -#include "transfersviewdelegate.h" -#include "transferdetails.h" -#include "core/transfertreemodel.h" -#include "core/kget.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -TransfersView::TransfersView(QWidget * parent) - : QTreeView(parent) -{ -// setItemsExpandable(false); - setRootIsDecorated(false); - setAnimated(true); - setAllColumnsShowFocus(true); - header()->setDefaultAlignment(Qt::AlignCenter); - header()->setMinimumSectionSize(80); - header()->setContextMenuPolicy(Qt::CustomContextMenu); - header()->setClickable(true); - m_headerMenu = new KMenu(header()); - - setSelectionMode(QAbstractItemView::ExtendedSelection); - setDragEnabled(true); - setAcceptDrops(true); - setDropIndicatorShown(true); - setEditTriggers(QAbstractItemView::NoEditTriggers); - setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - - connect(header(), SIGNAL(customContextMenuRequested(QPoint)), - SLOT(slotShowHeaderMenu(QPoint))); - connect(header(), SIGNAL(sectionCountChanged(int,int)), this, SLOT(populateHeaderActions())); - connect(header(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(slotSectionMoved(int,int,int))); - connect(header(), SIGNAL(sectionResized(int,int,int)), this, SLOT(slotSaveHeader())); - connect(this, SIGNAL(doubleClicked(QModelIndex)), - this, SLOT(slotItemActivated(QModelIndex))); - connect(this, SIGNAL(collapsed(QModelIndex)), - this, SLOT(slotItemCollapsed(QModelIndex))); - connect(KGet::model(), SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(closeExpandableDetails(QModelIndex,int,int))); -} - -TransfersView::~TransfersView() -{ -} - -void TransfersView::setModel(QAbstractItemModel * model) -{ - QTreeView::setModel(model); - int nGroups = model->rowCount(QModelIndex()); - - for(int i = 0; i < nGroups; i++) - { - kDebug() << "openEditor for row " << i; - openPersistentEditor(model->index(i, TransferTreeModel::Status, QModelIndex())); - } - - QByteArray loadedState = QByteArray::fromBase64(Settings::headerState().toAscii()); - if (loadedState.isEmpty()) { - setColumnWidth(0 , 230); - } else { - header()->restoreState(loadedState); - } - - //Workaround if the saved headerState is corrupted - header()->setRootIndex(QModelIndex()); - - populateHeaderActions(); - toggleMainGroup(); - connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT (toggleMainGroup())); -} - -void TransfersView::dropEvent(QDropEvent * event) -{ - QModelIndex dropIndex = indexAt(event->pos()); - QTreeView::dropEvent(event); - - setExpanded(dropIndex, true); -} - -void TransfersView::rowsInserted(const QModelIndex & parent, int start, int end) -{ - kDebug() << "TransfersView::rowsInserted"; - - if(!parent.isValid()) - { - kDebug() << "parent is not valid " << start << " " << end; - - for(int i = start; i <= end; i++) - { - kDebug() << "openEditor for row " << i; - openPersistentEditor(model()->index(i, TransferTreeModel::Status, parent)); - } - } - - QTreeView::rowsInserted(parent, start, end); - - // sadly it has to be done again, copy from setModel() above - // TODO: do it only when the model count was 0, i.e. on first item insertation - QByteArray loadedState = QByteArray::fromBase64(Settings::headerState().toAscii()); - if (loadedState.isEmpty()) { - setColumnWidth(0 , 230); - } else { - header()->restoreState(loadedState); - } - populateHeaderActions(); - - setExpanded(parent, true); - toggleMainGroup(); -} - -void TransfersView::populateHeaderActions() -{ - m_headerMenu->clear(); - m_headerMenu->addTitle(i18n("Select columns")); - - QSignalMapper *columnMapper = new QSignalMapper(this); - connect(columnMapper, SIGNAL(mapped(int)), SLOT(slotHideSection(int))); - - //Create for each column an action with the column-header as name - QVector orderedMenuItems(header()->count()); - for (int i = 0; i < header()->count(); ++i) { - KAction *action = new KAction(this); - action->setText(model()->headerData(i, Qt::Horizontal).toString()); - action->setCheckable(true); - action->setChecked(!header()->isSectionHidden(i)); - orderedMenuItems[header()->visualIndex(i)] = action; - - connect(action, SIGNAL(toggled(bool)), columnMapper, SLOT(map())); - columnMapper->setMapping(action, i); - } - - //append the sorted actions - for (int i = 0; i < orderedMenuItems.count(); ++i) { - m_headerMenu->addAction(orderedMenuItems[i]); - } -} - -void TransfersView::slotHideSection(int logicalIndex) -{ - const bool hide = !header()->isSectionHidden(logicalIndex); - header()->setSectionHidden(logicalIndex, hide); - slotSaveHeader(); -} - -void TransfersView::slotSectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex) -{ - Q_UNUSED(logicalIndex) - - //first item is the title, so increase the indexes by one - ++oldVisualIndex; - ++newVisualIndex; - QList actions = m_headerMenu->actions(); - - QAction *before = actions.last(); - if (newVisualIndex + 1 < actions.count()) { - if (newVisualIndex > oldVisualIndex) { - before = actions[newVisualIndex + 1]; - } else { - before = actions[newVisualIndex]; - } - } - - QAction *action = actions[oldVisualIndex]; - m_headerMenu->removeAction(action); - m_headerMenu->insertAction(before, action); - slotSaveHeader(); -} - -void TransfersView::slotSaveHeader() -{ - Settings::setHeaderState(header()->saveState().toBase64()); - Settings::self()->writeConfig(); -} - -void TransfersView::dragMoveEvent ( QDragMoveEvent * event ) -{ - Q_UNUSED(event) - - closeExpandableDetails(); - QTreeView::dragMoveEvent(event); -} - -void TransfersView::slotItemActivated(const QModelIndex & index) -{ - if (!index.isValid()) - return; - - TransferTreeModel * transferTreeModel = KGet::model(); - ModelItem * item = transferTreeModel->itemFromIndex(index); - TransfersViewDelegate *view_delegate = static_cast (itemDelegate()); - - if(!item) - return; - - if(!item->isGroup() && index.column() == 0) { - if(!view_delegate->isExtended(index)) { - TransferHandler *handler = item->asTransfer()->transferHandler(); - QWidget *widget = getDetailsWidgetForTransfer(handler); - - m_editingIndexes.append(index); - view_delegate->extendItem(widget, index); - } - else { - m_editingIndexes.removeAll(index); - view_delegate->contractItem(index); - } - KGet::actionCollection()->action("transfer_show_details")->setChecked(view_delegate->isExtended(index)); - } else if (!item->isGroup() && static_cast(item)->transferHandler()->status() == Job::Finished) { - new KRun(static_cast(item)->transferHandler()->dest(), this); - } -} - -void TransfersView::slotItemCollapsed(const QModelIndex & index) -{ - if (!index.isValid()) - return; - - TransferTreeModel * transferTreeModel = KGet::model(); - ModelItem * item = transferTreeModel->itemFromIndex(index); - TransfersViewDelegate *view_delegate = static_cast (itemDelegate()); - - if(!item) - return; - - if(item->isGroup()) { - TransferGroupHandler * groupHandler = item->asGroup()->groupHandler(); - QList transfers = groupHandler->transfers(); - - foreach(TransferHandler * transfer, transfers) { - kDebug() << "Transfer = " << transfer->source().prettyUrl(); - view_delegate->contractItem(KGet::model()->itemFromTransferHandler(transfer)->index()); - } - } -} - -void TransfersView::toggleMainGroup() -{ - // show or hide the first group header if there's only one download group - int nGroups = model()->rowCount(QModelIndex()); - - if(nGroups <= 1) { - setRootIndex(model()->index(0, 0, QModelIndex())); - } - else { - setRootIndex(QModelIndex()); - } - header()->setRootIndex(QModelIndex());//HACK: else the header isn't visible with no visible items in the view -} - -void TransfersView::rowsAboutToBeRemoved(const QModelIndex & parent, int start, int end) -{ - Q_UNUSED(parent) - Q_UNUSED(start) - Q_UNUSED(end) - - closeExpandableDetails(currentIndex()); -} - -void TransfersView::slotShowHeaderMenu(const QPoint &point) -{ - m_headerMenu->popup(header()->mapToGlobal(point)); -} - -void TransfersView::closeExpandableDetails(const QModelIndex &transferIndex) -{ - TransfersViewDelegate *view_delegate = static_cast (itemDelegate()); - - if(transferIndex.isValid()) { - view_delegate->contractItem(transferIndex); - m_editingIndexes.removeAll(transferIndex); - } else { - view_delegate->contractAll(); - m_editingIndexes.clear(); - } -} - -void TransfersView::selectionChanged(const QItemSelection & selected, const QItemSelection & deselected) -{ - Q_UNUSED(deselected) - if (!selected.indexes().isEmpty()) { - TransfersViewDelegate *view_delegate = static_cast(itemDelegate()); - KGet::actionCollection()->action("transfer_show_details")->setChecked(view_delegate->isExtended(selected.indexes().first())); - } - - QTreeView::selectionChanged(selected, deselected); -} - -void TransfersView::closeExpandableDetails(const QModelIndex &parent, int rowStart, int rowEnd) -{ - Q_UNUSED(parent) - Q_UNUSED(rowStart) - Q_UNUSED(rowEnd) - - TransfersViewDelegate *view_delegate = static_cast (itemDelegate()); - - view_delegate->contractAll(); - m_editingIndexes.clear(); -} - -QWidget *TransfersView::getDetailsWidgetForTransfer(TransferHandler *handler) -{ - QGroupBox *groupBox = new QGroupBox(i18n("Transfer Details")); - - QVBoxLayout *layout = new QVBoxLayout(groupBox); - QWidget *detailsWidget = TransferDetails::detailsWidget(handler); - layout->addWidget(detailsWidget); - - return groupBox; -} - -#include "moc_transfersview.cpp" diff --git a/kget/ui/transfersview.h b/kget/ui/transfersview.h deleted file mode 100644 index 88b75abf..00000000 --- a/kget/ui/transfersview.h +++ /dev/null @@ -1,59 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - - 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. -*/ - -#ifndef TRANSFERSVIEW_H -#define TRANSFERSVIEW_H - -#include - -class KMenu; -class TransferHandler; - -class TransfersView : public QTreeView -{ - Q_OBJECT - - public: - TransfersView(QWidget * parent = 0); - ~TransfersView(); - - void setModel(QAbstractItemModel * model); - - private: - void dropEvent(QDropEvent * event); - void rowsInserted(const QModelIndex &, int, int); - - protected: - void dragMoveEvent ( QDragMoveEvent * event ); - void rowsAboutToBeRemoved(const QModelIndex & parent, int start, int end); - - public slots: - void closeExpandableDetails(const QModelIndex &index = QModelIndex()); - void closeExpandableDetails(const QModelIndex &parent, int rowStart, int rowEnd); - void slotItemActivated(const QModelIndex & index); - void slotItemCollapsed(const QModelIndex & index); - - private slots: - void toggleMainGroup();// show or hide the first group header if there's only one download group - void slotShowHeaderMenu(const QPoint &point); - void selectionChanged(const QItemSelection & selected, const QItemSelection & deselected); - void slotHideSection(int logicalIndex); - void slotSectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex); - void slotSaveHeader(); - void populateHeaderActions(); - - private: - QWidget *getDetailsWidgetForTransfer(TransferHandler *handler); - - QList m_editingIndexes; - KMenu *m_headerMenu; -}; - -#endif diff --git a/kget/ui/transfersviewdelegate.cpp b/kget/ui/transfersviewdelegate.cpp deleted file mode 100644 index bb3d1ac8..00000000 --- a/kget/ui/transfersviewdelegate.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - Copyright (C) 2007 by Javier Goday - Copyright (C) 2008 Lukas Appelhans - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "ui/transfersviewdelegate.h" - -#include "transferdetails.h" -#include "ui/contextmenu.h" -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfergrouphandler.h" -#include "core/transfertreemodel.h" -#include "core/transfertreeselectionmodel.h" -#include "settings.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -GroupStatusButton::GroupStatusButton(const QModelIndex & index, QWidget * parent) - : QToolButton(parent), - m_status(None), - m_index(index), - m_timerId(-1), - m_iconSize(22), - m_gradientId(0) -{ - setAttribute(Qt::WA_NoSystemBackground); -} - -void GroupStatusButton::checkStateSet() -{ - // kDebug() << "GroupStatusButton::checkStateSet"; - - QToolButton::checkStateSet(); - - if(isChecked()) - { - if(m_status == None) - m_gradientId = 0.9; - m_status = Selecting; - } - else - { - if(m_status == None) - m_gradientId = 1; - m_status = Deselecting; - } - - setMouseTracking(!isChecked()); - - if(m_timerId == -1) - m_timerId = startTimer(100); -} - -void GroupStatusButton::enterEvent(QEvent * event) -{ - Q_UNUSED(event) - if(!isChecked()) - { - m_status = Blinking; - - if(m_timerId == -1) - { - m_timerId = startTimer(100); - - if(m_status == !BlinkingExiting) - m_gradientId = 1; - } - } -} - -void GroupStatusButton::leaveEvent(QEvent * event) -{ - Q_UNUSED(event) - if(m_status == Blinking) - m_status = BlinkingExiting; -} - -void GroupStatusButton::paintEvent(QPaintEvent * event) -{ - Q_UNUSED(event) - - QPainter p(this); - - const int offset = (rect().width() - m_iconSize) / 2; - - if(m_gradientId == 0) - m_gradientId = isChecked() ? 1 : 0.7; - - QRadialGradient gradient(height() / 2.0, height() / 2.0, height() / 2); - - QPen pen; - - if(KGet::selectionModel()->isSelected(m_index)) - { - gradient.setColorAt(0, palette().color(QPalette::AlternateBase)); - gradient.setColorAt(m_gradientId, Qt::transparent); - gradient.setColorAt(1, Qt::transparent); - pen.setColor(palette().color(QPalette::AlternateBase)); - } - else - { - gradient.setColorAt(0, palette().color(QPalette::Highlight)); - gradient.setColorAt(m_gradientId, Qt::transparent); - gradient.setColorAt(1, Qt::transparent); - pen.setColor(palette().color(QPalette::Highlight)); - } - - QRect r = rect().adjusted(0, 0, 0, 1); - - p.fillRect(r, gradient); - - p.setRenderHint(QPainter::Antialiasing); - - if(isChecked()) - { - pen.setWidth(1); - p.setPen(pen); - p.drawEllipse(rect().x()+5, rect().y()+4, rect().width()-10, rect().width()-10); - } - - p.drawPixmap(rect().topLeft() + QPoint(offset, offset - 1), - icon().pixmap(m_iconSize, isChecked() || m_status == Blinking ? - QIcon::Normal : QIcon::Disabled)); -} - -void GroupStatusButton::timerEvent(QTimerEvent *event) -{ - Q_UNUSED(event) - - if(m_status == Selecting) - { - m_gradientId+=0.04; - - if(m_gradientId >= 1) - { - m_status = None; - m_gradientId = 1; - killTimer(m_timerId); - m_timerId = -1; - } - } - else if(m_status == Deselecting) - { - m_gradientId-=0.04; - - if(m_gradientId <= 0.7) - { - m_status = None; - m_gradientId = 0.7; - killTimer(m_timerId); - m_timerId = -1; - } - } - else if(m_status == Blinking) - { - if(isChecked()) - { - m_status = Selecting; - m_gradientId = 0.9; - return; - } - - m_gradientId-=0.04; - - if(m_gradientId <= 0.7) - { - m_gradientId = 1; - } - } - else if(m_status == BlinkingExiting) - { - m_gradientId-=0.04; - - if(m_gradientId <= 0.7) - { - m_status = None; - m_gradientId = 0.7; - killTimer(m_timerId); - m_timerId = -1; - } - } - - update(); -} - -GroupStatusEditor::GroupStatusEditor(const QModelIndex &index, QWidget *parent) - : QWidget(parent), - m_index(index) -{ - setMinimumWidth(80); - - m_layout = new QHBoxLayout(); - m_layout->addStretch(); - setLayout(m_layout); - - m_btGroup = new QButtonGroup(this); - m_btGroup->setExclusive(true); - - m_startBt = new GroupStatusButton(m_index, this); - m_startBt->setCheckable(true); - m_startBt->setAutoRaise(true); - m_startBt->setIcon(KIcon("media-playback-start")); - m_startBt->setFixedSize(36, 36); - m_startBt->setIconSize(QSize(22, 22)); - m_layout->addWidget(m_startBt); - m_btGroup->addButton(m_startBt); - - m_stopBt = new GroupStatusButton(m_index, this); - m_stopBt->setCheckable(true); - m_stopBt->setAutoRaise(true); - m_stopBt->setIcon(KIcon("media-playback-pause")); - m_stopBt->setFixedSize(36, 36); - m_stopBt->setIconSize(QSize(22, 22)); - m_layout->addWidget(m_stopBt); - m_btGroup->addButton(m_stopBt); - - m_stopBt->setChecked(true); - - m_layout->addStretch(); - m_layout->setMargin(1); - - connect(m_startBt, SIGNAL(toggled(bool)), this, SLOT(slotStatusChanged())); -} - -void GroupStatusEditor::setRunning(bool running) -{ - if(running == m_startBt->isChecked()) - return; - - if(running) - m_startBt->setChecked(true); - else - m_stopBt->setChecked(true); -} - -bool GroupStatusEditor::isRunning() -{ - return m_startBt->isChecked(); -} - -void GroupStatusEditor::slotStatusChanged() -{ - emit changedStatus(this); -} - - -BasicTransfersViewDelegate::BasicTransfersViewDelegate(QAbstractItemView *parent) - : KExtendableItemDelegate(parent) -{ -} - -QWidget *BasicTransfersViewDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Status) { - GroupStatusEditor *qroupStatusEditor = new GroupStatusEditor(index, parent); - connect(qroupStatusEditor, SIGNAL(changedStatus(GroupStatusEditor*)), this, SLOT(slotGroupStatusChanged(GroupStatusEditor*))); - return qroupStatusEditor; - } else { - return KExtendableItemDelegate::createEditor(parent, option, index); - } -} - -void BasicTransfersViewDelegate::slotGroupStatusChanged(GroupStatusEditor *editor) -{ - commitData(editor); -} - -void BasicTransfersViewDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Status) { - GroupStatusEditor *groupEditor = static_cast(editor); - groupEditor->setRunning(KGet::model()->itemFromIndex(index)->asGroup()->groupHandler()->status() == JobQueue::Running); - } else { - KExtendableItemDelegate::setEditorData(editor, index); - } -} - -void BasicTransfersViewDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ - if (index.column() == TransferTreeModel::Status) { - GroupStatusEditor *groupEditor = static_cast(editor); - TransferGroupHandler *groupHandler = KGet::model()->itemFromIndex(index)->asGroup()->groupHandler(); - - if (groupEditor->isRunning()) { - groupHandler->start(); - } else { - groupHandler->stop(); - } - } else { - KExtendableItemDelegate::setModelData(editor, model, index); - } -} - -TransfersViewDelegate::TransfersViewDelegate(QAbstractItemView *parent) - : BasicTransfersViewDelegate(parent) -{ - Q_ASSERT(qobject_cast(parent)); - setExtendPixmap(SmallIcon("arrow-right")); - setContractPixmap(SmallIcon("arrow-down")); -} - -void TransfersViewDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const -{ - TransferTreeModel * transferTreeModel = KGet::model(); - - ModelItem * item = transferTreeModel->itemFromIndex(index); - - if (item->isGroup()) - { - painter->save(); - - if (option.state & QStyle::State_Selected) - { - } - else - { - static bool backgroundInitialized = false; - static QPixmap groupBackground(64, 35); - static QPalette palette(QApplication::palette()); - - if(!backgroundInitialized || palette!= QApplication::palette()) - { - const QRect rect = groupBackground.rect(); - QPainter p(&groupBackground); - - QLinearGradient gradient(rect.x(), rect.y(), - rect.x(), (rect.y() + rect.height())); - - gradient.setColorAt(0, QApplication::palette().color(QPalette::Base)); - gradient.setColorAt(0.5, QApplication::palette().color(QPalette::AlternateBase).darker(110)); - gradient.setColorAt(1, QApplication::palette().color(QPalette::Base)); - - p.fillRect(rect, gradient); - backgroundInitialized = true; - } - - painter->drawTiledPixmap(option.rect, groupBackground); - } - - KExtendableItemDelegate::paint(painter, option, index); - - painter->restore(); - } - else { - if (KGet::selectionModel()->isSelected(index)) - painter->fillRect(option.rect, QApplication::palette().color(option.state & QStyle::State_Active ? - QPalette::Active : QPalette::Inactive, - QPalette::Highlight)); - - KExtendableItemDelegate::paint(painter, option, index); - - if (index.column() == 3 && !isExtended(transferTreeModel->index(index.row(), 0, index.parent()))) { // the percent column - TransferHandler *transferHandler = item->asTransfer()->transferHandler(); - - // following progressbar code has mostly been taken from Qt4 examples/network/torrent/mainview.cpp - // Set up a QStyleOptionProgressBar to precisely mimic the - // environment of a progress bar. - QStyleOptionProgressBar progressBarOption; - progressBarOption.state = QStyle::State_Enabled; - progressBarOption.direction = QApplication::layoutDirection(); - progressBarOption.rect = option.rect; - progressBarOption.fontMetrics = QApplication::fontMetrics(); - progressBarOption.minimum = 0; - progressBarOption.maximum = 100; - progressBarOption.textAlignment = Qt::AlignCenter; - progressBarOption.textVisible = true; - - // Set the progress and text values of the style option. - int progress = transferHandler->percent(); - if (progress >= 0 && progress <= 100) { - progressBarOption.progress = progress; - progressBarOption.text = QString().sprintf("%d%%", progressBarOption.progress); - } else { - progressBarOption.text = i18nc("not available", "n/a"); - } - - progressBarOption.rect.setY(progressBarOption.rect.y() + - (option.rect.height() - QApplication::fontMetrics().height()) / 2); - progressBarOption.rect.setHeight(QApplication::fontMetrics().height()); - - // Draw the progress bar onto the view. - QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter); - } - } - -/// These lines are just for testing purposes. Uncomment them to show on the view the repaint events. -// static int i=0; -// kDebug() << "paint!!! " << i++ << " " << index.internalPointer() << " " << index.column(); -// -// painter->drawRect(option.rect); -// painter->drawText(option.rect.topLeft(), QString::number(i)); -} - -void TransfersViewDelegate::drawFocus(QPainter * painter, const QStyleOptionViewItem & option, const - QRect & rect) const -{ - Q_UNUSED(painter) - Q_UNUSED(option) - Q_UNUSED(rect) -} - -QSize TransfersViewDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const -{ - Q_UNUSED(option) - - TransferTreeModel *transferTreeModel = KGet::model(); - ModelItem *item = transferTreeModel->itemFromIndex(index); - - if (!item) { - kWarning() << "Sizehint for non-existing item."; - return QSize(); - } - - if (transferTreeModel->itemFromIndex(index)->isGroup()) - { - return QSize(0, 35); - } - else { - QSize ret(KExtendableItemDelegate::sizeHint(option, index)); - ret.rheight() += 8; - return ret; - } -} - -bool TransfersViewDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index) -{ - Q_UNUSED(model) - Q_UNUSED(option) - - if (event->type() == QEvent::MouseButtonRelease) - { - QMouseEvent * mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::RightButton) - { - // kDebug() << "TransfersViewDelegate::editorEvent() -> rightClick"; - - KMenu *popup = 0; - - TransferTreeModel * transferTreeModel = KGet::model(); - - ModelItem * item = transferTreeModel->itemFromIndex(index); - if (item->isGroup()) - { - // kDebug() << "isTransferGroup = true"; - TransferGroupHandler * transferGroupHandler = item->asGroup()->groupHandler(); - - popup = ContextMenu::createTransferGroupContextMenu(transferGroupHandler, qobject_cast(this)); - } - else - { - // kDebug() << "isTransferGroup = false"; - - TransferHandler * transferHandler = item->asTransfer()->transferHandler(); - - popup = ContextMenu::createTransferContextMenu(transferHandler, qobject_cast(this)); - } - - if (popup) { - popup->exec(QCursor::pos()); - popup->deleteLater(); - } - } - } - - return false; -} - -#include "moc_transfersviewdelegate.cpp" diff --git a/kget/ui/transfersviewdelegate.h b/kget/ui/transfersviewdelegate.h deleted file mode 100644 index 66bb0653..00000000 --- a/kget/ui/transfersviewdelegate.h +++ /dev/null @@ -1,113 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2006 Dario Massarin - Copyright (C) 2007 by Javier Goday - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#ifndef TRANSFERSVIEWDELEGATE_H -#define TRANSFERSVIEWDELEGATE_H - -#include - -#include -#include - -#include -#include - -class TransferHandler; -class TransferObserver; -class TransfersViewDelegate; - -class GroupStatusButton : public QToolButton -{ - Q_OBJECT - - public: - GroupStatusButton(const QModelIndex &index, QWidget *parent); - - protected: - void checkStateSet(); - void enterEvent(QEvent * event); - void leaveEvent(QEvent * event); - void paintEvent(QPaintEvent * event); - void timerEvent(QTimerEvent *event); - - private: - enum {None, Selecting, Deselecting, Blinking, BlinkingExiting} m_status; - QModelIndex m_index; - - int m_timerId; - int m_iconSize; - - float m_gradientId; -}; - -class GroupStatusEditor : public QWidget -{ - Q_OBJECT - - public: - GroupStatusEditor(const QModelIndex &index, QWidget *parent); - - void setRunning(bool running); - bool isRunning(); - - private slots: - void slotStatusChanged(); - - signals: - void changedStatus(GroupStatusEditor *editor); - - private: - QModelIndex m_index; - - QHBoxLayout * m_layout; - - QButtonGroup * m_btGroup; - GroupStatusButton * m_startBt; - GroupStatusButton * m_stopBt; -}; - -/** - * The BasicTransfersViewDelegate handles the setting of the status of a group - */ -class BasicTransfersViewDelegate : public KExtendableItemDelegate -{ - Q_OBJECT - - public: - BasicTransfersViewDelegate(QAbstractItemView *parent); - - virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; - virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; - - private slots: - virtual void slotGroupStatusChanged(GroupStatusEditor *editor); -}; - -class TransfersViewDelegate : public BasicTransfersViewDelegate -{ - Q_OBJECT - - public: - TransfersViewDelegate(QAbstractItemView *parent); - - void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const; - - void drawFocus(QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect) const; - - QSize sizeHint (const QStyleOptionViewItem & option, const QModelIndex & index) const; - - bool editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index); -}; - -#endif - diff --git a/kget/ui/tray.cpp b/kget/ui/tray.cpp deleted file mode 100644 index 7af26b74..00000000 --- a/kget/ui/tray.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 by Fabian Henze - - 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. -*/ -#include "ui/tray.h" -#include "mainwindow.h" -#include "ui/newtransferdialog.h" -#include -#include -#include -#include -#include - -#include - -/** class Tray - * Reimplementation of the KStatusNotifierItem class - */ -Tray::Tray(MainWindow * parent) - : KStatusNotifierItem(parent) -{ - // set up the context menu - KMenu * cm = contextMenu(); - cm->addAction( parent->actionCollection()->action("new_download") ); - cm->addAction( parent->actionCollection()->action("import_links") ); - cm->addSeparator(); - cm->addAction( parent->actionCollection()->action("start_all_download") ); - cm->addAction( parent->actionCollection()->action("stop_all_download") ); - cm->addSeparator(); - cm->addAction( parent->actionCollection()->action("options_configure") ); - - // Set up basic tray parameters - setCategory(ApplicationStatus); - setIconByName("kget"); - setTitle(i18n("KGet")); - setContextMenu(cm); - setAssociatedWidget(parent); - setToolTipIconByName("kget"); - setToolTipTitle(i18n("Download Manager")); - // Not of much use atm, but maybe we want to set this later? - // setToolTipSubTitle("[..]"); - - // filter middle mouse clicks to ask scheduler to paste URL - connect( this, SIGNAL(secondaryActivateRequested(QPoint)), - this, SLOT(slotActivated()) ); -} - - -// filter middle mouse clicks to ask scheduler to paste URL -void Tray::slotActivated() -{ - // Here we paste the transfer - QString newtransfer = QApplication::clipboard()->text(); - newtransfer = newtransfer.trimmed(); - - if(!newtransfer.isEmpty()) - NewTransferDialogHandler::showNewTransferDialog(KUrl(newtransfer)); -} - -// display a play icon when downloading and -// switch between Active or Passive state -void Tray::setDownloading( bool downloading ) -{ - kDebug() << "Tray::setDownloading"; - - if (downloading) - { - if (status() == KStatusNotifierItem::Active) - return; - setStatus(KStatusNotifierItem::Active); - setOverlayIconByName("media-playback-start"); - } - else - { - if (status() == KStatusNotifierItem::Passive) - return; - setStatus(KStatusNotifierItem::Passive); - setOverlayIconByName(QString()); - } -} - -bool Tray::isDownloading() -{ - // KStatusNotifierItem::NeedsAttention is not handled here, - // as we do not use it. - return (status() == KStatusNotifierItem::Active); -} - -#include "moc_tray.cpp" diff --git a/kget/ui/tray.h b/kget/ui/tray.h deleted file mode 100644 index 304a6bd0..00000000 --- a/kget/ui/tray.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2009 by Fabian Henze - - 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. -*/ - -#ifndef TRAY_H -#define TRAY_H - -#include - -class MainWindow; -class KGet; - -/** - * This class implements the main tray icon for kget. It has a popup - * from which the user can open a new transfer, configure kget, - * minimize/restore or quit the app (default behavior). - * - * @short KGet's system tray icon. - **/ - -class Tray : public KStatusNotifierItem -{ -Q_OBJECT -public: - Tray( MainWindow * parent ); - - void setDownloading(bool downloading); - bool isDownloading(); - -private slots: - void slotActivated(); -}; - -#endif diff --git a/kget/ui/verificationadddlg.ui b/kget/ui/verificationadddlg.ui deleted file mode 100644 index 6494997c..00000000 --- a/kget/ui/verificationadddlg.ui +++ /dev/null @@ -1,77 +0,0 @@ - - - VerificationAddDlg - - - - 0 - 0 - 297 - 63 - - - - - - - - - Hash type: - - - - - - - Hash: - - - - - - - Enter a hash key - - - true - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
-
- - hashTypes - newHash - - -
diff --git a/kget/ui/verificationdialog.cpp b/kget/ui/verificationdialog.cpp deleted file mode 100644 index 15f41f89..00000000 --- a/kget/ui/verificationdialog.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 "verificationdialog.h" - -#include -#include - -#include -#include - -#include "core/filemodel.h" -#include "core/transferhandler.h" -#include "core/verifier.h" -#include "core/verificationmodel.h" -#include "core/verificationdelegate.h" -#include "settings.h" - -VerificationAddDlg::VerificationAddDlg(VerificationModel *model, QWidget *parent, Qt::WFlags flags) - : KDialog(parent, flags), - m_model(model) -{ - setCaption(i18n("Add checksum")); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - - QStringList supportedTypes = Verifier::supportedVerficationTypes(); - supportedTypes.sort(); - ui.hashTypes->addItems(supportedTypes); - - setButtons(KDialog::Yes | KDialog::Cancel); - setButtonGuiItem(KDialog::Yes, KStandardGuiItem::add()); - - updateButton(); - - connect(ui.newHash, SIGNAL(textChanged(QString)), this, SLOT(updateButton())); - connect(ui.hashTypes, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButton())); - connect(this, SIGNAL(yesClicked()), this, SLOT(addChecksum())); -} - -QSize VerificationAddDlg::sizeHint() const -{ - QSize sh = KDialog::sizeHint(); - sh.setHeight(minimumSize().height()); - sh.setWidth(sh.width() * 1.5); - return sh; -} - -void VerificationAddDlg::updateButton() -{ - const QString type = ui.hashTypes->currentText(); - const QString hash = ui.newHash->text(); - const bool enabled = Verifier::isChecksum(type, hash); - - enableButton(KDialog::Yes, enabled); - enableButton(KDialog::User1, enabled); -} - -void VerificationAddDlg::addChecksum() -{ - if (m_model) { - m_model->addChecksum(ui.hashTypes->currentText(), ui.newHash->text()); - } -} - -VerificationDialog::VerificationDialog(QWidget *parent, TransferHandler *transfer, const KUrl &file) - : KGetSaveSizeDialog("VerificationDialog", parent), - m_transfer(transfer), - m_verifier(transfer->verifier(file)), - m_model(0), - m_proxy(0), - m_fileModel(0) -{ - if (m_verifier) { - m_model = m_verifier->model(); - connect(m_verifier, SIGNAL(verified(bool)), this, SLOT(slotVerified(bool))); - } - - setCaption(i18n("Transfer Verification for %1", file.fileName())); - showButtonSeparator(true); - QWidget *widget = new QWidget(this); - ui.setupUi(widget); - setMainWidget(widget); - ui.add->setGuiItem(KStandardGuiItem::add()); - ui.remove->setGuiItem(KStandardGuiItem::remove()); - ui.verifying->hide(); - - if (m_model) { - m_proxy = new QSortFilterProxyModel(this); - m_proxy->setSourceModel(m_model); - ui.usedHashes->setModel(m_proxy); - ui.usedHashes->setItemDelegate(new VerificationDelegate(this)); - - QByteArray loadedState = QByteArray::fromBase64(Settings::verificationHeaderState().toAscii()); - if (!loadedState.isEmpty()) { - ui.usedHashes->header()->restoreState(loadedState); - } - - m_fileModel = m_transfer->fileModel(); - if (m_fileModel) { - m_file = m_fileModel->index(file, FileItem::File); - connect(m_fileModel, SIGNAL(fileFinished(KUrl)), this, SLOT(fileFinished(KUrl))); - } - - updateButtons(); - - connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(updateButtons())); - connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(updateButtons())); - connect(ui.usedHashes, SIGNAL(clicked(QModelIndex)), this, SLOT(updateButtons())); - connect(ui.add, SIGNAL(clicked()), this, SLOT(addClicked())); - connect(ui.remove, SIGNAL(clicked()), this, SLOT(removeClicked())); - connect(ui.verify, SIGNAL(clicked()), this, SLOT(verifyClicked())); - } - - setButtons(KDialog::Close); - - connect(this, SIGNAL(finished()), this, SLOT(slotFinished())); -} - -QSize VerificationDialog::sizeHint() const -{ - QSize sh = KDialog::sizeHint(); - sh.setWidth(sh.width() * 1.2); - return sh; -} - -void VerificationDialog::slotFinished() -{ - if (m_model) { - Settings::setVerificationHeaderState(ui.usedHashes->header()->saveState().toBase64()); - } -} - -void VerificationDialog::fileFinished(const KUrl &file) -{ - if (m_fileModel && (m_fileModel->getUrl(m_file) == file)) { - updateButtons(); - } -} - -void VerificationDialog::updateButtons() -{ - ui.remove->setEnabled(m_model && ui.usedHashes->selectionModel()->hasSelection()); - - //check if the download finished and if the selected index is verifyable - bool verifyEnabled = false; - if (m_fileModel && m_fileModel->downloadFinished(m_fileModel->getUrl(m_file))) { - const QModelIndexList indexes = ui.usedHashes->selectionModel()->selectedRows(); - if (indexes.count() == 1) { - verifyEnabled = m_verifier->isVerifyable(indexes.first()); - } - } - ui.verify->setEnabled(verifyEnabled); -} - -void VerificationDialog::removeClicked() -{ - while (ui.usedHashes->selectionModel()->hasSelection()) { - const QModelIndex index = ui.usedHashes->selectionModel()->selectedRows().first(); - m_model->removeRow(m_proxy->mapToSource(index).row()); - } -} - -void VerificationDialog::addClicked() -{ - VerificationAddDlg *dialog = new VerificationAddDlg(m_model, this); - dialog->show(); -} - -void VerificationDialog::verifyClicked() -{ - const QModelIndex index = m_proxy->mapToSource(ui.usedHashes->selectionModel()->selectedRows().first()); - if (index.isValid()) { - m_verifier->verify(index); - ui.progressBar->setMaximum(0); - ui.verifying->show(); - } -} - -void VerificationDialog::slotVerified(bool verified) -{ - ui.progressBar->setMaximum(1); - ui.verifying->hide(); - - if (verified) { - QString fileName; - if (m_fileModel) { - fileName = m_fileModel->getUrl(m_file).fileName(); - } - - KMessageBox::information(this, - i18n("%1 was successfully verified.", fileName), - i18n("Verification successful")); - } -} - -#include "moc_verificationdialog.cpp" diff --git a/kget/ui/verificationdialog.h b/kget/ui/verificationdialog.h deleted file mode 100644 index 483c3ba0..00000000 --- a/kget/ui/verificationdialog.h +++ /dev/null @@ -1,81 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2009 Matthias Fuchs * -* * -* 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 VERIFICATIONDIALOG_H -#define VERIFICATIONDIALOG_H - -#include "ui_verificationdialog.h" -#include "ui_verificationadddlg.h" - -#include "../core/basedialog.h" - -class FileModel; -#include -class TransferHandler; -class Verifier; -class VerificationModel; - -class VerificationAddDlg : public KDialog -{ - Q_OBJECT - - public: - explicit VerificationAddDlg(VerificationModel *model, QWidget *parent = 0, Qt::WFlags flags = 0); - - virtual QSize sizeHint() const; - - private slots: - void addChecksum(); - void updateButton(); - - private: - Ui::VerificationAddDlg ui; - VerificationModel *m_model; - QHash m_diggestLength; -}; - -class VerificationDialog : public KGetSaveSizeDialog -{ - Q_OBJECT - - public: - VerificationDialog(QWidget *parent, TransferHandler *transfer, const KUrl &file); - - virtual QSize sizeHint() const; - - private slots: - void fileFinished(const KUrl &file); - void updateButtons(); - void addClicked(); - void removeClicked(); - void verifyClicked(); - void slotVerified(bool verified); - void slotFinished(); - - private: - TransferHandler *m_transfer; - Verifier *m_verifier; - VerificationModel *m_model; - QSortFilterProxyModel *m_proxy; - FileModel *m_fileModel; - QModelIndex m_file; - Ui::VerificationDialog ui; -}; - -#endif //VERIFICATIONDIALOG_H diff --git a/kget/ui/verificationdialog.ui b/kget/ui/verificationdialog.ui deleted file mode 100644 index 91427f73..00000000 --- a/kget/ui/verificationdialog.ui +++ /dev/null @@ -1,98 +0,0 @@ - - - VerificationDialog - - - - 0 - 0 - 500 - 300 - - - - - - - QAbstractItemView::ExtendedSelection - - - false - - - true - - - false - - - true - - - - - - - - - - - - - Verify the finished download with the selected checksum. - - - &Verify - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 0 - - - - - Verifying: - - - - - - - 1 - - - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- - usedHashes - - -
diff --git a/kget/ui/viewscontainer.cpp b/kget/ui/viewscontainer.cpp deleted file mode 100644 index f57ab83d..00000000 --- a/kget/ui/viewscontainer.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - -#include "viewscontainer.h" - -#include "core/kget.h" -#include "core/transferhandler.h" -#include "core/transfertreeselectionmodel.h" -#include "core/transfertreemodel.h" -#include "transfersview.h" -#include "transfersviewdelegate.h" - -#include - -ViewsContainer::ViewsContainer(QWidget * parent) - : QWidget(parent) -{ - QVBoxLayout *layout = new QVBoxLayout(); - layout->setSpacing(1); - layout->setMargin(0); - - m_transfersView = new TransfersView(this); - TransfersViewDelegate *transfersViewDelegate = new TransfersViewDelegate(m_transfersView); - m_transfersView->setItemDelegate(transfersViewDelegate); - m_transfersView->setModel(KGet::model()); - m_transfersView->setSelectionModel(KGet::selectionModel()); - m_transfersView->setSelectionMode(QAbstractItemView::ExtendedSelection); - - layout->addWidget(m_transfersView); - setLayout(layout); -} - -void ViewsContainer::showTransferDetails(TransferHandler * transfer) -{ - TransferTreeModel *model = KGet::model(); - m_transfersView->slotItemActivated(model->itemFromHandler(transfer)->index()); -} - -void ViewsContainer::closeTransferDetails(TransferHandler * transfer) -{ - TransferTreeModel *model = KGet::model(); - m_transfersView->closeExpandableDetails(model->itemFromHandler(transfer)->index()); -} - -void ViewsContainer::selectAll() -{ - m_transfersView->selectAll(); -} - -#include "moc_viewscontainer.cpp" diff --git a/kget/ui/viewscontainer.h b/kget/ui/viewscontainer.h deleted file mode 100644 index 9b5dc465..00000000 --- a/kget/ui/viewscontainer.h +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE project - - Copyright (C) 2005 Dario Massarin - Copyright (C) 2007 Urs Wolfer - Copyright (C) 2010 Matthias Fuchs - - 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. -*/ - - -#ifndef VIEWSCONTAINER_H -#define VIEWSCONTAINER_H - -#include - -class TransfersView; -class TransferHandler; - -class ViewsContainer : public QWidget -{ - Q_OBJECT - public: - ViewsContainer(QWidget * parent = 0); - - public slots: - void showTransferDetails(TransferHandler * transfer); - void closeTransferDetails(TransferHandler * transfer); - void selectAll(); - - private: - TransfersView * m_transfersView; -}; - -#endif diff --git a/krdc/CMakeLists.txt b/krdc/CMakeLists.txt deleted file mode 100644 index 5b8eeeeb..00000000 --- a/krdc/CMakeLists.txt +++ /dev/null @@ -1,80 +0,0 @@ -project(krdc) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - include(GenerateExportHeader) - include(FeatureSummary) - - find_package(KDELibs4 4.23.0 REQUIRED) - - include_directories(${KDE4_INCLUDES}) - add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -endif() - -kde4_optional_find_package(LibVNCServer 0.9.8) -set_package_properties(LibVNCServer PROPERTIES - DESCRIPTION "VNC server / client library" - URL "http://libvncserver.sourceforge.net/" - PURPOSE "Needed to build VNC client support in KRDC" -) - -# v1.0.2 required -find_program(FREERDP_EXECUTABLE xfreerdp) -add_feature_info(xfreerdp - FREERDP_EXECUTABLE - "A free Remote Desktop Protocol (RDP) Implementation" -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/core/ - ${CMAKE_CURRENT_BINARY_DIR}/core/ - ${CMAKE_CURRENT_BINARY_DIR} -) - -add_subdirectory(core) -# add_subdirectory(konsole) -add_subdirectory(vnc) -add_subdirectory(rdp) - -if(ENABLE_TESTING) - add_subdirectory(test) -endif() - -add_definitions( - -DKDE_DEFAULT_DEBUG_AREA=5010 - -DBUILD_ZEROCONF -) - -set(krdc_SRCS - config/hostpreferenceslist.cpp - config/preferencesdialog.cpp - floatingtoolbar.cpp - bookmarkmanager.cpp - connectiondelegate.cpp - remotedesktopsmodel.cpp - systemtrayicon.cpp - tabbedviewwidget.cpp - mainwindow.cpp - main.cpp -) - -add_executable(krdc ${krdc_SRCS}) - -target_link_libraries(krdc - KDE4::kfile - KDE4::kio - KDE4::kdeui - KDE4::kcmutils - krdccore -) - -target_link_libraries(krdc KDE4::kdnssd) - -install(TARGETS krdc DESTINATION ${KDE4_BIN_INSTALL_DIR}) -install(FILES krdcui.rc DESTINATION ${KDE4_DATA_INSTALL_DIR}/krdc) -install(PROGRAMS krdc.desktop DESTINATION ${KDE4_XDG_APPS_INSTALL_DIR}) -install(FILES pointcursor.png pointcursormask.png DESTINATION ${KDE4_DATA_INSTALL_DIR}/krdc/pics) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) -endif() diff --git a/krdc/COPYING b/krdc/COPYING deleted file mode 100644 index 8900e10b..00000000 --- a/krdc/COPYING +++ /dev/null @@ -1,347 +0,0 @@ -NOTE! The GPL below is copyrighted by the Free Software Foundation, but -the instance of code that it refers to (the kde programs) are copyrighted -by the authors who actually wrote it. - ---------------------------------------------------------------------------- - - 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 Library 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) 19yy - - 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) 19yy 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 Library General -Public License instead of this License. diff --git a/krdc/COPYING.DOC b/krdc/COPYING.DOC deleted file mode 100644 index 4a0fe1c8..00000000 --- a/krdc/COPYING.DOC +++ /dev/null @@ -1,397 +0,0 @@ - GNU Free Documentation License - Version 1.2, November 2002 - - - Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. - 51 Franklin St, 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. - - -0. PREAMBLE - -The purpose of this License is to make a manual, textbook, or other -functional and useful document "free" in the sense of freedom: to -assure everyone the effective freedom to copy and redistribute it, -with or without modifying it, either commercially or noncommercially. -Secondarily, this License preserves for the author and publisher a way -to get credit for their work, while not being considered responsible -for modifications made by others. - -This License is a kind of "copyleft", which means that derivative -works of the document must themselves be free in the same sense. It -complements the GNU General Public License, which is a copyleft -license designed for free software. - -We have designed this License in order to use it for manuals for free -software, because free software needs free documentation: a free -program should come with manuals providing the same freedoms that the -software does. But this License is not limited to software manuals; -it can be used for any textual work, regardless of subject matter or -whether it is published as a printed book. We recommend this License -principally for works whose purpose is instruction or reference. - - -1. APPLICABILITY AND DEFINITIONS - -This License applies to any manual or other work, in any medium, that -contains a notice placed by the copyright holder saying it can be -distributed under the terms of this License. Such a notice grants a -world-wide, royalty-free license, unlimited in duration, to use that -work under the conditions stated herein. The "Document", below, -refers to any such manual or work. Any member of the public is a -licensee, and is addressed as "you". You accept the license if you -copy, modify or distribute the work in a way requiring permission -under copyright law. - -A "Modified Version" of the Document means any work containing the -Document or a portion of it, either copied verbatim, or with -modifications and/or translated into another language. - -A "Secondary Section" is a named appendix or a front-matter section of -the Document that deals exclusively with the relationship of the -publishers or authors of the Document to the Document's overall subject -(or to related matters) and contains nothing that could fall directly -within that overall subject. (Thus, if the Document is in part a -textbook of mathematics, a Secondary Section may not explain any -mathematics.) The relationship could be a matter of historical -connection with the subject or with related matters, or of legal, -commercial, philosophical, ethical or political position regarding -them. - -The "Invariant Sections" are certain Secondary Sections whose titles -are designated, as being those of Invariant Sections, in the notice -that says that the Document is released under this License. If a -section does not fit the above definition of Secondary then it is not -allowed to be designated as Invariant. The Document may contain zero -Invariant Sections. If the Document does not identify any Invariant -Sections then there are none. - -The "Cover Texts" are certain short passages of text that are listed, -as Front-Cover Texts or Back-Cover Texts, in the notice that says that -the Document is released under this License. A Front-Cover Text may -be at most 5 words, and a Back-Cover Text may be at most 25 words. - -A "Transparent" copy of the Document means a machine-readable copy, -represented in a format whose specification is available to the -general public, that is suitable for revising the document -straightforwardly with generic text editors or (for images composed of -pixels) generic paint programs or (for drawings) some widely available -drawing editor, and that is suitable for input to text formatters or -for automatic translation to a variety of formats suitable for input -to text formatters. A copy made in an otherwise Transparent file -format whose markup, or absence of markup, has been arranged to thwart -or discourage subsequent modification by readers is not Transparent. -An image format is not Transparent if used for any substantial amount -of text. A copy that is not "Transparent" is called "Opaque". - -Examples of suitable formats for Transparent copies include plain -ASCII without markup, Texinfo input format, LaTeX input format, SGML -or XML using a publicly available DTD, and standard-conforming simple -HTML, PostScript or PDF designed for human modification. Examples of -transparent image formats include PNG, XCF and JPG. Opaque formats -include proprietary formats that can be read and edited only by -proprietary word processors, SGML or XML for which the DTD and/or -processing tools are not generally available, and the -machine-generated HTML, PostScript or PDF produced by some word -processors for output purposes only. - -The "Title Page" means, for a printed book, the title page itself, -plus such following pages as are needed to hold, legibly, the material -this License requires to appear in the title page. For works in -formats which do not have any title page as such, "Title Page" means -the text near the most prominent appearance of the work's title, -preceding the beginning of the body of the text. - -A section "Entitled XYZ" means a named subunit of the Document whose -title either is precisely XYZ or contains XYZ in parentheses following -text that translates XYZ in another language. (Here XYZ stands for a -specific section name mentioned below, such as "Acknowledgements", -"Dedications", "Endorsements", or "History".) To "Preserve the Title" -of such a section when you modify the Document means that it remains a -section "Entitled XYZ" according to this definition. - -The Document may include Warranty Disclaimers next to the notice which -states that this License applies to the Document. These Warranty -Disclaimers are considered to be included by reference in this -License, but only as regards disclaiming warranties: any other -implication that these Warranty Disclaimers may have is void and has -no effect on the meaning of this License. - - -2. VERBATIM COPYING - -You may copy and distribute the Document in any medium, either -commercially or noncommercially, provided that this License, the -copyright notices, and the license notice saying this License applies -to the Document are reproduced in all copies, and that you add no other -conditions whatsoever to those of this License. You may not use -technical measures to obstruct or control the reading or further -copying of the copies you make or distribute. However, you may accept -compensation in exchange for copies. If you distribute a large enough -number of copies you must also follow the conditions in section 3. - -You may also lend copies, under the same conditions stated above, and -you may publicly display copies. - - -3. COPYING IN QUANTITY - -If you publish printed copies (or copies in media that commonly have -printed covers) of the Document, numbering more than 100, and the -Document's license notice requires Cover Texts, you must enclose the -copies in covers that carry, clearly and legibly, all these Cover -Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on -the back cover. Both covers must also clearly and legibly identify -you as the publisher of these copies. The front cover must present -the full title with all words of the title equally prominent and -visible. You may add other material on the covers in addition. -Copying with changes limited to the covers, as long as they preserve -the title of the Document and satisfy these conditions, can be treated -as verbatim copying in other respects. - -If the required texts for either cover are too voluminous to fit -legibly, you should put the first ones listed (as many as fit -reasonably) on the actual cover, and continue the rest onto adjacent -pages. - -If you publish or distribute Opaque copies of the Document numbering -more than 100, you must either include a machine-readable Transparent -copy along with each Opaque copy, or state in or with each Opaque copy -a computer-network location from which the general network-using -public has access to download using public-standard network protocols -a complete Transparent copy of the Document, free of added material. -If you use the latter option, you must take reasonably prudent steps, -when you begin distribution of Opaque copies in quantity, to ensure -that this Transparent copy will remain thus accessible at the stated -location until at least one year after the last time you distribute an -Opaque copy (directly or through your agents or retailers) of that -edition to the public. - -It is requested, but not required, that you contact the authors of the -Document well before redistributing any large number of copies, to give -them a chance to provide you with an updated version of the Document. - - -4. MODIFICATIONS - -You may copy and distribute a Modified Version of the Document under -the conditions of sections 2 and 3 above, provided that you release -the Modified Version under precisely this License, with the Modified -Version filling the role of the Document, thus licensing distribution -and modification of the Modified Version to whoever possesses a copy -of it. In addition, you must do these things in the Modified Version: - -A. Use in the Title Page (and on the covers, if any) a title distinct - from that of the Document, and from those of previous versions - (which should, if there were any, be listed in the History section - of the Document). You may use the same title as a previous version - if the original publisher of that version gives permission. -B. List on the Title Page, as authors, one or more persons or entities - responsible for authorship of the modifications in the Modified - Version, together with at least five of the principal authors of the - Document (all of its principal authors, if it has fewer than five), - unless they release you from this requirement. -C. State on the Title page the name of the publisher of the - Modified Version, as the publisher. -D. Preserve all the copyright notices of the Document. -E. Add an appropriate copyright notice for your modifications - adjacent to the other copyright notices. -F. Include, immediately after the copyright notices, a license notice - giving the public permission to use the Modified Version under the - terms of this License, in the form shown in the Addendum below. -G. Preserve in that license notice the full lists of Invariant Sections - and required Cover Texts given in the Document's license notice. -H. Include an unaltered copy of this License. -I. Preserve the section Entitled "History", Preserve its Title, and add - to it an item stating at least the title, year, new authors, and - publisher of the Modified Version as given on the Title Page. If - there is no section Entitled "History" in the Document, create one - stating the title, year, authors, and publisher of the Document as - given on its Title Page, then add an item describing the Modified - Version as stated in the previous sentence. -J. Preserve the network location, if any, given in the Document for - public access to a Transparent copy of the Document, and likewise - the network locations given in the Document for previous versions - it was based on. These may be placed in the "History" section. - You may omit a network location for a work that was published at - least four years before the Document itself, or if the original - publisher of the version it refers to gives permission. -K. For any section Entitled "Acknowledgements" or "Dedications", - Preserve the Title of the section, and preserve in the section all - the substance and tone of each of the contributor acknowledgements - and/or dedications given therein. -L. Preserve all the Invariant Sections of the Document, - unaltered in their text and in their titles. Section numbers - or the equivalent are not considered part of the section titles. -M. Delete any section Entitled "Endorsements". Such a section - may not be included in the Modified Version. -N. Do not retitle any existing section to be Entitled "Endorsements" - or to conflict in title with any Invariant Section. -O. Preserve any Warranty Disclaimers. - -If the Modified Version includes new front-matter sections or -appendices that qualify as Secondary Sections and contain no material -copied from the Document, you may at your option designate some or all -of these sections as invariant. To do this, add their titles to the -list of Invariant Sections in the Modified Version's license notice. -These titles must be distinct from any other section titles. - -You may add a section Entitled "Endorsements", provided it contains -nothing but endorsements of your Modified Version by various -parties--for example, statements of peer review or that the text has -been approved by an organization as the authoritative definition of a -standard. - -You may add a passage of up to five words as a Front-Cover Text, and a -passage of up to 25 words as a Back-Cover Text, to the end of the list -of Cover Texts in the Modified Version. Only one passage of -Front-Cover Text and one of Back-Cover Text may be added by (or -through arrangements made by) any one entity. If the Document already -includes a cover text for the same cover, previously added by you or -by arrangement made by the same entity you are acting on behalf of, -you may not add another; but you may replace the old one, on explicit -permission from the previous publisher that added the old one. - -The author(s) and publisher(s) of the Document do not by this License -give permission to use their names for publicity for or to assert or -imply endorsement of any Modified Version. - - -5. COMBINING DOCUMENTS - -You may combine the Document with other documents released under this -License, under the terms defined in section 4 above for modified -versions, provided that you include in the combination all of the -Invariant Sections of all of the original documents, unmodified, and -list them all as Invariant Sections of your combined work in its -license notice, and that you preserve all their Warranty Disclaimers. - -The combined work need only contain one copy of this License, and -multiple identical Invariant Sections may be replaced with a single -copy. If there are multiple Invariant Sections with the same name but -different contents, make the title of each such section unique by -adding at the end of it, in parentheses, the name of the original -author or publisher of that section if known, or else a unique number. -Make the same adjustment to the section titles in the list of -Invariant Sections in the license notice of the combined work. - -In the combination, you must combine any sections Entitled "History" -in the various original documents, forming one section Entitled -"History"; likewise combine any sections Entitled "Acknowledgements", -and any sections Entitled "Dedications". You must delete all sections -Entitled "Endorsements". - - -6. COLLECTIONS OF DOCUMENTS - -You may make a collection consisting of the Document and other documents -released under this License, and replace the individual copies of this -License in the various documents with a single copy that is included in -the collection, provided that you follow the rules of this License for -verbatim copying of each of the documents in all other respects. - -You may extract a single document from such a collection, and distribute -it individually under this License, provided you insert a copy of this -License into the extracted document, and follow this License in all -other respects regarding verbatim copying of that document. - - -7. AGGREGATION WITH INDEPENDENT WORKS - -A compilation of the Document or its derivatives with other separate -and independent documents or works, in or on a volume of a storage or -distribution medium, is called an "aggregate" if the copyright -resulting from the compilation is not used to limit the legal rights -of the compilation's users beyond what the individual works permit. -When the Document is included in an aggregate, this License does not -apply to the other works in the aggregate which are not themselves -derivative works of the Document. - -If the Cover Text requirement of section 3 is applicable to these -copies of the Document, then if the Document is less than one half of -the entire aggregate, the Document's Cover Texts may be placed on -covers that bracket the Document within the aggregate, or the -electronic equivalent of covers if the Document is in electronic form. -Otherwise they must appear on printed covers that bracket the whole -aggregate. - - -8. TRANSLATION - -Translation is considered a kind of modification, so you may -distribute translations of the Document under the terms of section 4. -Replacing Invariant Sections with translations requires special -permission from their copyright holders, but you may include -translations of some or all Invariant Sections in addition to the -original versions of these Invariant Sections. You may include a -translation of this License, and all the license notices in the -Document, and any Warranty Disclaimers, provided that you also include -the original English version of this License and the original versions -of those notices and disclaimers. In case of a disagreement between -the translation and the original version of this License or a notice -or disclaimer, the original version will prevail. - -If a section in the Document is Entitled "Acknowledgements", -"Dedications", or "History", the requirement (section 4) to Preserve -its Title (section 1) will typically require changing the actual -title. - - -9. TERMINATION - -You may not copy, modify, sublicense, or distribute the Document except -as expressly provided for under this License. Any other attempt to -copy, modify, sublicense or distribute the Document 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. - - -10. FUTURE REVISIONS OF THIS LICENSE - -The Free Software Foundation may publish new, revised versions -of the GNU Free Documentation 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. See -http://www.gnu.org/copyleft/. - -Each version of the License is given a distinguishing version number. -If the Document specifies that a particular numbered version of this -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that specified version or -of any later version that has been published (not as a draft) by the -Free Software Foundation. If the Document does not specify a version -number of this License, you may choose any version ever published (not -as a draft) by the Free Software Foundation. - - -ADDENDUM: How to use this License for your documents - -To use this License in a document you have written, include a copy of -the License in the document and put the following copyright and -license notices just after the title page: - - Copyright (c) YEAR YOUR NAME. - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. - A copy of the license is included in the section entitled "GNU - Free Documentation License". - -If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, -replace the "with...Texts." line with this: - - with the Invariant Sections being LIST THEIR TITLES, with the - Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. - -If you have Invariant Sections without Cover Texts, or some other -combination of the three, merge those two alternatives to suit the -situation. - -If your document contains nontrivial examples of program code, we -recommend releasing these examples in parallel under your choice of -free software license, such as the GNU General Public License, -to permit their use in free software. diff --git a/krdc/COPYING.LIB b/krdc/COPYING.LIB deleted file mode 100644 index 2d2d780e..00000000 --- a/krdc/COPYING.LIB +++ /dev/null @@ -1,510 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations -below. - - When we speak of free software, we are referring to freedom of use, -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 and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it -becomes a de-facto standard. To achieve this, non-free programs must -be allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control -compilation and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least - three years, to give the same user the materials specified in - Subsection 6a, above, for a charge no more than the cost of - performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply, and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License -may add an explicit geographical distribution limitation excluding those -countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms -of the ordinary General Public License). - - To apply these terms, attach the following notices to the library. -It is safest to attach them to the start of each source file to most -effectively convey the exclusion of warranty; and each file should -have at least the "copyright" line and a pointer to where the full -notice is found. - - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the library, -if necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James - Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/krdc/Messages.sh b/krdc/Messages.sh deleted file mode 100755 index e7f9a81b..00000000 --- a/krdc/Messages.sh +++ /dev/null @@ -1,6 +0,0 @@ -#! /bin/sh -$EXTRACTRC *.ui */*.ui >> rc.cpp || exit 11 -$EXTRACTRC *.rc */*.rc >> rc.cpp || exit 12 -$EXTRACTRC */*.kcfg >> rc.cpp -$XGETTEXT *.cpp */*.cpp -o $podir/krdc.pot -rm -f rc.cpp diff --git a/krdc/bookmarkmanager.cpp b/krdc/bookmarkmanager.cpp deleted file mode 100644 index 335d982c..00000000 --- a/krdc/bookmarkmanager.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "bookmarkmanager.h" - -#include "mainwindow.h" - -#include -#include -#include - -BookmarkManager::BookmarkManager(KActionCollection *collection, KMenu *menu, MainWindow *parent) - : QObject(parent), - KBookmarkOwner(), - m_mainWindow(parent) -{ - const QString file = KStandardDirs::locateLocal("data", "krdc/bookmarks.xml"); - - m_manager = KBookmarkManager::managerForFile(file, "krdc"); - m_manager->setUpdate(true); - m_bookmarkMenu = new KBookmarkMenu(m_manager, this, menu, collection); - - KBookmarkGroup root = m_manager->root(); - KBookmark bm = root.first(); - while (!bm.isNull()) { - if (bm.metaDataItem("krdc-history") == "historyfolder") // get it also when user renamed it - break; - bm = root.next(bm); - } - - if (bm.isNull()) { - kDebug(5010) << "History folder not found. Create it."; - bm = m_manager->root().createNewFolder(i18n("History")); - bm.setMetaDataItem("krdc-history", "historyfolder"); - m_manager->emitChanged(); - } - - m_historyGroup = bm.toGroup(); -} - -BookmarkManager::~BookmarkManager() -{ - delete m_bookmarkMenu; -} - -void BookmarkManager::addHistoryBookmark(RemoteView *view) -{ - KBookmark bm = m_historyGroup.first(); - const QString urlString = urlForView(view); - const KUrl url = KUrl(urlString); - while (!bm.isNull()) { - if (bm.url() == url) { - kDebug(5010) << "Found URL. Move it at the history start."; - m_historyGroup.moveBookmark(bm, KBookmark()); - bm.updateAccessMetadata(); - m_manager->emitChanged(m_historyGroup); - return; - } - bm = m_historyGroup.next(bm); - } - - if (bm.isNull()) { - kDebug(5010) << "Add new history bookmark."; - bm = m_historyGroup.addBookmark(titleForUrl(urlString), urlString); - bm.updateAccessMetadata(); - m_historyGroup.moveBookmark(bm, KBookmark()); - m_manager->emitChanged(m_historyGroup); - } -} - -void BookmarkManager::openBookmark(const KBookmark &bm, Qt::MouseButtons, Qt::KeyboardModifiers) -{ - emit openUrl(bm.url()); -} - -void BookmarkManager::openFolderinTabs(const KBookmarkGroup &bookmarkGroup) -{ - KBookmark bm = bookmarkGroup.first(); - while (!bm.isNull()) { - emit openUrl(bm.url()); - bm = bookmarkGroup.next(bm); - } -} - -bool BookmarkManager::addBookmarkEntry() const -{ - return true; -} - -bool BookmarkManager::editBookmarkEntry() const -{ - return true; -} - -QString BookmarkManager::currentUrl() const -{ - RemoteView *view = m_mainWindow->currentRemoteView(); - if (view) - return urlForView(view); - else - return QString(); -} - -QString BookmarkManager::urlForView(RemoteView *view) const -{ - return view->url().prettyUrl(KUrl::RemoveTrailingSlash); - -} - -QString BookmarkManager::currentTitle() const -{ - return titleForUrl(currentUrl()); -} - -QString BookmarkManager::titleForUrl(const QString &url) const -{ - return QUrl::fromPercentEncoding(url.toUtf8()); - -} - -bool BookmarkManager::supportsTabs() const -{ - return true; -} - -QList > BookmarkManager::currentBookmarkList() const -{ - QList > list; - - QMapIterator iter(m_mainWindow->remoteViewList()); - - while (iter.hasNext()) { - RemoteView *next = iter.next().value(); - const QString url = next->url().prettyUrl(KUrl::RemoveTrailingSlash); - list << QPair(url, url); - } - - return list; -} - -void BookmarkManager::addManualBookmark(const QString &url, const QString &text) -{ - m_manager->root().addBookmark(url, text); - emit m_manager->emitChanged(); -} - -KBookmarkManager* BookmarkManager::getManager() -{ - return m_manager; -} - -const QStringList BookmarkManager::findBookmarkAddresses(const KBookmarkGroup &group, const QString &url) -{ - QStringList bookmarkAddresses = QStringList(); - KBookmark bm = group.first(); - while (!bm.isNull()) { - if (bm.isGroup()) { - bookmarkAddresses.append(findBookmarkAddresses(bm.toGroup(), url)); - } - - if (bm.url() == url) { - bookmarkAddresses.append(bm.address()); - } - bm = group.next(bm); - } - return bookmarkAddresses; -} - -void BookmarkManager::removeByUrl(KBookmarkManager *manager, const QString &url, bool ignoreHistory, const QString updateTitle) -{ - foreach(const QString &address, findBookmarkAddresses(manager->root(), url)) { - KBookmark bm = manager->findByAddress(address); - if (ignoreHistory && bm.parentGroup().metaDataItem("krdc-history") == "historyfolder") { - if (!updateTitle.isEmpty()) { - kDebug(5010) << "Update" << bm.fullText(); - bm.setFullText(updateTitle); - } - } else { - if (!bm.isGroup()) { // please don't delete groups... happened in testing - kDebug(5010) << "Delete" << bm.fullText(); - bm.parentGroup().deleteBookmark(bm); - } - } - } - - manager->emitChanged(); -} - -void BookmarkManager::updateTitle(KBookmarkManager *manager, const QString &url, const QString &title) -{ - foreach(const QString &address, findBookmarkAddresses(manager->root(), url)) { - KBookmark bm = manager->findByAddress(address); - bm.setFullText(title); - kDebug(5010) << "Update" << bm.fullText(); - } - manager->emitChanged(); -} - -#include "moc_bookmarkmanager.cpp" diff --git a/krdc/bookmarkmanager.h b/krdc/bookmarkmanager.h deleted file mode 100644 index 9a31c019..00000000 --- a/krdc/bookmarkmanager.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef BOOKMARKMANAGER_H -#define BOOKMARKMANAGER_H - -#include "core/remoteview.h" - -#include - -class KMenu; -class KActionCollection; -class KBookmarkMenu; - -class MainWindow; - -class BookmarkManager : public QObject, public KBookmarkOwner -{ - Q_OBJECT - -public: - BookmarkManager(KActionCollection *collection, KMenu *menu, MainWindow *parent); - ~BookmarkManager(); - - virtual QString currentUrl() const; - virtual QString currentTitle() const; - virtual bool addBookmarkEntry() const; - virtual bool editBookmarkEntry() const; - virtual bool supportsTabs() const; - virtual QList > currentBookmarkList() const; - void addHistoryBookmark(RemoteView *view); - void addManualBookmark(const QString &url, const QString &text); - KBookmarkManager* getManager(); - // removes all bookmarks with url, possibly ignore the history folder and update it's title there if it's set - static void removeByUrl(KBookmarkManager *manager, const QString &url, bool ignoreHistory = false, const QString updateTitle = QString()); - static void updateTitle(KBookmarkManager *manager, const QString &url, const QString &title); - // returns a QStringList for all bookmarks that point to this url using KBookmark::address() - static const QStringList findBookmarkAddresses(const KBookmarkGroup &group, const QString &url); - -signals: - void openUrl(const KUrl &url); - -private slots: - void openBookmark(const KBookmark &bm, Qt::MouseButtons, Qt::KeyboardModifiers); - void openFolderinTabs(const KBookmarkGroup &bookmarkGroup); - -private: - QString urlForView(RemoteView *view) const; - QString titleForUrl(const QString &url) const; - - KBookmarkMenu *m_bookmarkMenu; - KBookmarkManager *m_manager; - KBookmarkGroup m_historyGroup; - - MainWindow *m_mainWindow; -}; - -#endif diff --git a/krdc/config/general.ui b/krdc/config/general.ui deleted file mode 100644 index cb3adac3..00000000 --- a/krdc/config/general.ui +++ /dev/null @@ -1,219 +0,0 @@ - - - General - - - - 0 - 0 - 363 - 464 - - - - - - - Remember open sessions for next startup - - - - - - - Remember connection history - - - - - - - Remember passwords (KPasswdStore) - - - - - - - Enable system tray icon - - - - - - - Show status bar - - - - - - - Keep aspect ratio when scaling - - - - - - - - - Background color of empty place: - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - - - - - - When Connecting - - - - - - Show the preferences dialog for new connections - - - - - - - This option will resize the window to fit the connection size. If it is too big, it will maximize the window. - - - Resize to fit - - - - - - - This option switches to fullscreen only if the connection resolution is the same as the current screen resolution - - - Switch to Fullscreen if appropriate - - - - - - - - - - Tab Settings - - - - - - Always show tab bar - - - - - - - Show close button on tabs - - - - - - - Middle-click on a tab closes it - - - - - - - - - Tab position: - - - - - - - - Top - - - - - Bottom - - - - - Left - - - - - Right - - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KColorButton - QPushButton -
kcolorbutton.h
-
-
- -
diff --git a/krdc/config/hostpreferenceslist.cpp b/krdc/config/hostpreferenceslist.cpp deleted file mode 100644 index 8b9938ed..00000000 --- a/krdc/config/hostpreferenceslist.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "hostpreferenceslist.h" -#include "hostpreferences.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -HostPreferencesList::HostPreferencesList(QWidget *parent, MainWindow *mainWindow, KConfigGroup hostPrefsConfig) - : QWidget(parent) - , m_hostPrefsConfig(hostPrefsConfig) - , m_mainWindow(mainWindow) -{ - hostList = new QListWidget(this); - connect(hostList, SIGNAL(itemSelectionChanged()), SLOT(selectionChanged())); - connect(hostList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(configureHost())); - - configureButton = new KPushButton(this); - configureButton->setEnabled(false); - configureButton->setText(i18n("Configure...")); - configureButton->setIcon(KIcon("configure")); - connect(configureButton, SIGNAL(clicked()), SLOT(configureHost())); - - removeButton = new KPushButton(this); - removeButton->setEnabled(false); - removeButton->setText(i18n("Remove")); - removeButton->setIcon(KIcon("list-remove")); - connect(removeButton, SIGNAL(clicked()), SLOT(removeHost())); - - QVBoxLayout *buttonLayout = new QVBoxLayout; - buttonLayout->addWidget(configureButton); - buttonLayout->addWidget(removeButton); - buttonLayout->addStretch(); - - QHBoxLayout *mainLayout = new QHBoxLayout(this); - mainLayout->addWidget(hostList); - mainLayout->addLayout(buttonLayout); - - setLayout(mainLayout); - - readConfig(); -} - -HostPreferencesList::~HostPreferencesList() -{ -} - -void HostPreferencesList::readConfig() -{ - QStringList urls = m_hostPrefsConfig.groupList(); - - for (int i = 0; i < urls.size(); ++i) - hostList->addItem(new QListWidgetItem(urls.at(i))); -} - -void HostPreferencesList::saveSettings() -{ - m_hostPrefsConfig.sync(); -} - -void HostPreferencesList::configureHost() -{ - QList selectedItems = hostList->selectedItems(); - - foreach(QListWidgetItem *selectedItem, selectedItems) { - const QString url = selectedItem->text(); - - kDebug(5010) << "Configure host: " << url; - - HostPreferences* prefs = 0; - - const QList remoteViewFactories(m_mainWindow->remoteViewFactoriesList()); - foreach(RemoteViewFactory *factory, remoteViewFactories) { - if (factory->supportsUrl(url)) { - prefs = factory->createHostPreferences(m_hostPrefsConfig.group(url), this); - if (prefs) { - kDebug(5010) << "Found plugin to handle url (" + url + "): " + prefs->metaObject()->className(); - } else { - kDebug(5010) << "Found plugin to handle url (" + url + "), but plugin does not provide preferences"; - } - } - } - - if (prefs) { - prefs->showDialog(this); - delete prefs; - } else { - KMessageBox::error(this, - i18n("The selected host cannot be handled."), - i18n("Unusable URL")); - } - } -} - -void HostPreferencesList::removeHost() -{ - const QList selectedItems = hostList->selectedItems(); - - foreach(QListWidgetItem *selectedItem, selectedItems) { - kDebug(5010) << "Remove host: " << selectedItem->text(); - - m_hostPrefsConfig.deleteGroup(selectedItem->text()); - delete(selectedItem); - } - - saveSettings(); - hostList->clearSelection(); -} - -void HostPreferencesList::selectionChanged() -{ - const bool enabled = hostList->selectedItems().isEmpty() ? false : true; - - configureButton->setEnabled(enabled); - removeButton->setEnabled(enabled); -} - -#include "moc_hostpreferenceslist.cpp" diff --git a/krdc/config/hostpreferenceslist.h b/krdc/config/hostpreferenceslist.h deleted file mode 100644 index 9a088719..00000000 --- a/krdc/config/hostpreferenceslist.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef HOSTPREFERENCESLIST_H -#define HOSTPREFERENCESLIST_H - -#include "mainwindow.h" - -#include - -#include -#include - -class KPushButton; - -#include - -class HostPreferencesList : public QWidget -{ - Q_OBJECT - -public: - HostPreferencesList(QWidget *parent, MainWindow *mainWindow, KConfigGroup hostPrefsConfig); - ~HostPreferencesList(); - -private slots: - void readConfig(); - void saveSettings(); - void configureHost(); - void removeHost(); - void selectionChanged(); - -private: - KConfigGroup m_hostPrefsConfig; - - KPushButton *configureButton; - KPushButton *removeButton; - QListWidget *hostList; - MainWindow *m_mainWindow; -}; - -#endif // HOSTPREFERENCESLIST_H diff --git a/krdc/config/preferencesdialog.cpp b/krdc/config/preferencesdialog.cpp deleted file mode 100644 index 7d5152cf..00000000 --- a/krdc/config/preferencesdialog.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2010 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "preferencesdialog.h" - -#include "hostpreferenceslist.h" -#include "ui_general.h" - -#include -#include -#include -#include -#include -#include - -PreferencesDialog::PreferencesDialog(QWidget *parent, KConfigSkeleton *skeleton) - : KConfigDialog(parent, "preferences", skeleton) - , m_settingsChanged(false) -{ - QWidget *generalPage = new QWidget(this); - Ui::General generalUi; - generalUi.setupUi(generalPage); - addPage(generalPage, i18nc("General Config", "General"), "krdc", i18n("General Configuration")); - - HostPreferencesList *hostPreferencesList = new HostPreferencesList(this, - qobject_cast(parent), - skeleton->config()->group("hostpreferences")); - addPage(hostPreferencesList, i18n("Hosts"), "computer", i18n("Host Configuration")); - - m_pluginSelector = new KPluginSelector(); - KService::List offers = KServiceTypeTrader::self()->query("KRDC/Plugin"); - m_pluginSelector->addPlugins(KPluginInfo::fromServices(offers), KPluginSelector::ReadConfigFile, - i18n("Plugins"), "Service", KGlobal::config()); - m_pluginSelector->load(); - addPage(m_pluginSelector, i18n("Plugins"), "preferences-plugin", i18n("Plugin Configuration")); - - connect(this, SIGNAL(accepted()), SLOT(saveState())); - connect(this, SIGNAL(defaultClicked()), SLOT(loadDefaults())); - connect(m_pluginSelector, SIGNAL(changed(bool)), SLOT(settingsChanged())); -} - -void PreferencesDialog::saveState() -{ - //TODO: relaod plugins at runtime? - m_pluginSelector->save(); -} - -void PreferencesDialog::loadDefaults() -{ - m_pluginSelector->defaults(); - enableButton(Default, false); -} - -void PreferencesDialog::settingsChanged() -{ - enableButton(Apply, true); - enableButton(Default, true); -} - -bool PreferencesDialog::isDefault() -{ - return KConfigDialog::isDefault() && m_pluginSelector->isDefault(); -} diff --git a/krdc/config/preferencesdialog.h b/krdc/config/preferencesdialog.h deleted file mode 100644 index 13424c66..00000000 --- a/krdc/config/preferencesdialog.h +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef PREFERENCESDIALOG_H -#define PREFERENCESDIALOG_H - -#include - -class KConfigSkeleton; -class KPluginSelector; - -class PreferencesDialog : public KConfigDialog -{ - Q_OBJECT - -public: - PreferencesDialog(QWidget *parent, KConfigSkeleton *config); - -protected: - virtual bool isDefault(); - -private slots: - void saveState(); - void loadDefaults(); - void settingsChanged(); - -private: - KPluginSelector *m_pluginSelector; - bool m_settingsChanged; -}; - -#endif diff --git a/krdc/connectiondelegate.cpp b/krdc/connectiondelegate.cpp deleted file mode 100644 index 3fe7ba7c..00000000 --- a/krdc/connectiondelegate.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "connectiondelegate.h" -#include "remotedesktopsmodel.h" - -#include -#include -#include -#include -#include - -ConnectionDelegate::ConnectionDelegate(QObject *parent) : - QStyledItemDelegate(parent) -{ -} - -QString ConnectionDelegate::displayText(const QVariant &value, const QLocale& locale) const -{ - if (value.type() == QVariant::DateTime) { - QDateTime lastConnected = value.toDateTime(); - QDateTime currentTime = QDateTime::currentDateTimeUtc(); - - int daysAgo = lastConnected.daysTo(currentTime); - if (daysAgo <= 1 && lastConnected.secsTo(currentTime) < 86400) { - int minutesAgo = lastConnected.secsTo(currentTime) / 60; - int hoursAgo = minutesAgo / 60; - if (hoursAgo < 1) { - if (minutesAgo < 1) - return i18n("Less than a minute ago"); - return i18np("A minute ago", "%1 minutes ago", minutesAgo); - } else { - return i18np("An hour ago", "%1 hours ago", hoursAgo); - } - } else { // 1 day or more - if (daysAgo < 30) - return i18np("Yesterday", "%1 days ago", daysAgo); - if (daysAgo < 365) - return i18np("Over a month ago", "%1 months ago", daysAgo / 30); - return i18np("A year ago", "%1 years ago", daysAgo / 365); - } - - } - // These aren't the strings you're looking for, move along. - return QStyledItemDelegate::displayText(value, locale); -} - -void ConnectionDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (index.column() == RemoteDesktopsModel::Favorite) { - QVariant value = index.data(Qt::CheckStateRole); - if (value.isValid()) { - Qt::CheckState checkState = static_cast(value.toInt()); - KIcon favIcon = KIcon("bookmarks"); - KIcon::Mode mode = (checkState == Qt::Checked) ? KIcon::Active : KIcon::Disabled; - favIcon.paint(painter, option.rect, option.decorationAlignment, mode); - - } - } else { - QStyledItemDelegate::paint(painter, option, index); - } -} - -QSize ConnectionDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (index.column() == RemoteDesktopsModel::Favorite) - return QSize(KIconLoader::SizeSmall, KIconLoader::SizeSmall); - return QStyledItemDelegate::sizeHint(option, index); -} diff --git a/krdc/connectiondelegate.h b/krdc/connectiondelegate.h deleted file mode 100644 index b93148e0..00000000 --- a/krdc/connectiondelegate.h +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef CONNECTIONDELEGATE_H -#define CONNECTIONDELEGATE_H - -#include - -class ConnectionDelegate : public QStyledItemDelegate -{ - Q_OBJECT -public: - explicit ConnectionDelegate(QObject *parent = 0); - QString displayText(const QVariant &value, const QLocale& locale) const; - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; -signals: - -public slots: - -}; - -#endif // CONNECTIONDELEGATE_H diff --git a/krdc/core/CMakeLists.txt b/krdc/core/CMakeLists.txt deleted file mode 100644 index 11846ab8..00000000 --- a/krdc/core/CMakeLists.txt +++ /dev/null @@ -1,46 +0,0 @@ -add_definitions(-DKDE_DEFAULT_DEBUG_AREA=5010) - -set(krdccore_SRCS - remoteviewfactory.cpp - remoteview.cpp - hostpreferences.cpp -) - -kde4_add_kcfg_files(krdccore_SRCS settings.kcfgc) - -add_library(krdccore SHARED ${krdccore_SRCS}) - -target_link_libraries(krdccore - KDE4::kdecore - KDE4::kdeui - KDE4::kpasswdstore -) - -set_target_properties(krdccore PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -generate_export_header(krdccore) - -install( - TARGETS krdccore - DESTINATION ${KDE4_LIB_INSTALL_DIR} -) - -# Install headers -set(krdccore_HDRS - remoteviewfactory.h - remoteview.h - hostpreferences.h -) - -install( - FILES ${krdccore_HDRS} - DESTINATION ${KDE4_INCLUDE_INSTALL_DIR}/krdc -) - -install( - FILES krdc_plugin.desktop - DESTINATION ${KDE4_SERVICETYPES_INSTALL_DIR} -) diff --git a/krdc/core/hostpreferences.cpp b/krdc/core/hostpreferences.cpp deleted file mode 100644 index aaecb3e7..00000000 --- a/krdc/core/hostpreferences.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2010 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "hostpreferences.h" - -#include "settings.h" - -#include -#include -#include -#include - -#include -#include -#include - -HostPreferences::HostPreferences(KConfigGroup configGroup, QObject *parent) - : QObject(parent), - m_configGroup(configGroup), - m_connected(false), - showAgainCheckBox(0), - walletSupportCheckBox(0) -{ - m_hostConfigured = m_configGroup.hasKey("showConfigAgain"); -} - -HostPreferences::~HostPreferences() -{ -} - -KConfigGroup HostPreferences::configGroup() -{ - return m_configGroup; -} - -void HostPreferences::acceptConfig() -{ - setShowConfigAgain(showAgainCheckBox->isChecked()); - setWalletSupport(walletSupportCheckBox->isChecked()); -} - -bool HostPreferences::hostConfigured() -{ - return m_hostConfigured; -} - -void HostPreferences::setShowConfigAgain(bool show) -{ - m_configGroup.writeEntry("showConfigAgain", show); -} - -bool HostPreferences::showConfigAgain() -{ - return m_configGroup.readEntry("showConfigAgain", true); -} - -void HostPreferences::setWalletSupport(bool walletSupport) -{ - m_configGroup.writeEntry("walletSupport", walletSupport); -} - -bool HostPreferences::walletSupport() -{ - return m_configGroup.readEntry("walletSupport", true); -} - -void HostPreferences::setHeight(int height) -{ - if (height >= 0) - m_configGroup.writeEntry("height", height); -} - -int HostPreferences::height() -{ - return m_configGroup.readEntry("height", Settings::height()); -} - -void HostPreferences::setWidth(int width) -{ - if (width >= 0) - m_configGroup.writeEntry("width", width); -} - -int HostPreferences::width() -{ - return m_configGroup.readEntry("width", Settings::width()); -} - -bool HostPreferences::fullscreenScale() -{ - return m_configGroup.readEntry("fullscreenScale", false); -} - -void HostPreferences::setFullscreenScale(bool scale) -{ - m_configGroup.writeEntry("fullscreenScale", scale); -} - -bool HostPreferences::windowedScale() -{ - return m_configGroup.readEntry("windowedScale", false); -} - -void HostPreferences::setWindowedScale(bool scale) -{ - m_configGroup.writeEntry("windowedScale", scale); -} - -bool HostPreferences::grabAllKeys() -{ - return m_configGroup.readEntry("grabAllKeys", false); -} - -void HostPreferences::setGrabAllKeys(bool grab) -{ - m_configGroup.writeEntry("grabAllKeys", grab); -} - -bool HostPreferences::showLocalCursor() -{ - return m_configGroup.readEntry("showLocalCursor", false); -} - -void HostPreferences::setShowLocalCursor(bool show) -{ - m_configGroup.writeEntry("showLocalCursor", show); -} - -bool HostPreferences::viewOnly() -{ - return m_configGroup.readEntry("viewOnly", false); -} - -void HostPreferences::setViewOnly(bool view) -{ - m_configGroup.writeEntry("viewOnly", view); -} - -bool HostPreferences::showDialogIfNeeded(QWidget *parent) -{ - if (hostConfigured()) { - if (showConfigAgain()) { - kDebug(5010) << "Show config dialog again"; - return showDialog(parent); - } else - return true; // no changes, no need to save - } else { - kDebug(5010) << "No config found, create new"; - if (Settings::showPreferencesForNewConnections()) - return showDialog(parent); - else - return true; - } -} - - -bool HostPreferences::showDialog(QWidget *parent) -{ - // Prepare dialog - KDialog *dialog = new KDialog(parent); - dialog->setCaption(i18n("Host Configuration")); - - QWidget *mainWidget = dialog->mainWidget(); - QVBoxLayout *layout = new QVBoxLayout(mainWidget); - - KTitleWidget *titleWidget = new KTitleWidget(dialog); - titleWidget->setText(i18n("Host Configuration")); - if (m_connected) { - titleWidget->setComment(QString("%1").arg( - i18n("Note that settings might only apply when you connect next time to this host."))); - } - titleWidget->setPixmap(KIcon("krdc")); - layout->addWidget(titleWidget); - - QWidget* widget = createProtocolSpecificConfigPage(); - - if (widget) { - if (widget->layout()) - widget->layout()->setMargin(0); - - layout->addWidget(widget); - } - - showAgainCheckBox = new QCheckBox(mainWidget); - showAgainCheckBox->setText(i18n("Show this dialog again for this host")); - showAgainCheckBox->setChecked(showConfigAgain()); - - walletSupportCheckBox = new QCheckBox(mainWidget); - walletSupportCheckBox->setText(i18n("Remember password (KPasswdStore)")); - walletSupportCheckBox->setChecked(walletSupport()); - - layout->addWidget(showAgainCheckBox); - layout->addWidget(walletSupportCheckBox); - layout->addStretch(1); - - // WORKAROUND: it seems that KDialog does not set the minimum size properly in some cases. - // see for example issue #244539. also it looks like KTitleWidget returns a too small size hint when a comment is shown. - QSize minimumSize = dialog->sizeHint(); - if (m_connected) { - minimumSize += QSize(0, 50); - } - dialog->setMinimumSize(minimumSize); - - // Show dialog - if (dialog->exec() == KDialog::Accepted) { - kDebug(5010) << "HostPreferences config dialog accepted"; - acceptConfig(); - return true; - } else { - return false; - } -} - -void HostPreferences::setShownWhileConnected(bool connected) -{ - m_connected = connected; -} - -#include "moc_hostpreferences.cpp" diff --git a/krdc/core/hostpreferences.h b/krdc/core/hostpreferences.h deleted file mode 100644 index d5bb9321..00000000 --- a/krdc/core/hostpreferences.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef HOSTPREFERENCES_H -#define HOSTPREFERENCES_H - -#include "remoteview.h" - -#include - -#include - -#include - -#include - -#include -#include -class KConfig; -class KConfigGroup; - -class KRDCCORE_EXPORT HostPreferences : public QObject -{ - Q_OBJECT - -public: - ~HostPreferences(); - - KConfigGroup configGroup(); - - bool walletSupport(); - - /** Whether scaling is enabled when session is full screen. Note: only windowedScale seems to be used. */ - bool fullscreenScale(); - void setFullscreenScale(bool scale); - - /** Whether scaling is enabled when session is not full screen */ - bool windowedScale(); - void setWindowedScale(bool scale); - - bool grabAllKeys(); - void setGrabAllKeys(bool grab); - - bool showLocalCursor(); - void setShowLocalCursor(bool show); - - bool viewOnly(); - void setViewOnly(bool view); - - /** Saved height. Generally used for the viewsize. */ - int height(); - void setHeight(int height); - /** Saved width. Generally used for the viewsize. */ - int width(); - void setWidth(int width); - - /** - * Show the configuration dialog if needed, ie. if the user did - * check "show this dialog again for this host". - * Returns true if user pressed ok. - */ - bool showDialogIfNeeded(QWidget *parent); - - /** Show the configuration dialog */ - bool showDialog(QWidget *parent); - - /** If @p connected is true, a message is shown that settings might only apply after a reconnect. */ - void setShownWhileConnected(bool connected); - -protected: - HostPreferences(KConfigGroup configGroup, QObject *parent); - - virtual QWidget* createProtocolSpecificConfigPage() = 0; - - /** Called when the user validates the config dialog. */ - virtual void acceptConfig(); - - bool hostConfigured(); - bool showConfigAgain(); - - KConfigGroup m_configGroup; - -private: - void setShowConfigAgain(bool show); - void setWalletSupport(bool walletSupport); - - bool m_hostConfigured; - bool m_connected; - - QCheckBox *showAgainCheckBox; - QCheckBox *walletSupportCheckBox; -}; - -#endif diff --git a/krdc/core/krdc.kcfg b/krdc/core/krdc.kcfg deleted file mode 100644 index 12f5b39a..00000000 --- a/krdc/core/krdc.kcfg +++ /dev/null @@ -1,116 +0,0 @@ - - - kdemacros.h - - - - false - - - true - - - - - - true - - - true - - - true - - - false - - - #00417F - - - true - - - false - - - true - - - true - - - true - - - 0 - - - false - - - false - - - 2 - - - 1 - - - - - 1 - - - false - - - 800 - - - 600 - - - - - 800 - - - 600 - - - 7 - - - 2 - - - 0 - - - false - - - - - - - - - true - - - true - - - 2 - - - /media - - - diff --git a/krdc/core/krdc_plugin.desktop b/krdc/core/krdc_plugin.desktop deleted file mode 100644 index 990bedd7..00000000 --- a/krdc/core/krdc_plugin.desktop +++ /dev/null @@ -1,63 +0,0 @@ -[Desktop Entry] -Type=ServiceType -X-KDE-ServiceType=KRDC/Plugin -Name=KRDC Plugin -Name[ast]=Complemente KRDC -Name[bg]=Приставка KRDC -Name[bs]=KRDC Dodatak -Name[ca]=Connector del KRDC -Name[ca@valencia]=Connector del KRDC -Name[cs]=Modul KRDC -Name[da]=KRDC-plugin -Name[de]=KRDC-Modul -Name[el]=Πρόσθετο KRDC -Name[en_GB]=KRDC Plugin -Name[es]=Complemento de KRDC -Name[et]=KRDC plugin -Name[eu]=KRDC plugina -Name[fi]=Kopete-liitännäinen -Name[fr]=Module externe KRDC -Name[ga]=Breiseán KRDC -Name[gl]=Engadido KRDC -Name[hr]=Priključak KRDC -Name[hu]=KRDC-bővítmény -Name[ia]=Plug-in de KRDC -Name[is]=KRDC íforrit -Name[it]=Estensione di KRDC -Name[ja]=KRDC プラグイン -Name[kk]=KRDC плагині -Name[km]=កម្មវិធី​ជំនួយ KRDC -Name[ko]=KRDC 플러그인 -Name[lt]=KRDC priedas -Name[lv]=KRDC spraudnis -Name[mr]=के-आर-डी-सी प्लगइन -Name[nb]=KRDC programtillegg -Name[nds]=KRDC-Moduul -Name[nl]=KRDC-plugin -Name[nn]=KRDC-programtillegg -Name[pa]=KRDC ਪਲੱਗਇਨ -Name[pl]=Wtyczka KRDC -Name[pt]='Plugin' do KRDC -Name[pt_BR]=Plugin KRDC -Name[ro]=Extensie KRDC -Name[ru]=Модуль KRDC -Name[si]=KRDC ප්ලගිනය -Name[sk]=Modul KRDC -Name[sl]=Vstavek za KRDC -Name[sr]=Прикључак КРДЦ‑а -Name[sr@ijekavian]=Прикључак КРДЦ‑а -Name[sr@ijekavianlatin]=Priključak KRDC‑a -Name[sr@latin]=Priključak KRDC‑a -Name[sv]=Insticksprogram för KRDC -Name[th]=ส่วนเสริมของ KRDC -Name[tr]=KRDC Eklentisi -Name[ug]=KRDC قىستۇرما -Name[uk]=Додаток KRDC -Name[x-test]=xxKRDC Pluginxx -Name[zh_CN]=KRDC 插件 -Name[zh_TW]=KRDC 外掛程式 - -# Sorting of the plugin. -# 0 is the highest value. -[PropertyDef::X-KDE-KRDC-Sorting] -Type=int diff --git a/krdc/core/remoteview.cpp b/krdc/core/remoteview.cpp deleted file mode 100644 index 617d1758..00000000 --- a/krdc/core/remoteview.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2002-2003 Tim Jansen -** Copyright (C) 2007-2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "remoteview.h" - -#ifndef QTONLY - #include - #include -#endif - -#include - -RemoteView::RemoteView(QWidget *parent) - : QWidget(parent), - m_status(Disconnected), - m_host(QString()), - m_port(0), - m_viewOnly(false), - m_grabAllKeys(false), - m_scale(false), - m_keyboardIsGrabbed(false), -#ifndef QTONLY - m_passwdStore(0), -#endif - m_dotCursorState(CursorOff) -{ -} - -RemoteView::~RemoteView() -{ -#ifndef QTONLY - delete m_passwdStore; -#endif -} - -RemoteView::RemoteStatus RemoteView::status() -{ - return m_status; -} - -void RemoteView::setStatus(RemoteView::RemoteStatus s) -{ - if (m_status == s) - return; - - if (((1+ m_status) != s) && (s != Disconnected)) { - // follow state transition rules - - if (s == Disconnecting) { - if (m_status == Disconnected) - return; - } else { - Q_ASSERT(((int) s) >= 0); - if (m_status > s) { - m_status = Disconnected; - emit statusChanged(Disconnected); - } - // smooth state transition - RemoteStatus origState = m_status; - for (int i = origState; i < s; ++i) { - m_status = (RemoteStatus) i; - emit statusChanged((RemoteStatus) i); - } - } - } - m_status = s; - emit statusChanged(m_status); -} - -bool RemoteView::supportsScaling() const -{ - return false; -} - -bool RemoteView::supportsLocalCursor() const -{ - return false; -} - -QString RemoteView::host() -{ - return m_host; -} - -QSize RemoteView::framebufferSize() -{ - return QSize(0, 0); -} - -void RemoteView::startQuitting() -{ -} - -bool RemoteView::isQuitting() -{ - return false; -} - -int RemoteView::port() -{ - return m_port; -} - -void RemoteView::updateConfiguration() -{ -} - -void RemoteView::keyEvent(QKeyEvent *) -{ -} - -bool RemoteView::viewOnly() -{ - return m_viewOnly; -} - -void RemoteView::setViewOnly(bool viewOnly) -{ - m_viewOnly = viewOnly; -} - -bool RemoteView::grabAllKeys() -{ - return m_grabAllKeys; -} - -void RemoteView::setGrabAllKeys(bool grabAllKeys) -{ - m_grabAllKeys = grabAllKeys; - - if (grabAllKeys) { - m_keyboardIsGrabbed = true; - grabKeyboard(); - } else if (m_keyboardIsGrabbed) { - releaseKeyboard(); - } -} - -QPixmap RemoteView::takeScreenshot() -{ - return QPixmap::grabWidget(this); -} - -void RemoteView::showDotCursor(DotCursorState state) -{ - m_dotCursorState = state; -} - -RemoteView::DotCursorState RemoteView::dotCursorState() const -{ - return m_dotCursorState; -} - -bool RemoteView::scaling() const -{ - return m_scale; -} - -void RemoteView::enableScaling(bool scale) -{ - m_scale = scale; -} - -void RemoteView::switchFullscreen(bool) -{ -} - -void RemoteView::scaleResize(int, int) -{ -} - -KUrl RemoteView::url() -{ - return m_url; -} - -#ifndef QTONLY -QString RemoteView::readWalletPassword(bool fromUserNameOnly) -{ - window()->setDisabled(true); // WORKAROUND: disable inputs so users cannot close the current tab (see #181230) - m_passwdStore = new KPasswdStore(this); - m_passwdStore->setStoreID("KRDC"); - window()->setDisabled(false); - - if (m_passwdStore) { - const qlonglong windowId = window()->winId(); - bool walletOK = m_passwdStore->openStore(windowId); - if (walletOK) { - kDebug(5010) << "Wallet OK"; - - QString key; - if (fromUserNameOnly) - key = m_url.userName(); - else - key = m_url.prettyUrl(KUrl::RemoveTrailingSlash); - - QString password = m_passwdStore->getPasswd(key.toUtf8(), windowId); - if (!password.isEmpty()) { - kDebug(5010) << "Password read OK"; - - return password; - } - } - } - return QString(); -} - -void RemoteView::saveWalletPassword(const QString &password, bool fromUserNameOnly) -{ - QString key; - if (fromUserNameOnly) - key = m_url.userName(); - else - key = m_url.prettyUrl(KUrl::RemoveTrailingSlash); - - const qlonglong windowId = window()->winId(); - if (m_passwdStore && m_passwdStore->openStore(windowId)) { - kDebug(5010) << "Write wallet password"; - m_passwdStore->storePasswd(key.toUtf8(), password, windowId); - } -} -#endif - -QCursor RemoteView::localDotCursor() const -{ -#ifdef QTONLY - return QCursor(); //TODO -#else - QPixmap cursorPixmap(KGlobal::dirs()->findResource("appdata", - "pics/pointcursor.png")); - QBitmap cursorMask(KGlobal::dirs()->findResource("appdata", - "pics/pointcursormask.png")); - cursorPixmap.setMask(cursorMask); - return QCursor(cursorPixmap); -#endif -} - -void RemoteView::focusInEvent(QFocusEvent *event) -{ - if (m_grabAllKeys) { - m_keyboardIsGrabbed = true; - grabKeyboard(); - } - - QWidget::focusInEvent(event); -} - -void RemoteView::focusOutEvent(QFocusEvent *event) -{ - if (m_grabAllKeys || m_keyboardIsGrabbed) { - m_keyboardIsGrabbed = false; - releaseKeyboard(); - } - - QWidget::focusOutEvent(event); -} - -#include "moc_remoteview.cpp" diff --git a/krdc/core/remoteview.h b/krdc/core/remoteview.h deleted file mode 100644 index b90061c2..00000000 --- a/krdc/core/remoteview.h +++ /dev/null @@ -1,415 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2002-2003 Tim Jansen -** Copyright (C) 2007-2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef REMOTEVIEW_H -#define REMOTEVIEW_H - -#ifdef QTONLY - #include - #define KUrl QUrl - #define KRDCCORE_EXPORT -#else - #include - #include - #include "krdccore_export.h" -#endif - -#include - -class HostPreferences; - -/** - * Generic widget that displays a remote framebuffer. - * Implement this if you want to add another backend. - * - * Things to take care of: - * @li The RemoteView is responsible for its size. In - * non-scaling mode, set the fixed size of the widget - * to the remote resolution. In scaling mode, set the - * maximum size to the remote size and minimum size to the - * smallest resolution that your scaler can handle. - * @li if you override mouseMoveEvent() - * you must ignore the QEvent, because the KRDC widget will - * need it for stuff like toolbar auto-hide and bump - * scrolling. If you use x11Event(), make sure that - * MotionNotify events will be forwarded. - * - */ -class KRDCCORE_EXPORT RemoteView : public QWidget -{ - Q_OBJECT - -public: - - Q_ENUMS(Quality) - - enum Quality { - Unknown, - High, - Medium, - Low - }; - - /** - * Describes the state of a local cursor, if there is such a concept in the backend. - * With local cursors, there are two cursors: the cursor on the local machine (client), - * and the cursor on the remote machine (server). Because there is usually some lag, - * some backends show both cursors simultanously. In the VNC backend the local cursor - * is a dot and the remote cursor is the 'real' cursor, usually an arrow. - */ - - Q_ENUMS(DotCursorState) - - enum DotCursorState { - CursorOn, ///< Always show local cursor (and the remote one). - CursorOff, ///< Never show local cursor, only the remote one. - /// Try to measure the lag and enable the local cursor if the latency is too high. - CursorAuto - }; - - /** - * State of the connection. The state of the connection is returned - * by @ref RemoteView::status(). - * - * Not every state transition is allowed. You are only allowed to transition - * a state to the following state, with three exceptions: - * @li You can move from every state directly to Disconnected - * @li You can move from every state except Disconnected to - * Disconnecting - * @li You can move from Disconnected to Connecting - * - * @ref RemoteView::setStatus() will follow this rules for you. - * (If you add/remove a state here, you must adapt it) - */ - - Q_ENUMS(RemoteStatus) - - enum RemoteStatus { - Connecting = 0, - Authenticating = 1, - Preparing = 2, - Connected = 3, - Disconnecting = -1, - Disconnected = -2 - }; - - Q_ENUMS(ErrorCode) - - enum ErrorCode { - None = 0, - Internal, - Connection, - Protocol, - IO, - Name, - NoServer, - ServerBlocked, - Authentication - }; - - virtual ~RemoteView(); - - /** - * Checks whether the backend supports scaling. The - * default implementation returns false. - * @return true if scaling is supported - * @see scaling() - */ - virtual bool supportsScaling() const; - - /** - * Checks whether the widget is in scale mode. The - * default implementation always returns false. - * @return true if scaling is activated. Must always be - * false if @ref supportsScaling() returns false - * @see supportsScaling() - */ - virtual bool scaling() const; - - /** - * Checks whether the backend supports the concept of local cursors. The - * default implementation returns false. - * @return true if local cursors are supported/known - * @see DotCursorState - * @see showDotCursor() - * @see dotCursorState() - */ - virtual bool supportsLocalCursor() const; - - /** - * Sets the state of the dot cursor, if supported by the backend. - * The default implementation does nothing. - * @param state the new state (CursorOn, CursorOff or - * CursorAuto) - * @see dotCursorState() - * @see supportsLocalCursor() - */ - virtual void showDotCursor(DotCursorState state); - - /** - * Returns the state of the local cursor. The default implementation returns - * always CursorOff. - * @return true if local cursors are supported/known - * @see showDotCursor() - * @see supportsLocalCursor() - */ - virtual DotCursorState dotCursorState() const; - - /** - * Checks whether the view is in view-only mode. This means - * that all input is ignored. - */ - virtual bool viewOnly(); - - /** - * Checks whether grabbing all possible keys is enabled. - */ - virtual bool grabAllKeys(); - - /** - * Returns the resolution of the remote framebuffer. - * It should return a null @ref QSize when the size - * is not known. - * The backend must also emit a @ref framebufferSizeChanged() - * when the size of the framebuffer becomes available - * for the first time or the size changed. - * @return the remote framebuffer size, a null QSize - * if unknown - */ - virtual QSize framebufferSize(); - - /** - * Initiate the disconnection. This doesn't need to happen - * immediately. The call must not block. - * @see isQuitting() - */ - virtual void startQuitting(); - - /** - * Checks whether the view is currently quitting. - * @return true if it is quitting - * @see startQuitting() - * @see setStatus() - */ - virtual bool isQuitting(); - - /** - * @return the host the view is connected to - */ - virtual QString host(); - - /** - * @return the port the view is connected to - */ - virtual int port(); - - /** - * Initialize the view (for example by showing configuration - * dialogs to the user) and start connecting. Should not block - * without running the event loop (so displaying a dialog is ok). - * When the view starts connecting the application must call - * @ref setStatus() with the status Connecting. - * @return true if successful (so far), false - * otherwise - * @see connected() - * @see disconnected() - * @see disconnectedError() - * @see statusChanged() - */ - virtual bool start() = 0; - - /** - * Called when the configuration is changed. - * The default implementation does nothing. - */ - virtual void updateConfiguration(); - - /** - * @return screenshot of the view - */ - virtual QPixmap takeScreenshot(); - -#ifndef QTONLY - /** - * Returns the current host preferences of this view. - */ - virtual HostPreferences* hostPreferences() = 0; -#endif - - /** - * Returns the current status of the connection. - * @return the status of the connection - * @see setStatus() - */ - RemoteStatus status(); - - /** - * @return the current url - */ - KUrl url(); - -public slots: - /** - * Called to enable or disable scaling. - * Ignored if @ref supportsScaling() is false. - * The default implementation does nothing. - * @param s true to enable, false to disable. - * @see supportsScaling() - * @see scaling() - */ - virtual void enableScaling(bool scale); - - /** - * Enables/disables the view-only mode. - * Ignored if @ref supportsScaling() is false. - * The default implementation does nothing. - * @param viewOnly true to enable, false to disable. - * @see supportsScaling() - * @see viewOnly() - */ - virtual void setViewOnly(bool viewOnly); - - /** - * Enables/disables grabbing all possible keys. - * @param grabAllKeys true to enable, false to disable. - * Default is false. - * @see grabAllKeys() - */ - virtual void setGrabAllKeys(bool grabAllKeys); - - /** - * Called to let the backend know it when - * we switch from/to fullscreen. - * @param on true when switching to fullscreen, - * false when switching from fullscreen. - */ - virtual void switchFullscreen(bool on); - - /** - * Sends a QKeyEvent to the remote server. - * @param event the key to send - */ - virtual void keyEvent(QKeyEvent *event); - - /** - * Called when the visible place changed so remote - * view can resize itself. - */ - virtual void scaleResize(int w, int h); - -Q_SIGNALS: - /** - * Emitted when the size of the remote screen changes. Also - * called when the size is known for the first time. - * @param x the width of the screen - * @param y the height of the screen - */ - void framebufferSizeChanged(int w, int h); - - /** - * Emitted when the view connected successfully. - */ - void connected(); - - /** - * Emitted when the view disconnected without error. - */ - void disconnected(); - - /** - * Emitted when the view disconnected with error. - */ - void disconnectedError(); - - /** - * Emitted when the view has a specific error. - */ - void errorMessage(const QString &title, const QString &message); - - /** - * Emitted when the status of the view changed. - * @param s the new status - */ - void statusChanged(RemoteView::RemoteStatus s); - - /** - * Emitted when the password dialog is shown or hidden. - * @param b true when the dialog is shown, false when it has been hidden - */ - void showingPasswordDialog(bool b); - - /** - * Emitted when the mouse on the remote side has been moved. - * @param x the new x coordinate - * @param y the new y coordinate - * @param buttonMask the mask of mouse buttons (bit 0 for first mouse - * button, 1 for second button etc)a - */ - void mouseStateChanged(int x, int y, int buttonMask); - -protected: - RemoteView(QWidget *parent = 0); - - void focusInEvent(QFocusEvent *event); - void focusOutEvent(QFocusEvent *event); - - /** - * The status of the remote view. - */ - RemoteStatus m_status; - - /** - * Set the status of the connection. - * Emits a statusChanged() signal. - * Note that the states need to be set in a certain order, - * see @ref Status. setStatus() will try to do this - * transition automatically, so if you are in Connecting - * and call setStatus(Preparing), setStatus() will - * emit a Authenticating and then Preparing. - * If you transition backwards, it will emit a - * Disconnected before doing the transition. - * @param s the new status - */ - virtual void setStatus(RemoteStatus s); - - QCursor localDotCursor() const; - - QString m_host; - int m_port; - bool m_viewOnly; - bool m_grabAllKeys; - bool m_scale; - bool m_keyboardIsGrabbed; - KUrl m_url; - -#ifndef QTONLY - QString readWalletPassword(bool fromUserNameOnly = false); - void saveWalletPassword(const QString &password, bool fromUserNameOnly = false); - KPasswdStore *m_passwdStore; -#endif - - DotCursorState m_dotCursorState; -}; - -#endif diff --git a/krdc/core/remoteviewfactory.cpp b/krdc/core/remoteviewfactory.cpp deleted file mode 100644 index ddb49b1a..00000000 --- a/krdc/core/remoteviewfactory.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "remoteviewfactory.h" - -#include - -RemoteViewFactory::RemoteViewFactory(QObject *parent) - : QObject(parent) -{ -} - -RemoteViewFactory::~RemoteViewFactory() -{ -} - -#include "moc_remoteviewfactory.cpp" diff --git a/krdc/core/remoteviewfactory.h b/krdc/core/remoteviewfactory.h deleted file mode 100644 index e5d57b4c..00000000 --- a/krdc/core/remoteviewfactory.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef REMOTEVIEWFACTORY_H -#define REMOTEVIEWFACTORY_H - -#include "remoteview.h" - -#include -#include -#include - -class KUrl; - -/** - * Convenience macros to export a KRDC plugin. Suppose you created the plugin - * FooRemoteViewFactory. In FooRemoteViewFactory you will have to put the following line: - * - * @code - * KRDC_PLUGIN_EXPORT(FooRemoteViewFactory) - * @endcode - * - * The rest will be done for you. - */ -#define KRDC_PLUGIN_EXPORT( c ) \ - K_PLUGIN_FACTORY( KrdcFactory, registerPlugin< c >(); ) \ - K_EXPORT_PLUGIN( KrdcFactory("c") ) - -/** - * Factory to be implemented by any plugin. - */ -class KRDCCORE_EXPORT RemoteViewFactory : public QObject -{ - Q_OBJECT - -public: - /** - * Deconstructor. - */ - virtual ~RemoteViewFactory(); - - /** - * Returns true if the provided @p url is supported by the current plugin. - */ - virtual bool supportsUrl(const KUrl &url) const = 0; - - /** - * Returns a new RemoteView implementing object. - */ - virtual RemoteView *createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) = 0; - - /** - * Returns a new HostPreferences implementing object or 0 if no settings are available. - */ - virtual HostPreferences *createHostPreferences(KConfigGroup configGroup, QWidget *parent) = 0; - - /** - * Returns the supported scheme. - * @see KUrl::scheme() - */ - virtual QString scheme() const = 0; - - /** - * Returns the text of the action in the file menu (by default). - */ - virtual QString connectActionText() const = 0; - - /** - * Returns the text of the connect button on the startscreen. - */ - virtual QString connectButtonText() const = 0; - - /** - * Returns the tooltip next to the url navigator when the user presses - * the connect action. - */ - virtual QString connectToolTipText() const = 0; - -protected: - /** - * Protected constructor so it cannot be instantiated. - */ - RemoteViewFactory(QObject *parent = 0); - -}; - -#endif // REMOTEVIEWFACTORY_H diff --git a/krdc/core/settings.kcfgc b/krdc/core/settings.kcfgc deleted file mode 100644 index 2173c271..00000000 --- a/krdc/core/settings.kcfgc +++ /dev/null @@ -1,5 +0,0 @@ -ClassName=Settings -File=krdc.kcfg -Mutators=true -Singleton=true -Visibility=KDE_EXPORT diff --git a/krdc/floatingtoolbar.cpp b/krdc/floatingtoolbar.cpp deleted file mode 100644 index e04c2ec2..00000000 --- a/krdc/floatingtoolbar.cpp +++ /dev/null @@ -1,486 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007-2008 Urs Wolfer -** Parts of this file have been take from okular: -** Copyright (C) 2004-2005 Enrico Ros -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "floatingtoolbar.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -static const int actionIconSize = 22; -static const int toolBarRBMargin = 2; -static const double toolBarOpacity = 0.8; -static const int visiblePixelWhenAutoHidden = 6; -static const int autoHideTimeout = 500; -static const int initialAutoHideTimeout = 2000; - -/** - * Denotes the verious states of the animation. - */ -enum AnimState { - Hiding, - Showing, - Still -}; - -class FloatingToolBarPrivate -{ -public: - FloatingToolBarPrivate(FloatingToolBar *qq) - : q(qq) - , anchorSide(FloatingToolBar::Left) - , offsetPlaceHolder(new QWidget(qq)) - , animState(Still) - , toDelete(false) - , visible(false) - , sticky(false) - , opacity(toolBarOpacity) - // set queuedShow to true so we show the toolbar if we get a resize event on the anchorWidget - , queuedShow(true) { - } - - // rebuild contents and reposition then widget - void buildToolBar(); - void reposition(); - // compute the visible and hidden positions along current side - QPoint getInnerPoint() const; - QPoint getOuterPoint() const; - - FloatingToolBar *q; - - QWidget *anchorWidget; - FloatingToolBar::Side anchorSide; - QWidget *offsetPlaceHolder; - - QTimer *animTimer; - QTimer *autoHideTimer; - QPoint currentPosition; - QPoint endPosition; - AnimState animState; - bool toDelete; - bool visible; - bool sticky; - qreal opacity; - bool queuedShow; - - QPixmap backgroundPixmap; -}; - -FloatingToolBar::FloatingToolBar(QWidget *parent, QWidget *anchorWidget) - : QToolBar(parent), d(new FloatingToolBarPrivate(this)) -{ - ; - addWidget(d->offsetPlaceHolder); - - setMouseTracking(true); - setIconSize(QSize(actionIconSize, actionIconSize)); - d->anchorWidget = anchorWidget; - - d->animTimer = new QTimer(this); - connect(d->animTimer, SIGNAL(timeout()), this, SLOT(animate())); - - d->autoHideTimer = new QTimer(this); - connect(d->autoHideTimer, SIGNAL(timeout()), this, SLOT(hide())); - - // apply a filter to get notified when anchor changes geometry - d->anchorWidget->installEventFilter(this); -} - -FloatingToolBar::~FloatingToolBar() -{ - delete d; -} - -void FloatingToolBar::addAction(QAction *action) -{ - QToolBar::addAction(action); - - // rebuild toolbar shape and contents only if the toolbar is already visible, - // otherwise it will be done in showAndAnimate() - if (isVisible()) - d->reposition(); -} - -void FloatingToolBar::setSide(Side side) -{ - d->anchorSide = side; - - if (isVisible()) - d->reposition(); -} - -void FloatingToolBar::setSticky(bool sticky) -{ - d->sticky = sticky; - - if (sticky) - d->autoHideTimer->stop(); -} - -void FloatingToolBar::showAndAnimate() -{ - if (d->animState == Showing) - return; - - d->animState = Showing; - - show(); - - // force update for case when toolbar has not been built yet - d->reposition(); - - // start scrolling in - d->animTimer->start(20); - - // This permits to show the toolbar for a while when going full screen. - if (!d->sticky) - d->autoHideTimer->start(initialAutoHideTimeout); -} - -void FloatingToolBar::hideAndDestroy() -{ - if (d->animState == Hiding) - return; - - // set parameters for sliding out - d->animState = Hiding; - d->toDelete = true; - d->endPosition = d->getOuterPoint(); - - // start scrolling out - d->animTimer->start(20); -} - -void FloatingToolBar::hide() -{ - if (underMouse()) - return; - - if (d->visible) { - QPoint diff; - switch (d->anchorSide) { - case Left: - diff = QPoint(visiblePixelWhenAutoHidden, 0); - break; - case Right: - diff = QPoint(-visiblePixelWhenAutoHidden, 0); - break; - case Top: - diff = QPoint(0, visiblePixelWhenAutoHidden); - break; - case Bottom: - diff = QPoint(0, -visiblePixelWhenAutoHidden); - break; - } - d->animState = Hiding; - d->endPosition = d->getOuterPoint() + diff; - - // start scrolling out - d->animTimer->start(20); - } -} - -bool FloatingToolBar::eventFilter(QObject *obj, QEvent *e) -{ - if (obj == d->anchorWidget && e->type() == QEvent::Resize) { - if (d->queuedShow) { // if the toolbar is not visible yet, try to show it if the anchor widget is in fullscreen already - d->queuedShow = false; - showAndAnimate(); - return true; - } - - // if anchorWidget changed geometry reposition toolbar - d->animTimer->stop(); - if ((d->animState == Hiding || !d->visible) && d->toDelete) - deleteLater(); - else - d->reposition(); - } - - return QToolBar::eventFilter(obj, e); -} - -void FloatingToolBar::paintEvent(QPaintEvent *e) -{ - QToolBar::paintEvent(e); - - // paint the internal pixmap over the widget - QPainter p(this); - p.setOpacity(d->opacity); - p.drawImage(e->rect().topLeft(), d->backgroundPixmap.toImage(), e->rect()); -} - -void FloatingToolBar::mousePressEvent(QMouseEvent *e) -{ - if (e->button() == Qt::LeftButton) - setCursor(Qt::SizeAllCursor); - - QToolBar::mousePressEvent(e); -} - -void FloatingToolBar::mouseMoveEvent(QMouseEvent *e) -{ - // show the toolbar again when it is auto-hidden - if (!d->visible) { - showAndAnimate(); - return; - } - - if ((QApplication::mouseButtons() & Qt::LeftButton) != Qt::LeftButton) - return; - - // compute the nearest side to attach the widget to - const QPoint parentPos = mapToParent(e->pos()); - const float nX = (float)parentPos.x() / (float)d->anchorWidget->width(); - const float nY = (float)parentPos.y() / (float)d->anchorWidget->height(); - if (nX > 0.3 && nX < 0.7 && nY > 0.3 && nY < 0.7) - return; - bool LT = nX < (1.0 - nY); - bool LB = nX < (nY); - Side side = LT ? (LB ? Left : Top) : (LB ? Bottom : Right); - - // check if side changed - if (side == d->anchorSide) - return; - - d->anchorSide = side; - d->reposition(); - emit orientationChanged((int)side); - - QToolBar::mouseMoveEvent(e); -} - -void FloatingToolBar::enterEvent(QEvent *e) -{ - // Stop the autohide timer while the mouse is inside - d->autoHideTimer->stop(); - - if (!d->visible) - showAndAnimate(); - QToolBar::enterEvent(e); -} - -void FloatingToolBar::leaveEvent(QEvent *e) -{ - if (!d->sticky) - d->autoHideTimer->start(autoHideTimeout); - QToolBar::leaveEvent(e); -} - -void FloatingToolBar::mouseReleaseEvent(QMouseEvent *e) -{ - if (e->button() == Qt::LeftButton) - setCursor(Qt::ArrowCursor); - - QToolBar::mouseReleaseEvent(e); -} - -void FloatingToolBar::wheelEvent(QWheelEvent *e) -{ - e->accept(); - - const qreal diff = e->delta() / 100.0 / 15.0; -// kDebug(5010) << diff; - if (((d->opacity <= 1) && (diff > 0)) || ((d->opacity >= 0) && (diff < 0))) - d->opacity += diff; - - update(); - - QToolBar::wheelEvent(e); -} - -void FloatingToolBarPrivate::buildToolBar() -{ - const bool prevUpdates = q->updatesEnabled(); - q->setUpdatesEnabled(false); - - // 1. init numbers we are going to use - const bool topLeft = anchorSide == FloatingToolBar::Left || anchorSide == FloatingToolBar::Top; - const bool vertical = anchorSide == FloatingToolBar::Left || anchorSide == FloatingToolBar::Right; - - if (vertical) { - offsetPlaceHolder->setFixedSize(1, 7); - q->setOrientation(Qt::Vertical); - } else { - offsetPlaceHolder->setFixedSize(7, 1); - q->setOrientation(Qt::Horizontal); - } - - // 2. compute widget size - const int myWidth = q->sizeHint().width() - 1; - const int myHeight = q->sizeHint().height() - 1; - - // 3. resize pixmap, mask and widget - QBitmap mask(myWidth + 1, myHeight + 1); - backgroundPixmap = QPixmap(myWidth + 1, myHeight + 1); - backgroundPixmap.fill(Qt::transparent); - - q->resize(myWidth + 1, myHeight + 1); - - // 4. create and set transparency mask - QPainter maskPainter(&mask); - mask.fill(Qt::white); - maskPainter.setBrush(Qt::black); - if (vertical) - maskPainter.drawRoundRect(topLeft ? -10 : 0, 0, myWidth + 10, myHeight, 2000 / (myWidth + 10), 2000 / myHeight); - else - maskPainter.drawRoundRect(0, topLeft ? -10 : 0, myWidth, myHeight + 10, 2000 / myWidth, 2000 / (myHeight + 10)); - maskPainter.end(); - q->setMask(mask); - - // 5. draw background - QPainter bufferPainter(&backgroundPixmap); - bufferPainter.translate(0.5, 0.5); - QPalette pal = q->palette(); - // 5.1. draw horizontal/vertical gradient - QLinearGradient grad; - switch (anchorSide) { - case FloatingToolBar::Left: - grad = QLinearGradient(0, 1, myWidth + 1, 1); - break; - case FloatingToolBar::Right: - grad = QLinearGradient(myWidth + 1, 1, 0, 1); - break; - case FloatingToolBar::Top: - grad = QLinearGradient(1, 0, 1, myHeight + 1); - break; - case FloatingToolBar::Bottom: - grad = QLinearGradient(1, myHeight + 1, 0, 1); - break; - } - grad.setColorAt(0, pal.color(QPalette::Active, QPalette::Button)); - grad.setColorAt(1, pal.color(QPalette::Active, QPalette::Light)); - bufferPainter.setBrush(QBrush(grad)); - // 5.2. draw rounded border - bufferPainter.setPen( pal.color(QPalette::Active, QPalette::Dark).lighter(40)); - bufferPainter.setRenderHints(QPainter::Antialiasing); - if (vertical) - bufferPainter.drawRoundRect(topLeft ? -10 : 0, 0, myWidth + 10, myHeight, 2000 / (myWidth + 10), 2000 / myHeight); - else - bufferPainter.drawRoundRect(0, topLeft ? -10 : 0, myWidth, myHeight + 10, 2000 / myWidth, 2000 / (myHeight + 10)); - // 5.3. draw handle - bufferPainter.translate(-0.5, -0.5); - bufferPainter.setPen(pal.color(QPalette::Active, QPalette::Mid)); - if (vertical) { - int dx = anchorSide == FloatingToolBar::Left ? 2 : 4; - bufferPainter.drawLine(dx, 6, dx + myWidth - 8, 6); - bufferPainter.drawLine(dx, 9, dx + myWidth - 8, 9); - bufferPainter.setPen(pal.color(QPalette::Active, QPalette::Light)); - bufferPainter.drawLine(dx + 1, 7, dx + myWidth - 7, 7); - bufferPainter.drawLine(dx + 1, 10, dx + myWidth - 7, 10); - } else { - int dy = anchorSide == FloatingToolBar::Top ? 2 : 4; - bufferPainter.drawLine(6, dy, 6, dy + myHeight - 8); - bufferPainter.drawLine(9, dy, 9, dy + myHeight - 8); - bufferPainter.setPen(pal.color(QPalette::Active, QPalette::Light)); - bufferPainter.drawLine(7, dy + 1, 7, dy + myHeight - 7); - bufferPainter.drawLine(10, dy + 1, 10, dy + myHeight - 7); - } - - q->setUpdatesEnabled(prevUpdates); -} - -void FloatingToolBarPrivate::reposition() -{ - // note: hiding widget here will gives better gfx, but ends drag operation - // rebuild widget and move it to its final place - buildToolBar(); - if (!visible) { - currentPosition = getOuterPoint(); - endPosition = getInnerPoint(); - } else { - currentPosition = getInnerPoint(); - endPosition = getOuterPoint(); - } - q->move(currentPosition); -} - -QPoint FloatingToolBarPrivate::getInnerPoint() const -{ - // returns the final position of the widget - if (anchorSide == FloatingToolBar::Left) - return QPoint(0, (anchorWidget->height() - q->height()) / 2); - if (anchorSide == FloatingToolBar::Top) - return QPoint((anchorWidget->width() - q->width()) / 2, 0); - if (anchorSide == FloatingToolBar::Right) - return QPoint(anchorWidget->width() - q->width() + toolBarRBMargin, (anchorWidget->height() - q->height()) / 2); - return QPoint((anchorWidget->width() - q->width()) / 2, anchorWidget->height() - q->height() + toolBarRBMargin); -} - -QPoint FloatingToolBarPrivate::getOuterPoint() const -{ - // returns the point from which the transition starts - if (anchorSide == FloatingToolBar::Left) - return QPoint(-q->width(), (anchorWidget->height() - q->height()) / 2); - if (anchorSide == FloatingToolBar::Top) - return QPoint((anchorWidget->width() - q->width()) / 2, -q->height()); - if (anchorSide == FloatingToolBar::Right) - return QPoint(anchorWidget->width() + toolBarRBMargin, (anchorWidget->height() - q->height()) / 2); - return QPoint((anchorWidget->width() - q->width()) / 2, anchorWidget->height() + toolBarRBMargin); -} - -void FloatingToolBar::animate() -{ - if (KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) { - // move currentPosition towards endPosition - int dX = d->endPosition.x() - d->currentPosition.x(); - int dY = d->endPosition.y() - d->currentPosition.y(); - dX = dX / 6 + qMax(-1, qMin(1, dX)); - dY = dY / 6 + qMax(-1, qMin(1, dY)); - d->currentPosition.setX(d->currentPosition.x() + dX); - d->currentPosition.setY(d->currentPosition.y() + dY); - } else { - d->currentPosition = d->endPosition; - } - - move(d->currentPosition); - - // handle arrival to the end - if (d->currentPosition == d->endPosition) { - d->animTimer->stop(); - switch (d->animState) { - case Hiding: - d->visible = false; - d->animState = Still; - if (d->toDelete) - deleteLater(); - break; - case Showing: - d->visible = true; - d->animState = Still; - break; - default: - kDebug(5010) << "Illegal state"; - } - } -} - -#include "moc_floatingtoolbar.cpp" diff --git a/krdc/floatingtoolbar.h b/krdc/floatingtoolbar.h deleted file mode 100644 index 99dfa7e9..00000000 --- a/krdc/floatingtoolbar.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007-2008 Urs Wolfer -** Parts of this file have been take from okular: -** Copyright (C) 2004-2005 Enrico Ros -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef FLOATINGTOOLBAR_H -#define FLOATINGTOOLBAR_H - -#include - -/** - * @short A toolbar widget that slides in from a side. - * - * This is a shaped widget that slides in from a side of the 'anchor widget' - * it's attached to. It can be dragged and docked on {left,top,right,bottom} - * sides and contains actions. - */ -class FloatingToolBar : public QToolBar -{ - Q_OBJECT -public: - FloatingToolBar(QWidget *parent, QWidget *anchorWidget); - ~FloatingToolBar(); - - Q_ENUMS(Side) - enum Side { Left = 0, Top = 1, Right = 2, Bottom = 3 }; - - void addAction(QAction *action); - void setSide(Side side); - -Q_SIGNALS: - void orientationChanged(int side); - -public Q_SLOTS: - void setSticky(bool sticky); - void showAndAnimate(); - void hideAndDestroy(); - -protected: - bool eventFilter(QObject *o, QEvent *e); - void paintEvent(QPaintEvent *); - void mousePressEvent(QMouseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void enterEvent(QEvent *e); - void leaveEvent(QEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void wheelEvent(QWheelEvent *e); - -private: - class FloatingToolBarPrivate *d; - -private Q_SLOTS: - void animate(); - void hide(); -}; - -#endif diff --git a/krdc/konsole/CMakeLists.txt b/krdc/konsole/CMakeLists.txt deleted file mode 100644 index f551fbb8..00000000 --- a/krdc/konsole/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ - -set(BUILD_KONSOLE true) -if(BUILD_KONSOLE) - set(konsoleplugin_SRCS - konsoleviewfactory.cpp - konsoleview.cpp - ) - - kde4_add_plugin(krdc_konsoleplugin ${konsoleplugin_SRCS}) - - target_link_libraries(krdc_konsoleplugin - KDE4::kdecore - KDE4::kdeui - KDE4::kparts - krdccore - ) - install(TARGETS krdc_konsoleplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - - install(FILES krdc_konsole.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) -endif(BUILD_KONSOLE) diff --git a/krdc/konsole/konsoleview.cpp b/krdc/konsole/konsoleview.cpp deleted file mode 100644 index 40e8c076..00000000 --- a/krdc/konsole/konsoleview.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "konsoleview.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -KonsoleView::KonsoleView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) - : RemoteView(parent) -{ - m_url = url; - m_host = url.host(); - m_port = url.port(); - - m_hostPreferences = new KonsoleHostPreferences(configGroup, this); - -// QSize size = QSize(640, 480); - const QSize size = (qobject_cast(parent))->size(); - setStatus(Connected); - setFixedSize(size); - setFixedSize(size); - emit framebufferSizeChanged(size.width(), size.height()); - - KPluginFactory* factory = KPluginLoader("konsolepart").factory(); - KParts::ReadOnlyPart* part = factory ? (factory->create(this)) : 0; - if (part != 0) { -// connect(part, SIGNAL(destroyed(QObject*)), this, SLOT(terminalExited())); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setMargin(0); - mainLayout->setSpacing(0); - m_terminalWidget = part->widget(); - mainLayout->addWidget(m_terminalWidget); - m_terminal = qobject_cast(part); - m_terminal->showShellInDir(QDir::homePath()); - m_terminal->sendInput("echo " + url.userName() + '@' + url.host()/* + ':' + url.port()*/ + '\n'); -// m_terminal->sendInput("clear\n"); - m_terminalWidget->resize(size); - } -} - -KonsoleView::~KonsoleView() -{ - emit disconnected(); - setStatus(Disconnected); -} - -bool KonsoleView::eventFilter(QObject *obj, QEvent *event) -{ - if (m_viewOnly) { - if (event->type() == QEvent::KeyPress || - event->type() == QEvent::KeyRelease || - event->type() == QEvent::MouseButtonDblClick || - event->type() == QEvent::MouseButtonPress || - event->type() == QEvent::MouseButtonRelease || - event->type() == QEvent::MouseMove) - return true; - } - return RemoteView::eventFilter(obj, event); -} - -QSize KonsoleView::framebufferSize() -{ - return minimumSizeHint(); -} - -QSize KonsoleView::sizeHint() const -{ - return RemoteView::sizeHint(); - return maximumSize(); -} - -bool KonsoleView::isQuitting() -{ - return false; -} - -bool KonsoleView::start() -{ - setStatus(Connected); - emit connected(); - m_terminalWidget->setFocus(); - return true; -} - -HostPreferences* KonsoleView::hostPreferences() -{ - return m_hostPreferences; -} - -void KonsoleView::switchFullscreen(bool on) -{ - Q_UNUSED(on); -} - -#include "moc_konsoleview.cpp" diff --git a/krdc/konsole/konsoleview.h b/krdc/konsole/konsoleview.h deleted file mode 100644 index 5f52afcd..00000000 --- a/krdc/konsole/konsoleview.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef KONSOLEVIEW_H -#define KONSOLEVIEW_H - -#include "konsoleview.h" - -#include "remoteview.h" -#include "hostpreferences.h" - -#include - -class KonsoleHostPreferences; -class TerminalInterface; - -class KonsoleView : public RemoteView -{ - Q_OBJECT - -public: - explicit KonsoleView(QWidget *parent = 0, const KUrl &url = KUrl(), KConfigGroup configGroup = KConfigGroup()); - - virtual ~KonsoleView(); - - virtual QSize framebufferSize(); - QSize sizeHint() const; - - virtual bool isQuitting(); - virtual bool start(); - HostPreferences* hostPreferences(); - -public slots: - virtual void switchFullscreen(bool on); - -protected: - bool eventFilter(QObject *obj, QEvent *event); - -private: - KonsoleHostPreferences *m_hostPreferences; - TerminalInterface* m_terminal; - QWidget *m_terminalWidget; -}; - - -class KonsoleHostPreferences : public HostPreferences -{ - Q_OBJECT -public: - explicit KonsoleHostPreferences(KConfigGroup configGroup, QObject *parent = 0) - : HostPreferences(configGroup, parent) {} - -protected: - virtual QWidget* createProtocolSpecificConfigPage() { return 0; }; -}; - -#endif // KONSOLEVIEW_H diff --git a/krdc/konsole/konsoleviewfactory.cpp b/krdc/konsole/konsoleviewfactory.cpp deleted file mode 100644 index f5e63f06..00000000 --- a/krdc/konsole/konsoleviewfactory.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "konsoleviewfactory.h" - -#include -#include - -KRDC_PLUGIN_EXPORT(KonsoleViewFactory) - -KonsoleViewFactory::KonsoleViewFactory(QObject *parent, const QVariantList &args) - : RemoteViewFactory(parent) -{ - Q_UNUSED(args); - - KGlobal::locale()->insertCatalog("krdc"); -} - -KonsoleViewFactory::~KonsoleViewFactory() -{ -} - -bool KonsoleViewFactory::supportsUrl(const KUrl &url) const -{ - return (url.scheme().compare("konsole", Qt::CaseInsensitive) == 0); -} - -RemoteView *KonsoleViewFactory::createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) -{ - return new KonsoleView(parent, url, configGroup); -} - -HostPreferences *KonsoleViewFactory::createHostPreferences(KConfigGroup configGroup, QWidget *parent) -{ - Q_UNUSED(configGroup); - Q_UNUSED(parent); - - return 0; -} - -QString KonsoleViewFactory::scheme() const -{ - return "konsole"; -} - -QString KonsoleViewFactory::connectActionText() const -{ - return i18n("New Konsole Connection..."); //FIXME -} - -QString KonsoleViewFactory::connectButtonText() const -{ - return i18n("KRDC Konsole Connection"); -} - -QString KonsoleViewFactory::connectToolTipText() const -{ - return i18n("Enter the address here. Port is optional.
" - "Example: konsoleserver (host)"); -} - -#include "moc_konsoleviewfactory.cpp" diff --git a/krdc/konsole/konsoleviewfactory.h b/krdc/konsole/konsoleviewfactory.h deleted file mode 100644 index 8a5f7050..00000000 --- a/krdc/konsole/konsoleviewfactory.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef KONSOLEVIEWFACTORY_H -#define KONSOLEVIEWFACTORY_H - -#include "remoteviewfactory.h" - -#include "konsoleview.h" - -class KonsoleViewFactory : public RemoteViewFactory -{ - Q_OBJECT - -public: - explicit KonsoleViewFactory(QObject *parent, const QVariantList &args); - - virtual ~KonsoleViewFactory(); - - virtual bool supportsUrl(const KUrl &url) const; - - virtual RemoteView *createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup); - - virtual HostPreferences *createHostPreferences(KConfigGroup configGroup, QWidget *parent); - - virtual QString scheme() const; - - virtual QString connectActionText() const; - - virtual QString connectButtonText() const; - - virtual QString connectToolTipText() const; -}; - -#endif // KONSOLEVIEWFACTORY_H diff --git a/krdc/konsole/krdc_konsole.desktop b/krdc/konsole/krdc_konsole.desktop deleted file mode 100644 index 0f3fe4a8..00000000 --- a/krdc/konsole/krdc_konsole.desktop +++ /dev/null @@ -1,126 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KRDC/Plugin -Icon=krdc -Name=Konsole -Name[ast]=Konsole -Name[bg]=Konsole -Name[bs]=Konzola -Name[ca]=Konsole -Name[ca@valencia]=Konsole -Name[cs]=Konsole -Name[da]=Konsole -Name[de]=Konsole -Name[el]=Konsole -Name[en_GB]=Konsole -Name[eo]=Konsole -Name[es]=Konsole -Name[et]=Konsool -Name[eu]=Konsole -Name[fi]=Konsoli -Name[fr]=Konsole -Name[ga]=Konsole -Name[gl]=Konsole -Name[hr]=Konsole -Name[hsb]=Konsola -Name[hu]=Konsole -Name[ia]=Konsole -Name[is]=Konsole -Name[it]=Konsole -Name[ja]=Konsole -Name[kk]=Konsole -Name[km]=កុងសូល -Name[ko]=Konsole -Name[lt]=Konsole -Name[lv]=Konsole -Name[mai]=कंसोल -Name[mr]=कंसोल -Name[nb]=Konsole -Name[nds]=Konsole -Name[nl]=Konsole -Name[nn]=Konsoll -Name[pa]=ਕਨਸੋਲ -Name[pl]=Konsola -Name[pt]=Konsole -Name[pt_BR]=Konsole -Name[ro]=Konsolă -Name[ru]=Konsole -Name[si]=Konsole -Name[sk]=Konsole -Name[sl]=Konsole -Name[sr]=Конзола -Name[sr@ijekavian]=Конзола -Name[sr@ijekavianlatin]=Konsole -Name[sr@latin]=Konsole -Name[sv]=Terminal -Name[th]=คอนโซล-K -Name[tr]=Konsole -Name[ug]=Konsole -Name[uk]=Konsole -Name[x-test]=xxKonsolexx -Name[zh_CN]=Konsole -Name[zh_TW]=終端機_Konsole -Comment=Allows managing SSH or Telnet sessions through KRDC -Comment[ast]=Permite la xestión de sesiones SSH o Telnet per KRDC -Comment[bg]=Управление на сесии на SSH и Telnet през KRDC -Comment[bs]=Dopušta uređivanje SSH ili Telnet sesija kroz KRDC -Comment[ca]=Permet gestionar sessions SSH o Telnet mitjançant el KRDC -Comment[ca@valencia]=Permet gestionar sessions SSH o Telnet mitjançant el KRDC -Comment[cs]=Umožňuje spravovat sezení SSH nebo Telnet pomocí KRDC -Comment[da]=Muliggør håndtering af SSH- eller Telnet-sessioner via KRDC -Comment[de]=Erlaubt die Verwaltung von SSH- und Telnet-Sitzungen über KRDC -Comment[el]=Επιτρέπει τη διαχείριση συνεδριών SSH ή Telnet μέσω του KRDC -Comment[en_GB]=Allows managing SSH or Telnet sessions through KRDC -Comment[es]=Permite la gestión de sesiones SSH o Telnet mediante KRDC -Comment[et]=SSH- või Telneti seansside haldamise võimaldamine KRDC kaudu -Comment[eu]=SSH edo Telnet saioak KRDC bidez kudeatzea baimentzen du -Comment[fi]=Mahdollistaa SSH- ja Telnet-istuntojen hallinnan KRDC:llä -Comment[fr]=Permet de gérer des sessions « SSH » ou « Telnet » au travers de KRDC -Comment[ga]=Ceadaíonn sé duit seisiúin SSH nó Telnet a bhainistiú trí KRDC -Comment[gl]=Permite a xestión de sesións SSH ou Telnet por medio de KRCC -Comment[hr]=Omogućuje upravljanje sjednicama SSH-a i Telneta kroz KRDC -Comment[hu]=SSH vagy telnet használata a KRDC-n keresztül -Comment[ia]=Permitte gerer sessiones SSH o Telnet per medio de KRDC -Comment[is]=Gefur kost á að stjórna SSH eða Telnet setum með KRDC -Comment[it]=Permette la gestione di sessioni SSH o Telnet con KRDC -Comment[ja]=KRDC から SSH や Telnet セッションを管理できるようにします -Comment[kk]=KRDC арқылы SSH не Telnet сеанстарын басқаруға мүмкіндік беру -Comment[km]=អនុញ្ញាត​ឲ្យ​គ្រប់គ្រង​​សម័យ SSH ឬ Telnet តាមរយៈ KRDC -Comment[ko]=KRDC를 통해서 원격 SSH나 텔넷 세션 관리하기 -Comment[lt]=Leisti valdyti SSH ar Telnet sesijas per KRDC -Comment[lv]=Ļauj pārvaldīt SSH un Telnet sesijas caur KRDC -Comment[nb]=Tillater å styre SSH eller Telnet-økter gjennom KRDC -Comment[nds]=SSH- oder Telnet-Törns över KRDC plegen -Comment[nl]=Staat het beheer van ssh- of telnet-sessies toe via KRDC -Comment[nn]=Lèt deg handtera SSH- eller Telnet-økter gjennom KRDC -Comment[pa]=KRDC ਰਾਹੀਂ SSH ਜਾਂ ਟੇਲਨੈਟ (Telnet) ਸ਼ੈਸ਼ਨ ਮਨਜ਼ੂਰੀ -Comment[pl]=Pozwala zarządzać sesjami SSH lub Telnet za pomocą KRDC -Comment[pt]=Permite a gestão de sessões SSH ou Telnet através do KRDC -Comment[pt_BR]=Permite o gerenciamento de sessões SSH ou Telnet através do KRDC -Comment[ro]=Permite gestiunea sesiunilor SSH sau Telnet prin KRDC -Comment[ru]=Разрешить управление сеансами SSH или Telnet через KRDC -Comment[si]=KRDC හරහා Telnet හෝ SSH වාර පාලනයට ඉඩ දෙයි -Comment[sk]=Umožňuje spravovanie SSH alebo Telnet sedení pomocou KRDC -Comment[sl]=Omogoča upravljanje sej SSH ali Telnet prek KRDC -Comment[sr]=Управљање ССХ и ТЕЛНЕТ везама кроз КРДЦ -Comment[sr@ijekavian]=Управљање ССХ и ТЕЛНЕТ везама кроз КРДЦ -Comment[sr@ijekavianlatin]=Upravljanje SSH i TELNET vezama kroz KRDC -Comment[sr@latin]=Upravljanje SSH i TELNET vezama kroz KRDC -Comment[sv]=Tillåter hantering av SSH- eller Telnet-sessioner via KRDC -Comment[th]=อนุญาตให้ทำการจัดการวาระการเชื่อมต่อ SSH หรือ Telnet ผ่านทางโปรแกรม KRDC -Comment[tr]=KRDC üzerinden SSH ve Telnet oturumlarını yönetmenizi sağlar -Comment[uk]=Надає змогу керувати сеансами SSH або Telnet за допомогою KRDC -Comment[x-test]=xxAllows managing SSH or Telnet sessions through KRDCxx -Comment[zh_CN]=允许用户通过 KRDC 管理 SSH 或 Telnet 会话 -Comment[zh_TW]=允許透過 KRDC 管理 SSH 或 Telnet 工作階段 - -X-KDE-PluginInfo-Author=Urs Wolfer -X-KDE-PluginInfo-Email=uwolfer@kde.org -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-Library=krdc_konsoleplugin -X-KDE-PluginInfo-Name=krdc_konsoleplugin - -X-KDE-KRDC-Sorting=70 diff --git a/krdc/krdc.desktop b/krdc/krdc.desktop deleted file mode 100755 index bcf4747a..00000000 --- a/krdc/krdc.desktop +++ /dev/null @@ -1,128 +0,0 @@ -# KDE Config File -[Desktop Entry] -Type=Application -Exec=krdc --icon '%i' --caption '%c' %u -Icon=krdc -Terminal=false -MimeType=inode/vnd.kde.service.rfb; -Name=KRDC -Name[ar]=KRDC -Name[ast]=KRDC -Name[bg]=KRDC -Name[bs]=KRDC -Name[ca]=KRDC -Name[ca@valencia]=KRDC -Name[cs]=KRDC -Name[da]=KRDC -Name[de]=KRDC -Name[el]=KRDC -Name[en_GB]=KRDC -Name[eo]=KRDC -Name[es]=KRDC -Name[et]=KRDC -Name[eu]=KRDC -Name[fi]=KRDC -Name[fr]=KRDC -Name[ga]=KRDC -Name[gl]=KRDC -Name[hne]=केआरडीसी -Name[hr]=KRDC -Name[hu]=KRDC -Name[ia]=KRDC -Name[is]=KRDC -Name[it]=KRDC -Name[ja]=KRDC -Name[kk]=KRDC -Name[km]=KRDC -Name[ko]=KRDC -Name[lt]=KDE nutolusio darbastalio klientas -Name[lv]=KRDC -Name[ml]=കെആര്‍ഡിസി -Name[mr]=के-आर-डी-सी -Name[nb]=KRDC -Name[nds]=KRDC -Name[nl]=KRDC -Name[nn]=KRDC -Name[pa]=KRDC -Name[pl]=KRDC -Name[pt]=KRDC -Name[pt_BR]=KRDC -Name[ro]=KRDC -Name[ru]=KRDC -Name[si]=KRDC -Name[sk]=KRDC -Name[sl]=KRDC -Name[sq]=KRDC -Name[sr]=КРДЦ -Name[sr@ijekavian]=КРДЦ -Name[sr@ijekavianlatin]=KRDC -Name[sr@latin]=KRDC -Name[sv]=KRDC -Name[tr]=KRDC -Name[ug]=KRDC -Name[uk]=KRDC -Name[wa]=KRDC -Name[x-test]=xxKRDCxx -Name[zh_CN]=KRDC -Name[zh_TW]=遠端桌面_KRDC -GenericName=Remote Desktop Client -GenericName[ar]=عميل سطح المكتب البعيد -GenericName[ast]=Veceru d'escritoriu remotu -GenericName[bg]=Отдалечен работен плот -GenericName[bs]=Klijent udaljene radne površine -GenericName[ca]=Client d'escriptori remot -GenericName[ca@valencia]=Client d'escriptori remot -GenericName[cs]=Klient vzdálené pracovní plochy -GenericName[da]=Klient til fjernskrivebord -GenericName[de]=Verbindung zu entferntem Rechner -GenericName[el]=Πελάτης απομακρυσμένης επιφάνειας εργασίας -GenericName[en_GB]=Remote Desktop Client -GenericName[es]=Cliente de escritorio remoto -GenericName[et]=Kaugtöölaua klient -GenericName[eu]=Urruneko mahaigainaren bezeroa -GenericName[fi]=Etätyöpöytäasiakas -GenericName[fr]=Connexion à un bureau distant -GenericName[ga]=Cliant Deisce Cianda -GenericName[gl]=Cliente de conexión remota ao escritorio -GenericName[hne]=रिमोट डेस्कटाप क्लाएंट -GenericName[hr]=Klijent za udaljeno povezivanje -GenericName[hu]=Távoli asztal -GenericName[ia]=Cliente de scriptorio remote -GenericName[is]=Tengingar við fjarlæg skjáborð -GenericName[it]=Client per connessione a desktop remoto -GenericName[ja]=リモートデスクトップクライアント -GenericName[kk]=Қашықтан үстелге қосылу клиенті -GenericName[km]=កម្មវិធី​មើល​ផ្ទៃតុ​ពី​ចម្ងាយ -GenericName[ko]=원격 데스크톱 클라이언트 -GenericName[lt]=Nutolusio darbastalio klientas -GenericName[lv]=Attālinātās darbvirsmas klients -GenericName[ml]=വിദൂര പണിയിട ക്ലയന്റ് -GenericName[mr]=दूरस्थ डेस्कटॉप ग्राहक -GenericName[nb]=Tilkobling til annet skrivebord -GenericName[nds]=Schriefdisch-Feernverbinnen -GenericName[nl]=Client voor verbinding met extern bureaublad -GenericName[nn]=Skrivebordssamband over nettverket -GenericName[pa]=ਰਿਮੋਟ ਡੈਸਕਟਾਪ ਕਲਾਈਟ -GenericName[pl]=Klient zdalnego dostępu do pulpitu -GenericName[pt]=Cliente de Ecrãs Remotos -GenericName[pt_BR]=Cliente de área de trabalho remota -GenericName[ro]=Client pentru birou la distanță -GenericName[ru]=Удалённый доступ к рабочему столу -GenericName[si]=දුරස්ථ වැඩතල යෙදුම -GenericName[sk]=Klient vzdialenej pracovnej plochy -GenericName[sl]=Odjemalec za oddaljena namizja -GenericName[sr]=Клијент удаљене површи -GenericName[sr@ijekavian]=Клијент удаљене површи -GenericName[sr@ijekavianlatin]=Klijent udaljene površi -GenericName[sr@latin]=Klijent udaljene površi -GenericName[sv]=Fjärranslutning till skrivbord -GenericName[th]=ไคลเอนต์เชื่อมต่อพื้นที่ทำงานทางไกล -GenericName[tr]=Uzak Masaüstü İstemcisi -GenericName[ug]=يىراقتىكى ئۈستەلئۈستى خېرىدارى -GenericName[uk]=Клієнт з'єднання з віддаленою стільницею -GenericName[x-test]=xxRemote Desktop Clientxx -GenericName[zh_CN]=远程桌面客户端 -GenericName[zh_TW]=遠端桌面客戶端 -X-DocPath=krdc/index.html -Categories=Qt;KDE;Network;RemoteAccess; -StartupNotify=true diff --git a/krdc/krdcui.rc b/krdc/krdcui.rc deleted file mode 100644 index 997a32d4..00000000 --- a/krdc/krdcui.rc +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - &Session - - - - - - - - - - - - - -Remote View Toolbar - - - - - - - - - - - diff --git a/krdc/main.cpp b/krdc/main.cpp deleted file mode 100644 index 8c73b9f8..00000000 --- a/krdc/main.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2001-2003 Tim Jansen -** Copyright (C) 2007 - 2012 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "mainwindow.h" - -#include -#include -#include -#include -#include - -#include - -int main(int argc, char **argv) -{ - QElapsedTimer startupTimer; - startupTimer.start(); - KAboutData aboutData("krdc", 0, ki18n("KRDC"), KDE_VERSION_STRING, - ki18n("KDE Remote Desktop Client"), KAboutData::License_GPL, - ki18n("(c) 2007-2013, Urs Wolfer\n" - "(c) 2001-2003, Tim Jansen\n" - "(c) 2002-2003, Arend van Beelen jr.\n" - "(c) 2000-2002, Const Kaplinsky\n" - "(c) 2000, Tridia Corporation\n" - "(c) 1999, AT&T Laboratories Boston\n" - "(c) 1999-2003, Matthew Chapman\n" - "(c) 2009, Collabora Ltd")); - - aboutData.addAuthor(ki18n("Urs Wolfer"), ki18n("Developer, Maintainer"), "uwolfer@kde.org"); - aboutData.addAuthor(ki18n("Tony Murray"), ki18n("Developer"), "murraytony@gmail.com"); - aboutData.addAuthor(ki18n("Tim Jansen"), ki18n("Former Developer"), "tim@tjansen.de"); - aboutData.addAuthor(ki18n("Arend van Beelen jr."), ki18n("Initial RDP backend"), "arend@auton.nl"); - aboutData.addCredit(ki18n("Brad Hards"), ki18n("Google Summer of Code 2007 KRDC project mentor"), - "bradh@frogmouth.net"); - aboutData.addCredit(ki18n("LibVNCServer / LibVNCClient developers"), ki18n("VNC client library"), - "libvncserver-common@lists.sf.net", "http://libvncserver.sourceforge.net/"); - - KCmdLineArgs::init(argc, argv, &aboutData); - - KCmdLineOptions options; - options.add("fullscreen", ki18n("Start KRDC with the provided URL in fullscreen mode (works only with one URL)")); - options.add("!+[URL]", ki18n("URLs to connect after startup")); - - KCmdLineArgs::addCmdLineOptions(options); - - KApplication app; - - MainWindow *mainwindow = new MainWindow; - mainwindow->show(); - - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - if (args->count() > 0) { - for (int i = 0; i < args->count(); ++i) { - KUrl u(args->url(i)); - - if (u.scheme().isEmpty() || u.host().isEmpty()) { // unusable url; try to recover it... - QString arg(args->url(i).url()); - - kDebug(5010) << "unusable url; try to recover it:" << arg; - - if (arg.lastIndexOf('/') != 0) - arg = arg.right(arg.length() - arg.lastIndexOf('/') - 1); - - if (!arg.contains("://")) - arg.prepend("vnc://"); // vnc was default in kde3 times... - - kDebug(5010) << "recovered url:" << arg; - - u = arg; - } - - if (!u.isValid()) - continue; - - mainwindow->newConnection(u, ((args->isSet("fullscreen")) && (args->count() == 1))); - } - } - - kDebug(5010) << "########## KRDC ready:" << startupTimer.elapsed() << "ms ##########"; - - return app.exec(); -} diff --git a/krdc/mainwindow.cpp b/krdc/mainwindow.cpp deleted file mode 100644 index f9323315..00000000 --- a/krdc/mainwindow.cpp +++ /dev/null @@ -1,1203 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** Copyright (C) 2009 - 2010 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "mainwindow.h" - -#include "remoteview.h" -#include "settings.h" -#include "config/preferencesdialog.h" -#include "floatingtoolbar.h" -#include "bookmarkmanager.h" -#include "connectiondelegate.h" -#include "remotedesktopsmodel.h" -#include "systemtrayicon.h" -#include "tabbedviewwidget.h" -#include "hostpreferences.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 -#include -#include -#include - -MainWindow::MainWindow(QWidget *parent) - : KXmlGuiWindow(parent), - m_fullscreenWindow(0), - m_protocolInput(0), - m_addressInput(0), - m_toolBar(0), - m_currentRemoteView(-1), - m_systemTrayIcon(0), - m_dockWidgetTableView(0), - m_newConnectionTableView(0), - m_newConnectionWidget(0) -{ - loadAllPlugins(); - - setupActions(); - - setStandardToolBarMenuEnabled(true); - - m_tabWidget = new TabbedViewWidget(this); - m_tabWidget->setMovable(true); - m_tabWidget->setTabPosition((KTabWidget::TabPosition) Settings::tabPosition()); - - m_tabWidget->setTabsClosable(Settings::tabCloseButton()); - - connect(m_tabWidget, SIGNAL(closeRequest(QWidget*)), SLOT(closeTab(QWidget*))); - - if (Settings::tabMiddleClick()) - connect(m_tabWidget, SIGNAL(mouseMiddleClick(QWidget*)), SLOT(closeTab(QWidget*))); - - connect(m_tabWidget, SIGNAL(mouseDoubleClick(QWidget*)), SLOT(openTabSettings(QWidget*))); - connect(m_tabWidget, SIGNAL(mouseDoubleClick()), SLOT(newConnectionPage())); - connect(m_tabWidget, SIGNAL(contextMenu(QWidget*,QPoint)), SLOT(tabContextMenu(QWidget*,QPoint))); - - m_tabWidget->setMinimumSize(600, 400); - setCentralWidget(m_tabWidget); - - createDockWidget(); - - setupGUI(ToolBar | Keys | Save | Create); - - if (Settings::systemTrayIcon()) { - m_systemTrayIcon = new SystemTrayIcon(this); - if(m_fullscreenWindow) m_systemTrayIcon->setAssociatedWidget(m_fullscreenWindow); - } - - connect(m_tabWidget, SIGNAL(currentChanged(int)), SLOT(tabChanged(int))); - - if (Settings::showStatusBar()) - statusBar()->showMessage(i18n("KDE Remote Desktop Client started")); - - updateActionStatus(); // disable remote view actions - - if (Settings::openSessions().count() == 0) // just create a new connection tab if there are no open sessions - m_tabWidget->addTab(newConnectionWidget(), i18n("New Connection")); - - if (Settings::rememberSessions()) // give some time to create and show the window first - QTimer::singleShot(100, this, SLOT(restoreOpenSessions())); -} - -MainWindow::~MainWindow() -{ -} - -void MainWindow::setupActions() -{ - QAction *connectionAction = actionCollection()->addAction("new_connection"); - connectionAction->setText(i18n("New Connection")); - connectionAction->setIcon(KIcon("network-connect")); - connect(connectionAction, SIGNAL(triggered()), SLOT(newConnectionPage())); - - QAction *screenshotAction = actionCollection()->addAction("take_screenshot"); - screenshotAction->setText(i18n("Copy Screenshot to Clipboard")); - screenshotAction->setIconText(i18n("Screenshot")); - screenshotAction->setIcon(KIcon("ksnapshot")); - connect(screenshotAction, SIGNAL(triggered()), SLOT(takeScreenshot())); - - KAction *fullscreenAction = actionCollection()->addAction("switch_fullscreen"); // note: please do not switch to KStandardShortcut unless you know what you are doing (see history of this file) - fullscreenAction->setText(i18n("Switch to Full Screen Mode")); - fullscreenAction->setIconText(i18n("Full Screen")); - fullscreenAction->setIcon(KIcon("view-fullscreen")); - fullscreenAction->setShortcut(KStandardShortcut::fullScreen()); - connect(fullscreenAction, SIGNAL(triggered()), SLOT(switchFullscreen())); - - QAction *viewOnlyAction = actionCollection()->addAction("view_only"); - viewOnlyAction->setCheckable(true); - viewOnlyAction->setText(i18n("View Only")); - viewOnlyAction->setIcon(KIcon("document-preview")); - connect(viewOnlyAction, SIGNAL(triggered(bool)), SLOT(viewOnly(bool))); - - KAction *disconnectAction = actionCollection()->addAction("disconnect"); - disconnectAction->setText(i18n("Disconnect")); - disconnectAction->setIcon(KIcon("network-disconnect")); - disconnectAction->setShortcut(QKeySequence::Close); - connect(disconnectAction, SIGNAL(triggered()), SLOT(disconnectHost())); - - QAction *showLocalCursorAction = actionCollection()->addAction("show_local_cursor"); - showLocalCursorAction->setCheckable(true); - showLocalCursorAction->setIcon(KIcon("input-mouse")); - showLocalCursorAction->setText(i18n("Show Local Cursor")); - showLocalCursorAction->setIconText(i18n("Local Cursor")); - connect(showLocalCursorAction, SIGNAL(triggered(bool)), SLOT(showLocalCursor(bool))); - - QAction *grabAllKeysAction = actionCollection()->addAction("grab_all_keys"); - grabAllKeysAction->setCheckable(true); - grabAllKeysAction->setIcon(KIcon("configure-shortcuts")); - grabAllKeysAction->setText(i18n("Grab All Possible Keys")); - grabAllKeysAction->setIconText(i18n("Grab Keys")); - connect(grabAllKeysAction, SIGNAL(triggered(bool)), SLOT(grabAllKeys(bool))); - - QAction *scaleAction = actionCollection()->addAction("scale"); - scaleAction->setCheckable(true); - scaleAction->setIcon(KIcon("zoom-fit-best")); - scaleAction->setText(i18n("Scale Remote Screen to Fit Window Size")); - scaleAction->setIconText(i18n("Scale")); - connect(scaleAction, SIGNAL(triggered(bool)), SLOT(scale(bool))); - - KStandardAction::quit(this, SLOT(quit()), actionCollection()); - KStandardAction::preferences(this, SLOT(preferences()), actionCollection()); - QAction *configNotifyAction = KStandardAction::configureNotifications(this, SLOT(configureNotifications()), actionCollection()); - configNotifyAction->setVisible(false); - m_menubarAction = KStandardAction::showMenubar(this, SLOT(showMenubar()), actionCollection()); - m_menubarAction->setChecked(!menuBar()->isHidden()); - - KActionMenu *bookmarkMenu = new KActionMenu(i18n("Bookmarks"), actionCollection()); - m_bookmarkManager = new BookmarkManager(actionCollection(), bookmarkMenu->menu(), this); - actionCollection()->addAction("bookmark" , bookmarkMenu); - connect(m_bookmarkManager, SIGNAL(openUrl(KUrl)), SLOT(newConnection(KUrl))); -} - -void MainWindow::loadAllPlugins() -{ - const KService::List offers = KServiceTypeTrader::self()->query("KRDC/Plugin"); - - KConfigGroup conf(KGlobal::config(), "Plugins"); - - for (int i = 0; i < offers.size(); i++) { - KService::Ptr offer = offers[i]; - - RemoteViewFactory *remoteView; - - KPluginInfo description(offer); - description.load(conf); - - const bool selected = description.isPluginEnabled(); - - if (selected) { - if ((remoteView = createPluginFromService(offer)) != 0) { - kDebug(5010) << "### Plugin " + description.name() + " found ###"; - kDebug(5010) << "# Version:" << description.version(); - kDebug(5010) << "# Description:" << description.comment(); - kDebug(5010) << "# Author:" << description.author(); - const int sorting = offer->property("X-KDE-KRDC-Sorting").toInt(); - kDebug(5010) << "# Sorting:" << sorting; - - m_remoteViewFactories.insert(sorting, remoteView); - } else { - kDebug(5010) << "Error loading KRDC plugin (" << (offers[i])->library() << ')'; - } - } else { - kDebug(5010) << "# Plugin " + description.name() + " found, however it's not activated, skipping..."; - continue; - } - } -} - -RemoteViewFactory *MainWindow::createPluginFromService(const KService::Ptr &service) -{ - //try to load the specified library - KPluginFactory *factory = KPluginLoader(service->library()).factory(); - - if (!factory) { - kError(5010) << "KPluginFactory could not load the plugin:" << service->library(); - return 0; - } - - RemoteViewFactory *plugin = factory->create(); - - return plugin; -} - -void MainWindow::restoreOpenSessions() -{ - const QStringList list = Settings::openSessions(); - QStringList::ConstIterator it = list.begin(); - QStringList::ConstIterator end = list.end(); - while (it != end) { - newConnection(*it); - ++it; - } -} - -KUrl MainWindow::getInputUrl() -{ - return KUrl(m_protocolInput->currentText() + "://" + m_addressInput->text()); -} - -void MainWindow::newConnection(const KUrl &newUrl, bool switchFullscreenWhenConnected, const QString &tabName) -{ - m_switchFullscreenWhenConnected = switchFullscreenWhenConnected; - - const KUrl url = newUrl.isEmpty() ? getInputUrl() : newUrl; - - if (!url.isValid() || (url.host().isEmpty() && url.port() < 0) - || (!url.path().isEmpty() && url.path() != QLatin1String("/"))) { - KMessageBox::error(this, - i18n("The entered address does not have the required form.\n Syntax: [username@]host[:port]"), - i18n("Malformed URL")); - return; - } - - if (m_protocolInput && m_addressInput) { - int index = m_protocolInput->findText(url.protocol()); - if (index>=0) m_protocolInput->setCurrentIndex(index); - m_addressInput->setText(url.authority()); - } - - RemoteView *view = 0; - KConfigGroup configGroup = Settings::self()->config()->group("hostpreferences").group(url.prettyUrl(KUrl::RemoveTrailingSlash)); - - foreach(RemoteViewFactory *factory, m_remoteViewFactories) { - if (factory->supportsUrl(url)) { - view = factory->createView(this, url, configGroup); - kDebug(5010) << "Found plugin to handle url (" + url.url() + "): " + view->metaObject()->className(); - break; - } - } - - if (!view) { - KMessageBox::error(this, - i18n("The entered address cannot be handled."), - i18n("Unusable URL")); - return; - } - - // Configure the view - HostPreferences* prefs = view->hostPreferences(); - if (! prefs->showDialogIfNeeded(this)) { - delete view; - return; - } - - view->showDotCursor(prefs->showLocalCursor() ? RemoteView::CursorOn : RemoteView::CursorOff); - view->setViewOnly(prefs->viewOnly()); - if (! switchFullscreenWhenConnected) view->enableScaling(prefs->windowedScale()); - - connect(view, SIGNAL(framebufferSizeChanged(int,int)), this, SLOT(resizeTabWidget(int,int))); - connect(view, SIGNAL(statusChanged(RemoteView::RemoteStatus)), this, SLOT(statusChanged(RemoteView::RemoteStatus))); - connect(view, SIGNAL(disconnected()), this, SLOT(disconnectHost())); - - view->winId(); // native widget workaround for bug 253365 - QScrollArea *scrollArea = createScrollArea(m_tabWidget, view); - - const int indexOfNewConnectionWidget = m_tabWidget->indexOf(m_newConnectionWidget); - if (indexOfNewConnectionWidget >= 0) - m_tabWidget->removeTab(indexOfNewConnectionWidget); - - const int newIndex = m_tabWidget->addTab(scrollArea, KIcon("krdc"), tabName.isEmpty() ? url.prettyUrl(KUrl::RemoveTrailingSlash) : tabName); - m_tabWidget->setCurrentIndex(newIndex); - m_remoteViewMap.insert(m_tabWidget->widget(newIndex), view); - tabChanged(newIndex); // force to update m_currentRemoteView (tabChanged is not emitted when start page has been disabled) - - view->start(); -} - -void MainWindow::openFromRemoteDesktopsModel(const QModelIndex &index) -{ - const QString urlString = index.data(10001).toString(); - const QString nameString = index.data(10003).toString(); - if (!urlString.isEmpty()) { - const KUrl url(urlString); - // first check if url has already been opened; in case show the tab - foreach (QWidget *widget, m_remoteViewMap.keys()) { - if (m_remoteViewMap.value(widget)->url() == url) { - m_tabWidget->setCurrentWidget(widget); - return; - } - } - - newConnection(url, false, nameString); - } -} - -void MainWindow::resizeTabWidget(int w, int h) -{ - kDebug(5010) << "tabwidget resize, view size: w: " << w << ", h: " << h; - if (m_fullscreenWindow) { - kDebug(5010) << "in fullscreen mode, refusing to resize"; - return; - } - - const QSize viewSize = QSize(w,h); - QDesktopWidget *desktop = QApplication::desktop(); - - if (Settings::fullscreenOnConnect()) { - int currentScreen = desktop->screenNumber(this); - const QSize screenSize = desktop->screenGeometry(currentScreen).size(); - - if (screenSize == viewSize) { - kDebug(5010) << "screen size equal to target view size -> switch to fullscreen mode"; - switchFullscreen(); - return; - } - } - - if (Settings::resizeOnConnect()) { - QWidget* currentWidget = m_tabWidget->currentWidget(); - const QSize newWindowSize = size() - currentWidget->frameSize() + viewSize; - - const QSize desktopSize = desktop->availableGeometry().size(); - kDebug(5010) << "new window size: " << newWindowSize << " available space:" << desktopSize; - - if ((newWindowSize.width() >= desktopSize.width()) || (newWindowSize.height() >= desktopSize.height())) { - kDebug(5010) << "remote desktop needs more space than available -> show window maximized"; - setWindowState(windowState() | Qt::WindowMaximized); - return; - } - - resize(newWindowSize); - } -} - -void MainWindow::statusChanged(RemoteView::RemoteStatus status) -{ - kDebug(5010) << status; - - // the remoteview is already deleted, so don't show it; otherwise it would crash - if (status == RemoteView::Disconnecting || status == RemoteView::Disconnected) - return; - - RemoteView *view = qobject_cast(QObject::sender()); - const QString host = view->host(); - - QString iconName = "krdc"; - QString message; - - switch (status) { - case RemoteView::Connecting: - iconName = "network-connect"; - message = i18n("Connecting to %1", host); - break; - case RemoteView::Authenticating: - iconName = "dialog-password"; - message = i18n("Authenticating at %1", host); - break; - case RemoteView::Preparing: - iconName = "view-history"; - message = i18n("Preparing connection to %1", host); - break; - case RemoteView::Connected: - iconName = "krdc"; - message = i18n("Connected to %1", host); - - if (view->grabAllKeys() != view->hostPreferences()->grabAllKeys()) { - view->setGrabAllKeys(view->hostPreferences()->grabAllKeys()); - updateActionStatus(); - } - - // when started with command line fullscreen argument - if (m_switchFullscreenWhenConnected) { - m_switchFullscreenWhenConnected = false; - switchFullscreen(); - } - - if (Settings::rememberHistory()) { - m_bookmarkManager->addHistoryBookmark(view); - } - - break; - default: - break; - } - - m_tabWidget->setTabIcon(m_tabWidget->indexOf(view), KIcon(iconName)); - if (Settings::showStatusBar()) - statusBar()->showMessage(message); -} - -void MainWindow::takeScreenshot() -{ - const QPixmap snapshot = currentRemoteView()->takeScreenshot(); - - QApplication::clipboard()->setPixmap(snapshot); -} - -void MainWindow::switchFullscreen() -{ - kDebug(5010); - - if (m_fullscreenWindow) { - // Leaving full screen mode - m_fullscreenWindow->setWindowState(0); - m_fullscreenWindow->hide(); - - m_tabWidget->setTabBarHidden(m_tabWidget->count() <= 1 && !Settings::showTabBar()); - m_tabWidget->setDocumentMode(false); - setCentralWidget(m_tabWidget); - - show(); - restoreGeometry(m_mainWindowGeometry); - if (m_systemTrayIcon) m_systemTrayIcon->setAssociatedWidget(this); - - foreach (RemoteView * view, m_remoteViewMap.values()) { - view->enableScaling(view->hostPreferences()->windowedScale()); - } - - if (m_toolBar) { - m_toolBar->hideAndDestroy(); - m_toolBar->deleteLater(); - m_toolBar = 0; - } - - actionCollection()->action("switch_fullscreen")->setIcon(KIcon("view-fullscreen")); - actionCollection()->action("switch_fullscreen")->setText(i18n("Switch to Full Screen Mode")); - actionCollection()->action("switch_fullscreen")->setIconText(i18n("Full Screen")); - - m_fullscreenWindow->deleteLater(); - m_fullscreenWindow = 0; - } else { - // Entering full screen mode - m_fullscreenWindow = new QWidget(this, Qt::Window); - m_fullscreenWindow->setWindowTitle(i18nc("window title when in full screen mode (for example displayed in tasklist)", - "KDE Remote Desktop Client (Full Screen)")); - - m_mainWindowGeometry = saveGeometry(); - - m_tabWidget->setTabBarHidden(true); - m_tabWidget->setDocumentMode(true); - - foreach(RemoteView *currentView, m_remoteViewMap) { - currentView->enableScaling(currentView->hostPreferences()->fullscreenScale()); - } - - QVBoxLayout *fullscreenLayout = new QVBoxLayout(m_fullscreenWindow); - fullscreenLayout->setContentsMargins(QMargins(0, 0, 0, 0)); - fullscreenLayout->addWidget(m_tabWidget); - - KToggleFullScreenAction::setFullScreen(m_fullscreenWindow, true); - - MinimizePixel *minimizePixel = new MinimizePixel(m_fullscreenWindow); - minimizePixel->winId(); // force it to be a native widget (prevents problem with QX11EmbedContainer) - connect(minimizePixel, SIGNAL(rightClicked()), m_fullscreenWindow, SLOT(showMinimized())); - m_fullscreenWindow->installEventFilter(this); - - m_fullscreenWindow->show(); - hide(); // hide after showing the new window so it stays on the same screen - - if (m_systemTrayIcon) m_systemTrayIcon->setAssociatedWidget(m_fullscreenWindow); - - actionCollection()->action("switch_fullscreen")->setIcon(KIcon("view-restore")); - actionCollection()->action("switch_fullscreen")->setText(i18n("Switch to Window Mode")); - actionCollection()->action("switch_fullscreen")->setIconText(i18n("Window Mode")); - showRemoteViewToolbar(); - } - if (m_tabWidget->currentWidget() == m_newConnectionWidget) { - m_addressInput->setFocus(); - } -} - -QScrollArea *MainWindow::createScrollArea(QWidget *parent, RemoteView *remoteView) -{ - RemoteViewScrollArea *scrollArea = new RemoteViewScrollArea(parent); - scrollArea->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); - - connect(scrollArea, SIGNAL(resized(int,int)), remoteView, SLOT(scaleResize(int,int))); - - QPalette palette = scrollArea->palette(); - palette.setColor(QPalette::Dark, Settings::backgroundColor()); - scrollArea->setPalette(palette); - - scrollArea->setBackgroundRole(QPalette::Dark); - scrollArea->setFrameStyle(QFrame::NoFrame); - - scrollArea->setWidget(remoteView); - - return scrollArea; -} - -void MainWindow::disconnectHost() -{ - kDebug(5010); - - RemoteView *view = qobject_cast(QObject::sender()); - - QWidget *widgetToDelete; - if (view) { - widgetToDelete = (QWidget*) view->parent()->parent(); - m_remoteViewMap.remove(m_remoteViewMap.key(view)); - } else { - widgetToDelete = m_tabWidget->currentWidget(); - view = currentRemoteView(); - m_remoteViewMap.remove(m_remoteViewMap.key(view)); - } - - saveHostPrefs(view); - view->startQuitting(); // some deconstructors can't properly quit, so quit early - m_tabWidget->removePage(widgetToDelete); - widgetToDelete->deleteLater(); - - // if closing the last connection, create new connection tab - if (m_tabWidget->count() == 0) { - newConnectionPage(false); - } - - // if the newConnectionWidget is the only tab and we are fullscreen, switch to window mode - if (m_fullscreenWindow && m_tabWidget->count() == 1 && m_tabWidget->currentWidget() == m_newConnectionWidget) { - switchFullscreen(); - } -} - -void MainWindow::closeTab(QWidget *widget) -{ - bool isNewConnectionPage = widget == m_newConnectionWidget; - - if (!isNewConnectionPage) { - RemoteView *view = m_remoteViewMap.value(widget); - m_remoteViewMap.remove(m_remoteViewMap.key(view)); - view->startQuitting(); - widget->deleteLater(); - } - - m_tabWidget->removePage(widget); - - // if closing the last connection, create new connection tab - if (m_tabWidget->count() == 0) { - newConnectionPage(false); - } - - // if the newConnectionWidget is the only tab and we are fullscreen, switch to window mode - if (m_fullscreenWindow && m_tabWidget->count() == 1 && m_tabWidget->currentWidget() == m_newConnectionWidget) { - switchFullscreen(); - } -} - -void MainWindow::openTabSettings(QWidget *widget) -{ - RemoteViewScrollArea *scrollArea = qobject_cast(widget); - if (!scrollArea) return; - RemoteView *view = qobject_cast(scrollArea->widget()); - if (!view) return; - - const QString url = view->url().url(); - kDebug(5010) << url; - - showSettingsDialog(url); -} - -void MainWindow::showSettingsDialog(const QString &url) -{ - HostPreferences *prefs = 0; - - foreach(RemoteViewFactory *factory, remoteViewFactoriesList()) { - if (factory->supportsUrl(url)) { - prefs = factory->createHostPreferences(Settings::self()->config()->group("hostpreferences").group(url), this); - if (prefs) { - kDebug(5010) << "Found plugin to handle url (" + url + "): " + prefs->metaObject()->className(); - } else { - kDebug(5010) << "Found plugin to handle url (" + url + "), but plugin does not provide preferences"; - } - } - } - - if (prefs) { - prefs->setShownWhileConnected(true); - prefs->showDialog(this); - } else { - KMessageBox::error(this, - i18n("The selected host cannot be handled."), - i18n("Unusable URL")); - } -} - -void MainWindow::showConnectionContextMenu(const QPoint &pos) -{ - // QTableView does not take headers into account when it does mapToGlobal(), so calculate the offset - QPoint offset = QPoint(m_newConnectionTableView->verticalHeader()->size().width(), - m_newConnectionTableView->horizontalHeader()->size().height()); - QModelIndex index = m_newConnectionTableView->indexAt(pos); - - if (!index.isValid()) - return; - - const QString url = index.data(10001).toString(); - const QString title = index.model()->index(index.row(), RemoteDesktopsModel::Title).data(Qt::DisplayRole).toString(); - const QString source = index.model()->index(index.row(), RemoteDesktopsModel::Source).data(Qt::DisplayRole).toString(); - - KMenu *menu = new KMenu(m_newConnectionTableView); - menu->addTitle(url); - - QAction *connectAction = menu->addAction(KIcon("network-connect"), i18n("Connect")); - QAction *renameAction = menu->addAction(KIcon("edit-rename"), i18n("Rename")); - QAction *settingsAction = menu->addAction(KIcon("configure"), i18n("Settings")); - QAction *deleteAction = menu->addAction(KIcon("edit-delete"), i18n("Delete")); - - // not very clean, but it works, - if (!(source == i18nc("Where each displayed link comes from", "Bookmarks") || - source == i18nc("Where each displayed link comes from", "History"))) { - renameAction->setEnabled(false); - deleteAction->setEnabled(false); - } - - QAction *selectedAction = menu->exec(m_newConnectionTableView->mapToGlobal(pos + offset)); - - if (selectedAction == connectAction) { - openFromRemoteDesktopsModel(index); - } else if (selectedAction == renameAction) { - //TODO: use inline editor if possible - bool ok = false; - const QString newTitle = KInputDialog::getText(i18n("Rename %1", title), i18n("Rename %1 to", title), title, &ok, this); - if (ok && !newTitle.isEmpty()) { - BookmarkManager::updateTitle(m_bookmarkManager->getManager(), url, newTitle); - } - } else if (selectedAction == settingsAction) { - showSettingsDialog(url); - } else if (selectedAction == deleteAction) { - - if (KMessageBox::warningContinueCancel(this, i18n("Are you sure you want to delete %1?", url), i18n("Delete %1", title), - KStandardGuiItem::del()) == KMessageBox::Continue) { - BookmarkManager::removeByUrl(m_bookmarkManager->getManager(), url); - } - } - - menu->deleteLater(); -} - -void MainWindow::tabContextMenu(QWidget *widget, const QPoint &point) -{ - RemoteViewScrollArea *scrollArea = qobject_cast(widget); - if (!scrollArea) return; - RemoteView *view = qobject_cast(scrollArea->widget()); - if (!view) return; - - const QString url = view->url().prettyUrl(KUrl::RemoveTrailingSlash); - kDebug(5010) << url; - - KMenu *menu = new KMenu(this); - menu->addTitle(url); - QAction *bookmarkAction = menu->addAction(KIcon("bookmark-new"), i18n("Add Bookmark")); - QAction *closeAction = menu->addAction(KIcon("tab-close"), i18n("Close Tab")); - QAction *selectedAction = menu->exec(point); - if (selectedAction) { - if (selectedAction == closeAction) { - closeTab(widget); - } else if (selectedAction == bookmarkAction) { - m_bookmarkManager->addManualBookmark(url, url); - } - } - menu->deleteLater(); -} - -void MainWindow::showLocalCursor(bool showLocalCursor) -{ - kDebug(5010) << showLocalCursor; - - RemoteView* view = currentRemoteView(); - view->showDotCursor(showLocalCursor ? RemoteView::CursorOn : RemoteView::CursorOff); - view->hostPreferences()->setShowLocalCursor(showLocalCursor); - saveHostPrefs(view); -} - -void MainWindow::viewOnly(bool viewOnly) -{ - kDebug(5010) << viewOnly; - - RemoteView* view = currentRemoteView(); - view->setViewOnly(viewOnly); - view->hostPreferences()->setViewOnly(viewOnly); - saveHostPrefs(view); -} - -void MainWindow::grabAllKeys(bool grabAllKeys) -{ - kDebug(5010); - - RemoteView* view = currentRemoteView(); - view->setGrabAllKeys(grabAllKeys); - view->hostPreferences()->setGrabAllKeys(grabAllKeys); - saveHostPrefs(view); -} - -void MainWindow::scale(bool scale) -{ - kDebug(5010); - - RemoteView* view = currentRemoteView(); - view->enableScaling(scale); - if (m_fullscreenWindow) - view->hostPreferences()->setFullscreenScale(scale); - else - view->hostPreferences()->setWindowedScale(scale); - - saveHostPrefs(view); -} - -void MainWindow::showRemoteViewToolbar() -{ - kDebug(5010); - - if (!m_toolBar) { - m_toolBar = new FloatingToolBar(m_fullscreenWindow, m_fullscreenWindow); - m_toolBar->winId(); // force it to be a native widget (prevents problem with QX11EmbedContainer) - m_toolBar->setSide(FloatingToolBar::Top); - - KComboBox *sessionComboBox = new KComboBox(m_toolBar); - sessionComboBox->setStyleSheet("QComboBox:!editable{background:transparent;}"); - sessionComboBox->setModel(m_tabWidget->getModel()); - sessionComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); - sessionComboBox->setCurrentIndex(m_tabWidget->currentIndex()); - connect(sessionComboBox, SIGNAL(activated(int)), m_tabWidget, SLOT(setCurrentIndex(int))); - connect(m_tabWidget, SIGNAL(currentChanged(int)), sessionComboBox, SLOT(setCurrentIndex(int))); - m_toolBar->addWidget(sessionComboBox); - - QToolBar *buttonBox = new QToolBar(m_toolBar); - - buttonBox->addAction(actionCollection()->action("new_connection")); - buttonBox->addAction(actionCollection()->action("switch_fullscreen")); - - QAction *minimizeAction = new QAction(m_toolBar); - minimizeAction->setIcon(KIcon("go-down")); - minimizeAction->setText(i18n("Minimize Full Screen Window")); - connect(minimizeAction, SIGNAL(triggered()), m_fullscreenWindow, SLOT(showMinimized())); - buttonBox->addAction(minimizeAction); - - buttonBox->addAction(actionCollection()->action("take_screenshot")); - buttonBox->addAction(actionCollection()->action("view_only")); - buttonBox->addAction(actionCollection()->action("show_local_cursor")); - buttonBox->addAction(actionCollection()->action("grab_all_keys")); - buttonBox->addAction(actionCollection()->action("scale")); - buttonBox->addAction(actionCollection()->action("disconnect")); - buttonBox->addAction(actionCollection()->action("file_quit")); - - QAction *stickToolBarAction = new QAction(m_toolBar); - stickToolBarAction->setCheckable(true); - stickToolBarAction->setIcon(KIcon("object-locked")); - stickToolBarAction->setText(i18n("Stick Toolbar")); - connect(stickToolBarAction, SIGNAL(triggered(bool)), m_toolBar, SLOT(setSticky(bool))); - buttonBox->addAction(stickToolBarAction); - - m_toolBar->addWidget(buttonBox); - } -} - -void setActionStatus(QAction* action, bool enabled, bool visible, bool checked) -{ - action->setEnabled(enabled); - action->setVisible(visible); - action->setChecked(checked); -} - -void MainWindow::updateActionStatus() -{ - kDebug(5010) << m_tabWidget->currentIndex(); - - bool enabled = true; - - if (m_tabWidget->currentWidget() == m_newConnectionWidget) - enabled = false; - - RemoteView* view = (m_currentRemoteView >= 0 && enabled) ? currentRemoteView() : 0; - - actionCollection()->action("take_screenshot")->setEnabled(enabled); - actionCollection()->action("disconnect")->setEnabled(enabled); - - setActionStatus(actionCollection()->action("view_only"), - enabled, - true, - view ? view->viewOnly() : false); - - setActionStatus(actionCollection()->action("show_local_cursor"), - enabled, - view ? view->supportsLocalCursor() : false, - view ? view->dotCursorState() == RemoteView::CursorOn : false); - - setActionStatus(actionCollection()->action("scale"), - enabled, - view ? view->supportsScaling() : false, - view ? view->scaling() : false); - - setActionStatus(actionCollection()->action("grab_all_keys"), - enabled, - enabled, - view ? view->grabAllKeys() : false); -} - -void MainWindow::preferences() -{ - // An instance of your dialog could be already created and could be - // cached, in which case you want to display the cached dialog - // instead of creating another one - if (PreferencesDialog::showDialog("preferences")) - return; - - // KConfigDialog didn't find an instance of this dialog, so lets - // create it: - PreferencesDialog *dialog = new PreferencesDialog(this, Settings::self()); - - // User edited the configuration - update your local copies of the - // configuration data - connect(dialog, SIGNAL(settingsChanged(QString)), - this, SLOT(updateConfiguration())); - - dialog->show(); -} - -void MainWindow::updateConfiguration() -{ - if (!Settings::showStatusBar()) - statusBar()->deleteLater(); - else - statusBar()->showMessage(""); // force creation of statusbar - - m_tabWidget->setTabBarHidden((m_tabWidget->count() <= 1 && !Settings::showTabBar()) || m_fullscreenWindow); - m_tabWidget->setTabPosition((KTabWidget::TabPosition) Settings::tabPosition()); - m_tabWidget->setTabsClosable(Settings::tabCloseButton()); - disconnect(m_tabWidget, SIGNAL(mouseMiddleClick(QWidget*)), this, SLOT(closeTab(QWidget*))); // just be sure it is not connected twice - if (Settings::tabMiddleClick()) - connect(m_tabWidget, SIGNAL(mouseMiddleClick(QWidget*)), SLOT(closeTab(QWidget*))); - - if (Settings::systemTrayIcon() && !m_systemTrayIcon) { - m_systemTrayIcon = new SystemTrayIcon(this); - if(m_fullscreenWindow) m_systemTrayIcon->setAssociatedWidget(m_fullscreenWindow); - } else if (m_systemTrayIcon) { - delete m_systemTrayIcon; - m_systemTrayIcon = 0; - } - - // update the scroll areas background color - for (int i = 0; i < m_tabWidget->count(); ++i) { - QPalette palette = m_tabWidget->widget(i)->palette(); - palette.setColor(QPalette::Dark, Settings::backgroundColor()); - m_tabWidget->widget(i)->setPalette(palette); - } - - // Send update configuration message to all views - foreach (RemoteView *view, m_remoteViewMap.values()) { - view->updateConfiguration(); - } - -} - -void MainWindow::quit(bool systemEvent) -{ - const bool haveRemoteConnections = !m_remoteViewMap.isEmpty(); - if (systemEvent || !haveRemoteConnections || KMessageBox::warningContinueCancel(this, - i18n("Are you sure you want to quit the KDE Remote Desktop Client?"), - i18n("Confirm Quit"), - KStandardGuiItem::quit(), KStandardGuiItem::cancel(), - "DoNotAskBeforeExit") == KMessageBox::Continue) { - - if (Settings::rememberSessions()) { // remember open remote views for next startup - QStringList list; - foreach (RemoteView *view, m_remoteViewMap.values()) { - kDebug(5010) << view->url(); - list.append(view->url().prettyUrl(KUrl::RemoveTrailingSlash)); - } - Settings::setOpenSessions(list); - } - - saveHostPrefs(); - - foreach (RemoteView *view, m_remoteViewMap.values()) { - view->startQuitting(); - } - - Settings::self()->writeConfig(); - - qApp->quit(); - } -} - -void MainWindow::configureNotifications() -{ - KNotificationConfigWidget::configure("krdc", this); -} - -void MainWindow::showMenubar() -{ - if (m_menubarAction->isChecked()) - menuBar()->show(); - else - menuBar()->hide(); -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *event) -{ - // check for close events from the fullscreen window. - if (obj == m_fullscreenWindow && event->type() == QEvent::Close) { - quit(true); - } - // allow other events to pass through. - return QObject::eventFilter(obj, event); -} - -void MainWindow::closeEvent(QCloseEvent *event) -{ - if (event->spontaneous()) { // Returns true if the event originated outside the application (a system event); otherwise returns false. - event->ignore(); - if (Settings::systemTrayIcon()) { - hide(); // just hide the mainwindow, keep it in systemtray - } else { - quit(); - } - } else { - quit(true); - } -} - -void MainWindow::saveProperties(KConfigGroup &group) -{ - kDebug(5010); - KMainWindow::saveProperties(group); - saveHostPrefs(); -} - - -void MainWindow::saveHostPrefs() -{ - foreach (RemoteView *view, m_remoteViewMap.values()) { - saveHostPrefs(view); - view->startQuitting(); - } -} - -void MainWindow::saveHostPrefs(RemoteView* view) -{ - // should saving this be a user option? - if (view && view->scaling()) { - QSize viewSize = m_tabWidget->currentWidget()->size(); - kDebug(5010) << "saving window size:" << viewSize; - view->hostPreferences()->setWidth(viewSize.width()); - view->hostPreferences()->setHeight(viewSize.height()); - } - - Settings::self()->config()->sync(); -} - -void MainWindow::tabChanged(int index) -{ - kDebug(5010) << index; - - m_tabWidget->setTabBarHidden((m_tabWidget->count() <= 1 && !Settings::showTabBar()) || m_fullscreenWindow); - - m_currentRemoteView = index; - - if (m_tabWidget->currentWidget() == m_newConnectionWidget) { - m_currentRemoteView = -1; - if(m_addressInput) m_addressInput->setFocus(); - } - - const QString tabTitle = m_tabWidget->tabText(index).remove('&'); - setCaption(tabTitle == i18n("New Connection") ? QString() : tabTitle); - - updateActionStatus(); -} - -QWidget* MainWindow::newConnectionWidget() -{ - if (m_newConnectionWidget) - return m_newConnectionWidget; - - m_newConnectionWidget = new QWidget(this); - - QVBoxLayout *startLayout = new QVBoxLayout(m_newConnectionWidget); - startLayout->setContentsMargins(QMargins(8, 12, 8, 4)); - - QLabel *headerLabel = new QLabel(m_newConnectionWidget); - headerLabel->setText(i18n("

KDE Remote Desktop Client


Enter or select the address of the desktop you would like to connect to.")); - - KPixmapWidget *headerIconWidget = new KPixmapWidget(m_newConnectionWidget); - headerIconWidget->setPixmap(KIcon("krdc").pixmap(80)); - - QHBoxLayout *headerLayout = new QHBoxLayout; - headerLayout->addWidget(headerLabel, 1, Qt::AlignTop); - headerLayout->addWidget(headerIconWidget); - startLayout->addLayout(headerLayout); - - QSortFilterProxyModel *remoteDesktopsModelProxy = new QSortFilterProxyModel(this); - remoteDesktopsModelProxy->setSourceModel(m_remoteDesktopsModel); - remoteDesktopsModelProxy->setFilterCaseSensitivity(Qt::CaseInsensitive); - remoteDesktopsModelProxy->setFilterRole(10002); - - { - QHBoxLayout *connectLayout = new QHBoxLayout; - - QLabel *addressLabel = new QLabel(i18n("Connect to:"), m_newConnectionWidget); - m_protocolInput = new KComboBox(m_newConnectionWidget); - m_addressInput = new KLineEdit(m_newConnectionWidget); - m_addressInput->setClearButtonShown(true); - m_addressInput->setClickMessage(i18n("Type here to connect to an address and filter the list.")); - connect(m_addressInput, SIGNAL(textChanged(QString)), remoteDesktopsModelProxy, SLOT(setFilterFixedString(QString))); - - foreach(RemoteViewFactory *factory, m_remoteViewFactories) { - m_protocolInput->addItem(factory->scheme()); - } - - connect(m_addressInput, SIGNAL(returnPressed()), SLOT(newConnection())); - m_addressInput->setToolTip(i18n("Type an IP or DNS Name here. Clear the line to get a list of connection methods.")); - - KPushButton *connectButton = new KPushButton(m_newConnectionWidget); - connectButton->setToolTip(i18n("Goto Address")); - connectButton->setIcon(KIcon("go-jump-locationbar")); - connect(connectButton, SIGNAL(clicked()), SLOT(newConnection())); - - connectLayout->addWidget(addressLabel); - connectLayout->addWidget(m_protocolInput); - connectLayout->addWidget(m_addressInput, 1); - connectLayout->addWidget(connectButton); - connectLayout->setContentsMargins(QMargins(0, 6, 0, 10)); - startLayout->addLayout(connectLayout); - } - - { - m_newConnectionTableView = new QTableView(m_newConnectionWidget); - m_newConnectionTableView->setModel(remoteDesktopsModelProxy); - - // set up the view so it looks nice - m_newConnectionTableView->setItemDelegate(new ConnectionDelegate(m_newConnectionTableView)); - m_newConnectionTableView->setShowGrid(false); - m_newConnectionTableView->setSelectionMode(QAbstractItemView::NoSelection); - m_newConnectionTableView->verticalHeader()->hide(); - m_newConnectionTableView->verticalHeader()->setDefaultSectionSize( - m_newConnectionTableView->fontMetrics().height() + 3); - m_newConnectionTableView->horizontalHeader()->setStretchLastSection(true); - m_newConnectionTableView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); - m_newConnectionTableView->resizeColumnsToContents(); - m_newConnectionTableView->setAlternatingRowColors(true); - // set up sorting and actions (double click open, right click custom menu) - m_newConnectionTableView->setSortingEnabled(true); - m_newConnectionTableView->sortByColumn(Settings::connectionListSortColumn(), Qt::SortOrder(Settings::connectionListSortOrder())); - connect(m_newConnectionTableView->horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), - SLOT(saveConnectionListSort(int,Qt::SortOrder))); - connect(m_newConnectionTableView, SIGNAL(doubleClicked(QModelIndex)), - SLOT(openFromRemoteDesktopsModel(QModelIndex))); - m_newConnectionTableView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_newConnectionTableView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showConnectionContextMenu(QPoint))); - - startLayout->addWidget(m_newConnectionTableView); - } - - return m_newConnectionWidget; -} - -void MainWindow::saveConnectionListSort(const int logicalindex, const Qt::SortOrder order) -{ - Settings::setConnectionListSortColumn(logicalindex); - Settings::setConnectionListSortOrder(order); - Settings::self()->writeConfig(); -} - -void MainWindow::newConnectionPage(bool clearInput) -{ - const int indexOfNewConnectionWidget = m_tabWidget->indexOf(m_newConnectionWidget); - if (indexOfNewConnectionWidget >= 0) - m_tabWidget->setCurrentIndex(indexOfNewConnectionWidget); - else { - const int index = m_tabWidget->addTab(newConnectionWidget(), i18n("New Connection")); - m_tabWidget->setCurrentIndex(index); - } - if(clearInput) { - m_addressInput->clear(); - } else { - m_addressInput->selectAll(); - } - m_addressInput->setFocus(); -} - -QMap MainWindow::remoteViewList() const -{ - return m_remoteViewMap; -} - -QList MainWindow::remoteViewFactoriesList() const -{ - return m_remoteViewFactories.values(); -} - -RemoteView* MainWindow::currentRemoteView() const -{ - if (m_currentRemoteView >= 0) { - return m_remoteViewMap.value(m_tabWidget->widget(m_currentRemoteView)); - } else { - return 0; - } -} - -void MainWindow::createDockWidget() -{ - QDockWidget *remoteDesktopsDockWidget = new QDockWidget(this); - QWidget *remoteDesktopsDockLayoutWidget = new QWidget(remoteDesktopsDockWidget); - QVBoxLayout *remoteDesktopsDockLayout = new QVBoxLayout(remoteDesktopsDockLayoutWidget); - remoteDesktopsDockWidget->setObjectName("remoteDesktopsDockWidget"); // required for saving position / state - remoteDesktopsDockWidget->setWindowTitle(i18n("Remote Desktops")); - QFontMetrics fontMetrics(remoteDesktopsDockWidget->font()); - remoteDesktopsDockWidget->setMinimumWidth(fontMetrics.width("vnc://192.168.100.100:6000")); - actionCollection()->addAction("remote_desktop_dockwidget", - remoteDesktopsDockWidget->toggleViewAction()); - - m_dockWidgetTableView = new QTableView(remoteDesktopsDockLayoutWidget); - m_remoteDesktopsModel = new RemoteDesktopsModel(this); - QSortFilterProxyModel *remoteDesktopsModelProxy = new QSortFilterProxyModel(this); - remoteDesktopsModelProxy->setSourceModel(m_remoteDesktopsModel); - remoteDesktopsModelProxy->setFilterCaseSensitivity(Qt::CaseInsensitive); - remoteDesktopsModelProxy->setFilterRole(10002); - m_dockWidgetTableView->setModel(remoteDesktopsModelProxy); - - m_dockWidgetTableView->setShowGrid(false); - m_dockWidgetTableView->verticalHeader()->hide(); - m_dockWidgetTableView->verticalHeader()->setDefaultSectionSize( - m_dockWidgetTableView->fontMetrics().height() + 2); - m_dockWidgetTableView->horizontalHeader()->hide(); - m_dockWidgetTableView->horizontalHeader()->setStretchLastSection(true); - // hide all columns, then show the one we want - for (int i=0; i < remoteDesktopsModelProxy->columnCount(); i++) { - m_dockWidgetTableView->hideColumn(i); - } - m_dockWidgetTableView->showColumn(RemoteDesktopsModel::Title); - m_dockWidgetTableView->sortByColumn(RemoteDesktopsModel::Title, Qt::AscendingOrder); - - connect(m_dockWidgetTableView, SIGNAL(doubleClicked(QModelIndex)), - SLOT(openFromRemoteDesktopsModel(QModelIndex))); - - KLineEdit *filterLineEdit = new KLineEdit(remoteDesktopsDockLayoutWidget); - filterLineEdit->setClickMessage(i18n("Filter")); - filterLineEdit->setClearButtonShown(true); - connect(filterLineEdit, SIGNAL(textChanged(QString)), remoteDesktopsModelProxy, SLOT(setFilterFixedString(QString))); - remoteDesktopsDockLayout->addWidget(filterLineEdit); - remoteDesktopsDockLayout->addWidget(m_dockWidgetTableView); - remoteDesktopsDockWidget->setWidget(remoteDesktopsDockLayoutWidget); - addDockWidget(Qt::LeftDockWidgetArea, remoteDesktopsDockWidget); -} - -#include "moc_mainwindow.cpp" diff --git a/krdc/mainwindow.h b/krdc/mainwindow.h deleted file mode 100644 index 8eba26c2..00000000 --- a/krdc/mainwindow.h +++ /dev/null @@ -1,174 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** Copyright (C) 2009 - 2010 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include "remoteview.h" -#include "remoteviewfactory.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -class KComboBox; -class KLineEdit; -class KPushButton; -class KToggleAction; -class KTabWidget; - -class BookmarkManager; -class FloatingToolBar; -class RemoteDesktopsModel; -class RemoteView; -class SystemTrayIcon; -class TabbedViewWidget; - -class MainWindow : public KXmlGuiWindow -{ - Q_OBJECT -public: - explicit MainWindow(QWidget *parent = 0); - ~MainWindow(); - - QMap remoteViewList() const; - QList remoteViewFactoriesList() const; - RemoteView* currentRemoteView() const; - -public slots: - void newConnection(const KUrl &newUrl = KUrl(), bool switchFullscreenWhenConnected = false, const QString &tabName = QString()); - -protected: - virtual void closeEvent(QCloseEvent *event); - bool eventFilter(QObject *obj, QEvent *event); // checks for close events on fs window - virtual void saveProperties(KConfigGroup &group); - void saveHostPrefs(); - void saveHostPrefs(RemoteView *view); - -private slots: - void restoreOpenSessions(); - void quit(bool systemEvent = false); - void preferences(); - void configureNotifications(); - void showMenubar(); - void resizeTabWidget(int w, int h); - void statusChanged(RemoteView::RemoteStatus status); - void showRemoteViewToolbar(); - void takeScreenshot(); - void switchFullscreen(); - void disconnectHost(); - void closeTab(QWidget *widget); - void openTabSettings(QWidget *widget); - void tabContextMenu(QWidget *widget, const QPoint &point); - void viewOnly(bool viewOnly); - void showLocalCursor(bool showLocalCursor); - void grabAllKeys(bool grabAllKeys); - void scale(bool scale); - void updateActionStatus(); - void updateConfiguration(); - void tabChanged(int index); - QWidget* newConnectionWidget(); - void newConnectionPage(bool clearInput = true); - void openFromRemoteDesktopsModel(const QModelIndex &index); - void createDockWidget(); - void showConnectionContextMenu(const QPoint &pos); - void saveConnectionListSort(const int logicalindex, const Qt::SortOrder order); - -private: - void setupActions(); - void loadAllPlugins(); - RemoteViewFactory *createPluginFromService(const KService::Ptr &service); - void showSettingsDialog(const QString &url); - QScrollArea *createScrollArea(QWidget *parent, RemoteView *remoteView); - KUrl getInputUrl(); - - QWidget *m_fullscreenWindow; - QByteArray m_mainWindowGeometry; - - KToggleAction *m_menubarAction; - TabbedViewWidget *m_tabWidget; - KComboBox *m_protocolInput; - KLineEdit *m_addressInput; - - FloatingToolBar *m_toolBar; - - BookmarkManager *m_bookmarkManager; - - QMap m_remoteViewMap; - QMap m_remoteViewFactories; - - int m_currentRemoteView; - bool m_switchFullscreenWhenConnected; - - SystemTrayIcon *m_systemTrayIcon; - QTableView *m_dockWidgetTableView; - QTableView *m_newConnectionTableView; - RemoteDesktopsModel *m_remoteDesktopsModel; - QWidget *m_newConnectionWidget; -}; - -class MinimizePixel : public QWidget -{ - Q_OBJECT -public: - explicit MinimizePixel(QWidget *parent) - : QWidget(parent) { - setFixedSize(1, 1); - move(QApplication::desktop()->screenGeometry().width() - 1, 0); - } - -signals: - void rightClicked(); - -protected: - void mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::RightButton) - emit rightClicked(); - } -}; - -class RemoteViewScrollArea : public QScrollArea -{ - Q_OBJECT -public: - explicit RemoteViewScrollArea(QWidget *parent) - : QScrollArea(parent) { - } - -signals: - void resized(int w, int h); - -protected: - void resizeEvent(QResizeEvent *event) { - QScrollArea::resizeEvent(event); - emit resized(width() - 2*frameWidth(), height() - 2*frameWidth()); - } -}; - -#endif diff --git a/krdc/pointcursor.png b/krdc/pointcursor.png deleted file mode 100644 index f5bf9e7a..00000000 Binary files a/krdc/pointcursor.png and /dev/null differ diff --git a/krdc/pointcursormask.png b/krdc/pointcursormask.png deleted file mode 100644 index 2e3a74c3..00000000 Binary files a/krdc/pointcursormask.png and /dev/null differ diff --git a/krdc/rdp/CMakeLists.txt b/krdc/rdp/CMakeLists.txt deleted file mode 100644 index abef2d0a..00000000 --- a/krdc/rdp/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ - -if(Q_WS_X11) - set(HAVE_XFREERDP true) -endif(Q_WS_X11) - -if(HAVE_XFREERDP) - add_definitions(-DKDE_DEFAULT_DEBUG_AREA=5012) - - include_directories( - ${CMAKE_CURRENT_BINARY_DIR} - ) - - set(rdpplugin_SRCS - rdphostpreferences.cpp - rdpviewfactory.cpp - rdpview.cpp - rdppreferences.ui - ) - - kde4_add_plugin(krdc_rdpplugin ${rdpplugin_SRCS}) - - target_link_libraries(krdc_rdpplugin - KDE4::kdecore - KDE4::kdeui - krdccore - ) - - set(kcm_krdc_rdpplugin_SRCS - rdppreferences.cpp - ) - - kde4_add_plugin(kcm_krdc_rdpplugin ${kcm_krdc_rdpplugin_SRCS}) - - target_link_libraries(kcm_krdc_rdpplugin - KDE4::kdeui - krdccore - ) - - add_dependencies(kcm_krdc_rdpplugin krdc_rdpplugin) - - install(TARGETS kcm_krdc_rdpplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - install(TARGETS krdc_rdpplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - - install(FILES krdc_rdp.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - install(FILES krdc_rdp_config.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - - install(FILES rdp.protocol DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - install(FILES smb2rdc.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}/ServiceMenus) -endif(HAVE_XFREERDP) diff --git a/krdc/rdp/krdc_rdp.desktop b/krdc/rdp/krdc_rdp.desktop deleted file mode 100644 index 66aab74b..00000000 --- a/krdc/rdp/krdc_rdp.desktop +++ /dev/null @@ -1,124 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KRDC/Plugin -Icon=krdc -Name=RDP -Name[ast]=RDP -Name[bg]=RDP -Name[bs]=RDP -Name[ca]=RDP -Name[ca@valencia]=RDP -Name[cs]=RDP -Name[da]=RDP -Name[de]=RDP -Name[el]=RDP -Name[en_GB]=RDP -Name[eo]=RDP -Name[es]=RDP -Name[et]=RDP -Name[eu]=RDP -Name[fi]=RDP -Name[fr]=RDP -Name[ga]=RDP -Name[gl]=RDP -Name[hr]=RDP -Name[hu]=RDP -Name[ia]=RDP -Name[is]=RDP -Name[it]=RDP -Name[ja]=RDP -Name[kk]=RDP -Name[km]=RDP -Name[ko]=RDP -Name[lt]=RDP -Name[lv]=RDP -Name[mr]=आर-डी-पी -Name[nb]=RDP -Name[nds]=RDP -Name[nl]=RDP -Name[nn]=RDP -Name[pa]=RDP -Name[pl]=RDP -Name[pt]=RDP -Name[pt_BR]=RDP -Name[ro]=RDP -Name[ru]=Базовая программа RDP -Name[si]=RDP -Name[sk]=RDP -Name[sl]=RDP -Name[sr]=РДП -Name[sr@ijekavian]=РДП -Name[sr@ijekavianlatin]=RDP -Name[sr@latin]=RDP -Name[sv]=RDP -Name[tr]=RDP -Name[ug]=RDP -Name[uk]=RDP -Name[wa]=RDP -Name[x-test]=xxRDPxx -Name[zh_CN]=RDP -Name[zh_TW]=RDP -Comment=Allows managing RDP sessions through KRDC -Comment[ast]=Permite la xestión de sesiones RDP per KRDC -Comment[bg]=Управление на сесии на RDP с KRDC -Comment[bs]=Dopušta upravljanje RPD sesijama kroz KRDC -Comment[ca]=Permet gestionar sessions RDP mitjançant el KRDC -Comment[ca@valencia]=Permet gestionar sessions RDP mitjançant el KRDC -Comment[cs]=Umožňuje spravování sezení RDP pomocí KRDC -Comment[da]=Muliggør håndtering af RDP-sessioner via KRDC -Comment[de]=Erlaubt die Verwaltung von RDP-Sitzungen über KRDC -Comment[el]=Επιτρέπει τη διαχείριση συνεδριών RDP μέσω του KRDC -Comment[en_GB]=Allows managing RDP sessions through KRDC -Comment[es]=Permite la gestión de sesiones RDP mediante KRDC -Comment[et]=RDP-seansside haldamise võimaldamine KRDC kaudu -Comment[eu]=RDP saioak KRDC bidez kudeatzea baimentzen du -Comment[fi]=Sallii RDP-istuntojen hallinnan KRDC:n kautta -Comment[fr]=Permet de gérer des sessions « RDP » au travers de KRDC -Comment[ga]=Ceadaíonn sé duit seisiúin RDP a bhainistiú trí KRDC -Comment[gl]=Permite xestionar sesións RDP por medio de KRDC -Comment[hr]=Omogućuje upravljanje sjednicama RDP-a kroz KRDC -Comment[hu]=RDP-kezelés KRDC-ből -Comment[ia]=Permitte gerer sessiones RDP per medio de KRDC -Comment[is]=Gefur kost á að stjórna RDP setum með KRDC -Comment[it]=Permette di gestire sessioni RDP con KRDC -Comment[ja]=KRDC から RDP セッションを管理できるようにします -Comment[kk]=KRDC арқылы RDP сеанстарын басқаруға мүмкіндік беру -Comment[km]=អនុញ្ញាត​ឲ្យ​គ្រប់គ្រង​សម័យ​របស់ RDP តាមរយៈ KRDC -Comment[ko]=KRDC를 통해서 RDP 세션 관리하기 -Comment[lt]=Leidžia valdyti RDP sesijas per KRDC -Comment[lv]=Ļauj pārvaldīt RDP sesijas caur KRDC -Comment[nb]=Tillater å styre RDP-økter gjennom KRDC -Comment[nds]=RDP-Törns över KRDC plegen -Comment[nl]=Staat het beheer van RDP-sessies toe via KRDC -Comment[nn]=Lèt deg handtera RDP-økter gjennom KRDC -Comment[pa]=KRDC ਰਾਹੀਂ RDP ਸ਼ੈਸ਼ਨਾਂ ਦੇ ਪਰਬੰਧ ਦੀ ਮਨਜ਼ੂਰੀ -Comment[pl]=Pozwala na zarządzanie sesjami RDP przez KRDC -Comment[pt]=Permite a gestão de sessões RDP através do KRDC -Comment[pt_BR]=Permite o gerenciamento de sessões RDP através do KRDC -Comment[ro]=Permite gestiunea sesiunilor RDP prin KRDC -Comment[ru]=Разрешить управление сеансами RDP через KRDC -Comment[si]=KRDC හරහා RDP වාර පාලනයට ඉඩ දෙයි -Comment[sk]=Umožňuje spravovanie RDP sedení pomocou KRDC -Comment[sl]=Omogoča upravljanje sej RDP prek KRDC -Comment[sr]=Управљање РДП сесијама кроз КРДЦ -Comment[sr@ijekavian]=Управљање РДП сесијама кроз КРДЦ -Comment[sr@ijekavianlatin]=Upravljanje RDP sesijama kroz KRDC -Comment[sr@latin]=Upravljanje RDP sesijama kroz KRDC -Comment[sv]=Tillåter hantering av RDP-sessioner via KRDC -Comment[th]=อนุญาตให้ทำการจัดการวาระการเชื่อมต่อ RDP ผ่านทางโปรแกรม KRDC -Comment[tr]=RDP oturumlarını KRDC üzerinden yönetmeye izin verir -Comment[uk]=Надає змогу керувати сеансами RDP за допомогою KRDC -Comment[x-test]=xxAllows managing RDP sessions through KRDCxx -Comment[zh_CN]=允许用户通过 KRDC 管理 RDP会话 -Comment[zh_TW]=允許透過 KRDC 管理 RDP 工作階段 - -X-KDE-PluginInfo-Author=Urs Wolfer -X-KDE-PluginInfo-Email=uwolfer@kde.org -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-Library=krdc_rdpplugin -X-KDE-PluginInfo-Name=krdc_rdpplugin - -X-KDE-KRDC-Sorting=60 diff --git a/krdc/rdp/krdc_rdp_config.desktop b/krdc/rdp/krdc_rdp_config.desktop deleted file mode 100644 index 9b7ea4ce..00000000 --- a/krdc/rdp/krdc_rdp_config.desktop +++ /dev/null @@ -1,62 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule -Name=RDP -Name[ast]=RDP -Name[bg]=RDP -Name[bs]=RDP -Name[ca]=RDP -Name[ca@valencia]=RDP -Name[cs]=RDP -Name[da]=RDP -Name[de]=RDP -Name[el]=RDP -Name[en_GB]=RDP -Name[eo]=RDP -Name[es]=RDP -Name[et]=RDP -Name[eu]=RDP -Name[fi]=RDP -Name[fr]=RDP -Name[ga]=RDP -Name[gl]=RDP -Name[hr]=RDP -Name[hu]=RDP -Name[ia]=RDP -Name[is]=RDP -Name[it]=RDP -Name[ja]=RDP -Name[kk]=RDP -Name[km]=RDP -Name[ko]=RDP -Name[lt]=RDP -Name[lv]=RDP -Name[mr]=आर-डी-पी -Name[nb]=RDP -Name[nds]=RDP -Name[nl]=RDP -Name[nn]=RDP -Name[pa]=RDP -Name[pl]=RDP -Name[pt]=RDP -Name[pt_BR]=RDP -Name[ro]=RDP -Name[ru]=Базовая программа RDP -Name[si]=RDP -Name[sk]=RDP -Name[sl]=RDP -Name[sr]=РДП -Name[sr@ijekavian]=РДП -Name[sr@ijekavianlatin]=RDP -Name[sr@latin]=RDP -Name[sv]=RDP -Name[tr]=RDP -Name[ug]=RDP -Name[uk]=RDP -Name[wa]=RDP -Name[x-test]=xxRDPxx -Name[zh_CN]=RDP -Name[zh_TW]=RDP - -X-KDE-Library=kcm_krdc_rdpplugin -X-KDE-ParentComponents=krdc_rdpplugin diff --git a/krdc/rdp/rdp.protocol b/krdc/rdp/rdp.protocol deleted file mode 100644 index 299ddb9e..00000000 --- a/krdc/rdp/rdp.protocol +++ /dev/null @@ -1,10 +0,0 @@ -[Protocol] -exec=krdc '%u' -protocol=rdp -helper=true -listing=false -reading=false -writing=false -makedir=false -deleting=false -Icon=krdc diff --git a/krdc/rdp/rdphostpreferences.cpp b/krdc/rdp/rdphostpreferences.cpp deleted file mode 100644 index 94f20903..00000000 --- a/krdc/rdp/rdphostpreferences.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2012 Urs Wolfer -** Copyright (C) 2012 AceLan Kao -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "rdphostpreferences.h" - -#include "settings.h" - -#include - -#include - -static const QStringList keymaps = (QStringList() - << "ar" - << "cs" - << "da" - << "de" - << "de-ch" - << "en-dv" - << "en-gb" - << "en-us" - << "es" - << "et" - << "fi" - << "fo" - << "fr" - << "fr-be" - << "fr-ca" - << "fr-ch" - << "he" - << "hr" - << "hu" - << "is" - << "it" - << "ja" - << "ko" - << "lt" - << "lv" - << "mk" - << "nl" - << "nl-be" - << "no" - << "pl" - << "pt" - << "pt-br" - << "ru" - << "sl" - << "sv" - << "th" - << "tr" -); - -static const int defaultKeymap = 7; // en-us - -inline int keymap2int(const QString &keymap) -{ - const int index = keymaps.lastIndexOf(keymap); - return (index == -1) ? defaultKeymap : index; -} - -inline QString int2keymap(int layout) -{ - if (layout >= 0 && layout < keymaps.count()) - return keymaps.at(layout); - else - return keymaps.at(defaultKeymap); -} - -RdpHostPreferences::RdpHostPreferences(KConfigGroup configGroup, QObject *parent) - : HostPreferences(configGroup, parent) -{ -} - -RdpHostPreferences::~RdpHostPreferences() -{ -} - -QWidget* RdpHostPreferences::createProtocolSpecificConfigPage() -{ - QWidget *rdpPage = new QWidget(); - rdpUi.setupUi(rdpPage); - - rdpUi.loginGroupBox->setVisible(false); - - rdpUi.kcfg_Height->setValue(height()); - rdpUi.kcfg_Width->setValue(width()); - rdpUi.kcfg_ColorDepth->setCurrentIndex(colorDepth()); - rdpUi.kcfg_KeyboardLayout->setCurrentIndex(keymap2int(keyboardLayout())); - rdpUi.kcfg_Sound->setCurrentIndex(sound()); - rdpUi.kcfg_Console->setChecked(console()); - rdpUi.kcfg_ExtraOptions->setText(extraOptions()); - rdpUi.kcfg_RemoteFX->setChecked(remoteFX()); - rdpUi.kcfg_Performance->setCurrentIndex(performance()); - rdpUi.kcfg_ShareMedia->setText(shareMedia()); - - connect(rdpUi.resolutionComboBox, SIGNAL(currentIndexChanged(int)), SLOT(updateWidthHeight(int))); - - const QString resolutionString = QString::number(width()) + 'x' + QString::number(height()); - const int resolutionIndex = rdpUi.resolutionComboBox->findText(resolutionString, Qt::MatchContains); - rdpUi.resolutionComboBox->setCurrentIndex((resolutionIndex == -1) ? rdpUi.resolutionComboBox->count() - 2 : resolutionIndex); // - 2 is index of custom resolution - - return rdpPage; -} - -void RdpHostPreferences::updateWidthHeight(int index) -{ - switch (index) { - case 0: - rdpUi.kcfg_Height->setValue(480); - rdpUi.kcfg_Width->setValue(640); - break; - case 1: - rdpUi.kcfg_Height->setValue(600); - rdpUi.kcfg_Width->setValue(800); - break; - case 2: - rdpUi.kcfg_Height->setValue(768); - rdpUi.kcfg_Width->setValue(1024); - break; - case 3: - rdpUi.kcfg_Height->setValue(1024); - rdpUi.kcfg_Width->setValue(1280); - break; - case 4: - rdpUi.kcfg_Height->setValue(1200); - rdpUi.kcfg_Width->setValue(1600); - break; - case 5: { - QDesktopWidget *desktop = QApplication::desktop(); - int currentScreen = desktop->screenNumber(rdpUi.kcfg_Height); - rdpUi.kcfg_Height->setValue(desktop->screenGeometry(currentScreen).height()); - rdpUi.kcfg_Width->setValue(desktop->screenGeometry(currentScreen).width()); - break; - } - case 7: - rdpUi.kcfg_Height->setValue(0); - rdpUi.kcfg_Width->setValue(0); - break; - case 6: - default: - break; - } - - const bool enabled = (index == 6) ? true : false; - - rdpUi.kcfg_Height->setEnabled(enabled); - rdpUi.kcfg_Width->setEnabled(enabled); - rdpUi.heightLabel->setEnabled(enabled); - rdpUi.widthLabel->setEnabled(enabled); -} - -void RdpHostPreferences::acceptConfig() -{ - HostPreferences::acceptConfig(); - - setHeight(rdpUi.kcfg_Height->value()); - setWidth(rdpUi.kcfg_Width->value()); - setColorDepth(rdpUi.kcfg_ColorDepth->currentIndex()); - setKeyboardLayout(int2keymap(rdpUi.kcfg_KeyboardLayout->currentIndex())); - setSound(rdpUi.kcfg_Sound->currentIndex()); - setConsole(rdpUi.kcfg_Console->isChecked()); - setExtraOptions(rdpUi.kcfg_ExtraOptions->text()); - setRemoteFX(rdpUi.kcfg_RemoteFX->isChecked()); - setPerformance(rdpUi.kcfg_Performance->currentIndex()); - setShareMedia(rdpUi.kcfg_ShareMedia->text()); -} - -void RdpHostPreferences::setColorDepth(int colorDepth) -{ - if (colorDepth >= 0) - m_configGroup.writeEntry("colorDepth", colorDepth); -} - -int RdpHostPreferences::colorDepth() const -{ - return m_configGroup.readEntry("colorDepth", Settings::colorDepth()); -} - -void RdpHostPreferences::setKeyboardLayout(const QString &keyboardLayout) -{ - if (!keyboardLayout.isNull()) - m_configGroup.writeEntry("keyboardLayout", keymap2int(keyboardLayout)); -} - -QString RdpHostPreferences::keyboardLayout() const -{ - return int2keymap(m_configGroup.readEntry("keyboardLayout", Settings::keyboardLayout())); -} - -void RdpHostPreferences::setSound(int sound) -{ - if (sound >= 0) - m_configGroup.writeEntry("sound", sound); -} - -int RdpHostPreferences::sound() const -{ - return m_configGroup.readEntry("sound", Settings::sound()); -} - -void RdpHostPreferences::setConsole(bool console) -{ - m_configGroup.writeEntry("console", console); -} - -bool RdpHostPreferences::console() const -{ - return m_configGroup.readEntry("console", Settings::console()); -} - -void RdpHostPreferences::setExtraOptions(const QString &extraOptions) -{ - if (!extraOptions.isNull()) - m_configGroup.writeEntry("extraOptions", extraOptions); -} - -QString RdpHostPreferences::extraOptions() const -{ - return m_configGroup.readEntry("extraOptions", Settings::extraOptions()); -} - -void RdpHostPreferences::setRemoteFX(bool remoteFX) -{ - m_configGroup.writeEntry("remoteFX", remoteFX); -} - -bool RdpHostPreferences::remoteFX() const -{ - return m_configGroup.readEntry("remoteFX", Settings::remoteFX()); -} - -void RdpHostPreferences::setPerformance(int performance) -{ - if (performance >= 0) - m_configGroup.writeEntry("performance", performance); -} - -int RdpHostPreferences::performance() const -{ - return m_configGroup.readEntry("performance", Settings::performance()); -} - -void RdpHostPreferences::setShareMedia(const QString &shareMedia) -{ - if (!shareMedia.isNull()) - m_configGroup.writeEntry("shareMedia", shareMedia); -} - -QString RdpHostPreferences::shareMedia() const -{ - return m_configGroup.readEntry("shareMedia", Settings::shareMedia()); -} - -#include "moc_rdphostpreferences.cpp" diff --git a/krdc/rdp/rdphostpreferences.h b/krdc/rdp/rdphostpreferences.h deleted file mode 100644 index 4fdc18df..00000000 --- a/krdc/rdp/rdphostpreferences.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2012 Urs Wolfer -** Copyright (C) 2012 AceLan Kao -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef RDPHOSTPREFERENCES_H -#define RDPHOSTPREFERENCES_H - -#include "hostpreferences.h" -#include "ui_rdppreferences.h" - -class RdpHostPreferences : public HostPreferences -{ - Q_OBJECT - -public: - explicit RdpHostPreferences(KConfigGroup configGroup, QObject *parent = 0); - ~RdpHostPreferences(); - - void setColorDepth(int colorDepth); - int colorDepth() const; - void setKeyboardLayout(const QString &keyboardLayout); - QString keyboardLayout() const; - void setSound(int sound); - int sound() const; - void setConsole(bool console); - bool console() const; - void setExtraOptions(const QString &extraOptions); - QString extraOptions() const; - void setRemoteFX(bool remoteFX); - bool remoteFX() const; - void setPerformance(int performance); - int performance() const; - void setShareMedia(const QString &shareMedia); - QString shareMedia() const; - -protected: - QWidget* createProtocolSpecificConfigPage(); - void acceptConfig(); - -private: - Ui::RdpPreferences rdpUi; - -private slots: - void updateWidthHeight(int index); -}; - -#endif diff --git a/krdc/rdp/rdppreferences.cpp b/krdc/rdp/rdppreferences.cpp deleted file mode 100644 index b10f6f51..00000000 --- a/krdc/rdp/rdppreferences.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "rdppreferences.h" -#include "remoteviewfactory.h" -#include "settings.h" - -#include "ui_rdppreferences.h" - -#include - -KRDC_PLUGIN_EXPORT(RdpPreferences) - -RdpPreferences::RdpPreferences(QWidget *parent, const QVariantList &args) - : KCModule(KrdcFactory::componentData(), parent, args) -{ - Ui::RdpPreferences rdpUi; - rdpUi.setupUi(this); - // would need a lot of code duplication. find a solution, bit it's not - // that important because you will not change this configuration each day... - // see rdp/rdphostpreferences.cpp - rdpUi.resolutionComboBox->hide(); - rdpUi.resolutionDummyLabel->hide(); - rdpUi.kcfg_Height->setEnabled(true); - rdpUi.kcfg_Width->setEnabled(true); - rdpUi.heightLabel->setEnabled(true); - rdpUi.widthLabel->setEnabled(true); - - addConfig(Settings::self(), this); -} - -RdpPreferences::~RdpPreferences() -{ -} - -void RdpPreferences::load() -{ - KCModule::load(); -} - -void RdpPreferences::save() -{ - KCModule::save(); -} - -#include "moc_rdppreferences.cpp" diff --git a/krdc/rdp/rdppreferences.h b/krdc/rdp/rdppreferences.h deleted file mode 100644 index a9c78e7e..00000000 --- a/krdc/rdp/rdppreferences.h +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef RDPPREFERENCES_H -#define RDPPREFERENCES_H - -#include "rdphostpreferences.h" - -#include - -class RdpPreferences : public KCModule -{ - Q_OBJECT - -public: - explicit RdpPreferences(QWidget *parent = 0, const QVariantList &args = QVariantList()); - ~RdpPreferences(); - - virtual void save(); - virtual void load(); - -}; - -#endif // RDPPREFERENCES_H diff --git a/krdc/rdp/rdppreferences.ui b/krdc/rdp/rdppreferences.ui deleted file mode 100644 index a4654756..00000000 --- a/krdc/rdp/rdppreferences.ui +++ /dev/null @@ -1,667 +0,0 @@ - - - RdpPreferences - - - - 0 - 0 - 484 - 452 - - - - - - - Connection - - - - - - - - Desktop &resolution: - - - resolutionComboBox - - - - - - - - - - - - - - - 280 - 0 - - - - Here you can specify the resolution of the remote desktop. This resolution determines the size of the desktop that will be presented to you. - - - 1 - - - - Minimal (640x480) - - - - - Small (800x600) - - - - - Normal (1024x768) - - - - - Large (1280x1024) - - - - - Very Large (1600x1200) - - - - - Current Screen Resolution - - - - - Custom Resolution (...) - - - - - Current KRDC Size - - - - - - - - - - false - - - &Width: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - kcfg_Width - - - - - - - false - - - This is the width of the remote desktop. You can only change this value manually if you select Custom as desktop resolution above. - - - 9999 - - - 800 - - - - - - - false - - - H&eight: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - kcfg_Height - - - - - - - false - - - This is the height of the remote desktop. You can only change this value manually if you select Custom as desktop resolution above. - - - 9999 - - - 600 - - - - - - - - - - - Color &depth: - - - kcfg_ColorDepth - - - - - - - - 280 - 0 - - - - - Low Color (8 Bit) - - - - - High Color (16 Bit) - - - - - True Color (24 Bit) - - - - - True Color with Alpha (32 Bit) - - - - - - - - &Keyboard layout: - - - kcfg_KeyboardLayout - - - - - - - - 280 - 0 - - - - Use this to specify your keyboard layout. This layout setting is used to send the correct keyboard codes to the server. - - - 7 - - - - Arabic (ar) - - - - - Czech (cs) - - - - - Danish (da) - - - - - German (de) - - - - - Swiss German (de-ch) - - - - - American Dvorak (en-dv) - - - - - British English (en-gb) - - - - - US English (en-us) - - - - - Spanish (es) - - - - - Estonian (et) - - - - - Finnish (fi) - - - - - Faroese (fo) - - - - - French (fr) - - - - - Belgian (fr-be) - - - - - French Canadian (fr-ca) - - - - - Swiss French (fr-ch) - - - - - Hebrew (he) - - - - - Croatian (hr) - - - - - Hungarian (hu) - - - - - Icelandic (is) - - - - - Italian (it) - - - - - Japanese (ja) - - - - - Korean (ko) - - - - - Lithuanian (lt) - - - - - Latvian (lv) - - - - - Macedonian (mk) - - - - - Dutch (nl) - - - - - Belgian Dutch (nl-be) - - - - - Norwegian (no) - - - - - Polish (pl) - - - - - Portuguese (pt) - - - - - Brazilian (pt-br) - - - - - Russian (ru) - - - - - Slovenian (sl) - - - - - Swedish (sv) - - - - - Thai (th) - - - - - Turkish (tr) - - - - - - - - Sound: - - - kcfg_Sound - - - - - - - - 280 - 0 - - - - - On This Computer - - - - - On Remote Computer - - - - - Disable Sound - - - - - - - - Performance: - - - kcfg_Performance - - - - - - - - 280 - 0 - - - - - Modem - - - - - Broadband - - - - - LAN - - - - - - - - RemoteFX: - - - kcfg_RemoteFX - - - - - - - Enhanced visual experience - - - RemoteFX covers a set of technologies that enhance visual experience of the Remote Desktop Protocol. - - - - - - - Share Media: - - - kcfg_ShareMedia - - - - - - - - 280 - 0 - - - - Share a local media directory with the remote host. - - - true - - - - - - - - - - Expert Options - - - - - - Console login: - - - kcfg_Console - - - - - - - Attach to Windows Server console - - - - - - - Extra options: - - - kcfg_ExtraOptions - - - - - - - - 280 - 0 - - - - Here you can enter additional xfreerdp (FreeRDP) options. - - - true - - - - - - - - - - Login - - - - - - - - Default user name: - - - - - - - No default user name - - - true - - - - - - - - - Automatically recognize "LDAP"-Logins and share passwords - - - - - - - - - - Qt::Vertical - - - - 428 - 16 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
-
- - resolutionComboBox - kcfg_Width - kcfg_Height - kcfg_ColorDepth - kcfg_KeyboardLayout - kcfg_Sound - kcfg_Performance - kcfg_RemoteFX - kcfg_ShareMedia - kcfg_Console - kcfg_ExtraOptions - kcfg_DefaultRdpUserName - kcfg_RecognizeLdapLogins - - -
diff --git a/krdc/rdp/rdpview.cpp b/krdc/rdp/rdpview.cpp deleted file mode 100644 index cbedf150..00000000 --- a/krdc/rdp/rdpview.cpp +++ /dev/null @@ -1,654 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2002 Arend van Beelen jr. -** Copyright (C) 2007 - 2012 Urs Wolfer -** Copyright (C) 2012 AceLan Kao -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "rdpview.h" - -#include "settings.h" - -#include -#include -#include -#include -#include - -#include -#include - -RdpView::RdpView(QWidget *parent, - const KUrl &url, - KConfigGroup configGroup, - const QString &user, const QString &password) - : RemoteView(parent), - m_user(user), - m_password(password), - m_quitFlag(false), - m_process(NULL) -{ - m_url = url; - m_host = url.host(); - m_port = url.port(); - - if (m_port <= 0) { - m_port = TCP_PORT_RDP; - } - - m_container = new QX11EmbedContainer(this); - m_container->installEventFilter(this); - - m_hostPreferences = new RdpHostPreferences(configGroup, this); -} - -RdpView::~RdpView() -{ - startQuitting(); -} - -// filter out key and mouse events to the container if we are view only -//FIXME: X11 events are passed to the app before getting caught in the Qt event processing -bool RdpView::eventFilter(QObject *obj, QEvent *event) -{ - if (m_viewOnly) { - if (event->type() == QEvent::KeyPress || - event->type() == QEvent::KeyRelease || - event->type() == QEvent::MouseButtonDblClick || - event->type() == QEvent::MouseButtonPress || - event->type() == QEvent::MouseButtonRelease || - event->type() == QEvent::MouseMove) - return true; - } - return RemoteView::eventFilter(obj, event); -} - -QSize RdpView::framebufferSize() -{ - return m_container->minimumSizeHint(); -} - -QSize RdpView::sizeHint() const -{ - return maximumSize(); -} - -void RdpView::startQuitting() -{ - kDebug(5012) << "About to quit"; - m_quitFlag = true; - if (m_process) { - m_process->terminate(); - m_process->waitForFinished(1000); - m_container->discardClient(); - } -} - -bool RdpView::isQuitting() -{ - return m_quitFlag; -} - -bool RdpView::start() -{ - m_container->show(); - - if (m_url.userName().isEmpty()) { - QString userName; - bool ok = false; - - userName = KInputDialog::getText(i18n("Enter Username"), - i18n("Please enter the username you would like to use for login."), - Settings::defaultRdpUserName(), &ok, this); - - if (ok) { - m_url.setUserName(userName); - } - } - - if (!m_url.userName().isEmpty()) { - const bool useLdapLogin = Settings::recognizeLdapLogins() && m_url.userName().contains('\\'); - kDebug(5012) << "Is LDAP login:" << useLdapLogin << m_url.userName(); - - QString walletPassword = QString(); - if (m_hostPreferences->walletSupport()) { - walletPassword = readWalletPassword(useLdapLogin); - } - if (!walletPassword.isNull()) { - m_url.setPassword(walletPassword); - } else { - KPasswordDialog dialog(this); - dialog.setPrompt(i18n("Access to the system requires a password.")); - if (dialog.exec() == KPasswordDialog::Accepted) { - m_url.setPassword(dialog.password()); - - if (m_hostPreferences->walletSupport()) { - saveWalletPassword(dialog.password(), useLdapLogin); - } - } - } - } - - // Check the version of FreeRDP so we can use pre-1.1 switches if needed - QProcess *xfreeRDPVersionCheck = new QProcess(this); - xfreeRDPVersionCheck->start("xfreerdp", QStringList("--version")); - xfreeRDPVersionCheck->waitForFinished(); - QString versionOutput = xfreeRDPVersionCheck->readAllStandardOutput(); - xfreeRDPVersionCheck->deleteLater(); - - m_process = new QProcess(m_container); - - QStringList arguments; - - if (versionOutput.contains(QLatin1String(" 1.0"))) { - kDebug(5012) << "Use FreeRDP 1.0 compatible arguments"; - - int width, height; - if (m_hostPreferences->width() > 0) { - width = m_hostPreferences->width(); - height = m_hostPreferences->height(); - } else { - width = this->parentWidget()->size().width(); - height = this->parentWidget()->size().height(); - } - arguments << "-g" << QString::number(width) + 'x' + QString::number(height); - - arguments << "-k" << keymapToXfreerdp(m_hostPreferences->keyboardLayout()); - - if (!m_url.userName().isEmpty()) { - // if username contains a domain, it needs to be set with another parameter - if (m_url.userName().contains('\\')) { - const QStringList splittedName = m_url.userName().split('\\'); - arguments << "-d" << splittedName.at(0); - arguments << "-u" << splittedName.at(1); - } else { - arguments << "-u" << m_url.userName(); - } - } else { - arguments << "-u" << ""; - } - - arguments << "-D"; // request the window has no decorations - arguments << "-X" << QString::number(m_container->winId()); - arguments << "-a" << QString::number((m_hostPreferences->colorDepth() + 1) * 8); - - switch (m_hostPreferences->sound()) { - case 1: - arguments << "-o"; - break; - case 0: - arguments << "--plugin" << "rdpsnd"; - break; - case 2: - default: - break; - } - - if (!m_hostPreferences->shareMedia().isEmpty()) { - QStringList shareMedia; - shareMedia << "--plugin" << "rdpdr" << "--data" << "disk:media:" + m_hostPreferences->shareMedia() << "--"; - arguments += shareMedia; - } - - QString performance; - switch (m_hostPreferences->performance()) { - case 0: - performance = 'm'; - break; - case 1: - performance = 'b'; - break; - case 2: - performance = 'l'; - break; - default: - break; - } - - arguments << "-x" << performance; - - if (m_hostPreferences->console()) { - arguments << "-0"; - } - - if (m_hostPreferences->remoteFX()) { - arguments << "--rfx"; - } - - if (!m_hostPreferences->extraOptions().isEmpty()) { - const QStringList additionalArguments = KShell::splitArgs(m_hostPreferences->extraOptions()); - arguments += additionalArguments; - } - - // krdc has no support for certificate management yet; it would not be possbile to connect to any host: - // "The host key for example.com has changed" ... - // "Add correct host key in ~/.freerdp/known_hosts to get rid of this message." - arguments << "--ignore-certificate"; - - // clipboard sharing is activated in KRDC; user can disable it at runtime - arguments << "--plugin" << "cliprdr"; - - arguments << "-t" << QString::number(m_port); - arguments << m_host; - - kDebug(5012) << "Starting xfreerdp with arguments: " << arguments.join(" "); - - arguments.removeLast(); // host must be last, remove and re-add it after the password - if (!m_url.password().isNull()) - arguments << "-p" << m_url.password(); - arguments << m_host; - - } else { - kDebug(5012) << "Use FreeRDP 1.1+ compatible arguments"; - - int width, height; - if (m_hostPreferences->width() > 0) { - width = m_hostPreferences->width(); - height = m_hostPreferences->height(); - } else { - width = this->parentWidget()->size().width(); - height = this->parentWidget()->size().height(); - } - arguments << "-decorations"; - arguments << "/w:" + QString::number(width); - arguments << "/h:" + QString::number(height); - - arguments << "/kbd:" + keymapToXfreerdp(m_hostPreferences->keyboardLayout()); - - if (!m_url.userName().isEmpty()) { - // if username contains a domain, it needs to be set with another parameter - if (m_url.userName().contains('\\')) { - const QStringList splittedName = m_url.userName().split('\\'); - arguments << "/d:" + splittedName.at(0); - arguments << "/u:" + splittedName.at(1); - } else { - arguments << "/u:" + m_url.userName(); - } - } else { - arguments << "/u:"; - } - - arguments << "/parent-window:" + QString::number(m_container->winId()); - arguments << "/bpp:" + QString::number((m_hostPreferences->colorDepth() + 1) * 8); - arguments << "/audio-mode:" + QString::number(m_hostPreferences->sound()); - - if (!m_hostPreferences->shareMedia().isEmpty()) { - QStringList shareMedia; - shareMedia << "/drive:media," + m_hostPreferences->shareMedia(); - arguments += shareMedia; - } - - QString performance; - switch (m_hostPreferences->performance()) { - case 0: - performance = "modem"; - break; - case 1: - performance = "broadband"; - break; - case 2: - performance = "lan"; - break; - default: - break; - } - - arguments << "/network:" + performance; - - if (m_hostPreferences->console()) { - arguments << "/admin"; - } - - if (m_hostPreferences->remoteFX()) { - arguments << "/rfx"; - } - - if (!m_hostPreferences->extraOptions().isEmpty()) { - const QStringList additionalArguments = KShell::splitArgs(m_hostPreferences->extraOptions()); - arguments += additionalArguments; - } - - // krdc has no support for certificate management yet; it would not be possbile to connect to any host: - // "The host key for example.com has changed" ... - // "Add correct host key in ~/.freerdp/known_hosts to get rid of this message." - arguments << "/cert-ignore"; - - // clipboard sharing is activated in KRDC; user can disable it at runtime - arguments << "+clipboard"; - - arguments << "/port:" + QString::number(m_port); - arguments << "/v:" + m_host; - - kDebug(5012) << "Starting xfreerdp with arguments: " << arguments.join(" "); - - //avoid printing the password in debug - if (!m_url.password().isNull()) { - arguments << "/p:" + m_url.password(); - } - } - - setStatus(Connecting); - - connect(m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError))); - connect(m_process, SIGNAL(readyReadStandardError()), SLOT(receivedStandardError())); - connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(receivedStandardOutput())); - connect(m_container, SIGNAL(clientClosed()), SLOT(connectionClosed())); - connect(m_container, SIGNAL(clientIsEmbedded()), SLOT(connectionOpened())); - - m_process->start("xfreerdp", arguments); - - return true; -} - -HostPreferences* RdpView::hostPreferences() -{ - return m_hostPreferences; -} - -void RdpView::switchFullscreen(bool on) -{ - if (on == true) { - m_container->grabKeyboard(); - } -} - -void RdpView::connectionOpened() -{ - kDebug(5012) << "Connection opened"; - const QSize size = m_container->minimumSizeHint(); - kDebug(5012) << "Size hint: " << size.width() << " " << size.height(); - setStatus(Connected); - setFixedSize(size); - resize(size); - m_container->setFixedSize(size); - emit framebufferSizeChanged(size.width(), size.height()); - emit connected(); - setFocus(); -} - -QPixmap RdpView::takeScreenshot() -{ - return QPixmap::grabWindow(m_container->clientWinId()); -} - -void RdpView::connectionClosed() -{ - emit disconnected(); - setStatus(Disconnected); - m_quitFlag = true; -} - -void RdpView::connectionError() -{ - emit disconnectedError(); - connectionClosed(); -} - -void RdpView::processError(QProcess::ProcessError error) -{ - kDebug(5012) << error; - if (m_quitFlag) // do not try to show error messages while quitting (prevent crashes) - return; - - if (m_status == Connecting) { - if (error == QProcess::FailedToStart) { - KMessageBox::error(0, i18n("Could not start \"xfreerdp\"; make sure xfreerdp is properly installed."), - i18n("RDP Failure")); - connectionError(); - return; - } - } -} - -void RdpView::receivedStandardError() -{ - const QString output(m_process->readAllStandardError()); - kDebug(5012) << output; - QString line; - int i = 0; - while (!(line = output.section('\n', i, i)).isEmpty()) { - - // the following error is issued by freerdp because of a bug in freerdp 1.0.1 and below; - // see: https://github.com/FreeRDP/FreeRDP/pull/576 - //"X Error of failed request: BadWindow (invalid Window parameter) - // Major opcode of failed request: 7 (X_ReparentWindow) - // Resource id in failed request: 0x71303348 - // Serial number of failed request: 36 - // Current serial number in output stream: 36" - if (line.contains(QLatin1String("X_ReparentWindow"))) { - KMessageBox::error(0, i18n("The version of \"xfreerdp\" you are using is too old.\n" - "xfreerdp 1.0.2 or greater is required."), - i18n("RDP Failure")); - connectionError(); - return; - } - i++; - } -} - -void RdpView::receivedStandardOutput() -{ - const QString output(m_process->readAllStandardOutput()); - kDebug(5012) << output; - QStringList splittedOutput = output.split('\n'); - Q_FOREACH (const QString &line, splittedOutput) { - // full xfreerdp message: "transport_connect: getaddrinfo (Name or service not known)" - if (line.contains(QLatin1String("Name or service not known"))) { - KMessageBox::error(0, i18n("Name or service not known."), - i18n("Connection Failure")); - connectionError(); - return; - - // full xfreerdp message: "unable to connect to example.com:3389" - } else if (line.contains(QLatin1String("unable to connect to"))) { - KMessageBox::error(0, i18n("Connection attempt to host failed."), - i18n("Connection Failure")); - connectionError(); - return; - - // looks like some generic xfreerdp error message, handle it if nothing was handled: - // "Error: protocol security negotiation failure" - } else if (line.contains(QLatin1String("Error: protocol security negotiation failure")) || // xfreerdp 1.0 - line.contains(QLatin1String("Error: protocol security negotiation or connection failure"))) { // xfreerdp 1.2 - KMessageBox::error(0, i18n("Connection attempt to host failed."), - i18n("Connection Failure")); - connectionError(); - return; - } - } -} - -void RdpView::setGrabAllKeys(bool grabAllKeys) -{ - Q_UNUSED(grabAllKeys); - // do nothing.. grabKeyboard seems not to be supported in QX11EmbedContainer -} - -QString RdpView::keymapToXfreerdp(const QString &keyboadLayout) -{ - if (keymapToXfreerdpHash.isEmpty()) { - keymapToXfreerdpHash = initKeymapToXfreerdp(); - } - return keymapToXfreerdpHash[keyboadLayout]; -} - -// list of xfreerdp --kbd-list -// this is a mapping for rdesktop comptibilty (old settings will still work) -// needs to be completed (when not in message freeze; needs new localization) -QHash RdpView::initKeymapToXfreerdp() -{ - QHash keymapToXfreerdpHash; - - // Keyboard Layouts - keymapToXfreerdpHash["ar"] = "0x00000401"; // Arabic (101) - // keymapToXfreerdpHash[""] = "0x00000402"; // Bulgarian - // keymapToXfreerdpHash[""] = "0x00000404"; // Chinese (Traditional) - US Keyboard - keymapToXfreerdpHash["cs"] = "0x00000405"; // Czech - keymapToXfreerdpHash["da"] = "0x00000406"; // Danish - keymapToXfreerdpHash["fo"] = "0x00000406"; // Danish, Faroese; legacy for rdesktop - keymapToXfreerdpHash["de"] = "0x00000407"; // German - // keymapToXfreerdpHash[""] = "0x00000408"; // Greek - keymapToXfreerdpHash["en-us"] = "0x00000409"; // US - keymapToXfreerdpHash["es"] = "0x0000040A"; // Spanish - keymapToXfreerdpHash["fi"] = "0x0000040B"; // Finnish - keymapToXfreerdpHash["fr"] = "0x0000040C"; // French - keymapToXfreerdpHash["he"] = "0x0000040D"; // Hebrew - keymapToXfreerdpHash["hu"] = "0x0000040E"; // Hungarian - keymapToXfreerdpHash["is"] = "0x0000040F"; // Icelandic - keymapToXfreerdpHash["it"] = "0x00000410"; // Italian - keymapToXfreerdpHash["ja"] = "0x00000411"; // Japanese - keymapToXfreerdpHash["ko"] = "0x00000412"; // Korean - keymapToXfreerdpHash["nl"] = "0x00000413"; // Dutch - keymapToXfreerdpHash["no"] = "0x00000414"; // Norwegian - keymapToXfreerdpHash["pl"] = "0x00000415"; // Polish (Programmers) - keymapToXfreerdpHash["pt-br"] = "0x00000416"; // Portuguese (Brazilian ABNT) - // keymapToXfreerdpHash[""] = "0x00000418"; // Romanian - keymapToXfreerdpHash["ru"] = "0x00000419"; // Russian - keymapToXfreerdpHash["hr"] = "0x0000041A"; // Croatian - // keymapToXfreerdpHash[""] = "0x0000041B"; // Slovak - // keymapToXfreerdpHash[""] = "0x0000041C"; // Albanian - keymapToXfreerdpHash["sv"] = "0x0000041D"; // Swedish - keymapToXfreerdpHash["th"] = "0x0000041E"; // Thai Kedmanee - keymapToXfreerdpHash["tr"] = "0x0000041F"; // Turkish Q - // keymapToXfreerdpHash[""] = "0x00000420"; // Urdu - // keymapToXfreerdpHash[""] = "0x00000422"; // Ukrainian - // keymapToXfreerdpHash[""] = "0x00000423"; // Belarusian - keymapToXfreerdpHash["sl"] = "0x00000424"; // Slovenian - keymapToXfreerdpHash["et"] = "0x00000425"; // Estonian - keymapToXfreerdpHash["lv"] = "0x00000426"; // Latvian - keymapToXfreerdpHash["lt"] = "0x00000427"; // Lithuanian IBM - // keymapToXfreerdpHash[""] = "0x00000429"; // Farsi - // keymapToXfreerdpHash[""] = "0x0000042A"; // Vietnamese - // keymapToXfreerdpHash[""] = "0x0000042B"; // Armenian Eastern - // keymapToXfreerdpHash[""] = "0x0000042C"; // Azeri Latin - keymapToXfreerdpHash["mk"] = "0x0000042F"; // FYRO Macedonian - // keymapToXfreerdpHash[""] = "0x00000437"; // Georgian - // keymapToXfreerdpHash[""] = "0x00000438"; // Faeroese - // keymapToXfreerdpHash[""] = "0x00000439"; // Devanagari - INSCRIPT - // keymapToXfreerdpHash[""] = "0x0000043A"; // Maltese 47-key - // keymapToXfreerdpHash[""] = "0x0000043B"; // Norwegian with Sami - // keymapToXfreerdpHash[""] = "0x0000043F"; // Kazakh - // keymapToXfreerdpHash[""] = "0x00000440"; // Kyrgyz Cyrillic - // keymapToXfreerdpHash[""] = "0x00000444"; // Tatar - // keymapToXfreerdpHash[""] = "0x00000445"; // Bengali - // keymapToXfreerdpHash[""] = "0x00000446"; // Punjabi - // keymapToXfreerdpHash[""] = "0x00000447"; // Gujarati - // keymapToXfreerdpHash[""] = "0x00000449"; // Tamil - // keymapToXfreerdpHash[""] = "0x0000044A"; // Telugu - // keymapToXfreerdpHash[""] = "0x0000044B"; // Kannada - // keymapToXfreerdpHash[""] = "0x0000044C"; // Malayalam - // keymapToXfreerdpHash[""] = "0x0000044E"; // Marathi - // keymapToXfreerdpHash[""] = "0x00000450"; // Mongolian Cyrillic - // keymapToXfreerdpHash[""] = "0x00000452"; // United Kingdom Extended - // keymapToXfreerdpHash[""] = "0x0000045A"; // Syriac - // keymapToXfreerdpHash[""] = "0x00000461"; // Nepali - // keymapToXfreerdpHash[""] = "0x00000463"; // Pashto - // keymapToXfreerdpHash[""] = "0x00000465"; // Divehi Phonetic - // keymapToXfreerdpHash[""] = "0x0000046E"; // Luxembourgish - // keymapToXfreerdpHash[""] = "0x00000481"; // Maori - // keymapToXfreerdpHash[""] = "0x00000804"; // Chinese (Simplified) - US Keyboard - keymapToXfreerdpHash["de-ch"] = "0x00000807"; // Swiss German - keymapToXfreerdpHash["en-gb"] = "0x00000809"; // United Kingdom - // keymapToXfreerdpHash[""] = "0x0000080A"; // Latin American - keymapToXfreerdpHash["fr-be"] = "0x0000080C"; // Belgian French - keymapToXfreerdpHash["nl-be"] = "0x00000813"; // Belgian (Period) - keymapToXfreerdpHash["pt"] = "0x00000816"; // Portuguese - // keymapToXfreerdpHash[""] = "0x0000081A"; // Serbian (Latin) - // keymapToXfreerdpHash[""] = "0x0000082C"; // Azeri Cyrillic - // keymapToXfreerdpHash[""] = "0x0000083B"; // Swedish with Sami - // keymapToXfreerdpHash[""] = "0x00000843"; // Uzbek Cyrillic - // keymapToXfreerdpHash[""] = "0x0000085D"; // Inuktitut Latin - // keymapToXfreerdpHash[""] = "0x00000C0C"; // Canadian French (legacy) - // keymapToXfreerdpHash[""] = "0x00000C1A"; // Serbian (Cyrillic) - keymapToXfreerdpHash["fr-ca"] = "0x00001009"; // Canadian French - keymapToXfreerdpHash["fr-ch"] = "0x0000100C"; // Swiss French - // keymapToXfreerdpHash[""] = "0x0000141A"; // Bosnian - // keymapToXfreerdpHash[""] = "0x00001809"; // Irish - // keymapToXfreerdpHash[""] = "0x0000201A"; // Bosnian Cyrillic - - // Keyboard Layout Variants - // keymapToXfreerdpHash[""] = "0x00010401"; // Arabic (102) - // keymapToXfreerdpHash[""] = "0x00010402"; // Bulgarian (Latin) - // keymapToXfreerdpHash[""] = "0x00010405"; // Czech (QWERTY) - // keymapToXfreerdpHash[""] = "0x00010407"; // German (IBM) - // keymapToXfreerdpHash[""] = "0x00010408"; // Greek (220) - keymapToXfreerdpHash["en-dv"] = "0x00010409"; // United States-Dvorak - // keymapToXfreerdpHash[""] = "0x0001040A"; // Spanish Variation - // keymapToXfreerdpHash[""] = "0x0001040E"; // Hungarian 101-key - // keymapToXfreerdpHash[""] = "0x00010410"; // Italian (142) - // keymapToXfreerdpHash[""] = "0x00010415"; // Polish (214) - // keymapToXfreerdpHash[""] = "0x00010416"; // Portuguese (Brazilian ABNT2) - // keymapToXfreerdpHash[""] = "0x00010419"; // Russian (Typewriter) - // keymapToXfreerdpHash[""] = "0x0001041B"; // Slovak (QWERTY) - // keymapToXfreerdpHash[""] = "0x0001041E"; // Thai Pattachote - // keymapToXfreerdpHash[""] = "0x0001041F"; // Turkish F - // keymapToXfreerdpHash[""] = "0x00010426"; // Latvian (QWERTY) - // keymapToXfreerdpHash[""] = "0x00010427"; // Lithuanian - // keymapToXfreerdpHash[""] = "0x0001042B"; // Armenian Western - // keymapToXfreerdpHash[""] = "0x00010439"; // Hindi Traditional - // keymapToXfreerdpHash[""] = "0x0001043A"; // Maltese 48-key - // keymapToXfreerdpHash[""] = "0x0001043B"; // Sami Extended Norway - // keymapToXfreerdpHash[""] = "0x00010445"; // Bengali (Inscript) - // keymapToXfreerdpHash[""] = "0x0001045A"; // Syriac Phonetic - // keymapToXfreerdpHash[""] = "0x00010465"; // Divehi Typewriter - // keymapToXfreerdpHash[""] = "0x0001080C"; // Belgian (Comma) - // keymapToXfreerdpHash[""] = "0x0001083B"; // Finnish with Sami - // keymapToXfreerdpHash[""] = "0x00011009"; // Canadian Multilingual Standard - // keymapToXfreerdpHash[""] = "0x00011809"; // Gaelic - // keymapToXfreerdpHash[""] = "0x00020401"; // Arabic (102) AZERTY - // keymapToXfreerdpHash[""] = "0x00020405"; // Czech Programmers - // keymapToXfreerdpHash[""] = "0x00020408"; // Greek (319) - // keymapToXfreerdpHash[""] = "0x00020409"; // United States-International - // keymapToXfreerdpHash[""] = "0x0002041E"; // Thai Kedmanee (non-ShiftLock) - // keymapToXfreerdpHash[""] = "0x0002083B"; // Sami Extended Finland-Sweden - // keymapToXfreerdpHash[""] = "0x00030408"; // Greek (220) Latin - // keymapToXfreerdpHash[""] = "0x00030409"; // United States-Dvorak for left hand - // keymapToXfreerdpHash[""] = "0x0003041E"; // Thai Pattachote (non-ShiftLock) - // keymapToXfreerdpHash[""] = "0x00040408"; // Greek (319) Latin - // keymapToXfreerdpHash[""] = "0x00040409"; // United States-Dvorak for right hand - // keymapToXfreerdpHash[""] = "0x00050408"; // Greek Latin - // keymapToXfreerdpHash[""] = "0x00050409"; // US English Table for IBM Arabic 238_L - // keymapToXfreerdpHash[""] = "0x00060408"; // Greek Polytonic - // keymapToXfreerdpHash[""] = "0xB0000407"; // German Neo - - // Keyboard Input Method Editors (IMEs) - // keymapToXfreerdpHash[""] = "0xE0010404"; // Chinese (Traditional) - Phonetic - // keymapToXfreerdpHash[""] = "0xE0010411"; // Japanese Input System (MS-IME2002) - // keymapToXfreerdpHash[""] = "0xE0010412"; // Korean Input System (IME 2000) - // keymapToXfreerdpHash[""] = "0xE0010804"; // Chinese (Simplified) - QuanPin - // keymapToXfreerdpHash[""] = "0xE0020404"; // Chinese (Traditional) - ChangJie - // keymapToXfreerdpHash[""] = "0xE0020804"; // Chinese (Simplified) - ShuangPin - // keymapToXfreerdpHash[""] = "0xE0030404"; // Chinese (Traditional) - Quick - // keymapToXfreerdpHash[""] = "0xE0030804"; // Chinese (Simplified) - ZhengMa - // keymapToXfreerdpHash[""] = "0xE0040404"; // Chinese (Traditional) - Big5 Code - // keymapToXfreerdpHash[""] = "0xE0050404"; // Chinese (Traditional) - Array - // keymapToXfreerdpHash[""] = "0xE0050804"; // Chinese (Simplified) - NeiMa - // keymapToXfreerdpHash[""] = "0xE0060404"; // Chinese (Traditional) - DaYi - // keymapToXfreerdpHash[""] = "0xE0070404"; // Chinese (Traditional) - Unicode - // keymapToXfreerdpHash[""] = "0xE0080404"; // Chinese (Traditional) - New Phonetic - // keymapToXfreerdpHash[""] = "0xE0090404"; // Chinese (Traditional) - New ChangJie - // keymapToXfreerdpHash[""] = "0xE00E0804"; // Chinese (Traditional) - Microsoft Pinyin IME 3.0 - // keymapToXfreerdpHash[""] = "0xE00F0404"; // Chinese (Traditional) - Alphanumeric - - return keymapToXfreerdpHash; -} - -#include "moc_rdpview.cpp" diff --git a/krdc/rdp/rdpview.h b/krdc/rdp/rdpview.h deleted file mode 100644 index 4870638b..00000000 --- a/krdc/rdp/rdpview.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2002 Arend van Beelen jr. -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef RDPVIEW_H -#define RDPVIEW_H - -#include "remoteview.h" - -#include "rdphostpreferences.h" - -#include - -#define TCP_PORT_RDP 3389 - -class RdpView; - -#include - -class RdpView : public RemoteView -{ - Q_OBJECT - -public: - explicit RdpView(QWidget *parent = 0, - const KUrl &url = KUrl(), - KConfigGroup configGroup = KConfigGroup(), - const QString &user = QString(), - const QString &password = QString()); - - virtual ~RdpView(); - - // functions regarding the window - virtual QSize framebufferSize(); // returns the size of the remote view - QSize sizeHint() const; // returns the suggested size - - // functions regarding the connection - virtual void startQuitting(); // start closing the connection - virtual bool isQuitting(); // are we currently closing the connection? - virtual bool start(); // open a connection - void setGrabAllKeys(bool grabAllKeys); - - HostPreferences* hostPreferences(); - - virtual QPixmap takeScreenshot(); - -public slots: - virtual void switchFullscreen(bool on); - -protected: - bool eventFilter(QObject *obj, QEvent *event); - -private: - QString keymapToXfreerdp(const QString &keyboadLayout); - QHash initKeymapToXfreerdp(); - - QString m_name; - QString m_user; - QString m_password; - - bool m_quitFlag; - QX11EmbedContainer *m_container; // container for the xfreerdp window - QProcess *m_process; // xfreerdp process - - RdpHostPreferences *m_hostPreferences; - -private slots: - void connectionOpened(); // called if xfreerdp started - void connectionClosed(); // called if xfreerdp quits - void connectionError(); // called if xfreerdp quits with error - void processError(QProcess::ProcessError error); // called if xfreerdp dies - void receivedStandardError(); // catches xfreerdp debug output - void receivedStandardOutput(); // catches xfreerdp output -}; - -static QHash keymapToXfreerdpHash; - -#endif diff --git a/krdc/rdp/rdpviewfactory.cpp b/krdc/rdp/rdpviewfactory.cpp deleted file mode 100644 index 8b367e9d..00000000 --- a/krdc/rdp/rdpviewfactory.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "rdpviewfactory.h" - -#include -#include -#include - -KRDC_PLUGIN_EXPORT(RdpViewFactory) - -RdpViewFactory::RdpViewFactory(QObject *parent, const QVariantList &args) - : RemoteViewFactory(parent) -{ - Q_UNUSED(args); - - KGlobal::locale()->insertCatalog("krdc"); - - m_connectToolTipString = i18n("Connect to a Windows Remote Desktop (RDP)"); - - QMetaObject::invokeMethod(this, "checkFreerdpAvailability", Qt::DirectConnection); -} - -RdpViewFactory::~RdpViewFactory() -{ -} - -bool RdpViewFactory::supportsUrl(const KUrl &url) const -{ - return (url.scheme().compare("rdp", Qt::CaseInsensitive) == 0); -} - -RemoteView *RdpViewFactory::createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) -{ - return new RdpView(parent, url, configGroup); -} - -HostPreferences *RdpViewFactory::createHostPreferences(KConfigGroup configGroup, QWidget *parent) -{ - return new RdpHostPreferences(configGroup, parent); -} - -QString RdpViewFactory::scheme() const -{ - return "rdp"; -} - -QString RdpViewFactory::connectActionText() const -{ - return i18n("New RDP Connection..."); -} - -QString RdpViewFactory::connectButtonText() const -{ - return m_connectToolTipString; -} - -QString RdpViewFactory::connectToolTipText() const -{ - return i18n("Enter the address here. Port is optional.
" - "Example: rdpserver:3389 (host:port)"); -} - -void RdpViewFactory::checkFreerdpAvailability() -{ - if (KStandardDirs::findExe("xfreerdp").isEmpty()) { - m_connectToolTipString += '\n' + i18n("The application \"xfreerdp\" cannot be found on your system; make sure it is properly installed " - "if you need RDP support."); - } -} - -#include "moc_rdpviewfactory.cpp" diff --git a/krdc/rdp/rdpviewfactory.h b/krdc/rdp/rdpviewfactory.h deleted file mode 100644 index 2a3ce9ee..00000000 --- a/krdc/rdp/rdpviewfactory.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef RDPVIEWFACTORY_H -#define RDPVIEWFACTORY_H - -#include "remoteviewfactory.h" - -#include "rdpview.h" -#include "rdppreferences.h" - -class RdpViewFactory : public RemoteViewFactory -{ - Q_OBJECT - -public: - explicit RdpViewFactory(QObject *parent, const QVariantList &args); - - virtual ~RdpViewFactory(); - - virtual bool supportsUrl(const KUrl &url) const; - - virtual RemoteView *createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup); - - virtual HostPreferences *createHostPreferences(KConfigGroup configGroup, QWidget *parent); - - virtual QString scheme() const; - - virtual QString connectActionText() const; - - virtual QString connectButtonText() const; - - virtual QString connectToolTipText() const; - -private Q_SLOTS: - void checkFreerdpAvailability(); - -private: - QString m_connectToolTipString; -}; - -#endif // RDPVIEWFACTORY_H diff --git a/krdc/rdp/smb2rdc.desktop b/krdc/rdp/smb2rdc.desktop deleted file mode 100644 index b6d48866..00000000 --- a/krdc/rdp/smb2rdc.desktop +++ /dev/null @@ -1,74 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KonqPopupMenu/Plugin -MimeType=application/x-smb-server; -Actions=smb2rdc; - -[Desktop Action smb2rdc] -Name=Open Remote Desktop Connection to This Machine -Name[ar]=افتح عن بعد سطح المكتب الاتصال إلى هذه الآلة -Name[ast]=Abrir conexón remota d'escritoriu a esti sistema -Name[bg]=Връзка с отдалечен работно място с избрания компютър -Name[bn]=এই মেশিনে প্রত্যন্ত ডেস্কটপের সংযোগ খোলো -Name[bs]=Otvara udaljenu vezu površi ka ovoj mašini -Name[ca]=Obre una connexió remota d'escriptori a aquesta màquina -Name[ca@valencia]=Obri una connexió remota d'escriptori a esta màquina -Name[cs]=Otevřít vzdálené připojení plochy k tomuto počítači -Name[da]=Åbn forbindelse til fjernskrivebord til denne maskine -Name[de]=Verbindung zur Arbeitsfläche dieses Rechners herstellen -Name[el]=Δημιουργία σύνδεσης σε απομακρυσμένη επιφάνεια εργασίας σε αυτό το μηχάνημα -Name[en_GB]=Open Remote Desktop Connection to This Machine -Name[eo]=Malfermi deforan tabulan konekton al tiu maŝino -Name[es]=Abrir conexión remota de escritorio a este sistema -Name[et]=Kaugtöölaua ühenduse avamine sellesse arvutisse -Name[eu]=Ireki urruneko mahaigainaren konexioa makina honetara -Name[fa]=باز کردن اتصال رومیزی راه دور برای این ماشین -Name[fi]=Avaa etätyöpöytäyhteys tähän koneeseen -Name[fr]=Ouvrir une connexion distante au bureau de cette machine -Name[ga]=Oscail Ceangal Deisce Cianda leis an Ríomhaire Seo -Name[gl]=Abrir unha conexión remota co escritorio desta máquina -Name[he]=פתח חיבור שולחן עבודה מרוחק למכונה זו -Name[hi]=इस मशीन के लिए रिमोट डेस्कटॉप कनेक्शन खोलें -Name[hne]=ये मसीन बर रिमोट डेस्कटाप कनेक्सन खोलव -Name[hr]=Otvorena veza udaljenog pristupa prema ovom uređaju -Name[hu]=Távoli munkaasztal nyitása itt -Name[ia]=Aperi connexion de scriptorio remote a iste machina -Name[is]=Opna fjarlæga skjáborðtengingu til þessarar vélar -Name[it]=Apri connessione a desktop remoto a questa macchina -Name[ja]=このホストへリモートデスクトップ接続を開く -Name[kk]=Осы компьютердегі үстелге қашық қосылымды ашу -Name[km]=បើក​ការ​ត​ភ្ជាប់​ផ្ទៃ​តុ​ពី​ចម្ងាយ​ទៅ​ម៉ាស៊ីន​នេះ -Name[ko]=이 시스템으로의 원격 데스크톱 연결 열기 -Name[lt]=Užmegzti nutolusio darbastalio prijungimą prie šio kompiuterio -Name[lv]=Avērt attālinātās darbirsmas savienojumu uz šo datoru -Name[ml]=വിദൂര പണിയിടത്തിന് ഈ യന്ത്രവുമായുള്ള ബന്ധം തുടങ്ങുക -Name[mr]=या यंत्राकरिता दूरस्थ डेस्कटॉप जुळवणी उघडा -Name[nb]=Åpne fjerntilkobling til skrivebord til denne maskinen -Name[nds]=Schriefdisch-Feernverbinnen na dissen Reekner opmaken -Name[ne]=यो मेशिनमा टाढाको डेस्कटप जडान खोल्नुहोस् -Name[nl]=Externe bureaubladverbinding met deze computer openen -Name[nn]=Opna samband til skrivebordet over nettverket til denne maskina -Name[pa]=ਇਸ ਮਸ਼ੀਨ ਨਾਲ ਰਿਮੋਟ ਡੈਸਕਟਾਪ ਕੁਨੈਕਸ਼ਨ ਖੋਲ੍ਹੋ -Name[pl]=Otwórz zdalne połączenie z pulpitem na tej maszynie -Name[pt]=Abrir uma Ligação Remota ao Ecrã deste Computador -Name[pt_BR]=Abrir conexões remotas para essa máquina -Name[ro]=Deschideți conexiune de birou distant spre această mașină -Name[ru]=Открыть соединение Remote Desktop с этой машиной -Name[si]=මෙම යන්ත්‍රය සඳහා දුරස්ථ වැඩතල සබඳතාව විවෘත කරන්න -Name[sk]=Otvoriť vzdialené pripojenie pracovnej plochy k tomuto počítaču -Name[sl]=Odpri povezavo z oddaljenim namizjem na tem računalniku -Name[sr]=Отворите удаљену везу површи ка овој машини -Name[sr@ijekavian]=Отворите удаљену везу површи ка овој машини -Name[sr@ijekavianlatin]=Otvorite udaljenu vezu površi ka ovoj mašini -Name[sr@latin]=Otvorite udaljenu vezu površi ka ovoj mašini -Name[sv]=Öppna fjärrskrivbordsanslutning till den här datorn -Name[th]=เปิดการเชื่อมต่อพื้นที่ทำงานทางไกลมายังเครื่องนี้ -Name[tr]=Bu Makineye Uzak Masaüstü Bağlantısı Aç -Name[uk]=Відкрити з'єднання з віддаленою стільницею до цього комп'ютера -Name[vi]=Mở kết nối màn hình nền từ xa đến máy này -Name[x-test]=xxOpen Remote Desktop Connection to This Machinexx -Name[zh_CN]=打开到此计算机的远程桌面连接 -Name[zh_HK]=開放遠端桌面連線到這電腦 -Name[zh_TW]=在此主機上開啟遠端桌面 -Exec=krdc %u -Icon=krdc diff --git a/krdc/remotedesktopsmodel.cpp b/krdc/remotedesktopsmodel.cpp deleted file mode 100644 index ed86ad05..00000000 --- a/krdc/remotedesktopsmodel.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "remotedesktopsmodel.h" -#include "bookmarkmanager.h" - -#include -#include -#include - -RemoteDesktopsModel::RemoteDesktopsModel(QObject *parent) - : QAbstractTableModel(parent) -{ - const QString file = KStandardDirs::locateLocal("data", "krdc/bookmarks.xml"); - m_manager = KBookmarkManager::managerForFile(file, "krdc"); - m_manager->setUpdate(true); - connect(m_manager, SIGNAL(changed(QString,QString)), SLOT(bookmarksChanged())); - buildModelFromBookmarkGroup(m_manager->root()); - -#ifdef BUILD_ZEROCONF - // Add RDP and NX if they start announcing via Zeroconf: - m_protocols["_rfb._tcp"] = "vnc"; - - zeroconfBrowser = new KDNSSD(); - connect(zeroconfBrowser, SIGNAL(finished()), this, SLOT(servicesChanged())); - zeroconfBrowser->startBrowse("_rfb._tcp"); - kDebug(5010) << "Browsing for zeroconf hosts."; -#endif -} - -RemoteDesktopsModel::~RemoteDesktopsModel() -{ -} - -int RemoteDesktopsModel::columnCount(const QModelIndex &) const -{ - return 6; // same as count of RemoteDesktopsModel::DisplayItems enum -} - -int RemoteDesktopsModel::rowCount(const QModelIndex &) const -{ - return remoteDesktops.size(); -} - -Qt::ItemFlags RemoteDesktopsModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - return 0; - if (index.column() == RemoteDesktopsModel::Favorite) { - return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; - } - return Qt::ItemIsEnabled; -} - -bool RemoteDesktopsModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (index.isValid() && role == Qt::CheckStateRole && index.column() == RemoteDesktopsModel::Favorite) { - bool checked = (Qt::CheckState)value.toUInt() == Qt::Checked; - remoteDesktops[index.row()].favorite = checked; - - RemoteDesktop rd = remoteDesktops.at(index.row()); - if (checked) { - KBookmarkGroup root = m_manager->root(); - root.addBookmark(rd.title, rd.url); - m_manager->emitChanged(root); - } else { - BookmarkManager::removeByUrl(m_manager, rd.url, true, rd.title); - } - return true; - } - return false; -} - -QVariant RemoteDesktopsModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); - - RemoteDesktop item = remoteDesktops.at(index.row()); - - switch (role) { - case Qt::DisplayRole: - switch (index.column()) { - case RemoteDesktopsModel::Favorite: - return item.favorite; - case RemoteDesktopsModel::Title: - return item.title; - case RemoteDesktopsModel::LastConnected: - return QVariant(QDateTime(item.lastConnected)); - case RemoteDesktopsModel::VisitCount: - return item.visits; - case RemoteDesktopsModel::Created: - if (item.created.isNull()) return QVariant(); - return KGlobal::locale()->formatDateTime(item.created.toLocalTime(), QLocale::NarrowFormat); - case RemoteDesktopsModel::Source: - switch (item.source) { - case RemoteDesktop::Bookmarks: - return i18nc("Where each displayed link comes from", "Bookmarks"); - case RemoteDesktop::History: - return i18nc("Where each displayed link comes from", "History"); - case RemoteDesktop::Zeroconf: - return i18nc("Where each displayed link comes from", "Zeroconf"); - case RemoteDesktop::None: - return i18nc("Where each displayed link comes from", "None"); - } - default: - return QVariant(); - } - - case Qt::CheckStateRole: - if (index.column() == RemoteDesktopsModel::Favorite) - return item.favorite ? Qt::Checked : Qt::Unchecked; - return QVariant(); - - case Qt::ToolTipRole: - switch(index.column()) { - case RemoteDesktopsModel::Favorite: - if (item.favorite) { - return i18nc("Remove the selected url from the bookarks menu", "Remove the bookmark for %1.", item.title); - } else { - return i18nc("Add the selected url to the bookmarks menu", "Bookmark %1.", item.title); - } - case RemoteDesktopsModel::LastConnected: - if (!item.lastConnected.isNull()) { - return KGlobal::locale()->formatDateTime(item.lastConnected.toLocalTime(), QLocale::NarrowFormat); - } - break; // else show default tooltip - case RemoteDesktopsModel::Created: - if (!item.created.isNull()) { - return KGlobal::locale()->formatDateTime(item.created.toLocalTime(), QLocale::NarrowFormat); - } - break; // else show default tooltip - default: - break; - } - return item.url; //use the url for the tooltip - - case 10001: //url for dockwidget - return item.url; - - case 10002: //filter - return QUrl::fromPercentEncoding(QString(item.url + item.title).toUtf8()); // return both user visible title and url data, percent encoded - - case 10003: //title for dockwidget - return item.title; - - default: - return QVariant(); - } -} - -QVariant RemoteDesktopsModel::headerData(int section, Qt::Orientation orientation, - int role) const -{ - if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - switch (section) { - case RemoteDesktopsModel::Favorite: - return QVariant(); // the favorite column is to small for a header - case RemoteDesktopsModel::Title: - return i18nc("Header of the connections list, title/url for remote connection", "Remote Desktop"); - case RemoteDesktopsModel::LastConnected: - return i18nc("Header of the connections list, the last time this connection was initiated", "Last Connected"); - case RemoteDesktopsModel::VisitCount: - return i18nc("Header of the connections list, the number of times this connection has been visited", "Visits"); - case RemoteDesktopsModel::Created: - return i18nc("Header of the connections list, the time when this entry was created", "Created"); - case RemoteDesktopsModel::Source: - return i18nc("Header of the connections list, where this entry comes from", "Source"); - } - } - return QVariant(); -} - -// does not trigger view update, you must do this by hand after using this function -void RemoteDesktopsModel::removeAllItemsFromSources(RemoteDesktop::Sources sources) -{ - QMutableListIterator iter(remoteDesktops); - while (iter.hasNext()) { - iter.next(); - // if it matches any of the specified sources, remove it - if ((iter.value().source & sources) > 0) - iter.remove(); - } -} - -void RemoteDesktopsModel::bookmarksChanged() -{ - kDebug(5010); - removeAllItemsFromSources(RemoteDesktop::Bookmarks | RemoteDesktop::History); - buildModelFromBookmarkGroup(m_manager->root()); - reset(); -} - -// Danger Will Roobinson, confusing code ahead! -void RemoteDesktopsModel::buildModelFromBookmarkGroup(const KBookmarkGroup &group) -{ - KBookmark bm = group.first(); - while (!bm.isNull()) { - if (bm.isGroup()) { - // recurse subfolders and treat it special if it is the history folder - buildModelFromBookmarkGroup(bm.toGroup()); - } else { // not a group - - RemoteDesktop item; - item.title = bm.fullText(); - item.url = bm.url().url(); - int index = remoteDesktops.indexOf(item); //search for this url to see if we need to update it - bool newItem = index < 0; // do we need to create a new item? - - // we want to merge all copies of a url into one link, so if the item exists, update it - if (group.metaDataItem("krdc-history") == "historyfolder") { - // set source and favorite (will override later if needed) - item.source = RemoteDesktop::History; - item.favorite = false; - - // since we are in the history folder collect statitics and add them - QDateTime connected = QDateTime(); - QDateTime created = QDateTime(); - bool ok = false; - // first the created datetime - created.setTime_t(bm.metaDataItem("time_added").toLongLong(&ok)); - if (ok) (newItem ? item : remoteDesktops[index]).created = created; - // then the last visited datetime - ok = false; - connected.setTime_t(bm.metaDataItem("time_visited").toLongLong(&ok)); - if (ok) (newItem ? item : remoteDesktops[index]).lastConnected = connected; - // finally the visited count - ok = false; - int visits = bm.metaDataItem("visit_count").toInt(&ok); - if (ok) (newItem ? item : remoteDesktops[index]).visits = visits; - } else { - if (newItem) { - // if this is a new item, just add the rest of the required data - item.lastConnected = QDateTime(); - item.created = QDateTime(); - item.visits = 0; - item.favorite = true; - item.source = RemoteDesktop::Bookmarks; - } else { - // otherwise override these fields with the info from the bookmark - remoteDesktops[index].title = bm.fullText(); - remoteDesktops[index].favorite = true; - remoteDesktops[index].source = RemoteDesktop::Bookmarks; - } - } - // if we have a new item, add it - if (newItem) - remoteDesktops.append(item); - } - bm = group.next(bm); // next item in the group - } -} - -#ifdef BUILD_ZEROCONF -void RemoteDesktopsModel::servicesChanged() -{ - //redo list because it is easier than finding and removing one that disappeared - KUrl url; - removeAllItemsFromSources(RemoteDesktop::Zeroconf); - foreach(const KDNSSDService &service, zeroconfBrowser->services()) { - url.setScheme(m_protocols[service.type].toLower()); - url.setHost(service.hostname); - url.setPort(service.port); - - RemoteDesktop item; - item.url = url.url(); - - if (!remoteDesktops.contains(item)) { - item.title = service.name; - item.source = RemoteDesktop::Zeroconf; - item.created = QDateTime::currentDateTime(); - item.favorite = false; - item.visits = 0; - remoteDesktops.append(item); - } - } - reset(); -} -#endif - -#include "moc_remotedesktopsmodel.cpp" diff --git a/krdc/remotedesktopsmodel.h b/krdc/remotedesktopsmodel.h deleted file mode 100644 index 0989040f..00000000 --- a/krdc/remotedesktopsmodel.h +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef REMOTEDESKTOPSMODEL_H -#define REMOTEDESKTOPSMODEL_H - -#include -#include - -#ifdef BUILD_ZEROCONF -#include -#endif - -class KBookmarkGroup; -class KBookmarkManager; - -struct RemoteDesktop { -public: - enum Source { None = 0x0, Bookmarks = 0x1, History = 0x2, Zeroconf = 0x4 }; - Q_DECLARE_FLAGS(Sources, Source) - QString title; - QString url; - QDateTime lastConnected; - QDateTime created; - int visits; - RemoteDesktop::Source source; - bool favorite; - bool operator<(const RemoteDesktop &rd) const { - if (lastConnected == rd.lastConnected) - return url < rd.url; - return rd.lastConnected < lastConnected; // seems backward but gets the desired result - } - bool operator==(const RemoteDesktop &rd) const { - return url == rd.url; - } -}; - -class RemoteDesktopsModel : public QAbstractTableModel -{ - Q_OBJECT - -public: - explicit RemoteDesktopsModel(QObject *parent); - ~RemoteDesktopsModel(); - - enum DisplayItems { Favorite, Title, LastConnected, VisitCount, Created, Source }; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; - -private: - QList remoteDesktops; - QString getLastConnectedString(QDateTime lastConnected, bool fuzzy = false) const; - void removeAllItemsFromSources(RemoteDesktop::Sources sources); - void buildModelFromBookmarkGroup(const KBookmarkGroup &group); - KBookmarkManager *m_manager; - -#ifdef BUILD_ZEROCONF - KDNSSD *zeroconfBrowser; - QHash m_protocols; -#endif - -private slots: - void bookmarksChanged(); -#ifdef BUILD_ZEROCONF - void servicesChanged(); -#endif -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(RemoteDesktop::Sources) - -#endif diff --git a/krdc/systemtrayicon.cpp b/krdc/systemtrayicon.cpp deleted file mode 100644 index b05aa724..00000000 --- a/krdc/systemtrayicon.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "systemtrayicon.h" - -#include "mainwindow.h" - -#include -#include -#include - -SystemTrayIcon::SystemTrayIcon(MainWindow *parent) - : KStatusNotifierItem(parent), - m_mainWindow(parent) -{ - setIconByName("krdc"); - setStatus(KStatusNotifierItem::Active); - setCategory(KStatusNotifierItem::ApplicationStatus); - - setToolTipIconByName("krdc"); - setToolTipTitle(i18n("KDE Remote Desktop Client")); - - contextMenu()->addSeparator(); - contextMenu()->addAction(parent->actionCollection()->action("bookmark")); - contextMenu()->addSeparator(); - - connect(this, SIGNAL(activateRequested(bool,QPoint)), this, SLOT(checkActivatedWindow(bool))); -} - -void SystemTrayIcon::checkActivatedWindow(bool active) -{ - // make sure the fullscreen window stays fullscreen by restoring the FullScreen state upon restore. - if(active && associatedWidget() != m_mainWindow) { - associatedWidget()->setWindowState(Qt::WindowFullScreen); - } -} - -SystemTrayIcon::~SystemTrayIcon() -{ -} - -#include "moc_systemtrayicon.cpp" diff --git a/krdc/systemtrayicon.h b/krdc/systemtrayicon.h deleted file mode 100644 index af433c87..00000000 --- a/krdc/systemtrayicon.h +++ /dev/null @@ -1,46 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef SYSTEMTRAYICON_H -#define SYSTEMTRAYICON_H - -#include - -class MainWindow; - -class SystemTrayIcon : public KStatusNotifierItem -{ - Q_OBJECT - -public: - explicit SystemTrayIcon(MainWindow *parent); - ~SystemTrayIcon(); - -public slots: - void checkActivatedWindow(bool active); - -private: - MainWindow *m_mainWindow; -}; - -#endif diff --git a/krdc/tabbedviewwidget.cpp b/krdc/tabbedviewwidget.cpp deleted file mode 100644 index 3d173d64..00000000 --- a/krdc/tabbedviewwidget.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "tabbedviewwidget.h" - -TabbedViewWidgetModel::TabbedViewWidgetModel(KTabWidget *modelTarget) - : QAbstractItemModel(modelTarget), m_tabWidget(modelTarget) -{ -} - -QModelIndex TabbedViewWidgetModel::index(int row, int column, const QModelIndex &parent) const -{ - if (!hasIndex(row, column, parent)) { - return QModelIndex(); - } - return createIndex(row, column, m_tabWidget->widget(row)); -} - -QModelIndex TabbedViewWidgetModel::parent(const QModelIndex &) const -{ - return QModelIndex(); -} - -int TabbedViewWidgetModel::columnCount(const QModelIndex &) const -{ - return 1; -} - - -int TabbedViewWidgetModel::rowCount(const QModelIndex &) const -{ - return m_tabWidget->count(); -} - -Qt::ItemFlags TabbedViewWidgetModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) { - return Qt::ItemIsEnabled; - } - return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; -} - -bool TabbedViewWidgetModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (index.isValid() && role == Qt::EditRole) { - m_tabWidget->setTabText(index.row(), value.toString()); - emit dataChanged(index, index); - return true; - } - return false; -} - -QVariant TabbedViewWidgetModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) { - return QVariant(); - } - - switch (role) { - case Qt::EditRole: - case Qt::DisplayRole: - return m_tabWidget->tabText(index.row()).remove(QRegExp("&(?!&)")); //remove accelerator string - case Qt::ToolTipRole: - return m_tabWidget->tabToolTip(index.row()); - case Qt::DecorationRole: - return m_tabWidget->tabIcon(index.row()); - default: - return QVariant(); - } -} - -void TabbedViewWidgetModel::emitLayoutAboutToBeChanged() -{ - emit layoutAboutToBeChanged(); -} - -void TabbedViewWidgetModel::emitLayoutChanged() -{ - emit layoutChanged(); -} - -void TabbedViewWidgetModel::emitDataChanged(int index) -{ - QModelIndex modelIndex = createIndex(index, 1); - emit dataChanged(modelIndex, modelIndex); -} - -TabbedViewWidget::TabbedViewWidget(QWidget *parent, Qt::WFlags flags) - : KTabWidget(parent, flags), m_model(new TabbedViewWidgetModel(this)) -{ -} - -TabbedViewWidget::~TabbedViewWidget() -{ -} - -TabbedViewWidgetModel* TabbedViewWidget::getModel() -{ - return m_model; -} - -int TabbedViewWidget::addTab(QWidget *page, const QString &label) -{ - int count = KTabWidget::count(); - m_model->beginInsertRows(QModelIndex(), count, count); - int ret = KTabWidget::addTab(page, label); - m_model->endInsertRows(); - return ret; -} - -int TabbedViewWidget::addTab(QWidget *page, const QIcon &icon, const QString &label) -{ - int count = KTabWidget::count(); - m_model->beginInsertRows(QModelIndex(), count, count); - int ret = KTabWidget::addTab(page, icon, label); - m_model->endInsertRows(); - return ret; -} - -int TabbedViewWidget::insertTab(int index, QWidget *page, const QString &label) -{ - m_model->beginInsertRows(QModelIndex(), index, index); - int ret = KTabWidget::insertTab(index, page, label); - m_model->endInsertRows(); - return ret; -} - -int TabbedViewWidget::insertTab(int index, QWidget *page, const QIcon &icon, const QString &label) -{ - m_model->beginInsertRows(QModelIndex(), index, index); - int ret = KTabWidget::insertTab(index, page, icon, label); - m_model->endInsertRows(); - return ret; -} - -void TabbedViewWidget::removePage(QWidget *page) -{ - int index = KTabWidget::indexOf(page); - m_model->beginRemoveRows(QModelIndex(), index, index); - KTabWidget::removeTab(index); - m_model->endRemoveRows(); -} - -void TabbedViewWidget::removeTab(int index) -{ - m_model->beginRemoveRows(QModelIndex(), index, index); - KTabWidget::removeTab(index); - m_model->endRemoveRows(); -} - -void TabbedViewWidget::moveTab(int from, int to) -{ - m_model->emitLayoutAboutToBeChanged(); - KTabWidget::moveTab(from, to); - m_model->emitLayoutChanged(); -} - -void TabbedViewWidget::setTabText(int index, const QString &label) -{ - KTabWidget::setTabText(index, label); - m_model->emitDataChanged(index); -} - -#include "moc_tabbedviewwidget.cpp" diff --git a/krdc/tabbedviewwidget.h b/krdc/tabbedviewwidget.h deleted file mode 100644 index 4cfd141f..00000000 --- a/krdc/tabbedviewwidget.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Tony Murray -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef TABBEDVIEWWIDGET_H -#define TABBEDVIEWWIDGET_H - -#include -#include - -class TabbedViewWidgetModel : public QAbstractItemModel -{ - friend class TabbedViewWidget; - Q_OBJECT -public: - explicit TabbedViewWidgetModel(KTabWidget *modelTarget); - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - QVariant data(const QModelIndex &index, int role) const; -protected: - void emitLayoutAboutToBeChanged(); - void emitLayoutChanged(); - void emitDataChanged(int index); -private: - KTabWidget *m_tabWidget; -}; - -class TabbedViewWidget : public KTabWidget -{ - Q_OBJECT -public: - explicit TabbedViewWidget(QWidget *parent = 0, Qt::WFlags flags = 0); - virtual ~TabbedViewWidget(); - TabbedViewWidgetModel* getModel(); - int addTab(QWidget *page, const QString &label); - int addTab(QWidget *page, const QIcon &icon, const QString &label); - int insertTab(int index, QWidget *page, const QString &label); - int insertTab(int index, QWidget *page, const QIcon &icon, const QString &label); - void removeTab(int index); - void removePage(QWidget *page); - void moveTab(int from, int to); - void setTabText(int index, const QString &label); -private: - TabbedViewWidgetModel *m_model; -}; - -#endif // FULLSCREENWINDOW_H - diff --git a/krdc/test/CMakeLists.txt b/krdc/test/CMakeLists.txt deleted file mode 100644 index ae926f39..00000000 --- a/krdc/test/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -include_directories( - ${CMAKE_CURRENT_BINARY_DIR} -) - -set(testplugin_SRCS - testviewfactory.cpp - testview.cpp -) - -kde4_add_plugin(krdc_testplugin ${testplugin_SRCS}) - -target_link_libraries(krdc_testplugin - KDE4::kdecore - KDE4::kdeui - krdccore -) -install(TARGETS krdc_testplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - -install(FILES krdc_test.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) diff --git a/krdc/test/krdc_test.desktop b/krdc/test/krdc_test.desktop deleted file mode 100644 index c1f7a453..00000000 --- a/krdc/test/krdc_test.desktop +++ /dev/null @@ -1,124 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KRDC/Plugin -Icon=krdc -Name=Test -Name[ast]=Preba -Name[bg]=Проба -Name[bs]=Test -Name[ca]=Prova -Name[ca@valencia]=Prova -Name[cs]=Test -Name[da]=Test -Name[de]=Test -Name[el]=Δοκιμή -Name[en_GB]=Test -Name[es]=Prueba -Name[et]=Test -Name[eu]=Proba -Name[fi]=Testi -Name[fr]=Test -Name[ga]=Tástáil -Name[gl]=Proba -Name[hr]=Test -Name[hsb]=Test -Name[hu]=Teszt -Name[ia]=Essaya -Name[is]=Prófun -Name[it]=Prova -Name[ja]=テスト -Name[kk]=Тест -Name[km]=សាកល្បង -Name[ko]=테스트 -Name[lt]=Testavimas -Name[lv]=Tests -Name[mai]=जाँच -Name[mr]=चाचणी -Name[nb]=Test -Name[nds]=Test -Name[nl]=Test -Name[nn]=Test -Name[pa]=ਟੈਸਟ -Name[pl]=Test -Name[pt]=Teste -Name[pt_BR]=Testar -Name[ro]=Test -Name[ru]=Проверка -Name[si]=පිරික්සුම -Name[sk]=Test -Name[sl]=Preizkus -Name[sr]=Проба -Name[sr@ijekavian]=Проба -Name[sr@ijekavianlatin]=Proba -Name[sr@latin]=Proba -Name[sv]=Prov -Name[th]=ทดสอบ -Name[tr]=Test -Name[ug]=سىنا -Name[uk]=Тест -Name[wa]=Asprouvaedje -Name[x-test]=xxTestxx -Name[zh_CN]=测试 -Name[zh_TW]=測試 -Comment=Testplugin for KRDC development -Comment[ast]=Complementu de preba pal desendolcu de KRDC -Comment[bg]=Пробна приставка за KRDC -Comment[bs]=Probni priključak za razvoj KRDC -Comment[ca]=Connector de prova del desenvolupament del KRDC -Comment[ca@valencia]=Connector de prova del desenvolupament del KRDC -Comment[cs]=Demonstrační modul pro vývoj KRDC -Comment[da]=Test-plugin til KRDC-udvikling -Comment[de]=Testmodul für die KRDC-Entwicklung -Comment[el]=Πρόσθετο δοκιμής για την ανάπτυξη του KRDC -Comment[en_GB]=Testplugin for KRDC development -Comment[es]=Complemento de prueba para el desarrollo de KRDC -Comment[et]=Plugin KRDC arendustegevuse testimiseks -Comment[eu]=Probako plugina KRDC garatzeko -Comment[fi]=KRDC-kehityksen testiliitännäinen -Comment[fr]=Module externe de test pour le développement de KRDC -Comment[ga]=Breiseán tástála le haghaidh fhorbairt KRDC -Comment[gl]=Engadido de proba para o desenvolvemento de KRDC -Comment[hr]=Testni priključak za razvoj KRDC-a -Comment[hu]=Tesztmodul KRDC-fejlesztőknek -Comment[ia]=Plug-in de essayo pro disveloppamento de KRDC -Comment[is]=Prófunaríforrit fyrir KRDC forritun -Comment[it]=Estensione di prova per lo sviluppo di KRDC -Comment[ja]=KRDC 開発のためのテスト用プラグイン -Comment[kk]=KRDC-құрастыруын үйрету үшін сынақ плагині -Comment[km]=ការ​អភិវឌ្ឍន៍ Testplugin សម្រាប់ KRDC -Comment[ko]=KRDC 개발을 위한 테스트 플러그인 -Comment[lt]=Įskiepis, skirtas KRDC programavimui -Comment[lv]=Demonstrācijas spraudnis KRDC izstrādei -Comment[nb]=Test-programtillegg for KRDC-utvikling -Comment[nds]=Testmoduul för't Utwickeln vun KRDC -Comment[nl]=Testplugin voor KRDC-ontwikkeling -Comment[nn]=Programtillegg for demonstrasjon og opplæring i KRDC-utvikling -Comment[pl]=Wtyczka demonstracyjna do nauki programowania KRDC -Comment[pt]='Plugin' de demonstração para o desenvolvimento com o KRDC -Comment[pt_BR]=Plugin de teste para o desenvolvimento no KRDC -Comment[ro]=Modul de testare pentru dezvoltarea KRDC -Comment[ru]=Демонстрационный модуль для изучения программирования модулей KRDC -Comment[si]=KRDC සංවර්ධනයක් සඳහා පිරික්සුම් ප්ලගිනය -Comment[sk]=Testovací modul pre vývoj KRDC -Comment[sl]=Preizkusni vstavek za razvoj KRDC -Comment[sr]=Пробни прикључак за развој КРДЦ‑а -Comment[sr@ijekavian]=Пробни прикључак за развој КРДЦ‑а -Comment[sr@ijekavianlatin]=Probni priključak za razvoj KRDC‑a -Comment[sr@latin]=Probni priključak za razvoj KRDC‑a -Comment[sv]=Testinsticksprogram för utveckling av KRDC -Comment[tr]=KRDC geliştirmesi için örnek eklenti -Comment[uk]=Тестовий додаток для розробки KRDC -Comment[x-test]=xxTestplugin for KRDC developmentxx -Comment[zh_CN]=KRDC 开发用的测试插件 -Comment[zh_TW]=KRDC 開發的測試外掛程式 - -X-KDE-PluginInfo-Author=Urs Wolfer -X-KDE-PluginInfo-Email=uwolfer@kde.org -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-Library=krdc_testplugin -X-KDE-PluginInfo-Name=krdc_testplugin - -X-KDE-KRDC-Sorting=80 diff --git a/krdc/test/testview.cpp b/krdc/test/testview.cpp deleted file mode 100644 index ab884681..00000000 --- a/krdc/test/testview.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "testview.h" - -#include - -TestView::TestView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) - : RemoteView(parent) -{ - m_hostPreferences = new TestHostPreferences(configGroup, this); - - Q_UNUSED(url); - - setAutoFillBackground(true); - - QPalette pal = palette(); - pal.setColor(QPalette::Dark, Qt::yellow); - setPalette(pal); - - const QSize size = QSize(640, 480); - setStatus(Connected); - setFixedSize(size); - setFixedSize(size); - emit framebufferSizeChanged(size.width(), size.height()); - emit connected(); -} - -TestView::~TestView() -{ - emit disconnected(); - setStatus(Disconnected); -} - -bool TestView::eventFilter(QObject *obj, QEvent *event) -{ - if (m_viewOnly) { - if (event->type() == QEvent::KeyPress || - event->type() == QEvent::KeyRelease || - event->type() == QEvent::MouseButtonDblClick || - event->type() == QEvent::MouseButtonPress || - event->type() == QEvent::MouseButtonRelease || - event->type() == QEvent::MouseMove) - return true; - } - return RemoteView::eventFilter(obj, event); -} - -QSize TestView::framebufferSize() -{ - return minimumSizeHint(); -} - -QSize TestView::sizeHint() const -{ - return maximumSize(); -} - -bool TestView::isQuitting() -{ - return false; -} - -bool TestView::start() -{ - return true; -} - -HostPreferences* TestView::hostPreferences() -{ - return m_hostPreferences; -} - -void TestView::switchFullscreen(bool on) -{ - Q_UNUSED(on); -} - -#include "moc_testview.cpp" diff --git a/krdc/test/testview.h b/krdc/test/testview.h deleted file mode 100644 index 75600cb7..00000000 --- a/krdc/test/testview.h +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef TESTVIEW_H -#define TESTVIEW_H - -#include "testview.h" - -#include "remoteview.h" -#include "hostpreferences.h" - -#include - -class TestHostPreferences; - -class TestView : public RemoteView -{ - Q_OBJECT - -public: - explicit TestView(QWidget *parent = 0, const KUrl &url = KUrl(), KConfigGroup configGroup = KConfigGroup()); - - virtual ~TestView(); - - virtual QSize framebufferSize(); - QSize sizeHint() const; - - virtual bool isQuitting(); - virtual bool start(); - HostPreferences* hostPreferences(); - -public slots: - virtual void switchFullscreen(bool on); - -protected: - bool eventFilter(QObject *obj, QEvent *event); - -private: - TestHostPreferences *m_hostPreferences; -}; - - -class TestHostPreferences : public HostPreferences -{ - Q_OBJECT -public: - explicit TestHostPreferences(KConfigGroup configGroup, QObject *parent = 0) - : HostPreferences(configGroup, parent) {} - -protected: - virtual QWidget* createProtocolSpecificConfigPage() { return 0; }; -}; - -#endif // TESTVIEW_H diff --git a/krdc/test/testviewfactory.cpp b/krdc/test/testviewfactory.cpp deleted file mode 100644 index 1cad4759..00000000 --- a/krdc/test/testviewfactory.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "testviewfactory.h" - -#include -#include - -KRDC_PLUGIN_EXPORT(TestViewFactory) - -TestViewFactory::TestViewFactory(QObject *parent, const QVariantList &args) - : RemoteViewFactory(parent) -{ - Q_UNUSED(args); - - KGlobal::locale()->insertCatalog("krdc"); -} - -TestViewFactory::~TestViewFactory() -{ -} - -bool TestViewFactory::supportsUrl(const KUrl &url) const -{ - return (url.scheme().compare("test", Qt::CaseInsensitive) == 0); -} - -RemoteView *TestViewFactory::createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) -{ - return new TestView(parent, url, configGroup); -} - -HostPreferences *TestViewFactory::createHostPreferences(KConfigGroup configGroup, QWidget *parent) -{ - Q_UNUSED(configGroup); - Q_UNUSED(parent); - - return 0; -} - -QString TestViewFactory::scheme() const -{ - return "test"; -} - -QString TestViewFactory::connectActionText() const -{ - return ("New Test Connection..."); // no i18n required, just internal test plugin! -} - -QString TestViewFactory::connectButtonText() const -{ - return ("KRDC Test Connection"); // no i18n required, just internal test plugin! -} - -QString TestViewFactory::connectToolTipText() const -{ - return ("Enter the address here. Port is optional.
" - "Example: testserver (host)"); // no i18n required, just internal test plugin! -} - -#include "moc_testviewfactory.cpp" diff --git a/krdc/test/testviewfactory.h b/krdc/test/testviewfactory.h deleted file mode 100644 index a5df4ec5..00000000 --- a/krdc/test/testviewfactory.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef TESTVIEWFACTORY_H -#define TESTVIEWFACTORY_H - -#include "remoteviewfactory.h" - -#include "testview.h" - -class TestViewFactory : public RemoteViewFactory -{ - Q_OBJECT - -public: - explicit TestViewFactory(QObject *parent, const QVariantList &args); - - virtual ~TestViewFactory(); - - virtual bool supportsUrl(const KUrl &url) const; - - virtual RemoteView *createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup); - - virtual HostPreferences *createHostPreferences(KConfigGroup configGroup, QWidget *parent); - - virtual QString scheme() const; - - virtual QString connectActionText() const; - - virtual QString connectButtonText() const; - - virtual QString connectToolTipText() const; -}; - -#endif // TESTVIEWFACTORY_H diff --git a/krdc/vnc/CMakeLists.txt b/krdc/vnc/CMakeLists.txt deleted file mode 100644 index 2b28cad6..00000000 --- a/krdc/vnc/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ - -if(LIBVNCSERVER_FOUND) - add_definitions(-DKDE_DEFAULT_DEBUG_AREA=5011) - - include_directories( - ${CMAKE_CURRENT_BINARY_DIR} - ${LIBVNCCLIENT_INCLUDE_DIR} - ) - - set(vncplugin_SRCS - vnchostpreferences.cpp - vncclientthread.cpp - vncviewfactory.cpp - vncview.cpp - vncpreferences.ui - ) - - kde4_add_plugin(krdc_vncplugin ${vncplugin_SRCS}) - - target_link_libraries(krdc_vncplugin - KDE4::kdecore - KDE4::kdeui - ${LIBVNCCLIENT_LIBRARIES} - krdccore - ) - - set(kcm_krdc_vncplugin_SRCS - vncpreferences.cpp - ) - - kde4_add_plugin(kcm_krdc_vncplugin ${kcm_krdc_vncplugin_SRCS}) - - target_link_libraries(kcm_krdc_vncplugin - KDE4::kdeui - krdccore - ) - - add_dependencies(kcm_krdc_vncplugin krdc_vncplugin) - - install(TARGETS kcm_krdc_vncplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - install(TARGETS krdc_vncplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) - - install(FILES krdc_vnc.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - install(FILES krdc_vnc_config.desktop DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) - - install(FILES vnc.protocol DESTINATION ${KDE4_SERVICES_INSTALL_DIR}) -endif(LIBVNCSERVER_FOUND) diff --git a/krdc/vnc/krdc_vnc.desktop b/krdc/vnc/krdc_vnc.desktop deleted file mode 100644 index dd4e9298..00000000 --- a/krdc/vnc/krdc_vnc.desktop +++ /dev/null @@ -1,122 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KRDC/Plugin -Icon=krdc -Name=VNC -Name[ast]=VNC -Name[bg]=VNC -Name[bs]=VNC -Name[ca]=VNC -Name[ca@valencia]=VNC -Name[cs]=VNC -Name[da]=VNC -Name[de]=VNC -Name[el]=VNC -Name[en_GB]=VNC -Name[eo]=VNC -Name[es]=VNC -Name[et]=VNC -Name[eu]=VNC -Name[fi]=VNC -Name[fr]=VNC -Name[ga]=VNC -Name[gl]=VNC -Name[hr]=VNC -Name[hu]=VNC -Name[ia]=VNC -Name[is]=VNC -Name[it]=VNC -Name[ja]=VNC -Name[kk]=VNC -Name[km]=VNC -Name[ko]=VNC -Name[lt]=VNC -Name[lv]=VNC -Name[nb]=VNC -Name[nds]=VNC -Name[nl]=VNC -Name[nn]=VNC -Name[pa]=VNC -Name[pl]=VNC -Name[pt]=VNC -Name[pt_BR]=VNC -Name[ro]=VNC -Name[ru]=VNC -Name[si]=VNC -Name[sk]=VNC -Name[sl]=VNC -Name[sr]=ВНЦ -Name[sr@ijekavian]=ВНЦ -Name[sr@ijekavianlatin]=VNC -Name[sr@latin]=VNC -Name[sv]=VNC -Name[tr]=VNC -Name[ug]=VNC -Name[uk]=VNC -Name[wa]=VNC -Name[x-test]=xxVNCxx -Name[zh_CN]=VNC -Name[zh_TW]=VNC -Comment=Allows managing VNC sessions through KRDC -Comment[ast]=Permite la xestión de sesiones VNC per KRDC -Comment[bg]=Управление на сесии на VNC с KRDC -Comment[bs]=Dopušta upravljanje VNC sesijama kroz KRDC -Comment[ca]=Permet gestionar sessions VNC mitjançant el KRDC -Comment[ca@valencia]=Permet gestionar sessions VNC mitjançant el KRDC -Comment[cs]=Umožňuje spravování sezení VNC pomocí KRDC -Comment[da]=Muliggør håndtering af VNC-sessioner via KRDC -Comment[de]=Erlaubt die Verwaltung von VNC-Sitzungen über KRDC -Comment[el]=Επιτρέπει τη διαχείριση συνεδριών VNC μέσω του KRDC -Comment[en_GB]=Allows managing VNC sessions through KRDC -Comment[es]=Permite la gestión de sesiones VNC mediante KRDC -Comment[et]=VNC-seansside haldamise võimaldamine KRDC kaudu -Comment[eu]=VNC saioak KRDC bidez kudeatzea baimentzen du -Comment[fi]=Mahdollistaa VNC-istuntojen hallinnan KRDC:llä -Comment[fr]=Permet de gérer des sessions « VNC » au travers de KRDC -Comment[ga]=Ceadaíonn sé duit seisiúin VNC a bhainistiú trí KRDC -Comment[gl]=Permite xestionar sesións VNC por medio de KRDC -Comment[hr]=Omogućuje upravljanje sjednicama VNC-a kroz KRDC -Comment[hu]=VNC-elérés KRDC-ből -Comment[ia]=Permitte gerer sessiones VNC per medio de KRDC -Comment[is]=Gefur kost á að stjórna VNC setum með KRDC -Comment[it]=Permette di gestire sessioni VNC con KRDC -Comment[ja]=KRDC から VNC セッションを管理できるようにします -Comment[kk]=KRDC арқылы VNC сеанстарын басқаруға мүмкіндік беру -Comment[km]=អនុញ្ញាត​ឲ្យ​គ្រប់គ្រង​សម័យ​របស់ VNC តាមរយៈ KRDC -Comment[ko]=KRDC를 통해서 VNC 세션 관리하기 -Comment[lt]=Leidžia valdyti VNC sesijas per KRDC -Comment[lv]=Ļauj pārvaldīt VNC sesijas caur KRDC -Comment[nb]=Tillater å styre VNC-økter gjennom KRDC -Comment[nds]=VNC-Törns över KRDC plegen -Comment[nl]=Staat het beheer van VNC-sessies toe via KRDC -Comment[nn]=Lèt deg handtera VNC-økter gjennom KRDC -Comment[pa]=KRDC ਰਾਹੀਂ VNC ਸ਼ੈਸ਼ਨਾਂ ਦੇ ਪਰਬੰਧ ਦੀ ਮਨਜ਼ੂਰੀ -Comment[pl]=Pozwala na zarządzanie sesjami VNC przez KRDC -Comment[pt]=Permite a gestão de sessões VNC através do KRDC -Comment[pt_BR]=Permite o gerenciamento de sessões VNC através do KRDC -Comment[ro]=Permite gestiunea sesiunilor VNC prin KRDC -Comment[ru]=Разрешить управление сеансами VNC через KRDC -Comment[si]=KRDC හරහා VNC වාර පාලනයට ඉඩ දෙයි -Comment[sk]=Umožňuje spravovanie VNC sedení pomocou KRDC -Comment[sl]=Omogoča upravljanje sej VNC prek KRDC -Comment[sr]=Управљање ВНЦ сесијама кроз КРДЦ -Comment[sr@ijekavian]=Управљање ВНЦ сесијама кроз КРДЦ -Comment[sr@ijekavianlatin]=Upravljanje VNC sesijama kroz KRDC -Comment[sr@latin]=Upravljanje VNC sesijama kroz KRDC -Comment[sv]=Tillåter hantering av VNC-sessioner via KRDC -Comment[tr]=VNC oturumlarını KRDC üzerinden yönetmeye izin verir -Comment[uk]=Надає змогу керувати сеансами VNC за допомогою KRDC -Comment[x-test]=xxAllows managing VNC sessions through KRDCxx -Comment[zh_CN]=允许用户通过 KRDC 管理 VNC 会话 -Comment[zh_TW]=允許透過 KRDC 管理 VNC 工作階段 - -X-KDE-PluginInfo-Author=Urs Wolfer -X-KDE-PluginInfo-Email=uwolfer@kde.org -X-KDE-PluginInfo-Version=1.0 -X-KDE-PluginInfo-Category=Service -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-Library=krdc_vncplugin -X-KDE-PluginInfo-Name=krdc_vncplugin - -X-KDE-KRDC-Sorting=20 diff --git a/krdc/vnc/krdc_vnc_config.desktop b/krdc/vnc/krdc_vnc_config.desktop deleted file mode 100644 index 548f6486..00000000 --- a/krdc/vnc/krdc_vnc_config.desktop +++ /dev/null @@ -1,61 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule -Name=VNC -Name[ast]=VNC -Name[bg]=VNC -Name[bs]=VNC -Name[ca]=VNC -Name[ca@valencia]=VNC -Name[cs]=VNC -Name[da]=VNC -Name[de]=VNC -Name[el]=VNC -Name[en_GB]=VNC -Name[eo]=VNC -Name[es]=VNC -Name[et]=VNC -Name[eu]=VNC -Name[fi]=VNC -Name[fr]=VNC -Name[ga]=VNC -Name[gl]=VNC -Name[hr]=VNC -Name[hu]=VNC -Name[ia]=VNC -Name[is]=VNC -Name[it]=VNC -Name[ja]=VNC -Name[kk]=VNC -Name[km]=VNC -Name[ko]=VNC -Name[lt]=VNC -Name[lv]=VNC -Name[nb]=VNC -Name[nds]=VNC -Name[nl]=VNC -Name[nn]=VNC -Name[pa]=VNC -Name[pl]=VNC -Name[pt]=VNC -Name[pt_BR]=VNC -Name[ro]=VNC -Name[ru]=VNC -Name[si]=VNC -Name[sk]=VNC -Name[sl]=VNC -Name[sr]=ВНЦ -Name[sr@ijekavian]=ВНЦ -Name[sr@ijekavianlatin]=VNC -Name[sr@latin]=VNC -Name[sv]=VNC -Name[tr]=VNC -Name[ug]=VNC -Name[uk]=VNC -Name[wa]=VNC -Name[x-test]=xxVNCxx -Name[zh_CN]=VNC -Name[zh_TW]=VNC - -X-KDE-Library=kcm_krdc_vncplugin -X-KDE-ParentComponents=krdc_vncplugin diff --git a/krdc/vnc/qtonly/README b/krdc/vnc/qtonly/README deleted file mode 100644 index 51fa9943..00000000 --- a/krdc/vnc/qtonly/README +++ /dev/null @@ -1,30 +0,0 @@ -Qt-only version of the KRDC VNC backend -======================================= - -In order to build it, you need the LibVNCClient (LibVNCServer) -library (version 0.9.1 or newer required): - http://sourceforge.net/project/showfiles.php?group_id=32584&package_id=24717 - -The following files from KRDC are required: - krdc/core/remoteview.{cpp,h} - krdc/vnc/vncview.{cpp,h} - krdc/vnc/vncclientthread.{cpp,h} - krdc/vnc/qtonly/main.cpp - krdc/vnc/qtonly/krdc-vnc-qtonly.pro - -Copy these files into a folder and run: - qmake - make - -In order to try it out, type: - ./krdc-vnc-qtonly vnc://:password@server:1 1 - (the last argument defines the quality as second argument (1-3, where 1 is - the best). Default is 2.) - -If you use these code in your project, make sure that QTONLY is defined (see -krdc-vnc-qtonly.pro). - -IMPORTANT NOTICE -================ -If you do any fixes or improvements in these files, please backport them to the original sources. -Please send a patch with the changes to . Thanks a lot! diff --git a/krdc/vnc/qtonly/krdc-vnc-qtonly.pro b/krdc/vnc/qtonly/krdc-vnc-qtonly.pro deleted file mode 100644 index 20510e35..00000000 --- a/krdc/vnc/qtonly/krdc-vnc-qtonly.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . -LIBS += -lvncclient -lgnutls -DEFINES += QTONLY - -HEADERS += remoteview.h vncclientthread.h vncview.h -SOURCES += main.cpp remoteview.cpp vncclientthread.cpp vncview.cpp diff --git a/krdc/vnc/qtonly/main.cpp b/krdc/vnc/qtonly/main.cpp deleted file mode 100644 index bb753578..00000000 --- a/krdc/vnc/qtonly/main.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include - -#include "vncview.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - if (QCoreApplication::arguments().count() < 2) { - qFatal("Please define an URL as argument. Example: vnc://:password@server:1\n" - "Optionally, you can define the quality as second argument (1-3, where 1 is the best). Default is 2."); - return 1; - } - VncView vncView(0, QCoreApplication::arguments().at(1)); - vncView.show(); - vncView.start(); - return app.exec(); -} diff --git a/krdc/vnc/vnc.protocol b/krdc/vnc/vnc.protocol deleted file mode 100644 index e191ad7d..00000000 --- a/krdc/vnc/vnc.protocol +++ /dev/null @@ -1,10 +0,0 @@ -[Protocol] -exec=krdc '%u' -protocol=vnc -helper=true -listing=false -reading=false -writing=false -makedir=false -deleting=false -Icon=krdc diff --git a/krdc/vnc/vncclientthread.cpp b/krdc/vnc/vncclientthread.cpp deleted file mode 100644 index 838cbb00..00000000 --- a/krdc/vnc/vncclientthread.cpp +++ /dev/null @@ -1,663 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "vncclientthread.h" - -#include -#include -#include -#include -#include -#include -#include - -static thread_local VncClientThread ** instances; - -// Dispatch from this static callback context to the member context. -rfbBool VncClientThread::newclientStatic(rfbClient *cl) -{ - VncClientThread *t = (VncClientThread *)rfbClientGetClientData(cl, 0); - Q_ASSERT(t); - - return t->newclient(); -} - -// Dispatch from this static callback context to the member context. -void VncClientThread::updatefbStatic(rfbClient *cl, int x, int y, int w, int h) -{ - VncClientThread *t = (VncClientThread *)rfbClientGetClientData(cl, 0); - Q_ASSERT(t); - - return t->updatefb(x, y, w, h); -} - -// Dispatch from this static callback context to the member context. -void VncClientThread::cuttextStatic(rfbClient *cl, const char *text, int textlen) -{ - VncClientThread *t = (VncClientThread *)rfbClientGetClientData(cl, 0); - Q_ASSERT(t); - - t->cuttext(text, textlen); -} - -// Dispatch from this static callback context to the member context. -char *VncClientThread::passwdHandlerStatic(rfbClient *cl) -{ - VncClientThread *t = (VncClientThread *)rfbClientGetClientData(cl, 0); - Q_ASSERT(t); - - return t->passwdHandler(); -} - -// Dispatch from this static callback context to the member context. -rfbCredential *VncClientThread::credentialHandlerStatic(rfbClient *cl, int credentialType) -{ - VncClientThread *t = (VncClientThread *)rfbClientGetClientData(cl, 0); - Q_ASSERT(t); - - return t->credentialHandler(credentialType); -} - -// Dispatch from this static callback context to the member context. -void VncClientThread::outputHandlerStatic(const char *format, ...) -{ - VncClientThread **t = instances; - - va_list args; - va_start(args, format); - (*t)->outputHandler(format, args); - va_end(args); -} - -void VncClientThread::setClientColorDepth(rfbClient* cl, VncClientThread::ColorDepth cd) -{ - switch(cd) { - case bpp32: { - cl->format.depth = 24; - cl->format.bitsPerPixel = 32; - cl->format.redShift = 16; - cl->format.greenShift = 8; - cl->format.blueShift = 0; - cl->format.redMax = 0xff; - cl->format.greenMax = 0xff; - cl->format.blueMax = 0xff; - } - case bpp16: - default: { - cl->format.depth = 16; - cl->format.bitsPerPixel = 16; - cl->format.redShift = 11; - cl->format.greenShift = 5; - cl->format.blueShift = 0; - cl->format.redMax = 0x1f; - cl->format.greenMax = 0x3f; - cl->format.blueMax = 0x1f; - break; - } - } -} - -rfbBool VncClientThread::newclient() -{ - setClientColorDepth(cl, colorDepth()); - - const int width = cl->width, height = cl->height, depth = cl->format.bitsPerPixel; - const int size = width * height * (depth / 8); - if (frameBuffer) - delete [] frameBuffer; // do not leak if we get a new framebuffer size - frameBuffer = new uint8_t[size]; - cl->frameBuffer = frameBuffer; - memset(cl->frameBuffer, '\0', size); - - switch (quality()) { - case RemoteView::High: { - cl->appData.encodingsString = "copyrect zlib hextile raw"; - cl->appData.compressLevel = 0; - cl->appData.qualityLevel = 9; - break; - } - case RemoteView::Medium: { - cl->appData.encodingsString = "copyrect tight zrle ultra zlib hextile corre rre raw"; - cl->appData.compressLevel = 5; - cl->appData.qualityLevel = 7; - break; - } - case RemoteView::Low: - case RemoteView::Unknown: - default: { - cl->appData.encodingsString = "copyrect tight zrle ultra zlib hextile corre rre raw"; - cl->appData.compressLevel = 9; - cl->appData.qualityLevel = 1; - } - } - - SetFormatAndEncodings(cl); - kDebug(5011) << "Client created"; - return true; -} - -void VncClientThread::updatefb(int x, int y, int w, int h) -{ -// kDebug(5011) << "updated client: x: " << x << ", y: " << y << ", w: " << w << ", h: " << h; - - const int width = cl->width, height = cl->height; - QImage img; - switch(colorDepth()) { - case bpp16: - img = QImage(cl->frameBuffer, width, height, QImage::Format_RGB16); - break; - case bpp32: - img = QImage(cl->frameBuffer, width, height, QImage::Format_RGB32); - break; - } - - if (img.isNull()) { - kDebug(5011) << "image not loaded"; - } - - if (m_stopped) { - return; // sending data to a stopped thread is not a good idea - } - - setImage(img); - - emitUpdated(x, y, w, h); -} - -void VncClientThread::cuttext(const char *text, int textlen) -{ - const QString cutText = QString::fromUtf8(text, textlen); - kDebug(5011) << cutText; - - if (!cutText.isEmpty()) { - emitGotCut(cutText); - } -} - -char *VncClientThread::passwdHandler() -{ - kDebug(5011) << "password request"; - - // Never request a password during a reconnect attempt. - if (!m_keepalive.failed) { - passwordRequest(); - m_passwordError = true; - } - return strdup(m_password.toUtf8()); -} - -rfbCredential *VncClientThread::credentialHandler(int credentialType) -{ - kDebug(5011) << "credential request" << credentialType; - - rfbCredential *cred = 0; - - switch (credentialType) { - case rfbCredentialTypeUser: - passwordRequest(true); - m_passwordError = true; - - cred = new rfbCredential; - cred->userCredential.username = strdup(username().toUtf8()); - cred->userCredential.password = strdup(password().toUtf8()); - break; - default: - kError(5011) << "credential request failed, unspported credentialType:" << credentialType; - outputErrorMessage(i18n("VNC authentication type is not supported.")); - break; - } - return cred; -} - -void VncClientThread::outputHandler(const char *format, ...) -{ - va_list args; - va_start(args, format); - - QString message; - message.vsprintf(format, args); - - va_end(args); - - message = message.trimmed(); - - kDebug(5011) << message; - - if ((message.contains("Couldn't convert ")) || - (message.contains("Unable to connect to VNC server"))) { - // Don't show a dialog if a reconnection is needed. Never contemplate - // reconnection if we don't have a password. - QString tmp = i18n("Server not found."); - if (m_keepalive.set && !m_password.isNull()) { - m_keepalive.failed = true; - if (m_previousDetails != tmp) { - m_previousDetails = tmp; - clientStateChange(RemoteView::Disconnected, tmp); - } - } else { - outputErrorMessageString = tmp; - } - } - - // Process general authentication failures before more specific authentication - // failures. All authentication failures cancel any auto-reconnection that - // may be in progress. - if (message.contains("VNC connection failed: Authentication failed")) { - m_keepalive.failed = false; - outputErrorMessageString = i18n("VNC authentication failed."); - } - if ((message.contains("VNC connection failed: Authentication failed, too many tries")) || - (message.contains("VNC connection failed: Too many authentication failures"))) { - m_keepalive.failed = false; - outputErrorMessageString = i18n("VNC authentication failed because of too many authentication tries."); - } - - if (message.contains("VNC server closed connection")) - outputErrorMessageString = i18n("VNC server closed connection."); - - // If we are not going to attempt a reconnection, at least tell the user - // the connection went away. - if (message.contains("read (")) { - // Don't show a dialog if a reconnection is needed. Never contemplate - // reconnection if we don't have a password. - QString tmp = i18n("Disconnected: %1.", message); - if (m_keepalive.set && !m_password.isNull()) { - m_keepalive.failed = true; - clientStateChange(RemoteView::Disconnected, tmp); - } else { - outputErrorMessageString = tmp; - } - } - - // internal messages, not displayed to user - if (message.contains("VNC server supports protocol version 3.889")) // see http://bugs.kde.org/162640 - outputErrorMessageString = "INTERNAL:APPLE_VNC_COMPATIBILTY"; -} - -VncClientThread::VncClientThread(QObject *parent) - : QThread(parent) - , frameBuffer(0) - , cl(0) - , m_stopped(false) -{ - // We choose a small value for interval...after all if the connection is - // supposed to sustain a VNC session, a reasonably frequent ping should - // be perfectly supportable. - m_keepalive.intervalSeconds = 1; - m_keepalive.failedProbes = 3; - m_keepalive.set = false; - m_keepalive.failed = false; - m_previousDetails = QString(); - outputErrorMessageString.clear(); //don't deliver error messages of old instances... - QMutexLocker locker(&mutex); - - QTimer *outputErrorMessagesCheckTimer = new QTimer(this); - outputErrorMessagesCheckTimer->setInterval(500); - connect(outputErrorMessagesCheckTimer, SIGNAL(timeout()), this, SLOT(checkOutputErrorMessage())); - outputErrorMessagesCheckTimer->start(); -} - -VncClientThread::~VncClientThread() -{ - if(isRunning()) { - stop(); - terminate(); - const bool quitSuccess = wait(1000); - kDebug(5011) << "Attempting to stop in deconstructor, will crash if this fails:" << quitSuccess; - } - - clientDestroy(); - - delete [] frameBuffer; -} - -void VncClientThread::checkOutputErrorMessage() -{ - if (!outputErrorMessageString.isEmpty()) { - kDebug(5011) << outputErrorMessageString; - QString errorMessage = outputErrorMessageString; - outputErrorMessageString.clear(); - // show authentication failure error only after the 3rd unsuccessful try - if ((errorMessage != i18n("VNC authentication failed.")) || m_passwordError) - outputErrorMessage(errorMessage); - } -} - -void VncClientThread::setHost(const QString &host) -{ - QMutexLocker locker(&mutex); - m_host = host; -} - -void VncClientThread::setPort(int port) -{ - QMutexLocker locker(&mutex); - m_port = port; -} - -void VncClientThread::setQuality(RemoteView::Quality quality) -{ - m_quality = quality; - //set color depth dependent on quality - switch(quality) { - case RemoteView::High: - setColorDepth(bpp32); - break; - case RemoteView::Medium: - case RemoteView::Low: - default: - setColorDepth(bpp16); - } -} - -void VncClientThread::setColorDepth(ColorDepth colorDepth) -{ - m_colorDepth= colorDepth; -} - -RemoteView::Quality VncClientThread::quality() const -{ - return m_quality; -} - -VncClientThread::ColorDepth VncClientThread::colorDepth() const -{ - return m_colorDepth; -} - -void VncClientThread::setImage(const QImage &img) -{ - QMutexLocker locker(&mutex); - m_image = img; -} - -const QImage VncClientThread::image(int x, int y, int w, int h) -{ - QMutexLocker locker(&mutex); - - if (w == 0) // full image requested - return m_image; - else - return m_image.copy(x, y, w, h); -} - -void VncClientThread::emitUpdated(int x, int y, int w, int h) -{ - emit imageUpdated(x, y, w, h); -} - -void VncClientThread::emitGotCut(const QString &text) -{ - emit gotCut(text); -} - -void VncClientThread::stop() -{ - QMutexLocker locker(&mutex); - m_stopped = true; -} - -void VncClientThread::run() -{ - QMutexLocker locker(&mutex); - - VncClientThread **threadTls = new VncClientThread *(); - *threadTls = this; - instances = threadTls; - while (!m_stopped) { // try to connect as long as the server allows - locker.relock(); - m_passwordError = false; - locker.unlock(); - - if (clientCreate(false)) { - // The initial connection attempt worked! - break; - } - - locker.relock(); - if (m_passwordError) { - locker.unlock(); - // Try again. - continue; - } - - // The initial connection attempt failed, and not because of a - // password problem. Bail out. - m_stopped = true; - locker.unlock(); - } - - locker.relock(); - kDebug(5011) << "--------------------- Starting main VNC event loop ---------------------"; - while (!m_stopped) { - locker.unlock(); - const int i = WaitForMessage(cl, 500); - if (m_stopped || i < 0) { - break; - } - if (i) { - if (!HandleRFBServerMessage(cl)) { - if (m_keepalive.failed) { - do { - // Reconnect after a short delay. That way, if the - // attempt fails very quickly, we don't sit in a very - // tight loop. - clientDestroy(); - msleep(1000); - clientStateChange(RemoteView::Connecting, i18n("Reconnecting.")); - } while (!clientCreate(true)); - continue; - } - kError(5011) << "HandleRFBServerMessage failed"; - break; - } - } - - locker.relock(); - while (!m_eventQueue.isEmpty()) { - ClientEvent* clientEvent = m_eventQueue.dequeue(); - locker.unlock(); - clientEvent->fire(cl); - delete clientEvent; - locker.relock(); - } - } - - m_stopped = true; -} - -/** - * Factor out the initialisation of the VNC client library. Notice this has - * both static parts as in @see rfbClientLog and @see rfbClientErr, - * as well as instance local data @see rfbGetClient(). - * - * On return from here, if cl is set, the connection will have been made else - * cl will not be set. - */ -bool VncClientThread::clientCreate(bool reinitialising) -{ - rfbClientLog = outputHandlerStatic; - rfbClientErr = outputHandlerStatic; - - //24bit color dept in 32 bits per pixel = default. Will change colordepth and bpp later if needed - cl = rfbGetClient(8, 3, 4); - setClientColorDepth(cl, this->colorDepth()); - cl->MallocFrameBuffer = newclientStatic; - cl->canHandleNewFBSize = true; - cl->GetPassword = passwdHandlerStatic; - cl->GetCredential = credentialHandlerStatic; - cl->GotFrameBufferUpdate = updatefbStatic; - cl->GotXCutText = cuttextStatic; - rfbClientSetClientData(cl, 0, this); - - cl->serverHost = strdup(m_host.toUtf8().constData()); - - if (m_port < 0 || !m_port) // port is invalid or empty... - m_port = 5900; // fallback: try an often used VNC port - - if (m_port >= 0 && m_port < 100) // the user most likely used the short form (e.g. :1) - m_port += 5900; - cl->serverPort = m_port; - - kDebug(5011) << "--------------------- trying init ---------------------"; - - if (!rfbInitClient(cl, 0, 0)) { - if (!reinitialising) { - // Don't whine on reconnection failure: presumably the network - // is simply still down. - kError(5011) << "rfbInitClient failed"; - } - cl = 0; - return false; - } - - if (reinitialising) { - clientStateChange(RemoteView::Connected, i18n("Reconnected.")); - } else { - clientStateChange(RemoteView::Connected, i18n("Connected.")); - } - clientSetKeepalive(); - return true; -} - -/** - * Undo @see clientCreate(). - */ -void VncClientThread::clientDestroy() -{ - - if (cl) { - // Disconnect from vnc server & cleanup allocated resources - rfbClientCleanup(cl); - cl = 0; - } -} - -/** - * The VNC client library does not make use of keepalives. We go behind its - * back to set it up. - */ -void VncClientThread::clientSetKeepalive() -{ - // If keepalive is disabled, do nothing. - m_keepalive.set = false; - m_keepalive.failed = false; - if (!m_keepalive.intervalSeconds) { - return; - } - int optval; - socklen_t optlen = sizeof(optval); - - // Try to set the option active - optval = 1; - if (setsockopt(cl->sock, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) { - kError(5011) << "setsockopt(SO_KEEPALIVE)" << strerror(errno); - return; - } - - // TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT are introduced in Linux 2.4 - // however NetBSD for example also implements the options -#ifdef TCP_KEEPIDLE - optval = m_keepalive.intervalSeconds; - if (setsockopt(cl->sock, IPPROTO_TCP, TCP_KEEPIDLE, &optval, optlen) < 0) { - kError(5011) << "setsockopt(TCP_KEEPIDLE)" << strerror(errno); - return; - } -#endif - -#ifdef TCP_KEEPINTVL - optval = m_keepalive.intervalSeconds; - if (setsockopt(cl->sock, IPPROTO_TCP, TCP_KEEPINTVL, &optval, optlen) < 0) { - kError(5011) << "setsockopt(TCP_KEEPINTVL)" << strerror(errno); - return; - } -#endif - -#ifdef TCP_KEEPCNT - optval = m_keepalive.failedProbes; - if(setsockopt(cl->sock, IPPROTO_TCP, TCP_KEEPCNT, &optval, optlen) < 0) { - kError(5011) << "setsockopt(TCP_KEEPCNT)" << strerror(errno); - return; - } -#endif - - m_keepalive.set = true; - kDebug(5011) << "TCP keepalive set"; -} - -/** - * The VNC client state changed. - */ -void VncClientThread::clientStateChange(RemoteView::RemoteStatus status, const QString &details) -{ - kDebug(5011) << status << details << m_host << ":" << m_port; - emit clientStateChanged(status, details); -} - -ClientEvent::~ClientEvent() -{ -} - -void PointerClientEvent::fire(rfbClient* cl) -{ - SendPointerEvent(cl, m_x, m_y, m_buttonMask); -} - -void KeyClientEvent::fire(rfbClient* cl) -{ - SendKeyEvent(cl, m_key, m_pressed); -} - -void ClientCutEvent::fire(rfbClient* cl) -{ - SendClientCutText(cl, text.toUtf8().data(), text.size()); -} - -void VncClientThread::mouseEvent(int x, int y, int buttonMask) -{ - QMutexLocker lock(&mutex); - if (m_stopped) - return; - - m_eventQueue.enqueue(new PointerClientEvent(x, y, buttonMask)); -} - -void VncClientThread::keyEvent(int key, bool pressed) -{ - QMutexLocker lock(&mutex); - if (m_stopped) - return; - - m_eventQueue.enqueue(new KeyClientEvent(key, pressed)); -} - -void VncClientThread::clientCut(const QString &text) -{ - QMutexLocker lock(&mutex); - if (m_stopped) - return; - - m_eventQueue.enqueue(new ClientCutEvent(text)); -} - -#include "moc_vncclientthread.cpp" diff --git a/krdc/vnc/vncclientthread.h b/krdc/vnc/vncclientthread.h deleted file mode 100644 index c6008576..00000000 --- a/krdc/vnc/vncclientthread.h +++ /dev/null @@ -1,234 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef VNCCLIENTTHREAD_H -#define VNCCLIENTTHREAD_H - -#ifdef QTONLY - #include - #define kDebug(n) qDebug() - #define kError(n) qDebug() - #define kBacktrace() "" - #define i18n tr -#else - #include - #include -#endif - -#include "remoteview.h" - -#include -#include -#include -#include - -extern "C" { -#include -} - -class ClientEvent -{ -public: - virtual ~ClientEvent(); - - virtual void fire(rfbClient*) = 0; -}; - -class KeyClientEvent : public ClientEvent -{ -public: - KeyClientEvent(int key, int pressed) - : m_key(key), m_pressed(pressed) {} - - void fire(rfbClient*); - -private: - int m_key; - int m_pressed; -}; - -class PointerClientEvent : public ClientEvent -{ -public: - PointerClientEvent(int x, int y, int buttonMask) - : m_x(x), m_y(y), m_buttonMask(buttonMask) {} - - void fire(rfbClient*); - -private: - int m_x; - int m_y; - int m_buttonMask; -}; - -class ClientCutEvent : public ClientEvent -{ -public: - explicit ClientCutEvent(const QString &text) - : text(text) {} - - void fire(rfbClient*); - -private: - QString text; -}; - -class VncClientThread: public QThread -{ - Q_OBJECT - -public: - Q_ENUMS(ColorDepth) - - enum ColorDepth { - bpp32, - bpp16 - }; - - explicit VncClientThread(QObject *parent = 0); - ~VncClientThread(); - const QImage image(int x = 0, int y = 0, int w = 0, int h = 0); - void setImage(const QImage &img); - void emitUpdated(int x, int y, int w, int h); - void emitGotCut(const QString &text); - void stop(); - void setHost(const QString &host); - void setPort(int port); - void setQuality(RemoteView::Quality quality); - void setPassword(const QString &password) { - m_password = password; - } - const QString password() const { - return m_password; - } - void setUsername(const QString &username) { - m_username = username; - } - const QString username() const { - return m_username; - } - - RemoteView::Quality quality() const; - ColorDepth colorDepth() const; - uint8_t *frameBuffer; - -signals: - void imageUpdated(int x, int y, int w, int h); - void gotCut(const QString &text); - void passwordRequest(bool includingUsername = false); - void outputErrorMessage(const QString &message); - - /** - * When we connect/disconnect/reconnect/etc., this signal will be emitted. - * - * @param status Is the client connected? - * @param details A sentence describing what happened. - */ - void clientStateChanged(RemoteView::RemoteStatus status, const QString &details); - -public slots: - void mouseEvent(int x, int y, int buttonMask); - void keyEvent(int key, bool pressed); - void clientCut(const QString &text); - -protected: - void run(); - -private: - void setClientColorDepth(rfbClient *cl, ColorDepth cd); - void setColorDepth(ColorDepth colorDepth); - - // These static methods are callback functions for libvncclient. Each - // of them calls back into the corresponding member function via some - // TLS-based logic. - static rfbBool newclientStatic(rfbClient *cl); - static void updatefbStatic(rfbClient *cl, int x, int y, int w, int h); - static void cuttextStatic(rfbClient *cl, const char *text, int textlen); - static char *passwdHandlerStatic(rfbClient *cl); - static rfbCredential *credentialHandlerStatic(rfbClient *cl, int credentialType); - static void outputHandlerStatic(const char *format, ...); - - // Member functions corresponding to the above static methods. - rfbBool newclient(); - void updatefb(int x, int y, int w, int h); - void cuttext(const char *text, int textlen); - char *passwdHandler(); - rfbCredential *credentialHandler(int credentialType); - void outputHandler(const char *format, ...); - - QImage m_image; - rfbClient *cl; - QString m_host; - QString m_password; - QString m_username; - int m_port; - QMutex mutex; - RemoteView::Quality m_quality; - ColorDepth m_colorDepth; - QQueue m_eventQueue; - QString outputErrorMessageString; - - volatile bool m_stopped; - volatile bool m_passwordError; - - /** - * Connection keepalive/reconnection support. - */ - struct { - /** - * Number of seconds between probes. If zero, we will not attempt - * to enable it. - */ - int intervalSeconds; - /** - * Number of failed probes required to recognise a disconnect. - */ - int failedProbes; - /** - * Was keepalive successfully set? - */ - bool set; - /** - * Did keepalive detect a disconnect? - */ - volatile bool failed; - } m_keepalive; - - // Initialise the VNC client library object. - bool clientCreate(bool reinitialising); - - // Uninitialise the VNC client library object. - void clientDestroy(); - - // Turn on keepalive support. - void clientSetKeepalive(); - - // Record a state change. - void clientStateChange(RemoteView::RemoteStatus status, const QString &details); - QString m_previousDetails; - -private slots: - void checkOutputErrorMessage(); -}; - -#endif diff --git a/krdc/vnc/vnchostpreferences.cpp b/krdc/vnc/vnchostpreferences.cpp deleted file mode 100644 index 25b55375..00000000 --- a/krdc/vnc/vnchostpreferences.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "vnchostpreferences.h" - -#include "settings.h" - -#include - -#include - -VncHostPreferences::VncHostPreferences(KConfigGroup configGroup, QObject *parent) - : HostPreferences(configGroup, parent) -{ -} - -VncHostPreferences::~VncHostPreferences() -{ -} - -QWidget* VncHostPreferences::createProtocolSpecificConfigPage() -{ - QWidget *vncPage = new QWidget(); - vncUi.setupUi(vncPage); - - vncUi.kcfg_Quality->setCurrentIndex(quality() - 1); - vncUi.kcfg_Scaling->setChecked(windowedScale()); - vncUi.kcfg_ScalingWidth->setValue(width()); - vncUi.kcfg_ScalingHeight->setValue(height()); - - connect(vncUi.resolutionComboBox, SIGNAL(currentIndexChanged(int)), SLOT(updateScalingWidthHeight(int))); - connect(vncUi.kcfg_Scaling, SIGNAL(toggled(bool)), SLOT(updateScaling(bool))); - - const QString resolutionString = QString::number(width()) + 'x' + QString::number(height()); - const int resolutionIndex = vncUi.resolutionComboBox->findText(resolutionString, Qt::MatchContains); - vncUi.resolutionComboBox->setCurrentIndex((resolutionIndex == -1) ? vncUi.resolutionComboBox->count() - 1 : resolutionIndex); - - updateScaling(windowedScale()); - - return vncPage; -} - -void VncHostPreferences::updateScalingWidthHeight(int index) -{ - switch (index) { - case 0: - vncUi.kcfg_ScalingHeight->setValue(480); - vncUi.kcfg_ScalingWidth->setValue(640); - break; - case 1: - vncUi.kcfg_ScalingHeight->setValue(600); - vncUi.kcfg_ScalingWidth->setValue(800); - break; - case 2: - vncUi.kcfg_ScalingHeight->setValue(768); - vncUi.kcfg_ScalingWidth->setValue(1024); - break; - case 3: - vncUi.kcfg_ScalingHeight->setValue(1024); - vncUi.kcfg_ScalingWidth->setValue(1280); - break; - case 4: - vncUi.kcfg_ScalingHeight->setValue(1200); - vncUi.kcfg_ScalingWidth->setValue(1600); - break; - case 5: { - QDesktopWidget *desktop = QApplication::desktop(); - int currentScreen = desktop->screenNumber(vncUi.kcfg_ScalingHeight); - vncUi.kcfg_ScalingHeight->setValue(desktop->screenGeometry(currentScreen).height()); - vncUi.kcfg_ScalingWidth->setValue(desktop->screenGeometry(currentScreen).width()); - break; - } - case 6: - default: - break; - } - - checkEnableCustomSize(index); -} - -void VncHostPreferences::updateScaling(bool enabled) -{ - vncUi.resolutionComboBox->setEnabled(enabled); - if(enabled) { - checkEnableCustomSize(vncUi.resolutionComboBox->currentIndex()); - } else { - checkEnableCustomSize(-1); - } -} - -void VncHostPreferences::checkEnableCustomSize(int index) -{ - const bool enabled = (index == 6); - - vncUi.kcfg_ScalingHeight->setEnabled(enabled); - vncUi.kcfg_ScalingWidth->setEnabled(enabled); - vncUi.heightLabel->setEnabled(enabled); - vncUi.widthLabel->setEnabled(enabled); -} - -void VncHostPreferences::acceptConfig() -{ - HostPreferences::acceptConfig(); - setQuality((RemoteView::Quality)(vncUi.kcfg_Quality->currentIndex() + 1)); - setWindowedScale(vncUi.kcfg_Scaling->isChecked()); - if(vncUi.kcfg_Scaling->isChecked()) { - setHeight(vncUi.kcfg_ScalingHeight->value()); - setWidth(vncUi.kcfg_ScalingWidth->value()); - } -} - -void VncHostPreferences::setQuality(RemoteView::Quality quality) -{ - if (quality >= 0 && quality <= 3) - m_configGroup.writeEntry("quality", (int) quality); -} - -RemoteView::Quality VncHostPreferences::quality() -{ - return (RemoteView::Quality) m_configGroup.readEntry("quality", (int) Settings::quality() + 1); -} - -#include "moc_vnchostpreferences.cpp" diff --git a/krdc/vnc/vnchostpreferences.h b/krdc/vnc/vnchostpreferences.h deleted file mode 100644 index 4ff100b3..00000000 --- a/krdc/vnc/vnchostpreferences.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef VNCHOSTPREFERENCES_H -#define VNCHOSTPREFERENCES_H - -#include "hostpreferences.h" -#include "ui_vncpreferences.h" - -class VncHostPreferences : public HostPreferences -{ - Q_OBJECT - -public: - explicit VncHostPreferences(KConfigGroup configGroup, QObject *parent = 0); - ~VncHostPreferences(); - - void setQuality(RemoteView::Quality quality); - RemoteView::Quality quality(); - -protected: - void acceptConfig(); - - virtual QWidget* createProtocolSpecificConfigPage(); - -private: - Ui::VncPreferences vncUi; - void checkEnableCustomSize(int index); - -private slots: - void updateScalingWidthHeight(int index); - void updateScaling(bool enabled); -}; - -#endif diff --git a/krdc/vnc/vncpreferences.cpp b/krdc/vnc/vncpreferences.cpp deleted file mode 100644 index dff0646e..00000000 --- a/krdc/vnc/vncpreferences.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "vncpreferences.h" -#include "remoteviewfactory.h" -#include "settings.h" - -#include "ui_vncpreferences.h" - -#include - -KRDC_PLUGIN_EXPORT(VncPreferences) - -VncPreferences::VncPreferences(QWidget *parent, const QVariantList &args) - : KCModule(KrdcFactory::componentData(), parent, args) -{ - Ui::VncPreferences vncUi; - vncUi.setupUi(this); - - // copying the RDP preferences... need to create generic code for the plugins. - vncUi.resolutionDummyLabel->hide(); - vncUi.resolutionComboBox->hide(); - vncUi.kcfg_ScalingHeight->setEnabled(true); - vncUi.kcfg_ScalingWidth->setEnabled(true); - vncUi.heightLabel->setEnabled(true); - vncUi.widthLabel->setEnabled(true); - - addConfig(Settings::self(), this); -} - -VncPreferences::~VncPreferences() -{ -} - -void VncPreferences::load() -{ - KCModule::load(); -} - -void VncPreferences::save() -{ - KCModule::save(); -} - -#include "moc_vncpreferences.cpp" diff --git a/krdc/vnc/vncpreferences.h b/krdc/vnc/vncpreferences.h deleted file mode 100644 index 54923f8f..00000000 --- a/krdc/vnc/vncpreferences.h +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef VNCPREFERENCES_H -#define VNCPREFERENCES_H - -#include "vnchostpreferences.h" - -#include - -class VncPreferences : public KCModule -{ - Q_OBJECT - -public: - explicit VncPreferences(QWidget *parent = 0, const QVariantList &args = QVariantList()); - ~VncPreferences(); - - virtual void save(); - virtual void load(); - -}; - -#endif // VNCPREFERENCES_H diff --git a/krdc/vnc/vncpreferences.ui b/krdc/vnc/vncpreferences.ui deleted file mode 100644 index 11950fbf..00000000 --- a/krdc/vnc/vncpreferences.ui +++ /dev/null @@ -1,224 +0,0 @@ - - - VncPreferences - - - - 0 - 0 - 436 - 151 - - - - - - - Connection - - - - - - Connection type: - - - kcfg_Quality - - - - - - - - 280 - 0 - - - - Use this to specify the performance of your connection. Note that you should select the speed of the weakest link - even if you have a high speed connection, it will not help you if the remote computer uses a slow modem. Choosing a level of quality that is too high on a slow link will cause slower response times. Choosing a lower quality will increase latencies in high speed connections and results in lower image quality, especially in 'Low Quality' mode. - - - - High Quality (LAN, direct connection) - - - - - Medium Quality (DSL, Cable, fast Internet) - - - - - Low Quality (Modem, ISDN, slow Internet) - - - - - - - - - - Scale to Size: - - - - - - - - - - - - - - false - - - - 280 - 0 - - - - Here you can specify the resolution of the remote desktop. This resolution determines the size of the desktop that will be presented to you. - - - 1 - - - - Minimal (640x480) - - - - - Small (800x600) - - - - - Normal (1024x768) - - - - - Large (1280x1024) - - - - - Very Large (1600x1200) - - - - - Current Screen Resolution - - - - - Custom Resolution (...) - - - - - - - - - - false - - - &Width: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - kcfg_ScalingWidth - - - - - - - false - - - This is the width of the remote desktop. You can only change this value manually if you select Custom as desktop resolution above. - - - 9999 - - - 800 - - - - - - - false - - - H&eight: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - kcfg_ScalingHeight - - - - - - - false - - - This is the height of the remote desktop. You can only change this value manually if you select Custom as desktop resolution above. - - - 9999 - - - 600 - - - - - - - - - - - - - - Qt::Vertical - - - - 428 - 16 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
-
- -
diff --git a/krdc/vnc/vncview.cpp b/krdc/vnc/vncview.cpp deleted file mode 100644 index 1c9df5bf..00000000 --- a/krdc/vnc/vncview.cpp +++ /dev/null @@ -1,615 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "vncview.h" - -#include -#include -#include -#include - -#ifdef QTONLY - #include - #include - #define KMessageBox QMessageBox - #define error(parent, message, caption) \ - critical(parent, caption, message) -#else - #include "settings.h" - #include - #include - #include - #include - #include -#endif - -// Definition of key modifier mask constants -#define KMOD_Alt_R 0x01 -#define KMOD_Alt_L 0x02 -#define KMOD_Meta_L 0x04 -#define KMOD_Control_L 0x08 -#define KMOD_Shift_L 0x10 - -VncView::VncView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) - : RemoteView(parent), - m_initDone(false), - m_buttonMask(0), - m_repaint(false), - m_quitFlag(false), - m_firstPasswordTry(true), - m_dontSendClipboard(false), - m_horizontalFactor(1.0), - m_verticalFactor(1.0), - m_forceLocalCursor(false) -{ - m_url = url; - m_host = url.host(); - m_port = url.port(); - - // BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting() - connect(&vncThread, SIGNAL(imageUpdated(int,int,int,int)), this, SLOT(updateImage(int,int,int,int)), Qt::BlockingQueuedConnection); - connect(&vncThread, SIGNAL(gotCut(QString)), this, SLOT(setCut(QString)), Qt::BlockingQueuedConnection); - connect(&vncThread, SIGNAL(passwordRequest(bool)), this, SLOT(requestPassword(bool)), Qt::BlockingQueuedConnection); - connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString))); - - m_clipboard = QApplication::clipboard(); - connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); - -#ifndef QTONLY - m_hostPreferences = new VncHostPreferences(configGroup, this); -#else - Q_UNUSED(configGroup); -#endif -} - -VncView::~VncView() -{ - if (!m_quitFlag) startQuitting(); -} - -bool VncView::eventFilter(QObject *obj, QEvent *event) -{ - if (m_viewOnly) { - if (event->type() == QEvent::KeyPress || - event->type() == QEvent::KeyRelease || - event->type() == QEvent::MouseButtonDblClick || - event->type() == QEvent::MouseButtonPress || - event->type() == QEvent::MouseButtonRelease || - event->type() == QEvent::Wheel || - event->type() == QEvent::MouseMove) - return true; - } - - return RemoteView::eventFilter(obj, event); -} - -QSize VncView::framebufferSize() -{ - return m_frame.size(); -} - -QSize VncView::sizeHint() const -{ - return size(); -} - -QSize VncView::minimumSizeHint() const -{ - return size(); -} - -void VncView::scaleResize(int w, int h) -{ - RemoteView::scaleResize(w, h); - - kDebug(5011) << w << h; - if (m_scale) { - m_verticalFactor = (qreal) h / m_frame.height(); - m_horizontalFactor = (qreal) w / m_frame.width(); - -#ifndef QTONLY - if (Settings::keepAspectRatio()) { - m_verticalFactor = m_horizontalFactor = qMin(m_verticalFactor, m_horizontalFactor); - } -#else - m_verticalFactor = m_horizontalFactor = qMin(m_verticalFactor, m_horizontalFactor); -#endif - - const qreal newW = m_frame.width() * m_horizontalFactor; - const qreal newH = m_frame.height() * m_verticalFactor; - setMaximumSize(newW, newH); //This is a hack to force Qt to center the view in the scroll area - resize(newW, newH); - } -} - -void VncView::updateConfiguration() -{ - RemoteView::updateConfiguration(); - - // Update the scaling mode in case KeepAspectRatio changed - scaleResize(parentWidget()->width(), parentWidget()->height()); -} - -void VncView::startQuitting() -{ - kDebug(5011) << "about to quit"; - - setStatus(Disconnecting); - - m_quitFlag = true; - - vncThread.stop(); - - unpressModifiers(); - - // Disconnect all signals so that we don't get any more callbacks from the client thread - vncThread.disconnect(); - - vncThread.quit(); - - const bool quitSuccess = vncThread.wait(500); - if (!quitSuccess) { - // happens when vncThread wants to call a slot via BlockingQueuedConnection, - // needs an event loop in this thread so execution continues after 'emit' - QEventLoop loop; - if (!loop.processEvents()) { - kDebug(5011) << "BUG: deadlocked, but no events to deliver?"; - } - vncThread.wait(500); - } - - kDebug(5011) << "Quit VNC thread success:" << quitSuccess; - - setStatus(Disconnected); -} - -bool VncView::isQuitting() -{ - return m_quitFlag; -} - -bool VncView::start() -{ - vncThread.setHost(m_host); - vncThread.setPort(m_port); - RemoteView::Quality quality; -#ifdef QTONLY - quality = (RemoteView::Quality)((QCoreApplication::arguments().count() > 2) ? - QCoreApplication::arguments().at(2).toInt() : 2); -#else - quality = m_hostPreferences->quality(); -#endif - - vncThread.setQuality(quality); - - // set local cursor on by default because low quality mostly means slow internet connection - if (quality == RemoteView::Low) { - showDotCursor(RemoteView::CursorOn); -#ifndef QTONLY - // KRDC does always just have one main window, so at(0) is safe - KXMLGUIClient *mainWindow = dynamic_cast(KMainWindow::memberList().at(0)); - if (mainWindow) - mainWindow->actionCollection()->action("show_local_cursor")->setChecked(true); -#endif - } - - setStatus(Connecting); - - vncThread.start(); - return true; -} - -bool VncView::supportsScaling() const -{ - return true; -} - -bool VncView::supportsLocalCursor() const -{ - return true; -} - -void VncView::requestPassword(bool includingUsername) -{ - kDebug(5011) << "request password"; - - setStatus(Authenticating); - - if (m_firstPasswordTry && !m_url.userName().isNull()) { - vncThread.setUsername(m_url.userName()); - } - -#ifndef QTONLY - // just try to get the passwort from the wallet the first time, otherwise it will loop (see issue #226283) - if (m_firstPasswordTry && m_hostPreferences->walletSupport()) { - QString walletPassword = readWalletPassword(); - - if (!walletPassword.isNull()) { - vncThread.setPassword(walletPassword); - m_firstPasswordTry = false; - return; - } - } -#endif - - if (m_firstPasswordTry && !m_url.password().isNull()) { - vncThread.setPassword(m_url.password()); - m_firstPasswordTry = false; - return; - } - -#ifdef QTONLY - bool ok; - if (includingUsername) { - QString username = QInputDialog::getText(this, //krazy:exclude=qclasses (code not used in kde build) - tr("Username required"), - tr("Please enter the username for the remote desktop:"), - QLineEdit::Normal, m_url.userName(), &ok); //krazy:exclude=qclasses - if (ok) - vncThread.setUsername(username); - else - startQuitting(); - } - - QString password = QInputDialog::getText(this, //krazy:exclude=qclasses - tr("Password required"), - tr("Please enter the password for the remote desktop:"), - QLineEdit::Password, QString(), &ok); //krazy:exclude=qclasses - m_firstPasswordTry = false; - if (ok) - vncThread.setPassword(password); - else - startQuitting(); -#else - KPasswordDialog dialog(this, includingUsername ? KPasswordDialog::ShowUsernameLine : KPasswordDialog::NoFlags); - dialog.setPrompt(m_firstPasswordTry ? i18n("Access to the system requires a password.") - : i18n("Authentication failed. Please try again.")); - if (includingUsername) dialog.setUsername(m_url.userName()); - if (dialog.exec() == KPasswordDialog::Accepted) { - m_firstPasswordTry = false; - vncThread.setPassword(dialog.password()); - if (includingUsername) vncThread.setUsername(dialog.username()); - } else { - kDebug(5011) << "password dialog not accepted"; - startQuitting(); - } -#endif -} - -void VncView::outputErrorMessage(const QString &message) -{ - kDebug(5011) << message; - - if (message == "INTERNAL:APPLE_VNC_COMPATIBILTY") { - setCursor(localDotCursor()); - m_forceLocalCursor = true; - return; - } - - startQuitting(); - - KMessageBox::error(this, message, i18n("VNC failure")); - - emit errorMessage(i18n("VNC failure"), message); -} - -#ifndef QTONLY -HostPreferences* VncView::hostPreferences() -{ - return m_hostPreferences; -} -#endif - -void VncView::updateImage(int x, int y, int w, int h) -{ -// kDebug(5011) << "got update" << width() << height(); - - m_x = x; - m_y = y; - m_w = w; - m_h = h; - - if (m_horizontalFactor != 1.0 || m_verticalFactor != 1.0) { - // If the view is scaled, grow the update rectangle to avoid artifacts - m_x-=1; - m_y-=1; - m_w+=2; - m_h+=2; - } - - m_frame = vncThread.image(); - - if (!m_initDone) { - if (!vncThread.username().isEmpty()) { - m_url.setUserName(vncThread.username()); - } - setAttribute(Qt::WA_OpaquePaintEvent); - installEventFilter(this); - - setCursor(((m_dotCursorState == CursorOn) || m_forceLocalCursor) ? localDotCursor() : Qt::BlankCursor); - - setMouseTracking(true); // get mouse events even when there is no mousebutton pressed - setFocusPolicy(Qt::WheelFocus); - setStatus(Connected); - emit connected(); - - if (m_scale) { -#ifndef QTONLY - kDebug(5011) << "Setting initial size w:" <width() << " h:" << m_hostPreferences->height(); - emit framebufferSizeChanged(m_hostPreferences->width(), m_hostPreferences->height()); - scaleResize(m_hostPreferences->width(), m_hostPreferences->height()); - kDebug() << "m_frame.size():" << m_frame.size() << "size()" << size(); -#else -//TODO: qtonly alternative -#endif - } - - m_initDone = true; - -#ifndef QTONLY - if (m_hostPreferences->walletSupport()) { - saveWalletPassword(vncThread.password()); - } -#endif - } - - if ((y == 0 && x == 0) && (m_frame.size() != size())) { - kDebug(5011) << "Updating framebuffer size"; - if (m_scale) { - setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); - if (parentWidget()) - scaleResize(parentWidget()->width(), parentWidget()->height()); - } else { - kDebug(5011) << "Resizing: " << m_frame.width() << m_frame.height(); - resize(m_frame.width(), m_frame.height()); - setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area - setMinimumSize(m_frame.width(), m_frame.height()); - emit framebufferSizeChanged(m_frame.width(), m_frame.height()); - } - } - - m_repaint = true; - repaint(qRound(m_x * m_horizontalFactor), qRound(m_y * m_verticalFactor), qRound(m_w * m_horizontalFactor), qRound(m_h * m_verticalFactor)); - m_repaint = false; -} - -void VncView::setViewOnly(bool viewOnly) -{ - RemoteView::setViewOnly(viewOnly); - - m_dontSendClipboard = viewOnly; - - if (viewOnly) - setCursor(Qt::ArrowCursor); - else - setCursor(m_dotCursorState == CursorOn ? localDotCursor() : Qt::BlankCursor); -} - -void VncView::showDotCursor(DotCursorState state) -{ - RemoteView::showDotCursor(state); - - setCursor(state == CursorOn ? localDotCursor() : Qt::BlankCursor); -} - -void VncView::enableScaling(bool scale) -{ - RemoteView::enableScaling(scale); - - if (scale) { - setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); - setMinimumSize(1, 1); - if (parentWidget()) - scaleResize(parentWidget()->width(), parentWidget()->height()); - } else { - m_verticalFactor = 1.0; - m_horizontalFactor = 1.0; - - setMaximumSize(m_frame.width(), m_frame.height()); //This is a hack to force Qt to center the view in the scroll area - setMinimumSize(m_frame.width(), m_frame.height()); - resize(m_frame.width(), m_frame.height()); - } -} - -void VncView::setCut(const QString &text) -{ - m_dontSendClipboard = true; - m_clipboard->setText(text, QClipboard::Clipboard); - m_dontSendClipboard = false; -} - -void VncView::paintEvent(QPaintEvent *event) -{ -// kDebug(5011) << "paint event: x: " << m_x << ", y: " << m_y << ", w: " << m_w << ", h: " << m_h; - if (m_frame.isNull() || m_frame.format() == QImage::Format_Invalid) { - kDebug(5011) << "no valid image to paint"; - RemoteView::paintEvent(event); - return; - } - - event->accept(); - - QPainter painter(this); - - if (m_repaint) { -// kDebug(5011) << "normal repaint"; - painter.drawImage(QRect(qRound(m_x*m_horizontalFactor), qRound(m_y*m_verticalFactor), - qRound(m_w*m_horizontalFactor), qRound(m_h*m_verticalFactor)), - m_frame.copy(m_x, m_y, m_w, m_h).scaled(qRound(m_w*m_horizontalFactor), - qRound(m_h*m_verticalFactor), - Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - } else { -// kDebug(5011) << "resize repaint"; - QRect rect = event->rect(); - if (rect.width() != width() || rect.height() != height()) { -// kDebug(5011) << "Partial repaint"; - const int sx = rect.x()/m_horizontalFactor; - const int sy = rect.y()/m_verticalFactor; - const int sw = rect.width()/m_horizontalFactor; - const int sh = rect.height()/m_verticalFactor; - painter.drawImage(rect, - m_frame.copy(sx, sy, sw, sh).scaled(rect.width(), rect.height(), - Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - } else { -// kDebug(5011) << "Full repaint" << width() << height() << m_frame.width() << m_frame.height(); - painter.drawImage(QRect(0, 0, width(), height()), - m_frame.scaled(m_frame.width() * m_horizontalFactor, m_frame.height() * m_verticalFactor, - Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - } - } - - RemoteView::paintEvent(event); -} - -void VncView::resizeEvent(QResizeEvent *event) -{ - RemoteView::resizeEvent(event); - update(); -} - -bool VncView::event(QEvent *event) -{ - switch (event->type()) { - case QEvent::KeyPress: - case QEvent::KeyRelease: -// kDebug(5011) << "keyEvent"; - keyEventHandler(static_cast(event)); - return true; - break; - case QEvent::MouseButtonDblClick: - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseMove: -// kDebug(5011) << "mouseEvent"; - mouseEventHandler(static_cast(event)); - return true; - break; - case QEvent::Wheel: -// kDebug(5011) << "wheelEvent"; - wheelEventHandler(static_cast(event)); - return true; - break; - default: - return RemoteView::event(event); - } -} - -void VncView::mouseEventHandler(QMouseEvent *e) -{ - if (e->type() != QEvent::MouseMove) { - if ((e->type() == QEvent::MouseButtonPress) || - (e->type() == QEvent::MouseButtonDblClick)) { - if (e->button() & Qt::LeftButton) - m_buttonMask |= 0x01; - if (e->button() & Qt::MiddleButton) - m_buttonMask |= 0x02; - if (e->button() & Qt::RightButton) - m_buttonMask |= 0x04; - } else if (e->type() == QEvent::MouseButtonRelease) { - if (e->button() & Qt::LeftButton) - m_buttonMask &= 0xfe; - if (e->button() & Qt::MiddleButton) - m_buttonMask &= 0xfd; - if (e->button() & Qt::RightButton) - m_buttonMask &= 0xfb; - } - } - - vncThread.mouseEvent(qRound(e->x() / m_horizontalFactor), qRound(e->y() / m_verticalFactor), m_buttonMask); -} - -void VncView::wheelEventHandler(QWheelEvent *event) -{ - int eb = 0; - if (event->delta() < 0) - eb |= 0x10; - else - eb |= 0x8; - - const int x = qRound(event->x() / m_horizontalFactor); - const int y = qRound(event->y() / m_verticalFactor); - - vncThread.mouseEvent(x, y, eb | m_buttonMask); - vncThread.mouseEvent(x, y, m_buttonMask); -} - -void VncView::keyEventHandler(QKeyEvent *e) -{ - // strip away autorepeating KeyRelease; see bug #206598 - if (e->isAutoRepeat() && (e->type() == QEvent::KeyRelease)) - return; - -// parts of this code are based on http://italc.sourcearchive.com/documentation/1.0.9.1/vncview_8cpp-source.html - rfbKeySym k = e->nativeVirtualKey(); - - // we do not handle Key_Backtab separately as the Shift-modifier - // is already enabled - if (e->key() == Qt::Key_Backtab) { - k = XK_Tab; - } - - const bool pressed = (e->type() == QEvent::KeyPress); - - // handle modifiers - if (k == XK_Shift_L || k == XK_Control_L || k == XK_Meta_L || k == XK_Alt_L) { - if (pressed) { - m_mods[k] = true; - } else if (m_mods.contains(k)) { - m_mods.remove(k); - } else { - unpressModifiers(); - } - } - - if (k) { - vncThread.keyEvent(k, pressed); - } -} - -void VncView::unpressModifiers() -{ - const QList keys = m_mods.keys(); - QList::const_iterator it = keys.constBegin(); - while (it != keys.end()) { - vncThread.keyEvent(*it, false); - it++; - } - m_mods.clear(); -} - -void VncView::clipboardDataChanged() -{ - kDebug(5011); - - if (m_status != Connected) - return; - - if (m_clipboard->ownsClipboard() || m_dontSendClipboard) - return; - - const QString text = m_clipboard->text(QClipboard::Clipboard); - - vncThread.clientCut(text); -} - -#include "moc_vncview.cpp" diff --git a/krdc/vnc/vncview.h b/krdc/vnc/vncview.h deleted file mode 100644 index 2cf72f22..00000000 --- a/krdc/vnc/vncview.h +++ /dev/null @@ -1,110 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2007 - 2013 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef VNCVIEW_H -#define VNCVIEW_H - -#include "remoteview.h" -#include "vncclientthread.h" - -#ifdef QTONLY - class KConfigGroup{}; -#else - #include "vnchostpreferences.h" -#endif - -#include - -extern "C" { -#include -} - -class VncView: public RemoteView -{ - Q_OBJECT - -public: - explicit VncView(QWidget *parent = 0, const KUrl &url = KUrl(), KConfigGroup configGroup = KConfigGroup()); - ~VncView(); - - QSize framebufferSize(); - QSize sizeHint() const; - QSize minimumSizeHint() const; - void startQuitting(); - bool isQuitting(); - bool start(); - bool supportsScaling() const; - bool supportsLocalCursor() const; - -#ifndef QTONLY - HostPreferences* hostPreferences(); -#endif - - void setViewOnly(bool viewOnly); - void showDotCursor(DotCursorState state); - void enableScaling(bool scale); - - virtual void updateConfiguration(); - -public slots: - void scaleResize(int w, int h); - -protected: - void paintEvent(QPaintEvent *event); - bool event(QEvent *event); - void resizeEvent(QResizeEvent *event); - bool eventFilter(QObject *obj, QEvent *event); - -private: - VncClientThread vncThread; - QClipboard *m_clipboard; - bool m_initDone; - int m_buttonMask; - QMap m_mods; - int m_x, m_y, m_w, m_h; - bool m_repaint; - bool m_quitFlag; - bool m_firstPasswordTry; - bool m_dontSendClipboard; - qreal m_horizontalFactor; - qreal m_verticalFactor; -#ifndef QTONLY - VncHostPreferences *m_hostPreferences; -#endif - QImage m_frame; - bool m_forceLocalCursor; - - void keyEventHandler(QKeyEvent *e); - void unpressModifiers(); - void wheelEventHandler(QWheelEvent *event); - void mouseEventHandler(QMouseEvent *event); - -private slots: - void updateImage(int x, int y, int w, int h); - void setCut(const QString &text); - void requestPassword(bool includingUsername); - void outputErrorMessage(const QString &message); - void clipboardDataChanged(); -}; - -#endif diff --git a/krdc/vnc/vncviewfactory.cpp b/krdc/vnc/vncviewfactory.cpp deleted file mode 100644 index 91e37388..00000000 --- a/krdc/vnc/vncviewfactory.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#include "vncviewfactory.h" - -#include - -KRDC_PLUGIN_EXPORT(VncViewFactory) - -VncViewFactory::VncViewFactory(QObject *parent, const QVariantList &args) - : RemoteViewFactory(parent) -{ - Q_UNUSED(args); - - KGlobal::locale()->insertCatalog("krdc"); -} - -VncViewFactory::~VncViewFactory() -{ -} - -bool VncViewFactory::supportsUrl(const KUrl &url) const -{ - const QString urlscheme = url.scheme(); - return (urlscheme.compare("vnc", Qt::CaseInsensitive) == 0 || urlscheme.compare("rfb", Qt::CaseInsensitive) == 0); -} - -RemoteView *VncViewFactory::createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup) -{ - return new VncView(parent, url, configGroup); -} - -HostPreferences *VncViewFactory::createHostPreferences(KConfigGroup configGroup, QWidget *parent) -{ - return new VncHostPreferences(configGroup, parent); -} - -QString VncViewFactory::scheme() const -{ - return "vnc"; -} - -QString VncViewFactory::connectActionText() const -{ - return i18n("New VNC Connection..."); -} - -QString VncViewFactory::connectButtonText() const -{ - return i18n("Connect to a VNC Remote Desktop"); -} - -QString VncViewFactory::connectToolTipText() const -{ - return i18n("Enter the address here.
" - "Example: vncserver:1 (host:port / screen)"); -} - -#include "moc_vncviewfactory.cpp" diff --git a/krdc/vnc/vncviewfactory.h b/krdc/vnc/vncviewfactory.h deleted file mode 100644 index 8fd2bbb9..00000000 --- a/krdc/vnc/vncviewfactory.h +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Urs Wolfer -** -** This file is part of KDE. -** -** 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; see the file COPYING. If not, write to -** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -** Boston, MA 02110-1301, USA. -** -****************************************************************************/ - -#ifndef VNCVIEWFACTORY_H -#define VNCVIEWFACTORY_H - -#include "remoteviewfactory.h" - -#include "vncview.h" -#include "vncpreferences.h" - -class VncViewFactory : public RemoteViewFactory -{ - Q_OBJECT - -public: - explicit VncViewFactory(QObject *parent, const QVariantList &args); - - virtual ~VncViewFactory(); - - virtual bool supportsUrl(const KUrl &url) const; - - virtual RemoteView *createView(QWidget *parent, const KUrl &url, KConfigGroup configGroup); - - virtual HostPreferences *createHostPreferences(KConfigGroup configGroup, QWidget *parent); - - virtual QString scheme() const; - - virtual QString connectActionText() const; - - virtual QString connectButtonText() const; - - virtual QString connectToolTipText() const; -}; - -#endif // VNCVIEWFACTORY_H diff --git a/krfb/CMakeLists.txt b/krfb/CMakeLists.txt deleted file mode 100644 index b1c48686..00000000 --- a/krfb/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -project(krfb) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - include(FeatureSummary) - - find_package(KDELibs4 4.23.0 REQUIRED) - - include_directories(${KDE4_INCLUDES}) - add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -endif() - -find_package(LibVNCServer REQUIRED) - -kde4_bool_to_01(X11_Xdamage_FOUND HAVE_XDAMAGE) -kde4_bool_to_01(X11_XShm_FOUND HAVE_XSHM) - -include_directories( - ${CMAKE_CURRENT_BINARY_DIR}/krfb - ${CMAKE_CURRENT_SOURCE_DIR}/krfb - ${CMAKE_CURRENT_SOURCE_DIR}/krfb/ui -) - -if(Q_WS_X11) - if(NOT X11_XTest_FOUND) - message(FATAL_ERROR "krfb requires the libXTest (http://xorg.freedesktop.org) to be built") - endif(NOT X11_XTest_FOUND) -endif(Q_WS_X11) - -add_subdirectory(krfb) -add_subdirectory(framebuffers) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) -endif() diff --git a/krfb/COPYING b/krfb/COPYING deleted file mode 100644 index 8900e10b..00000000 --- a/krfb/COPYING +++ /dev/null @@ -1,347 +0,0 @@ -NOTE! The GPL below is copyrighted by the Free Software Foundation, but -the instance of code that it refers to (the kde programs) are copyrighted -by the authors who actually wrote it. - ---------------------------------------------------------------------------- - - 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 Library 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) 19yy - - 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) 19yy 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 Library General -Public License instead of this License. diff --git a/krfb/COPYING.DOC b/krfb/COPYING.DOC deleted file mode 100644 index 4a0fe1c8..00000000 --- a/krfb/COPYING.DOC +++ /dev/null @@ -1,397 +0,0 @@ - GNU Free Documentation License - Version 1.2, November 2002 - - - Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. - 51 Franklin St, 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. - - -0. PREAMBLE - -The purpose of this License is to make a manual, textbook, or other -functional and useful document "free" in the sense of freedom: to -assure everyone the effective freedom to copy and redistribute it, -with or without modifying it, either commercially or noncommercially. -Secondarily, this License preserves for the author and publisher a way -to get credit for their work, while not being considered responsible -for modifications made by others. - -This License is a kind of "copyleft", which means that derivative -works of the document must themselves be free in the same sense. It -complements the GNU General Public License, which is a copyleft -license designed for free software. - -We have designed this License in order to use it for manuals for free -software, because free software needs free documentation: a free -program should come with manuals providing the same freedoms that the -software does. But this License is not limited to software manuals; -it can be used for any textual work, regardless of subject matter or -whether it is published as a printed book. We recommend this License -principally for works whose purpose is instruction or reference. - - -1. APPLICABILITY AND DEFINITIONS - -This License applies to any manual or other work, in any medium, that -contains a notice placed by the copyright holder saying it can be -distributed under the terms of this License. Such a notice grants a -world-wide, royalty-free license, unlimited in duration, to use that -work under the conditions stated herein. The "Document", below, -refers to any such manual or work. Any member of the public is a -licensee, and is addressed as "you". You accept the license if you -copy, modify or distribute the work in a way requiring permission -under copyright law. - -A "Modified Version" of the Document means any work containing the -Document or a portion of it, either copied verbatim, or with -modifications and/or translated into another language. - -A "Secondary Section" is a named appendix or a front-matter section of -the Document that deals exclusively with the relationship of the -publishers or authors of the Document to the Document's overall subject -(or to related matters) and contains nothing that could fall directly -within that overall subject. (Thus, if the Document is in part a -textbook of mathematics, a Secondary Section may not explain any -mathematics.) The relationship could be a matter of historical -connection with the subject or with related matters, or of legal, -commercial, philosophical, ethical or political position regarding -them. - -The "Invariant Sections" are certain Secondary Sections whose titles -are designated, as being those of Invariant Sections, in the notice -that says that the Document is released under this License. If a -section does not fit the above definition of Secondary then it is not -allowed to be designated as Invariant. The Document may contain zero -Invariant Sections. If the Document does not identify any Invariant -Sections then there are none. - -The "Cover Texts" are certain short passages of text that are listed, -as Front-Cover Texts or Back-Cover Texts, in the notice that says that -the Document is released under this License. A Front-Cover Text may -be at most 5 words, and a Back-Cover Text may be at most 25 words. - -A "Transparent" copy of the Document means a machine-readable copy, -represented in a format whose specification is available to the -general public, that is suitable for revising the document -straightforwardly with generic text editors or (for images composed of -pixels) generic paint programs or (for drawings) some widely available -drawing editor, and that is suitable for input to text formatters or -for automatic translation to a variety of formats suitable for input -to text formatters. A copy made in an otherwise Transparent file -format whose markup, or absence of markup, has been arranged to thwart -or discourage subsequent modification by readers is not Transparent. -An image format is not Transparent if used for any substantial amount -of text. A copy that is not "Transparent" is called "Opaque". - -Examples of suitable formats for Transparent copies include plain -ASCII without markup, Texinfo input format, LaTeX input format, SGML -or XML using a publicly available DTD, and standard-conforming simple -HTML, PostScript or PDF designed for human modification. Examples of -transparent image formats include PNG, XCF and JPG. Opaque formats -include proprietary formats that can be read and edited only by -proprietary word processors, SGML or XML for which the DTD and/or -processing tools are not generally available, and the -machine-generated HTML, PostScript or PDF produced by some word -processors for output purposes only. - -The "Title Page" means, for a printed book, the title page itself, -plus such following pages as are needed to hold, legibly, the material -this License requires to appear in the title page. For works in -formats which do not have any title page as such, "Title Page" means -the text near the most prominent appearance of the work's title, -preceding the beginning of the body of the text. - -A section "Entitled XYZ" means a named subunit of the Document whose -title either is precisely XYZ or contains XYZ in parentheses following -text that translates XYZ in another language. (Here XYZ stands for a -specific section name mentioned below, such as "Acknowledgements", -"Dedications", "Endorsements", or "History".) To "Preserve the Title" -of such a section when you modify the Document means that it remains a -section "Entitled XYZ" according to this definition. - -The Document may include Warranty Disclaimers next to the notice which -states that this License applies to the Document. These Warranty -Disclaimers are considered to be included by reference in this -License, but only as regards disclaiming warranties: any other -implication that these Warranty Disclaimers may have is void and has -no effect on the meaning of this License. - - -2. VERBATIM COPYING - -You may copy and distribute the Document in any medium, either -commercially or noncommercially, provided that this License, the -copyright notices, and the license notice saying this License applies -to the Document are reproduced in all copies, and that you add no other -conditions whatsoever to those of this License. You may not use -technical measures to obstruct or control the reading or further -copying of the copies you make or distribute. However, you may accept -compensation in exchange for copies. If you distribute a large enough -number of copies you must also follow the conditions in section 3. - -You may also lend copies, under the same conditions stated above, and -you may publicly display copies. - - -3. COPYING IN QUANTITY - -If you publish printed copies (or copies in media that commonly have -printed covers) of the Document, numbering more than 100, and the -Document's license notice requires Cover Texts, you must enclose the -copies in covers that carry, clearly and legibly, all these Cover -Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on -the back cover. Both covers must also clearly and legibly identify -you as the publisher of these copies. The front cover must present -the full title with all words of the title equally prominent and -visible. You may add other material on the covers in addition. -Copying with changes limited to the covers, as long as they preserve -the title of the Document and satisfy these conditions, can be treated -as verbatim copying in other respects. - -If the required texts for either cover are too voluminous to fit -legibly, you should put the first ones listed (as many as fit -reasonably) on the actual cover, and continue the rest onto adjacent -pages. - -If you publish or distribute Opaque copies of the Document numbering -more than 100, you must either include a machine-readable Transparent -copy along with each Opaque copy, or state in or with each Opaque copy -a computer-network location from which the general network-using -public has access to download using public-standard network protocols -a complete Transparent copy of the Document, free of added material. -If you use the latter option, you must take reasonably prudent steps, -when you begin distribution of Opaque copies in quantity, to ensure -that this Transparent copy will remain thus accessible at the stated -location until at least one year after the last time you distribute an -Opaque copy (directly or through your agents or retailers) of that -edition to the public. - -It is requested, but not required, that you contact the authors of the -Document well before redistributing any large number of copies, to give -them a chance to provide you with an updated version of the Document. - - -4. MODIFICATIONS - -You may copy and distribute a Modified Version of the Document under -the conditions of sections 2 and 3 above, provided that you release -the Modified Version under precisely this License, with the Modified -Version filling the role of the Document, thus licensing distribution -and modification of the Modified Version to whoever possesses a copy -of it. In addition, you must do these things in the Modified Version: - -A. Use in the Title Page (and on the covers, if any) a title distinct - from that of the Document, and from those of previous versions - (which should, if there were any, be listed in the History section - of the Document). You may use the same title as a previous version - if the original publisher of that version gives permission. -B. List on the Title Page, as authors, one or more persons or entities - responsible for authorship of the modifications in the Modified - Version, together with at least five of the principal authors of the - Document (all of its principal authors, if it has fewer than five), - unless they release you from this requirement. -C. State on the Title page the name of the publisher of the - Modified Version, as the publisher. -D. Preserve all the copyright notices of the Document. -E. Add an appropriate copyright notice for your modifications - adjacent to the other copyright notices. -F. Include, immediately after the copyright notices, a license notice - giving the public permission to use the Modified Version under the - terms of this License, in the form shown in the Addendum below. -G. Preserve in that license notice the full lists of Invariant Sections - and required Cover Texts given in the Document's license notice. -H. Include an unaltered copy of this License. -I. Preserve the section Entitled "History", Preserve its Title, and add - to it an item stating at least the title, year, new authors, and - publisher of the Modified Version as given on the Title Page. If - there is no section Entitled "History" in the Document, create one - stating the title, year, authors, and publisher of the Document as - given on its Title Page, then add an item describing the Modified - Version as stated in the previous sentence. -J. Preserve the network location, if any, given in the Document for - public access to a Transparent copy of the Document, and likewise - the network locations given in the Document for previous versions - it was based on. These may be placed in the "History" section. - You may omit a network location for a work that was published at - least four years before the Document itself, or if the original - publisher of the version it refers to gives permission. -K. For any section Entitled "Acknowledgements" or "Dedications", - Preserve the Title of the section, and preserve in the section all - the substance and tone of each of the contributor acknowledgements - and/or dedications given therein. -L. Preserve all the Invariant Sections of the Document, - unaltered in their text and in their titles. Section numbers - or the equivalent are not considered part of the section titles. -M. Delete any section Entitled "Endorsements". Such a section - may not be included in the Modified Version. -N. Do not retitle any existing section to be Entitled "Endorsements" - or to conflict in title with any Invariant Section. -O. Preserve any Warranty Disclaimers. - -If the Modified Version includes new front-matter sections or -appendices that qualify as Secondary Sections and contain no material -copied from the Document, you may at your option designate some or all -of these sections as invariant. To do this, add their titles to the -list of Invariant Sections in the Modified Version's license notice. -These titles must be distinct from any other section titles. - -You may add a section Entitled "Endorsements", provided it contains -nothing but endorsements of your Modified Version by various -parties--for example, statements of peer review or that the text has -been approved by an organization as the authoritative definition of a -standard. - -You may add a passage of up to five words as a Front-Cover Text, and a -passage of up to 25 words as a Back-Cover Text, to the end of the list -of Cover Texts in the Modified Version. Only one passage of -Front-Cover Text and one of Back-Cover Text may be added by (or -through arrangements made by) any one entity. If the Document already -includes a cover text for the same cover, previously added by you or -by arrangement made by the same entity you are acting on behalf of, -you may not add another; but you may replace the old one, on explicit -permission from the previous publisher that added the old one. - -The author(s) and publisher(s) of the Document do not by this License -give permission to use their names for publicity for or to assert or -imply endorsement of any Modified Version. - - -5. COMBINING DOCUMENTS - -You may combine the Document with other documents released under this -License, under the terms defined in section 4 above for modified -versions, provided that you include in the combination all of the -Invariant Sections of all of the original documents, unmodified, and -list them all as Invariant Sections of your combined work in its -license notice, and that you preserve all their Warranty Disclaimers. - -The combined work need only contain one copy of this License, and -multiple identical Invariant Sections may be replaced with a single -copy. If there are multiple Invariant Sections with the same name but -different contents, make the title of each such section unique by -adding at the end of it, in parentheses, the name of the original -author or publisher of that section if known, or else a unique number. -Make the same adjustment to the section titles in the list of -Invariant Sections in the license notice of the combined work. - -In the combination, you must combine any sections Entitled "History" -in the various original documents, forming one section Entitled -"History"; likewise combine any sections Entitled "Acknowledgements", -and any sections Entitled "Dedications". You must delete all sections -Entitled "Endorsements". - - -6. COLLECTIONS OF DOCUMENTS - -You may make a collection consisting of the Document and other documents -released under this License, and replace the individual copies of this -License in the various documents with a single copy that is included in -the collection, provided that you follow the rules of this License for -verbatim copying of each of the documents in all other respects. - -You may extract a single document from such a collection, and distribute -it individually under this License, provided you insert a copy of this -License into the extracted document, and follow this License in all -other respects regarding verbatim copying of that document. - - -7. AGGREGATION WITH INDEPENDENT WORKS - -A compilation of the Document or its derivatives with other separate -and independent documents or works, in or on a volume of a storage or -distribution medium, is called an "aggregate" if the copyright -resulting from the compilation is not used to limit the legal rights -of the compilation's users beyond what the individual works permit. -When the Document is included in an aggregate, this License does not -apply to the other works in the aggregate which are not themselves -derivative works of the Document. - -If the Cover Text requirement of section 3 is applicable to these -copies of the Document, then if the Document is less than one half of -the entire aggregate, the Document's Cover Texts may be placed on -covers that bracket the Document within the aggregate, or the -electronic equivalent of covers if the Document is in electronic form. -Otherwise they must appear on printed covers that bracket the whole -aggregate. - - -8. TRANSLATION - -Translation is considered a kind of modification, so you may -distribute translations of the Document under the terms of section 4. -Replacing Invariant Sections with translations requires special -permission from their copyright holders, but you may include -translations of some or all Invariant Sections in addition to the -original versions of these Invariant Sections. You may include a -translation of this License, and all the license notices in the -Document, and any Warranty Disclaimers, provided that you also include -the original English version of this License and the original versions -of those notices and disclaimers. In case of a disagreement between -the translation and the original version of this License or a notice -or disclaimer, the original version will prevail. - -If a section in the Document is Entitled "Acknowledgements", -"Dedications", or "History", the requirement (section 4) to Preserve -its Title (section 1) will typically require changing the actual -title. - - -9. TERMINATION - -You may not copy, modify, sublicense, or distribute the Document except -as expressly provided for under this License. Any other attempt to -copy, modify, sublicense or distribute the Document 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. - - -10. FUTURE REVISIONS OF THIS LICENSE - -The Free Software Foundation may publish new, revised versions -of the GNU Free Documentation 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. See -http://www.gnu.org/copyleft/. - -Each version of the License is given a distinguishing version number. -If the Document specifies that a particular numbered version of this -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that specified version or -of any later version that has been published (not as a draft) by the -Free Software Foundation. If the Document does not specify a version -number of this License, you may choose any version ever published (not -as a draft) by the Free Software Foundation. - - -ADDENDUM: How to use this License for your documents - -To use this License in a document you have written, include a copy of -the License in the document and put the following copyright and -license notices just after the title page: - - Copyright (c) YEAR YOUR NAME. - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. - A copy of the license is included in the section entitled "GNU - Free Documentation License". - -If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, -replace the "with...Texts." line with this: - - with the Invariant Sections being LIST THEIR TITLES, with the - Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. - -If you have Invariant Sections without Cover Texts, or some other -combination of the three, merge those two alternatives to suit the -situation. - -If your document contains nontrivial examples of program code, we -recommend releasing these examples in parallel under your choice of -free software license, such as the GNU General Public License, -to permit their use in free software. diff --git a/krfb/COPYING.LIB b/krfb/COPYING.LIB deleted file mode 100644 index 2d2d780e..00000000 --- a/krfb/COPYING.LIB +++ /dev/null @@ -1,510 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations -below. - - When we speak of free software, we are referring to freedom of use, -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 and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it -becomes a de-facto standard. To achieve this, non-free programs must -be allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control -compilation and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least - three years, to give the same user the materials specified in - Subsection 6a, above, for a charge no more than the cost of - performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply, and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License -may add an explicit geographical distribution limitation excluding those -countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms -of the ordinary General Public License). - - To apply these terms, attach the following notices to the library. -It is safest to attach them to the start of each source file to most -effectively convey the exclusion of warranty; and each file should -have at least the "copyright" line and a pointer to where the full -notice is found. - - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or -your school, if any, to sign a "copyright disclaimer" for the library, -if necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James - Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/krfb/NOTES b/krfb/NOTES deleted file mode 100644 index 24b30178..00000000 --- a/krfb/NOTES +++ /dev/null @@ -1,27 +0,0 @@ -Comments on various aspects of KRfb: - -- KRfb has been designed for three use cases: - * a user who needs help from an administrator or friend. The adminstrator can - connect to the user and change settings and so on while both are talking - on the telephone or using VoIP. - * a user who wants to show something to a friend, so he lets his friend - connect to his computer - * (advanced use case) somebody with several computers, that are running - GUIs, wants to control them. -- cases 1&2 are probably more mainstream and more important for novice users, - so KRfb is pre-configured for them. Case 3 is for advanced users and - therefore a little bit more difficult to configure. -- design goal of KRfb is to make it as easy to use as possible. I tried to - limit functionality whereever possible. -- the new-connection-dialog is extra large and has the pixmap on the left - side to capture the attention of the user before allowing a connection. -- the RFBController class is a mess. The interactions between the threaded, - callback-using libvncserver and the event-driven, single thread qt GUI are - quite complicated and I can only hope that it works. -- most limitations and problems of KRfb are caused either by limitations of - Rfb (for example no proper authentication of users, no encryption) or - by lack of a framework in Linux in general (no way to connect through a - NAT device). In the next months I am going to concentrate on improving the - latter. - -tim@tjansen.de diff --git a/krfb/README b/krfb/README deleted file mode 100644 index ada74b6d..00000000 --- a/krfb/README +++ /dev/null @@ -1,19 +0,0 @@ -KDE Desktop Sharing (krfb) -========================== - -KDE Desktop Sharing (krfb) is a small server for the RFB protocol, better -known as VNC. Unlike most other Unix/Linux RFB servers, KRfb allows you to -share your X11 session instead of creating a new X11 session. -It was originally based on x0rfbserver -(ttp://www.hexonet.de/software/x0rfbserver/), but there is not much code of -x0rfbserver left. Since version 0.6 it uses libvncserver -(http://libvncserver.sf.net) as backend. - - -Guide to documentation: -TODO - things to be done -INSTALL - Very short installation instructions -NOTES - reasons for various decisions -DCOP-INTERFACE - short documentation of the DCOP interface - - diff --git a/krfb/framebuffers/CMakeLists.txt b/krfb/framebuffers/CMakeLists.txt deleted file mode 100644 index 01921b5e..00000000 --- a/krfb/framebuffers/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_subdirectory(qt) -add_subdirectory(x11) - diff --git a/krfb/framebuffers/qt/CMakeLists.txt b/krfb/framebuffers/qt/CMakeLists.txt deleted file mode 100644 index c8eae9b8..00000000 --- a/krfb/framebuffers/qt/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -include_directories (${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} -) - -set (krfb_framebuffer_qt_SRCS - qtframebuffer.cpp - qtframebufferplugin.cpp -) - -kde4_add_plugin (krfb_framebuffer_qt - ${krfb_framebuffer_qt_SRCS} -) - -target_link_libraries (krfb_framebuffer_qt - ${QT_QTCORE_LIBRARY} - ${QT_QTGUI_LIBRARY} - KDE4::kdeui - krfbprivate -) - -install (TARGETS krfb_framebuffer_qt - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) - -install (FILES krfb_framebuffer_qt.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) - diff --git a/krfb/framebuffers/qt/krfb_framebuffer_qt.desktop b/krfb/framebuffers/qt/krfb_framebuffer_qt.desktop deleted file mode 100644 index fddc2ac3..00000000 --- a/krfb/framebuffers/qt/krfb_framebuffer_qt.desktop +++ /dev/null @@ -1,107 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Comment=Qt based Framebuffer for KRfb. -Comment[ast]=Esquema Qt de buffer pa KRfb -Comment[bg]=Основан на Qt фреймбуфер за KRfb. -Comment[bs]=Kadrobafer za KRfb na osnovu Qt -Comment[ca]=«Framebuffer» basat en Qt per al KRfb. -Comment[ca@valencia]=«Framebuffer» basat en Qt per al KRfb. -Comment[cs]=Framebuffer založený na Qt pro KRfb. -Comment[da]=Qt-baseret framebuffer til KRfb. -Comment[de]=Qt-basierter Framebuffer für KRfb -Comment[el]=Μνήμη εξόδου βίντεο καρέ με βάση το Qt για το KRfb. -Comment[en_GB]=Qt based Framebuffer for KRfb. -Comment[es]=Memoria intermedia de vídeo basada en Qt para KRfb. -Comment[et]=KRfb Qt põhine kaadripuhver -Comment[eu]=Qt-n oinarritutako KRfb-ren irteerako bideoa -Comment[fi]=QT-perustainen Kehyspuskuri KRfb:lle -Comment[fr]=Sortie vidéo fondée sur Qt pour Krfb. -Comment[ga]=Maolán fráma le haghaidh KRfb, bunaithe ar Qt. -Comment[gl]=Framebuffer baseado en Qt para KRfb. -Comment[hr]=Međuspremnik okvira baziran na Qt-u za KRfb. -Comment[hu]=Qt-alapú framebuffer a Krfb-hez. -Comment[ia]=Framebuffer basate sur Qt per KRfb -Comment[it]=Framebuffer basato su Qt per KRfb. -Comment[kk]=Qt негіздеген KRfb-нің кадр буфері. -Comment[km]=Framebuffer មាន​មូលដ្ឋាន​លើ Qt សម្រាប់ KRfb ។ -Comment[ko]=KRfb를 위한 Qt 기반 프레임버퍼. -Comment[lt]=Qt pagrindu veikiantis Framebuffer skirtas KRfb. -Comment[lv]=Qt balstīts kadrbuferis priekš KRfb. -Comment[nb]=Qt-basert rammebuffer for KRfb. -Comment[nds]=Op Qt opbuut Bildpuffer för KRfb -Comment[nl]=Op Qt gebaseerd framebuffer voor KRfb. -Comment[nn]=Qt basert framebuffer for KRfb. -Comment[pl]=Bufor ramki na podstawie Qt dla KRfb. -Comment[pt]='Framebuffer' baseado no Qt para o KRfb. -Comment[pt_BR]=Framebuffer baseado no Qt para o KRfb. -Comment[ru]=Буфер экрана для KRfb на базе Qt. -Comment[si]=KRfb සඳහා Qt මත පදනම් වූ රාමු බෆරය -Comment[sk]=Framebuffer založený na Qt pre KRfb. -Comment[sl]=Slikovni medpomnilnik za KRFB, ki temelji na Qt -Comment[sr]=Кадробафер за КРФБ на основу КуТ‑у -Comment[sr@ijekavian]=Кадробафер за КРФБ на основу КуТ‑у -Comment[sr@ijekavianlatin]=Kadrobafer za KRFB na osnovu Qt‑u -Comment[sr@latin]=Kadrobafer za KRFB na osnovu Qt‑u -Comment[sv]=Qt-baserad rambuffert för Krfb. -Comment[tr]=KRfb için Qt temelli Çerçeve tamponu. -Comment[uk]=Заснований на Qt буфер кадрів для KRfb. -Comment[x-test]=xxQt based Framebuffer for KRfb.xx -Comment[zh_CN]=基于 Qt 的 KRfb 帧缓冲机制 -Comment[zh_TW]=KRfb 的 Qt-based Framebuffer -Name=Qt Framebuffer for KRfb -Name[ast]=Esquema Qt de buffer pa KRfb -Name[bg]=Qt фреймбуфер за KRfb -Name[bs]=Qt-ov kadrobafer za KRFB -Name[ca]=«Framebuffer» Qt per al KRfb. -Name[ca@valencia]=«Framebuffer» Qt per al KRfb. -Name[cs]=Qt Framebuffer pro KRfb -Name[da]=Qt-framebuffer til KRfb -Name[de]=Qt-Framebuffer für KRfb -Name[el]=Qt Framebuffer for KRfb -Name[en_GB]=Qt Framebuffer for KRfb -Name[es]=Memoria intermedia de vídeo Qt para KRfb -Name[et]=KRfb Qt kaadripuhver -Name[eu]=KRfb-ren Qt-ko irteerako bideoa -Name[fi]=QT-kehyspuskuri KRfb:lle -Name[fr]=Sortie vidéo Qt pour Krfb -Name[ga]=Maolán fráma Qt le haghaidh KRfb -Name[gl]=Framebuffer de Qt para KRfb -Name[hr]=Qt Framebuffer za KRfb -Name[hu]=Qt framebuffer a Krfb-hez -Name[ia]=Framebuffer Qt per KRfb -Name[it]=Framebuffer Qt per KRfb -Name[kk]=Qt KRfb кадр буфері -Name[km]=Qt Framebuffer សម្រាប់for KRfb -Name[ko]=KRfb를 위한 Qt 프레임버퍼 -Name[lt]=Qt Framebufferis skirtas KRfb -Name[lv]=Qt kadrbuferis priekš KRfb. -Name[nb]=Qt rammebuffer for KRfb -Name[nds]=Qt-Bildpuffer för KRfb -Name[nl]=Qt-framebuffer voor KRfb -Name[nn]=Qt-framebuffer for KRfb -Name[pl]=Bufor ramki Qt dla KRfb -Name[pt]='Framebuffer' do Qt para o KRfb -Name[pt_BR]=Framebuffer do Qt para o KRfb -Name[ru]=Буфер экрана Qt для KRfb -Name[si]=KRfb සඳහා වන Qt රාමුබෆරය -Name[sk]=Qt Framebuffer pre KRfb -Name[sl]=Slikovni medpomnilnik Qt za KRFB -Name[sr]=КуТ‑ов кадробафер за КРФБ -Name[sr@ijekavian]=КуТ‑ов кадробафер за КРФБ -Name[sr@ijekavianlatin]=Qt‑ov kadrobafer za KRFB -Name[sr@latin]=Qt‑ov kadrobafer za KRFB -Name[sv]=Qt-rambuffert för Krfb -Name[tr]=KRfb için Qt Çerçeve tamponu -Name[uk]=Буфер кадрів на Qt для KRfb -Name[x-test]=xxQt Framebuffer for KRfbxx -Name[zh_CN]=KRfb 的 Qt 帧缓冲机制 -Name[zh_TW]=Krfb 的 Qt Framebuffer -Type=Service -ServiceTypes=krfb/framebuffer - -X-KDE-Library=krfb_framebuffer_qt -X-KDE-PluginInfo-Name=qt -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true diff --git a/krfb/framebuffers/qt/qtframebuffer.cpp b/krfb/framebuffers/qt/qtframebuffer.cpp deleted file mode 100644 index d3a291bc..00000000 --- a/krfb/framebuffers/qt/qtframebuffer.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ - -#include "qtframebuffer.h" -#include "moc_qtframebuffer.cpp" - -#include -#include -#include -#include - - -const int UPDATE_TIME = 500; - -QtFrameBuffer::QtFrameBuffer(WId id, QObject *parent) - : FrameBuffer(id, parent) -{ - fbImage = QPixmap::grabWindow(win).toImage(); - fb = new char[fbImage.byteCount()]; - t = new QTimer(this); - connect(t, SIGNAL(timeout()), SLOT(updateFrameBuffer())); -} - - -QtFrameBuffer::~QtFrameBuffer() -{ - delete [] fb; - fb = 0; -} - -int QtFrameBuffer::depth() -{ - return fbImage.depth(); -} - -int QtFrameBuffer::height() -{ - return fbImage.height(); -} - -int QtFrameBuffer::width() -{ - return fbImage.width(); -} - -void QtFrameBuffer::getServerFormat(rfbPixelFormat &format) -{ - format.bitsPerPixel = 32; - format.depth = 32; - format.trueColour = true; - - format.bigEndian = false; - format.redShift = 16; - format.greenShift = 8; - format.blueShift = 0; - format.redMax = 0xff; - format.greenMax = 0xff; - format.blueMax = 0xff; -} - -void QtFrameBuffer::updateFrameBuffer() -{ - QImage img = QPixmap::grabWindow(win).toImage(); - - - // verify what part of the image need to be marked as changed - // fbImage is the previous version of the image, - // img is the current one - -#if 0 // This is actually slower than updating the whole desktop... - QSize imgSize = img.size(); - QImage map(imgSize, QImage::Format_Mono); - map.fill(0); - - for (int x = 0; x < imgSize.width(); x++) { - for (int y = 0; y < imgSize.height(); y++) { - if (img.pixel(x, y) != fbImage.pixel(x, y)) { - map.setPixel(x, y, 1); - } - } - } - - QRegion r(QBitmap::fromImage(map)); - tiles = tiles + r.rects(); - -#else - tiles.append(img.rect()); -#endif - - memcpy(fb, (const char *)img.bits(), img.byteCount()); - fbImage = img; - -} - -int QtFrameBuffer::paddedWidth() -{ - return fbImage.width() * 4; -} - -void QtFrameBuffer::startMonitor() -{ - t->start(UPDATE_TIME); -} - -void QtFrameBuffer::stopMonitor() -{ - t->stop(); -} - diff --git a/krfb/framebuffers/qt/qtframebuffer.h b/krfb/framebuffers/qt/qtframebuffer.h deleted file mode 100644 index fbf5d0b2..00000000 --- a/krfb/framebuffers/qt/qtframebuffer.h +++ /dev/null @@ -1,44 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ - -#ifndef KRFB_FRAMEBUFFER_QT_QTFRAMEBUFFER_H -#define KRFB_FRAMEBUFFER_QT_QTFRAMEBUFFER_H - -#include -#include "framebuffer.h" - -#include -/** - @author Alessandro Praduroux -*/ -class QtFrameBuffer : public FrameBuffer -{ - Q_OBJECT -public: - explicit QtFrameBuffer(WId id, QObject *parent = 0); - - ~QtFrameBuffer(); - - virtual int depth(); - virtual int height(); - virtual int width(); - virtual int paddedWidth(); - virtual void getServerFormat(rfbPixelFormat &format); - virtual void startMonitor(); - virtual void stopMonitor(); - -public Q_SLOTS: - void updateFrameBuffer(); - -private: - QImage fbImage; - QTimer *t; -}; - -#endif diff --git a/krfb/framebuffers/qt/qtframebufferplugin.cpp b/krfb/framebuffers/qt/qtframebufferplugin.cpp deleted file mode 100644 index 64e34491..00000000 --- a/krfb/framebuffers/qt/qtframebufferplugin.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "qtframebufferplugin.h" - -#include "qtframebuffer.h" - -#include - - -QtFrameBufferPlugin::QtFrameBufferPlugin(QObject *parent, const QVariantList &args) - : FrameBufferPlugin(parent, args) -{ -} - -QtFrameBufferPlugin::~QtFrameBufferPlugin() -{ -} - -FrameBuffer *QtFrameBufferPlugin::frameBuffer(WId id) -{ - return new QtFrameBuffer(id); -} - -K_PLUGIN_FACTORY(factory, registerPlugin();) \ -K_EXPORT_PLUGIN(factory("krfb_framebuffer_qt")) - - -#include "moc_qtframebufferplugin.cpp" - diff --git a/krfb/framebuffers/qt/qtframebufferplugin.h b/krfb/framebuffers/qt/qtframebufferplugin.h deleted file mode 100644 index a69e7d97..00000000 --- a/krfb/framebuffers/qt/qtframebufferplugin.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KRFB_FRAMEBUFFER_QT_QTFRAMEBUFFERPLUGIN_H -#define KRFB_FRAMEBUFFER_QT_QTFRAMEBUFFERPLUGIN_H - -#include "framebufferplugin.h" - -#include - -#include - -class FrameBuffer; - -class QtFrameBufferPlugin : public FrameBufferPlugin -{ - Q_OBJECT - -public: - QtFrameBufferPlugin(QObject *parent, const QVariantList &args); - virtual ~QtFrameBufferPlugin(); - - virtual FrameBuffer *frameBuffer(WId id); - -private: - Q_DISABLE_COPY(QtFrameBufferPlugin) -}; - - -#endif // Header guard - diff --git a/krfb/framebuffers/x11/CMakeLists.txt b/krfb/framebuffers/x11/CMakeLists.txt deleted file mode 100644 index 7b61df04..00000000 --- a/krfb/framebuffers/x11/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} -) - -set(krfb_framebuffer_x11_SRCS - x11framebuffer.cpp - x11framebufferplugin.cpp -) - -set_source_files_properties( - ${CMAKE_CURRENT_SOURCE_DIR}/x11framebuffer.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/x11framebufferplugin.cpp - PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE -) - -kde4_add_plugin(krfb_framebuffer_x11 - ${krfb_framebuffer_x11_SRCS} -) - -target_link_libraries(krfb_framebuffer_x11 - KDE4::kdeui - ${QT_QTCORE_LIBRARY} - ${QT_QTGUI_LIBRARY} - ${X11_X11_LIB} - ${X11_Xdamage_LIB} - ${X11_Xext_LIB} - krfbprivate -) - -install( - TARGETS krfb_framebuffer_x11 - DESTINATION ${KDE4_PLUGIN_INSTALL_DIR} -) - -install( - FILES krfb_framebuffer_x11.desktop - DESTINATION ${KDE4_SERVICES_INSTALL_DIR} -) - diff --git a/krfb/framebuffers/x11/krfb_framebuffer_x11.desktop b/krfb/framebuffers/x11/krfb_framebuffer_x11.desktop deleted file mode 100644 index d68aa7da..00000000 --- a/krfb/framebuffers/x11/krfb_framebuffer_x11.desktop +++ /dev/null @@ -1,107 +0,0 @@ -[Desktop Entry] -Encoding=UTF-8 -Comment=X11 XDamage/XShm based Framebuffer for KRfb. -Comment[ast]=Esquema de buffer pa KRfb basáu en XDamage/XShm -Comment[bg]=Основан на X11 XDamage/XShm фреймбуфер за KRfb. -Comment[bs]=X11 XDamage/XShm baziran framebafer za KRfb. -Comment[ca]=«Framebuffer» basat en XDamage/XShmQt de l'X11 per al KRfb. -Comment[ca@valencia]=«Framebuffer» basat en XDamage/XShmQt de l'X11 per al KRfb. -Comment[cs]=Framebuffer založený na X11 XDamage/XShm pro KRfb. -Comment[da]=X11 XDamage/XShm-baseret framebuffer til KRfb. -Comment[de]=X11 XDamage/XShm-basierter Framebuffer für KRfb. -Comment[el]=Μνήμη εξόδου βίντεο καρέ με βάση το X11 XDamage/XShm για το KRfb. -Comment[en_GB]=X11 XDamage/XShm based Framebuffer for KRfb. -Comment[es]=Memoria intermedia de vídeo basada en X11 Damage/XShm para KRfb. -Comment[et]=KRfb X11 XDamage/XShm põhine kaadripuhver -Comment[eu]=X11 XDamage/XShm oinarritutako KRfb-ren irteerako bideoa. -Comment[fi]=X11 XDamage/XShm-perustainen kehyspuskui KRfb:lle. -Comment[fr]=Sortie vidéo fondée sur X11 « XDamage / XShm » pour Krfb. -Comment[ga]=Maolán fráma le haghaidh KRfb, bunaithe ar X11 XDamage/XShm -Comment[gl]=Framebuffer baseado en Xll XDamage/Xshm para XRfb. -Comment[hr]=Međuspreminik okvira baziran na X11 XDamage/XShm za KRfb. -Comment[hu]=X11 XDamage/XShm-alapú framebuffer a Krfb-hez. -Comment[ia]=Framebuffer basate sur X11 XDamage/XShm per KRfb. -Comment[it]=Framebuffer basato su XDamage/XShm di X11 per KRfb. -Comment[kk]=X11 XDamage/XShm негіздеген KRfb кадр буфері. -Comment[km]=X11 XDamage/XShm based Framebuffer សម្រាប់ KRfb ។ -Comment[ko]=KRfb를 위한 X11 XDamage/XShm 기반 프레임버퍼. -Comment[lt]=X11 XDamage/XShm paremtas Framebuffer skirtas KRfb. -Comment[lv]=X11 XDamage/XShm balstīts kadrbuferis priekš KRfb. -Comment[nb]=Rammebuffer for KRfb basert på X11 XDamage/XShm. -Comment[nds]=Op X11-XDamage/-XShm opbuut Bildpuffer för KRfb -Comment[nl]=Op X11 XDamage/XShm gebaseerd framebuffer voor KRfb. -Comment[nn]=X11 XDamage/XShm basert framebuffer for KRfb. -Comment[pl]=Bufor ramki na podstawie X11 XDamage/XShm dla KRfb. -Comment[pt]='Framebuffer' baseado no XDamage/XShm do X11 para o KRfb. -Comment[pt_BR]=Framebuffer baseado no XDamage/XShm do X11 para o KRfb. -Comment[ru]=Буфер экрана для KRfb на базе X11 XDamage/XShm -Comment[si]=KRfb සඳහා වන රාමු බෆරය මත පදනම් වූ X11 XDamage/XShm. -Comment[sk]=Framebuffer založený na X11 XDamage/XShm pre KRfb. -Comment[sl]=Slikovni medpomnilnik za KRFB, ki temelji na X11 XDamage/XShm -Comment[sr]=Кадробафер за КРФБ на основу Икс‑демиџа/Икс‑схма у Иксу11. -Comment[sr@ijekavian]=Кадробафер за КРФБ на основу Икс‑демиџа/Икс‑схма у Иксу11. -Comment[sr@ijekavianlatin]=Kadrobafer za KRFB na osnovu XDamagea/XShma u X11. -Comment[sr@latin]=Kadrobafer za KRFB na osnovu XDamagea/XShma u X11. -Comment[sv]=X11 XDamage/XShm-baserad rambuffert för Krfb. -Comment[tr]=KRfb için X11 XDamage/XShm temelli Çerçeve Tamponu. -Comment[uk]=Заснований на XDamage/XShm X11 буфер кадрів для KRfb. -Comment[x-test]=xxX11 XDamage/XShm based Framebuffer for KRfb.xx -Comment[zh_CN]=基于 X11 XDamage/XShm 扩展的 KRfb 帧缓冲机制。 -Comment[zh_TW]=KRfb 的 X11 XDamage/XShm based Framebuffer -Name=X11 Framebuffer for KRfb -Name[ast]=Buffer de X11 pa KRfb -Name[bg]=X11 фреймбуфер за KRfb -Name[bs]=X11 frame bafer za KRfb -Name[ca]=«Framebuffer» de l'X11 per al KRfb. -Name[ca@valencia]=«Framebuffer» de l'X11 per al KRfb. -Name[cs]=X11 Framebuffer pro KRfb -Name[da]=X11-framebuffer til KRfb -Name[de]=X11-Framebuffer für KRfb -Name[el]=X11 Framebuffer for KRfb -Name[en_GB]=X11 Framebuffer for KRfb -Name[es]=Memoria intermedia de vídeo X11 para KRfb -Name[et]=KRfb X11 kaadripuhver -Name[eu]=KRfb-ren X11-ko irteerako bideoa -Name[fi]=X11-kehyspuskuri KRfb:lle -Name[fr]=Sortie vidéo X11 pour Krfb -Name[ga]=Maolán fráma X11 le haghaidh KRfb -Name[gl]=Framebuffer de X11 para KRfb -Name[hr]=Međuspremnik okvira X11 za KRfb -Name[hu]=X11 framebuffer a Krfb-hez -Name[ia]=Framebuffer X11 per KRfb -Name[it]=Framebuffer X11 per KRfb -Name[kk]=X11 KRfb кадр буфері -Name[km]=X11 Framebuffer សម្រាប់ KRfb -Name[ko]=KRfb를 위한 X11 프레임버퍼 -Name[lt]=X11 Framebuffer skirtas KRfb -Name[lv]=X11 kadrbuferis priekš KRfb -Name[nb]=X11 rammebuffer for KRfb -Name[nds]=X11-Bildpuffer för KRfb -Name[nl]=X11 framebuffer voor KRfb -Name[nn]=X11-framebuffer for KRfb -Name[pl]=Bufor ramki X11 dla KRfb -Name[pt]='Framebuffer' do X11 para o KRfb -Name[pt_BR]=Framebuffer do X11 para o KRfb -Name[ru]=Буфер экрана X11 для KRfb -Name[si]=KRfb සඳහා X11 රාමු බෆරය -Name[sk]=X11 Framebuffer pre KRfb -Name[sl]=Slikovni medpomnilnik X11 za KRFB -Name[sr]=Икс11 кадробафер за КРФБ. -Name[sr@ijekavian]=Икс11 кадробафер за КРФБ. -Name[sr@ijekavianlatin]=X11 kadrobafer za KRFB. -Name[sr@latin]=X11 kadrobafer za KRFB. -Name[sv]=X11-rambuffert för Krfb -Name[tr]=KRfb için X11 Çerçeve Tamponu -Name[uk]=Буфер кадрів X11 для KRfb -Name[x-test]=xxX11 Framebuffer for KRfbxx -Name[zh_CN]=KRfb 的 X11 帧缓冲机制 -Name[zh_TW]=KRfb 的 X11 Framebuffer -Type=Service -ServiceTypes=krfb/framebuffer - -X-KDE-Library=krfb_framebuffer_x11 -X-KDE-PluginInfo-Name=x11 -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true diff --git a/krfb/framebuffers/x11/x11framebuffer.cpp b/krfb/framebuffers/x11/x11framebuffer.cpp deleted file mode 100644 index 782ff42b..00000000 --- a/krfb/framebuffers/x11/x11framebuffer.cpp +++ /dev/null @@ -1,387 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ - -#include "x11framebuffer.h" -#include "moc_x11framebuffer.cpp" - -#include - -#include -#include -#include - -#include -#include - -#include -#include - -#ifdef HAVE_XDAMAGE -#include -#endif - -#ifdef HAVE_XSHM -#include -#include -#include -#endif - -class X11FrameBuffer::P -{ - -public: -#ifdef HAVE_XDAMAGE - Damage damage; -#endif -#ifdef HAVE_XSHM - XShmSegmentInfo shminfo; -#endif - - XImage *framebufferImage; - XImage *updateTile; - EvWidget *ev; - bool useShm; - int xdamageBaseEvent; - bool running; -}; - -X11FrameBuffer::X11FrameBuffer(WId id, QObject *parent) - : FrameBuffer(id, parent), d(new X11FrameBuffer::P) -{ -#ifdef HAVE_XSHM - d->useShm = XShmQueryExtension(QX11Info::display()); - kDebug() << "shm: " << d->useShm; -#else - d->useShm = false; -#endif - d->running = false; - d->framebufferImage = XGetImage(QX11Info::display(), - id, - 0, - 0, - QApplication::desktop()->width(), //arg, must get a widget ??? - QApplication::desktop()->height(), - AllPlanes, - ZPixmap); - - if (d->useShm) { -#ifdef HAVE_XSHM - d->updateTile = XShmCreateImage(QX11Info::display(), - DefaultVisual(QX11Info::display(), 0), - d->framebufferImage->bits_per_pixel, - ZPixmap, - NULL, - &d->shminfo, - 32, - 32); - d->shminfo.shmid = shmget(IPC_PRIVATE, - d->updateTile->bytes_per_line * d->updateTile->height, - IPC_CREAT | 0777); - - d->shminfo.shmaddr = d->updateTile->data = (char *) - shmat(d->shminfo.shmid, 0, 0); - d->shminfo.readOnly = False; - - XShmAttach(QX11Info::display(), &d->shminfo); -#endif - } else { - ; - } - - kDebug() << "Got image. bpp: " << d->framebufferImage->bits_per_pixel - << ", depth: " << d->framebufferImage->depth - << ", padded width: " << d->framebufferImage->bytes_per_line - << " (sent: " << d->framebufferImage->width * 4 << ")"; - - fb = d->framebufferImage->data; -#ifdef HAVE_XDAMAGE - d->ev = new EvWidget(this); - kapp->installX11EventFilter(d->ev); -#endif -} - - -X11FrameBuffer::~X11FrameBuffer() -{ - XDestroyImage(d->framebufferImage); -#ifdef HAVE_XDAMAGE - kapp->removeX11EventFilter(d->ev); -#endif -#ifdef HAVE_XSHM - XShmDetach(QX11Info::display(), &d->shminfo); - XDestroyImage(d->updateTile); - shmdt(d->shminfo.shmaddr); - shmctl(d->shminfo.shmid, IPC_RMID, 0); -#endif - delete d; - fb = 0; // already deleted by XDestroyImage -} - - -int X11FrameBuffer::depth() -{ - return d->framebufferImage->depth; -} - -int X11FrameBuffer::height() -{ - return d->framebufferImage->height; -} - -int X11FrameBuffer::width() -{ - return d->framebufferImage->width; -} - -int X11FrameBuffer::paddedWidth() -{ - return d->framebufferImage->bytes_per_line; -} - -void X11FrameBuffer::getServerFormat(rfbPixelFormat &format) -{ - format.bitsPerPixel = d->framebufferImage->bits_per_pixel; - format.depth = d->framebufferImage->depth; - format.trueColour = true; - format.bigEndian = ((d->framebufferImage->bitmap_bit_order == MSBFirst) ? true : false); - - if (format.bitsPerPixel == 8) { - format.redShift = 0; - format.greenShift = 3; - format.blueShift = 6; - format.redMax = 7; - format.greenMax = 7; - format.blueMax = 3; - } else { - format.redShift = 0; - - if (d->framebufferImage->red_mask) - while (!(d->framebufferImage->red_mask & (1 << format.redShift))) { - format.redShift++; - } - - format.greenShift = 0; - - if (d->framebufferImage->green_mask) - while (!(d->framebufferImage->green_mask & (1 << format.greenShift))) { - format.greenShift++; - } - - format.blueShift = 0; - - if (d->framebufferImage->blue_mask) - while (!(d->framebufferImage->blue_mask & (1 << format.blueShift))) { - format.blueShift++; - } - - format.redMax = d->framebufferImage->red_mask >> format.redShift; - format.greenMax = d->framebufferImage->green_mask >> format.greenShift; - format.blueMax = d->framebufferImage->blue_mask >> format.blueShift; - } -} - -void X11FrameBuffer::handleXDamage(XEvent *event) -{ -#ifdef HAVE_XDAMAGE - XDamageNotifyEvent *dev = (XDamageNotifyEvent *)event; - QRect r(dev->area.x, dev->area.y, dev->area.width, dev->area.height); - tiles.append(r); - - /*if (!dev->more) { - XDamageSubtract(QX11Info::display(),d->damage, None, None); - }*/ -#endif -} - - -void X11FrameBuffer::cleanupRects() -{ - - QList cpy = tiles; - bool inserted = false; - tiles.clear(); -// kDebug() << "before cleanup: " << cpy.size(); - foreach(const QRect & r, cpy) { - if (tiles.size() > 0) { - for (int i = 0; i < tiles.size(); i++) { - // kDebug() << r << tiles[i]; - if (r.intersects(tiles[i])) { - tiles[i] |= r; - inserted = true; - break; - // kDebug() << "merged into " << tiles[i]; - } - } - - if (!inserted) { - tiles.append(r); - // kDebug() << "appended " << r; - } - } else { - // kDebug() << "appended " << r; - tiles.append(r); - } - } - - for (int i = 0; i < tiles.size(); i++) { - tiles[i].adjust(-30, -30, 30, 30); - - if (tiles[i].top() < 0) { - tiles[i].setTop(0); - } - - if (tiles[i].left() < 0) { - tiles[i].setLeft(0); - } - - if (tiles[i].bottom() > d->framebufferImage->height) { - tiles[i].setBottom(d->framebufferImage->height); - } - - if (tiles[i].right() > d->framebufferImage->width) { - tiles[i].setRight(d->framebufferImage->width); - } - } - -// kDebug() << "after cleanup: " << tiles.size(); -} - -void X11FrameBuffer::acquireEvents() -{ - - XEvent ev; - - while (XCheckTypedEvent(QX11Info::display(), d->xdamageBaseEvent + XDamageNotify, &ev)) { - handleXDamage(&ev); - } - - XDamageSubtract(QX11Info::display(), d->damage, None, None); -} - -QList< QRect > X11FrameBuffer::modifiedTiles() -{ - QList ret; - - if (!d->running) { - return ret; - } - - kapp->processEvents(); // try to make sure every damage event goes trough; - cleanupRects(); - QRect gl; - - //d->useShm = false; - if (tiles.size() > 0) { - if (d->useShm) { -#ifdef HAVE_XSHM - - foreach(const QRect & r, tiles) { -// kDebug() << r; - gl |= r; - int y = r.y(); - int x = r.x(); - - while (x < r.right()) { - while (y < r.bottom()) { - if (y + d->updateTile->height > d->framebufferImage->height) { - y = d->framebufferImage->height - d->updateTile->height; - } - - if (x + d->updateTile->width > d->framebufferImage->width) { - x = d->framebufferImage->width - d->updateTile->width; - } - -// kDebug() << "x: " << x << " (" << r.x() << ") y: " << y << " (" << r.y() << ") " << r; - XShmGetImage(QX11Info::display(), win, d->updateTile, x, y, AllPlanes); - int pxsize = d->framebufferImage->bits_per_pixel / 8; - char *dest = fb + ((d->framebufferImage->bytes_per_line * y) + (x * pxsize)); - char *src = d->updateTile->data; - - for (int i = 0; i < d->updateTile->height; i++) { - memcpy(dest, src, d->updateTile->bytes_per_line); - dest += d->framebufferImage->bytes_per_line; - src += d->updateTile->bytes_per_line; - } - - y += d->updateTile->height; - } - - x += d->updateTile->width; - y = r.y(); - } - } -#endif - } else { - foreach(const QRect & r, tiles) { - XGetSubImage(QX11Info::display(), - win, - r.left(), - r.top(), - r.width(), - r.height(), - AllPlanes, - ZPixmap, - d->framebufferImage, - r.left(), - r.top() - ); - } - } - } - -// kDebug() << "tot: " << gl; -// kDebug() << tiles.size(); - ret = tiles; - tiles.clear(); - return ret; -} - -void X11FrameBuffer::startMonitor() -{ - d->running = true; -#ifdef HAVE_XDAMAGE - d->damage = XDamageCreate(QX11Info::display(), win, XDamageReportRawRectangles); - XDamageSubtract(QX11Info::display(), d->damage, None, None); -#endif -} - -void X11FrameBuffer::stopMonitor() -{ - d->running = false; -#ifdef HAVE_XDAMAGE - XDamageDestroy(QX11Info::display(), d->damage); -#endif -} - - - -EvWidget::EvWidget(X11FrameBuffer *x11fb) - : QWidget(0), fb(x11fb) -{ -#ifdef HAVE_XDAMAGE - int er; - XDamageQueryExtension(QX11Info::display(), &xdamageBaseEvent, &er); -#endif -} - -bool EvWidget::x11Event(XEvent *event) -{ -#ifdef HAVE_XDAMAGE - - if (event->type == xdamageBaseEvent + XDamageNotify) { - fb->handleXDamage(event); - return true; - } - -#endif - return false; -} - - - diff --git a/krfb/framebuffers/x11/x11framebuffer.h b/krfb/framebuffers/x11/x11framebuffer.h deleted file mode 100644 index 7b70e1ef..00000000 --- a/krfb/framebuffers/x11/x11framebuffer.h +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ -#ifndef KRFB_FRAMEBUFFER_X11_X11FRAMEBUFFER_H -#define KRFB_FRAMEBUFFER_X11_X11FRAMEBUFFER_H - -#include -#include - -class X11FrameBuffer; - -class EvWidget: public QWidget -{ - Q_OBJECT - -public: - EvWidget(X11FrameBuffer *x11fb); - -protected: - bool x11Event(XEvent *event); - -private: - X11FrameBuffer *fb; - int xdamageBaseEvent; -}; - -/** - @author Alessandro Praduroux -*/ -class X11FrameBuffer : public FrameBuffer -{ - Q_OBJECT -public: - X11FrameBuffer(WId id, QObject *parent = 0); - - ~X11FrameBuffer(); - - virtual QList modifiedTiles(); - virtual int depth(); - virtual int height(); - virtual int width(); - virtual int paddedWidth(); - virtual void getServerFormat(rfbPixelFormat &format); - virtual void startMonitor(); - virtual void stopMonitor(); - - - void handleXDamage(XEvent *event); -private: - void cleanupRects(); - void acquireEvents(); - - class P; - P *const d; -}; - -#endif diff --git a/krfb/framebuffers/x11/x11framebufferplugin.cpp b/krfb/framebuffers/x11/x11framebufferplugin.cpp deleted file mode 100644 index 670ebb8b..00000000 --- a/krfb/framebuffers/x11/x11framebufferplugin.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "x11framebufferplugin.h" - -#include "x11framebuffer.h" - -#include - - -X11FrameBufferPlugin::X11FrameBufferPlugin(QObject *parent, const QVariantList &args) - : FrameBufferPlugin(parent, args) -{ -} - -X11FrameBufferPlugin::~X11FrameBufferPlugin() -{ -} - -FrameBuffer *X11FrameBufferPlugin::frameBuffer(WId id) -{ - return new X11FrameBuffer(id); -} - -K_PLUGIN_FACTORY(factory, registerPlugin();) \ -K_EXPORT_PLUGIN(factory("krfb_framebuffer_x11")) - - -#include "moc_x11framebufferplugin.cpp" - diff --git a/krfb/framebuffers/x11/x11framebufferplugin.h b/krfb/framebuffers/x11/x11framebufferplugin.h deleted file mode 100644 index 01b72e8f..00000000 --- a/krfb/framebuffers/x11/x11framebufferplugin.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KRFB_FRAMEBUFFER_X11_X11FRAMEBUFFERPLUGIN_H -#define KRFB_FRAMEBUFFER_X11_X11FRAMEBUFFERPLUGIN_H - -#include "framebufferplugin.h" - -#include - -#include - -class FrameBuffer; - -class X11FrameBufferPlugin : public FrameBufferPlugin -{ - Q_OBJECT - -public: - X11FrameBufferPlugin(QObject *parent, const QVariantList &args); - virtual ~X11FrameBufferPlugin(); - - virtual FrameBuffer *frameBuffer(WId id); - -private: - Q_DISABLE_COPY(X11FrameBufferPlugin) -}; - - -#endif // Header guard - diff --git a/krfb/krfb/CMakeLists.txt b/krfb/krfb/CMakeLists.txt deleted file mode 100644 index c0902984..00000000 --- a/krfb/krfb/CMakeLists.txt +++ /dev/null @@ -1,101 +0,0 @@ -configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/config-krfb.h.cmake - ${CMAKE_CURRENT_BINARY_DIR}/config-krfb.h -) - -##################################### -# First target: libkrfbprivate - a library -# for linking plugins against. - -set(krfbprivate_SRCS - framebuffer.cpp - framebufferplugin.cpp -) - -add_library(krfbprivate SHARED ${krfbprivate_SRCS}) -target_link_libraries(krfbprivate - ${QT_QTCORE_LIBRARY} - ${QT_QTGUI_LIBRARY} - ${X11_X11_LIB} - ${LIBVNCSERVER_LIBRARIES} -) - -set_target_properties(krfbprivate PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_VERSION} -) - -install( - TARGETS krfbprivate - DESTINATION ${KDE4_LIB_INSTALL_DIR} - LIBRARY NAMELINK_SKIP -) - -install( - FILES krfb-framebuffer.desktop - DESTINATION ${KDE4_SERVICETYPES_INSTALL_DIR} -) - -##################################### -# Second target: krfb - the app -# itself. - -set(krfb_SRCS - connectiondialog.cpp - events.cpp - framebuffermanager.cpp - main.cpp - mainwindow.cpp - sockethelpers.cpp - trayicon.cpp - rfbservermanager.cpp - rfbserver.cpp - rfbclient.cpp - invitationsrfbserver.cpp - invitationsrfbclient.cpp - configtcp.ui - configsecurity.ui - connectionwidget.ui - mainwidget.ui -) - -kde4_add_kcfg_files(krfb_SRCS krfbconfig.kcfgc) - -set_source_files_properties( - ${CMAKE_CURRENT_SOURCE_DIR}/events.cpp - PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE -) - -add_executable(krfb ${krfb_SRCS}) - -target_link_libraries(krfb - krfbprivate - vncserver - ${X11_Xext_LIB} - ${X11_X11_LIB} - ${X11_Xdamage_LIB} - ${X11_XTest_LIB} - ${QT_QTNETWORK_LIBRARY} - KDE4::kdnssd - KDE4::kdeui - KDE4::kpasswdstore - ${LIBVNCSERVER_LIBRARIES} -) - -install( - TARGETS krfb - DESTINATION ${KDE4_BIN_INSTALL_DIR} -) - -########### install files ############### - -install( - PROGRAMS krfb.desktop - DESTINATION ${KDE4_XDG_APPS_INSTALL_DIR} -) - -install( - FILES krfb.notifyrc - DESTINATION ${KDE4_CONFIG_INSTALL_DIR}/notifications -) - diff --git a/krfb/krfb/Messages.sh b/krfb/krfb/Messages.sh deleted file mode 100644 index ce9a4562..00000000 --- a/krfb/krfb/Messages.sh +++ /dev/null @@ -1,3 +0,0 @@ -#! /bin/sh -$EXTRACTRC ui/*.ui *.kcfg >> rc.cpp -$XGETTEXT *.cpp -o $podir/krfb.pot diff --git a/krfb/krfb/config-krfb.h.cmake b/krfb/krfb/config-krfb.h.cmake deleted file mode 100644 index 5a10d255..00000000 --- a/krfb/krfb/config-krfb.h.cmake +++ /dev/null @@ -1,5 +0,0 @@ -/* Define if XDamage is available */ -#cmakedefine HAVE_XDAMAGE 1 - -/* Define if XShm is available */ -#cmakedefine HAVE_XSHM 1 diff --git a/krfb/krfb/configsecurity.ui b/krfb/krfb/configsecurity.ui deleted file mode 100644 index f14cf29a..00000000 --- a/krfb/krfb/configsecurity.ui +++ /dev/null @@ -1,40 +0,0 @@ - - - Security - - - - 0 - 0 - 507 - 201 - - - - - - - Allow remote connections to control your desktop - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - diff --git a/krfb/krfb/configtcp.ui b/krfb/krfb/configtcp.ui deleted file mode 100644 index f91c06d4..00000000 --- a/krfb/krfb/configtcp.ui +++ /dev/null @@ -1,93 +0,0 @@ - - TCP - - - - 0 - 0 - 400 - 169 - - - - - 9 - - - 6 - - - - - Announce the service on the local network - - - true - - - - - - - Use default port - - - true - - - - - - - 0 - - - 6 - - - - - Listening port: - - - kcfg_port - - - - - - - false - - - 65535 - - - - - - - - - kcfg_useDefaultPort - kcfg_port - - - - kcfg_useDefaultPort - toggled(bool) - kcfg_port - setDisabled(bool) - - - 120 - 53 - - - 277 - 122 - - - - - diff --git a/krfb/krfb/connectiondialog.cpp b/krfb/krfb/connectiondialog.cpp deleted file mode 100644 index 277c7e5e..00000000 --- a/krfb/krfb/connectiondialog.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2010 Collabora Ltd - @author George Kiagiadakis - Copyright (C) 2004 Nadeem Hasan - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "connectiondialog.h" - -#include -#include -#include - -#include -#include - -template -ConnectionDialog::ConnectionDialog(QWidget *parent) - : KDialog(parent) -{ - setCaption(i18n("New Connection")); - setButtons(Ok | Cancel); - setDefaultButton(Cancel); - setModal(true); - - setMinimumSize(500, 200); - - m_connectWidget = new QWidget(this); - m_ui.setupUi(m_connectWidget); - - m_ui.pixmapWidget->setPixmap(KIcon("krfb").pixmap(128)); - - KGuiItem accept = KStandardGuiItem::ok(); - accept.setText(i18n("Accept Connection")); - setButtonGuiItem(Ok, accept); - - KGuiItem refuse = KStandardGuiItem::cancel(); - refuse.setText(i18n("Refuse Connection")); - setButtonGuiItem(Cancel, refuse); - - setMainWidget(m_connectWidget); -} - -//********** - -InvitationsConnectionDialog::InvitationsConnectionDialog(QWidget *parent) - : ConnectionDialog(parent) -{ -} - -void InvitationsConnectionDialog::setRemoteHost(const QString &host) -{ - m_ui.remoteHost->setText(host); -} - -#include "moc_connectiondialog.cpp" diff --git a/krfb/krfb/connectiondialog.h b/krfb/krfb/connectiondialog.h deleted file mode 100644 index fc9dcd1e..00000000 --- a/krfb/krfb/connectiondialog.h +++ /dev/null @@ -1,67 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2010 Collabora Ltd - @author George Kiagiadakis - Copyright (C) 2004 Nadeem Hasan - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef CONNECTIONDIALOG_H -#define CONNECTIONDIALOG_H - -#include "ui_connectionwidget.h" -#include - -template -class ConnectionDialog : public KDialog -{ -public: - ConnectionDialog(QWidget *parent); - ~ConnectionDialog() {}; - - void setAllowRemoteControl(bool b); - bool allowRemoteControl(); - -protected: - QWidget *m_connectWidget; - UI m_ui; -}; - -template -void ConnectionDialog::setAllowRemoteControl(bool b) -{ - m_ui.cbAllowRemoteControl->setChecked(b); - m_ui.cbAllowRemoteControl->setVisible(b); -} - -template -bool ConnectionDialog::allowRemoteControl() -{ - return m_ui.cbAllowRemoteControl->isChecked(); -} - -//********* - -class InvitationsConnectionDialog : public ConnectionDialog -{ - Q_OBJECT -public: - InvitationsConnectionDialog(QWidget *parent); - void setRemoteHost(const QString & host); -}; - -#endif // CONNECTIONDIALOG_H - diff --git a/krfb/krfb/connectionwidget.ui b/krfb/krfb/connectionwidget.ui deleted file mode 100644 index 63fa90dc..00000000 --- a/krfb/krfb/connectionwidget.ui +++ /dev/null @@ -1,155 +0,0 @@ - - ConnectionWidget - - - - 0 - 0 - 500 - 212 - - - - - - - - 0 - 0 - - - - - 128 - 128 - - - - - - - - - - - 0 - 0 - - - - - 13 - 75 - true - - - - Attention - - - false - - - 0 - - - - - - - - 0 - 0 - - - - -1 - - - 5 - - - Somebody is requesting a connection to your computer. Granting this will allow the remote user to watch your desktop. - - - Qt::AutoText - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - true - - - 0 - - - 0 - - - - - - - - - - 75 - true - - - - Remote system: - - - false - - - - - - - - 75 - true - - - - 123.234.123.234 - - - false - - - - - - - - - - 0 - 0 - - - - If you turn this option on, the remote user can enter keystrokes and use your mouse pointer. This gives them full control over your computer, so be careful. When the option is disabled the remote user can only watch your screen. - - - Allow remote user to &control keyboard and mouse - - - - - - - - - - KPixmapWidget - QWidget -
kpixmapwidget.h
-
-
- -
diff --git a/krfb/krfb/events.cpp b/krfb/krfb/events.cpp deleted file mode 100644 index 3d9e8d27..00000000 --- a/krfb/krfb/events.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* - This file is part of the KDE project - - Copyright (C) 2010 Collabora Ltd. - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "events.h" - -#include -#include -#include -#include - -#include -#include -#include - -enum { - LEFTSHIFT = 1, - RIGHTSHIFT = 2, - ALTGR = 4 -}; - -class EventData -{ -public: - EventData(); - - //keyboard - Display *dpy; - signed char modifiers[0x100]; - KeyCode keycodes[0x100]; - KeyCode leftShiftCode; - KeyCode rightShiftCode; - KeyCode altGrCode; - char modifierState; - - //mouse - int buttonMask; - -private: - void init(); -}; - -K_GLOBAL_STATIC(EventData, data) - -EventData::EventData() -{ - init(); -} - -void EventData::init() -{ - dpy = QX11Info::display(); - buttonMask = 0; - - //initialize keycodes - KeySym key, *keymap; - int i, j, minkey, maxkey, syms_per_keycode; - - memset(modifiers, -1, sizeof(modifiers)); - - XDisplayKeycodes(dpy, &minkey, &maxkey); - Q_ASSERT(minkey >= 8); - Q_ASSERT(maxkey < 256); - keymap = (KeySym *) XGetKeyboardMapping(dpy, minkey, - (maxkey - minkey + 1), - &syms_per_keycode); - Q_ASSERT(keymap); - - for (i = minkey; i <= maxkey; i++) { - for (j = 0; j < syms_per_keycode; j++) { - key = keymap[(i-minkey)*syms_per_keycode+j]; - - if (key >= ' ' && key < 0x100 && i == XKeysymToKeycode(dpy, key)) { - keycodes[key] = i; - modifiers[key] = j; - } - } - } - - leftShiftCode = XKeysymToKeycode(dpy, XK_Shift_L); - rightShiftCode = XKeysymToKeycode(dpy, XK_Shift_R); - altGrCode = XKeysymToKeycode(dpy, XK_Mode_switch); - - XFree((char *)keymap); -} - -/* this function adjusts the modifiers according to mod (as from modifiers) and data->modifierState */ -static void tweakModifiers(signed char mod, bool down) -{ - bool isShift = data->modifierState & (LEFTSHIFT | RIGHTSHIFT); - - if (mod < 0) { - return; - } - - if (isShift && mod != 1) { - if (data->modifierState & LEFTSHIFT) { - XTestFakeKeyEvent(data->dpy, data->leftShiftCode, - down, CurrentTime); - } - - if (data->modifierState & RIGHTSHIFT) { - XTestFakeKeyEvent(data->dpy, data->rightShiftCode, - down, CurrentTime); - } - } - - if (!isShift && mod == 1) { - XTestFakeKeyEvent(data->dpy, data->leftShiftCode, - down, CurrentTime); - } - - if ((data->modifierState & ALTGR) && mod != 2) { - XTestFakeKeyEvent(data->dpy, data->altGrCode, - !down, CurrentTime); - } - - if (!(data->modifierState & ALTGR) && mod == 2) { - XTestFakeKeyEvent(data->dpy, data->altGrCode, - down, CurrentTime); - } -} - -void EventHandler::handleKeyboard(bool down, rfbKeySym keySym) -{ -#define ADJUSTMOD(sym,state) \ - if(keySym==sym) { if(down) data->modifierState|=state; else data->modifierState&=~state; } - - ADJUSTMOD(XK_Shift_L, LEFTSHIFT); - ADJUSTMOD(XK_Shift_R, RIGHTSHIFT); - ADJUSTMOD(XK_Mode_switch, ALTGR); - - if (keySym >= ' ' && keySym < 0x100) { - KeyCode k; - - if (down) { - tweakModifiers(data->modifiers[keySym], True); - } - - k = data->keycodes[keySym]; - - if (k != NoSymbol) { - XTestFakeKeyEvent(data->dpy, k, down, CurrentTime); - } - - if (down) { - tweakModifiers(data->modifiers[keySym], False); - } - } else { - KeyCode k = XKeysymToKeycode(data->dpy, keySym); - - if (k != NoSymbol) { - XTestFakeKeyEvent(data->dpy, k, down, CurrentTime); - } - } -} - -void EventHandler::handlePointer(int buttonMask, int x, int y) -{ - QDesktopWidget *desktopWidget = QApplication::desktop(); - - int screen = desktopWidget->screenNumber(); - - if (screen < 0) { - screen = 0; - } - - XTestFakeMotionEvent(data->dpy, screen, x, y, CurrentTime); - - for (int i = 0; i < 5; i++) { - if ((data->buttonMask&(1 << i)) != (buttonMask&(1 << i))) { - XTestFakeButtonEvent(data->dpy, - i + 1, - (buttonMask&(1 << i)) ? True : False, - CurrentTime); - } - } - - data->buttonMask = buttonMask; -} diff --git a/krfb/krfb/events.h b/krfb/krfb/events.h deleted file mode 100644 index ac5a230e..00000000 --- a/krfb/krfb/events.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - This file is part of the KDE project - - Copyright (C) 2010 Collabora Ltd. - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef EVENTS_H -#define EVENTS_H - -#include "rfb.h" - -class EventHandler -{ -public: - static void handleKeyboard(bool down, rfbKeySym key); - static void handlePointer(int buttonMask, int x, int y); -}; - -#endif diff --git a/krfb/krfb/framebuffer.cpp b/krfb/krfb/framebuffer.cpp deleted file mode 100644 index dfc17d85..00000000 --- a/krfb/krfb/framebuffer.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ - -#include "framebuffer.h" - -FrameBuffer::FrameBuffer(WId id, QObject *parent) - : QObject(parent), win(id) -{ -} - -FrameBuffer::~FrameBuffer() -{ - delete fb; -} - -char *FrameBuffer::data() -{ - return fb; -} - -QList< QRect > FrameBuffer::modifiedTiles() -{ - QList ret = tiles; - tiles.clear(); - return ret; -} - -int FrameBuffer::width() -{ - return 0; -} - -int FrameBuffer::height() -{ - return 0; -} - -void FrameBuffer::getServerFormat(rfbPixelFormat &) -{ -} - -int FrameBuffer::depth() -{ - return 32; -} - -int FrameBuffer::paddedWidth() -{ - return width() * depth() / 8; -} - -void FrameBuffer::startMonitor() -{ -} - -void FrameBuffer::stopMonitor() -{ -} - - -#include "moc_framebuffer.cpp" - diff --git a/krfb/krfb/framebuffer.h b/krfb/krfb/framebuffer.h deleted file mode 100644 index db8fe399..00000000 --- a/krfb/krfb/framebuffer.h +++ /dev/null @@ -1,57 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - - 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. -*/ - -#ifndef FRAMEBUFFER_H -#define FRAMEBUFFER_H - -#include "rfb.h" - -#include - -#include -#include -#include - -#include - -class FrameBuffer; -/** - @author Alessandro Praduroux -*/ -class KDE_EXPORT FrameBuffer : public QObject -{ - Q_OBJECT -public: - explicit FrameBuffer(WId id, QObject *parent = 0); - - virtual ~FrameBuffer(); - - char *data(); - - virtual QList modifiedTiles(); - virtual int paddedWidth(); - virtual int width(); - virtual int height(); - virtual int depth(); - virtual void startMonitor(); - virtual void stopMonitor(); - - virtual void getServerFormat(rfbPixelFormat &format); - -protected: - WId win; - char *fb; - QList tiles; - -private: - Q_DISABLE_COPY(FrameBuffer) - -}; - -#endif diff --git a/krfb/krfb/framebuffermanager.cpp b/krfb/krfb/framebuffermanager.cpp deleted file mode 100644 index 43d28b94..00000000 --- a/krfb/krfb/framebuffermanager.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "framebuffermanager.h" - -#include "framebufferplugin.h" -#include "krfbconfig.h" - -#include -#include -#include - -#include - -class FrameBufferManagerStatic -{ -public: - FrameBufferManager instance; -}; - -K_GLOBAL_STATIC(FrameBufferManagerStatic, frameBufferManagerStatic) - -FrameBufferManager::FrameBufferManager() -{ - kDebug(); - - loadPlugins(); -} - -FrameBufferManager::~FrameBufferManager() -{ - kDebug(); -} - -FrameBufferManager *FrameBufferManager::instance() -{ - kDebug(); - - return &frameBufferManagerStatic->instance; -} - -void FrameBufferManager::loadPlugins() -{ - kDebug(); - - // Load the all the plugin factories here, for use later. - KService::List offers = KServiceTypeTrader::self()->query("krfb/framebuffer"); - - KService::List::const_iterator iter; - - for (iter = offers.constBegin(); iter < offers.constEnd(); ++iter) { - QString error; - KService::Ptr service = *iter; - - KPluginFactory *factory = KPluginLoader(service->library()).factory(); - - if (!factory) { - kWarning() << "KPluginFactory could not load the plugin:" << service->library(); - continue; - } - - FrameBufferPlugin *plugin = factory->create(this); - - if (plugin) { - kDebug() << "Loaded plugin:" << service->name(); - m_plugins.insert(service->library(), plugin); - } else { - kDebug() << error; - } - } -} - -QSharedPointer FrameBufferManager::frameBuffer(WId id) -{ - kDebug(); - - // See if there is still an existing framebuffer to this WId. - if (m_frameBuffers.contains(id)) { - QWeakPointer weakFrameBuffer = m_frameBuffers.value(id); - - if (weakFrameBuffer) { - kDebug() << "Found cached frame buffer."; - return weakFrameBuffer.toStrongRef(); - } else { - kDebug() << "Found deleted cached frame buffer. Don't use."; - m_frameBuffers.remove(id); - } - } - - // We don't already have that frame buffer. - QMap::const_iterator iter = m_plugins.constBegin(); - - while (iter != m_plugins.constEnd()) { - - if (iter.key() == KrfbConfig::preferredFrameBufferPlugin()) { - kDebug() << "Using FrameBuffer:" << KrfbConfig::preferredFrameBufferPlugin(); - - QSharedPointer frameBuffer(iter.value()->frameBuffer(id)); - - if (frameBuffer) { - m_frameBuffers.insert(id, frameBuffer.toWeakRef()); - - return frameBuffer; - } - } - - ++iter; - } - - // No valid framebuffer plugin found. - kDebug() << "No valid framebuffer found. returning null."; - return QSharedPointer(); -} - - -#include "moc_framebuffermanager.cpp" - diff --git a/krfb/krfb/framebuffermanager.h b/krfb/krfb/framebuffermanager.h deleted file mode 100644 index 2935bf00..00000000 --- a/krfb/krfb/framebuffermanager.h +++ /dev/null @@ -1,63 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KRFB_FRAMEBUFFERMANAGER_H -#define KRFB_FRAMEBUFFERMANAGER_H - -#include "framebuffer.h" - -#include - -#include -#include -#include -#include - -#include - -class FrameBufferPlugin; -class KPluginFactory; - -class KDE_EXPORT FrameBufferManager : public QObject -{ - Q_OBJECT - friend class FrameBufferManagerStatic; - -public: - static FrameBufferManager *instance(); - - virtual ~FrameBufferManager(); - - QSharedPointer frameBuffer(WId id); - -private: - Q_DISABLE_COPY(FrameBufferManager) - - FrameBufferManager(); - - void loadPlugins(); - - QMap m_plugins; - QMap > m_frameBuffers; -}; - - -#endif // Header guard - diff --git a/krfb/krfb/framebufferplugin.cpp b/krfb/krfb/framebufferplugin.cpp deleted file mode 100644 index 80d57927..00000000 --- a/krfb/krfb/framebufferplugin.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "framebufferplugin.h" - -#include "framebuffer.h" - -FrameBufferPlugin::FrameBufferPlugin(QObject *parent, const QVariantList &) - : QObject(parent) -{ -} - -FrameBufferPlugin::~FrameBufferPlugin() -{ -} - - -#include "moc_framebufferplugin.cpp" - diff --git a/krfb/krfb/framebufferplugin.h b/krfb/krfb/framebufferplugin.h deleted file mode 100644 index 190354e1..00000000 --- a/krfb/krfb/framebufferplugin.h +++ /dev/null @@ -1,45 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef LIB_KRFB_FRAMEBUFFERPLUGIN_H -#define LIB_KRFB_FRAMEBUFFERPLUGIN_H - -#include - -#include - -#include - -class FrameBuffer; - -class KDE_EXPORT FrameBufferPlugin : public QObject -{ - Q_OBJECT - -public: - FrameBufferPlugin(QObject *parent, const QVariantList &args); - virtual ~FrameBufferPlugin(); - - virtual FrameBuffer *frameBuffer(WId id) = 0; -}; - - -#endif // Header guard - diff --git a/krfb/krfb/invitationsrfbclient.cpp b/krfb/krfb/invitationsrfbclient.cpp deleted file mode 100644 index 6de87996..00000000 --- a/krfb/krfb/invitationsrfbclient.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "rfb.h" -#include "invitationsrfbclient.h" -#include "invitationsrfbserver.h" -#include "krfbconfig.h" -#include "sockethelpers.h" -#include "connectiondialog.h" -#include -#include -#include -#include - -struct PendingInvitationsRfbClient::Private -{ - Private(rfbClientPtr client) : - client(client), - askOnConnect(true) - {} - - rfbClientPtr client; - QSocketNotifier *notifier; - bool askOnConnect; -}; - -PendingInvitationsRfbClient::PendingInvitationsRfbClient(rfbClientPtr client, QObject *parent) : - PendingRfbClient(client, parent), - d(new Private(client)) -{ - d->client->clientGoneHook = RfbClient::clientGoneHookNoop; - d->notifier = new QSocketNotifier(client->sock, QSocketNotifier::Read, this); - d->notifier->setEnabled(true); - connect(d->notifier, SIGNAL(activated(int)), - this, SLOT(onSocketActivated())); -} - -PendingInvitationsRfbClient::~PendingInvitationsRfbClient() -{ - delete d; -} - -void PendingInvitationsRfbClient::processNewClient() -{ - QString host = peerAddress(m_rfbClient->sock) + ":" + QString::number(peerPort(m_rfbClient->sock)); - - if (d->askOnConnect == false) { - - KNotification::event( - "krfb/NewConnectionAutoAccepted", - QString(), - i18n("Accepted connection from %1", host) - ); - accept(new InvitationsRfbClient(m_rfbClient, parent())); - - } else { - - KNotification::event( - "krfb/NewConnectionOnHold", - QString(), - i18n("Received connection from %1, on hold (waiting for confirmation)", host) - ); - - InvitationsConnectionDialog *dialog = new InvitationsConnectionDialog(0); - dialog->setRemoteHost(host); - dialog->setAllowRemoteControl(KrfbConfig::allowDesktopControl()); - - connect(dialog, SIGNAL(okClicked()), SLOT(dialogAccepted())); - connect(dialog, SIGNAL(cancelClicked()), SLOT(reject())); - - dialog->show(); - } -} - -void PendingInvitationsRfbClient::onSocketActivated() -{ - //Process not only one, but all pending messages. - //poll() idea/code copied from vino: - // Copyright (C) 2003 Sun Microsystems, Inc. - // License: GPL v2 or later - struct pollfd pollfd = { d->client->sock, POLLIN|POLLPRI, 0 }; - - while(poll(&pollfd, 1, 0) == 1) { - - if(d->client->state == rfbClientRec::RFB_INITIALISATION) { - d->notifier->setEnabled(false); - //Client is Authenticated - processNewClient(); - break; - } - rfbProcessClientMessage(d->client); - - //This is how we handle disconnection. - //if rfbProcessClientMessage() finds out that it can't read the socket, - //it closes it and sets it to -1. So, we just have to check this here - //and call rfbClientConnectionGone() if necessary. This will call - //the clientGoneHook which in turn will remove this RfbClient instance - //from the server manager and will call deleteLater() to delete it - if (d->client->sock == -1) { - kDebug() << "disconnected from socket signal"; - d->notifier->setEnabled(false); - rfbClientConnectionGone(d->client); - break; - } - } -} - -bool PendingInvitationsRfbClient::checkPassword(const QByteArray & encryptedPassword) -{ - QByteArray password ; - kDebug() << "about to start autentication"; - - if(InvitationsRfbServer::instance->allowUnattendedAccess() && vncAuthCheckPassword( - InvitationsRfbServer::instance->unattendedPassword().toLocal8Bit(), - encryptedPassword) ) { - d->askOnConnect = false; - return true; - } - - return vncAuthCheckPassword( - InvitationsRfbServer::instance->desktopPassword().toLocal8Bit(), - encryptedPassword); -} - -void PendingInvitationsRfbClient::dialogAccepted() -{ - InvitationsConnectionDialog *dialog = qobject_cast(sender()); - Q_ASSERT(dialog); - - InvitationsRfbClient *client = new InvitationsRfbClient(m_rfbClient, parent()); - client->setControlEnabled(dialog->allowRemoteControl()); - accept(client); -} - -#include "moc_invitationsrfbclient.cpp" diff --git a/krfb/krfb/invitationsrfbclient.h b/krfb/krfb/invitationsrfbclient.h deleted file mode 100644 index 3a598802..00000000 --- a/krfb/krfb/invitationsrfbclient.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright (C) 2010 Collabora Ltd - @author George Kiagiadakis - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#ifndef INVITATIONSRFBCLIENT_H -#define INVITATIONSRFBCLIENT_H - -#include "rfbclient.h" - -class InvitationsRfbClient : public RfbClient -{ -public: - InvitationsRfbClient(rfbClientPtr client, QObject* parent = 0) - : RfbClient(client, parent) {} -}; - - -class PendingInvitationsRfbClient : public PendingRfbClient -{ - Q_OBJECT -public: - PendingInvitationsRfbClient(rfbClientPtr client, QObject *parent = 0); - virtual ~PendingInvitationsRfbClient(); - -protected Q_SLOTS: - virtual void processNewClient(); - virtual void onSocketActivated(); - virtual bool checkPassword(const QByteArray & encryptedPassword); - -private Q_SLOTS: - void dialogAccepted(); - -private: - struct Private; - Private* const d; -}; - -#endif // INVITATIONSRFBCLIENT_H diff --git a/krfb/krfb/invitationsrfbserver.cpp b/krfb/krfb/invitationsrfbserver.cpp deleted file mode 100644 index 3e384358..00000000 --- a/krfb/krfb/invitationsrfbserver.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "invitationsrfbserver.h" -#include "invitationsrfbclient.h" -#include "krfbconfig.h" -#include "rfbservermanager.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -static QString obscurePass(const QString &password) -{ - const QByteArray passwordbytes = password.toAscii(); - const QByteArray resultbytes = passwordbytes.toBase64(); - return QString::fromLatin1(resultbytes.constData(), resultbytes.size()); -} - -static QString unobscurePass(const QString &password) -{ - const QByteArray passwordbytes = password.toLatin1(); - const QByteArray resultbytes = QByteArray::fromBase64(passwordbytes); - return QString::fromAscii(resultbytes.constData(), resultbytes.size()); -} - -//static -InvitationsRfbServer *InvitationsRfbServer::instance; - -//static -void InvitationsRfbServer::init() -{ - instance = new InvitationsRfbServer; - instance->m_publicService = new KDNSSD(); - instance->setListeningAddress("0.0.0.0"); - instance->setListeningPort(KrfbConfig::port()); - instance->setPasswordRequired(true); - - instance->m_passwdStore = new KPasswdStore(instance); - instance->m_passwdStore->setStoreID("krfb"); - QString desktopPassword; - QString unattendedPassword; - if ( !instance->m_passwdStore->openStore() ) { - desktopPassword = instance->m_passwdStore->getPasswd(KPasswdStore::makeKey("desktopSharingPassword")); - if (!desktopPassword.isEmpty()) { - instance->m_desktopPassword = desktopPassword; - emit instance->passwordChanged(instance->m_desktopPassword); - } - - unattendedPassword = instance->m_passwdStore->getPasswd(KPasswdStore::makeKey("unattendedAccessPassword")); - if (!unattendedPassword.isEmpty()) { - instance->m_unattendedPassword = unattendedPassword; - } - } else { - kDebug() << "KPasswdStore is disabled, falling back to config file"; - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup krfbConfig(config,"Security"); - - desktopPassword = unobscurePass(krfbConfig.readEntry("desktopPassword", QString())); - if(!desktopPassword.isEmpty()) { - instance->m_desktopPassword = desktopPassword; - emit instance->passwordChanged(instance->m_desktopPassword); - } - - unattendedPassword = unobscurePass(krfbConfig.readEntry("unattendedPassword", QString())); - if(!unattendedPassword.isEmpty()) { - instance->m_unattendedPassword = unattendedPassword; - } - } -} - -const QString& InvitationsRfbServer::desktopPassword() const -{ - return m_desktopPassword; -} - -void InvitationsRfbServer::setDesktopPassword(const QString& password) -{ - m_desktopPassword = password; -} - -const QString& InvitationsRfbServer::unattendedPassword() const -{ - return m_unattendedPassword; -} - -void InvitationsRfbServer::setUnattendedPassword(const QString& password) -{ - m_unattendedPassword = password; -} - -bool InvitationsRfbServer::allowUnattendedAccess() const -{ - return m_allowUnattendedAccess; -} - -bool InvitationsRfbServer::start() -{ - if(RfbServer::start()) { - if(KrfbConfig::publishService()) { - m_publicService->publishService( - "_rfb._tcp", - KrfbConfig::port(), - i18n("%1@%2 (shared desktop)", KUser().loginName(), QHostInfo::localHostName()) - ); - } - return true; - } - return false; -} - -void InvitationsRfbServer::stop(bool disconnectClients) -{ - if(m_publicService) - m_publicService->unpublishService(); - RfbServer::stop(disconnectClients); -} - -void InvitationsRfbServer::toggleUnattendedAccess(bool allow) -{ - m_allowUnattendedAccess = allow; -} - -InvitationsRfbServer::InvitationsRfbServer() -{ - m_desktopPassword = readableRandomString(4)+"-"+readableRandomString(3); - m_unattendedPassword = readableRandomString(4)+"-"+readableRandomString(3); - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup krfbConfig(config,"Security"); - m_allowUnattendedAccess = krfbConfig.readEntry( - "allowUnattendedAccess", QVariant(false)).toBool(); -} - -InvitationsRfbServer::~InvitationsRfbServer() -{ - stop(); - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup krfbConfig(config,"Security"); - krfbConfig.writeEntry("allowUnattendedAccess",m_allowUnattendedAccess); - if (m_passwdStore && m_passwdStore->openStore()) { - m_passwdStore->storePasswd(KPasswdStore::makeKey("desktopSharingPassword"), m_desktopPassword); - m_passwdStore->storePasswd(KPasswdStore::makeKey("unattendedAccessPassword"), m_unattendedPassword); - } else { - krfbConfig.writeEntry("desktopPassword", obscurePass(m_desktopPassword)); - krfbConfig.writeEntry("unattendedPassword", obscurePass(m_unattendedPassword)); - krfbConfig.writeEntry("allowUnattendedAccess", m_allowUnattendedAccess); - } -} - -PendingRfbClient* InvitationsRfbServer::newClient(rfbClientPtr client) -{ - return new PendingInvitationsRfbClient(client, this); -} - -// a random string that doesn't contain i, I, o, O, 1, l, 0 -QString InvitationsRfbServer::readableRandomString(int length) -{ - QString str; - while (length) { - int r = KRandom::randomMax(62); - r += 48; - if (r > 57) { - r += 7; - } - if (r > 90) { - r += 6; - } - char c = char(r); - if ((c == 'i') || - (c == 'I') || - (c == '1') || - (c == 'l') || - (c == 'o') || - (c == 'O') || - (c == '0')) { - continue; - } - str += c; - length--; - } - return str; -} - -#include "moc_invitationsrfbserver.cpp" diff --git a/krfb/krfb/invitationsrfbserver.h b/krfb/krfb/invitationsrfbserver.h deleted file mode 100644 index d3afd052..00000000 --- a/krfb/krfb/invitationsrfbserver.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#ifndef INVITATIONSRFBSERVER_H -#define INVITATIONSRFBSERVER_H - -#include "rfbserver.h" - -#include -#include - -class InvitationsRfbServer : public RfbServer -{ - Q_OBJECT -public: - static InvitationsRfbServer *instance; - static void init(); - - const QString& desktopPassword() const; - void setDesktopPassword(const QString&); - const QString& unattendedPassword() const; - void setUnattendedPassword(const QString&); - bool allowUnattendedAccess() const; - -Q_SIGNALS: - void passwordChanged(const QString&); - -public Q_SLOTS: - bool start(); - void stop(bool disconnectClients=true); - void toggleUnattendedAccess(bool allow=true); - -protected: - InvitationsRfbServer(); - virtual ~InvitationsRfbServer(); - virtual PendingRfbClient* newClient(rfbClientPtr client); - -private: - KDNSSD *m_publicService; - bool m_allowUnattendedAccess; - QString m_desktopPassword; - QString m_unattendedPassword; - KPasswdStore *m_passwdStore; - - QString readableRandomString(int); - Q_DISABLE_COPY(InvitationsRfbServer) -}; - -#endif // INVITATIONSRFBSERVER_H diff --git a/krfb/krfb/krfb-framebuffer.desktop b/krfb/krfb/krfb-framebuffer.desktop deleted file mode 100644 index 35efd14d..00000000 --- a/krfb/krfb/krfb-framebuffer.desktop +++ /dev/null @@ -1,55 +0,0 @@ -[Desktop Entry] -Type=ServiceType -X-KDE-ServiceType=krfb/framebuffer - -Comment=Frame Buffer plugins for KRfb -Comment[ast]=Complementu de buffer pa KRfb -Comment[bg]=Приставки за фреймбуфер за KRfb -Comment[bs]=Priključci framebafera za KRfb -Comment[ca]=Connectors de «framebuffer» per al KRfb. -Comment[ca@valencia]=Connectors de «framebuffer» per al KRfb. -Comment[cs]=Moduly Frame bufferu pro KRfb -Comment[da]=Framebuffer-plugins til KRfb -Comment[de]=Framebuffer-Module für KRfb -Comment[el]=Πρόσθετα μνήμης εξόδου βίντεο καρέ για το KRfb -Comment[en_GB]=Frame Buffer plugins for KRfb -Comment[es]=Complementos de memoria intermedia de vídeo para KRfb -Comment[et]=KRfb kaadripuhvri plugin -Comment[eu]=Irteerako bideoaren pluginak KRfb-rentzako -Comment[fi]=Kehyspuskuriliitännäinen kohteelle KRfb -Comment[fr]=Modules externes de sortie vidéo pour Krfb -Comment[ga]=Breiseáin Mhaoláin Fráma le haghaidh KRfb -Comment[gl]=Engadido de frame buffer para KRfb -Comment[hr]=Priključci za međuspremnike okvira za KRfb -Comment[hu]=Framebuffer bővítmények a Krfb-hez -Comment[ia]=Plug-ins de Frame Buffer per KRfb -Comment[it]=Estensioni del framebuffer per KRfb -Comment[ja]=KRfb の フレームバッファプラグイン -Comment[kk]=KRfb кадр буфер плагині -Comment[km]=កម្មវិធី​ជំនួយ​ Frame Buffer សម្រាប់ KRfb -Comment[ko]=KRfb 프레임버퍼 플러그인 -Comment[lt]=Frame Buffer priedai skirti KRfb -Comment[lv]=Kadru bufera sprudņi priekš KRfb -Comment[nb]=Rammebuffer-programtillegg for KRfb -Comment[nds]=Bildpuffer-Modulen för KRfb -Comment[nl]=Framebuffer-plugins voor KRfb -Comment[nn]=Framebuffer-tillegg KRfb -Comment[pa]=KRfb ਲਈ ਫਰੇਮ ਬਫ਼ਰ ਪਲੱਗਇਨ -Comment[pl]=Wtyczki buforów ramek dla KRfb -Comment[pt]='Plugins' de 'framebuffers' para o KRfb -Comment[pt_BR]=Plugins de framebuffers para o KRfb -Comment[ru]=Модуль буфера кадров для KRfb -Comment[si]=KRfb සඳහා රාමු බෆර ප්ලගින -Comment[sk]=Frame Buffer modul pre KRfb -Comment[sl]=Vstavki slikovnih medpomnilnikov za KRFB -Comment[sr]=Прикључци кадробафера за КРФБ -Comment[sr@ijekavian]=Прикључци кадробафера за КРФБ -Comment[sr@ijekavianlatin]=Priključci kadrobafera za KRFB -Comment[sr@latin]=Priključci kadrobafera za KRFB -Comment[sv]=Insticksprogram med rambuffert för Krfb -Comment[th]=ส่วนเสริมของ KRfb สำหรับจัดการเฟรมบัฟเฟอร์ -Comment[tr]=KRfb için Çerçeve Tamponu eklentileri -Comment[uk]=Додатки буфера кадрів для KRfb -Comment[x-test]=xxFrame Buffer plugins for KRfbxx -Comment[zh_CN]=KRfb 帧缓冲插件 -Comment[zh_TW]=KRfb 的 Frame Buffer 外掛程式 diff --git a/krfb/krfb/krfb.desktop b/krfb/krfb/krfb.desktop deleted file mode 100755 index 70769df3..00000000 --- a/krfb/krfb/krfb.desktop +++ /dev/null @@ -1,147 +0,0 @@ -# KDE Config File -[Desktop Entry] -Type=Application -Exec=krfb --icon '%i' --caption '%c' -Icon=krfb -StartupNotify=true -X-DocPath=krfb/index.html -Terminal=false -Name=Krfb -Name[ar]=Krfb -Name[ast]=Krfb -Name[bg]=Krfb -Name[bn]=কে-আর-এফ-বি -Name[br]=Krfb -Name[bs]=Krfb -Name[ca]=Krfb -Name[ca@valencia]=Krfb -Name[cs]=Krfb -Name[da]=Krfb -Name[de]=Krfb -Name[el]=Krfb -Name[en_GB]=Krfb -Name[eo]=Krfb -Name[es]=Krfb -Name[et]=Krfb -Name[eu]=Krfb -Name[fi]=Krfb -Name[fr]=Krfb -Name[ga]=Krfb -Name[gl]=Krfb -Name[he]=Krfb -Name[hi]=केआरएफबी -Name[hne]=केआरएफबी -Name[hr]=Krfb -Name[hu]=Krfb -Name[ia]=Krfb -Name[is]=Krfb -Name[it]=Krfb -Name[ja]=Krfb -Name[kk]=Krfb -Name[km]=Krfb -Name[ko]=Krfb -Name[lt]=Krfb -Name[lv]=Krfb -Name[ml]=കെആര്‍എഫ്ബി -Name[mr]=के-आर-एफ-बी -Name[nb]=Krfb -Name[nds]=KRfb -Name[ne]=Krfb -Name[nl]=Krfb -Name[nn]=Krfb -Name[pa]=Krfb -Name[pl]=Krfb -Name[pt]=Krfb -Name[pt_BR]=Krfb -Name[ro]=Krfb -Name[ru]=Krfb -Name[si]=Krfb -Name[sk]=Krfb -Name[sl]=Krfb -Name[sq]=Krfb -Name[sr]=КРФБ -Name[sr@ijekavian]=КРФБ -Name[sr@ijekavianlatin]=KRFB -Name[sr@latin]=KRFB -Name[sv]=Krfb -Name[tr]=Krfb -Name[ug]=Krfb -Name[uk]=Krfb -Name[uz]=Krfb -Name[uz@cyrillic]=Krfb -Name[vi]=Krfb -Name[x-test]=xxKrfbxx -Name[zh_CN]=Krfb -Name[zh_HK]=Krfb -Name[zh_TW]=桌面分享_Krfb -GenericName=Desktop Sharing -GenericName[ar]=مشاركة سطح المكتب -GenericName[ast]=Escritoriu compartíu -GenericName[bg]=Споделяне на работния плот -GenericName[bn]=ডেস্কটপ ভাগাভাগি -GenericName[br]=Rannañ ar vurev -GenericName[bs]=Dijeljenje radne površine -GenericName[ca]=Compartició de l'escriptori -GenericName[ca@valencia]=Compartició de l'escriptori -GenericName[cs]=Sdílení pracovní plochy -GenericName[cy]=Rhannu Penbwrdd -GenericName[da]=Skrivebordsdeling -GenericName[de]=Arbeitsfläche freigeben -GenericName[el]=Κοινή χρήση επιφάνειας εργασίας -GenericName[en_GB]=Desktop Sharing -GenericName[eo]=Tabula komunigado -GenericName[es]=Escritorio compartido -GenericName[et]=Töölaua jagamine -GenericName[eu]=Mahaigaina partekatzea -GenericName[fa]=اشتراک رومیزی -GenericName[fi]=Työpöydän jakaminen -GenericName[fr]=Partage de bureaux -GenericName[ga]=Roinnt Deisce -GenericName[gl]=Compartimento de escritorio -GenericName[he]=שיתוף שולחנות עבודה -GenericName[hi]=डेस्कटॉप साझेदारी -GenericName[hne]=डेस्कटाप साझेदारी -GenericName[hr]=Dijeljenje radne površine -GenericName[hu]=Munkaasztal-megosztás -GenericName[ia]=Compartir de scriptorio -GenericName[is]=Skjáborðsmiðlun -GenericName[it]=Condivisione del desktop -GenericName[ja]=デスクトップ共有 -GenericName[kk]=Үстелді ортақтастыру -GenericName[km]=ការ​ចែក​រំលែក​ផ្ទៃ​តុ -GenericName[ko]=데스크톱 공유 -GenericName[lt]=Dalinimasis darbastaliu -GenericName[lv]=Darbvirsmas koplietošana -GenericName[ml]=പണിയിടം പങ്കുവെക്കല്‍ -GenericName[mr]=डेस्कटॉप शेअरींग -GenericName[nb]=Delte skrivebord -GenericName[nds]=Schriefdisch-Freegaav -GenericName[ne]=डेस्कटप साझेदारी -GenericName[nl]=Bureaublad delen -GenericName[nn]=Skrivebordsdeling -GenericName[pa]=ਡੈਸਕਟਾਪ ਸ਼ੇਅਰਿੰਗ -GenericName[pl]=Współdzielenie pulpitu -GenericName[pt]=Partilha do Ecrã -GenericName[pt_BR]=Compartilhamento de ambiente de trabalho -GenericName[ro]=Partajare birou -GenericName[ru]=Общий рабочий стол -GenericName[si]=වැඩතල හවුල් -GenericName[sk]=Zdieľanie pracovnej plochy -GenericName[sl]=Souporaba namizja -GenericName[sr]=Дељење површи -GenericName[sr@ijekavian]=Дијељење површи -GenericName[sr@ijekavianlatin]=Dijeljenje površi -GenericName[sr@latin]=Deljenje površi -GenericName[sv]=Dela ut skrivbordet -GenericName[th]=ใช้งานพื้นที่ทำงานร่วมกัน -GenericName[tr]=Masaüstü Paylaşımı -GenericName[ug]=ئۈستەلئۈستىنى ھەمبەھىرلەش -GenericName[uk]=Спільні стільниці -GenericName[uz]=Ish stoli bilan boʻlishish -GenericName[uz@cyrillic]=Иш столи билан бўлишиш -GenericName[vi]=Chia sẻ màn hình nền -GenericName[x-test]=xxDesktop Sharingxx -GenericName[zh_CN]=桌面共享 -GenericName[zh_HK]=桌面分享 -GenericName[zh_TW]=桌面分享 -Categories=Qt;KDE;System;Network;RemoteAccess; diff --git a/krfb/krfb/krfb.kcfg b/krfb/krfb/krfb.kcfg deleted file mode 100644 index bd0affd8..00000000 --- a/krfb/krfb/krfb.kcfg +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - true - - - - 5900 - - - - true - - - - - - true - - - - false - - - - - - - - - - - - krfb_framebuffer_x11 - - - diff --git a/krfb/krfb/krfb.notifyrc b/krfb/krfb/krfb.notifyrc deleted file mode 100644 index 593dbc16..00000000 --- a/krfb/krfb/krfb.notifyrc +++ /dev/null @@ -1,1278 +0,0 @@ -[krfb] -IconName=krfb -Comment=Desktop Sharing -Comment[af]=Werkskerm Deeling -Comment[ar]=مشاركة سطح المكتب -Comment[ast]=Escritoriu compartíu -Comment[bg]=Споделяне на работния плот -Comment[bn]=ডেস্কটপ ভাগাভাগি -Comment[br]=Rannañ ar vurev -Comment[bs]=Dijeljenje radne površine -Comment[ca]=Compartició de l'escriptori -Comment[ca@valencia]=Compartició de l'escriptori -Comment[cs]=Sdílení pracovní plochy -Comment[cy]=Rhannu Penbwrdd -Comment[da]=Skrivebordsdeling -Comment[de]=Arbeitsflächen-Freigabe -Comment[el]=Κοινή χρήση επιφάνειας εργασίας -Comment[en_GB]=Desktop Sharing -Comment[eo]=Tabula komunigado -Comment[es]=Escritorio compartido -Comment[et]=Töölaua jagamine -Comment[eu]=Mahaigaina partekatzea -Comment[fi]=Työpöydän jakaminen -Comment[fr]=Partage de bureaux -Comment[ga]=Roinnt Deisce -Comment[gl]=Compartición do escritorio -Comment[he]=שיתוף שולחנות עבודה -Comment[hi]=डेस्कटॉप साझेदारी -Comment[hne]=डेस्कटाप साझेदारी -Comment[hr]=Dijeljenje radne površine -Comment[hu]=Munkaasztal-megosztás -Comment[ia]=Compartir de scriptorio -Comment[is]=Skjáborðamiðlun -Comment[it]=Condivisione del desktop -Comment[ja]=デスクトップ共有 -Comment[kk]=Үстелді ортақтастыру -Comment[km]=ការ​ចែក​រំលែក​ផ្ទែ​តុ -Comment[ko]=데스크톱 공유 -Comment[lt]=Dalinimasis darbastaliu -Comment[lv]=Darbvirsmas koplietošana -Comment[mk]=Делење на работната површина -Comment[ml]=പണിയിടം പങ്കുവെക്കല്‍ -Comment[mr]=डेस्कटॉप शेअरींग -Comment[ms]=Perkongsian Ruang Kerja -Comment[nb]=Delte skrivebord -Comment[nds]=Schriefdisch-Freegaav -Comment[nl]=Bureaublad delen -Comment[nn]=Skrivebordsdeling -Comment[pa]=ਡੈਸਕਟਾਪ ਸ਼ੇਅਰਿੰਗ -Comment[pl]=Współdzielenie pulpitu -Comment[pt]=Partilha do Ecrã -Comment[pt_BR]=Compartilhamento do ambiente de trabalho -Comment[ro]=Partajare birou -Comment[ru]=Параметры общего рабочего стола -Comment[si]=වැඩතල හවුල් -Comment[sk]=Zdieľanie pracovnej plochy -Comment[sl]=Souporaba namizja -Comment[sr]=Дељење површи -Comment[sr@ijekavian]=Дијељење површи -Comment[sr@ijekavianlatin]=Dijeljenje površi -Comment[sr@latin]=Deljenje površi -Comment[sv]=Dela ut skrivbordet -Comment[ta]=பணிமேடை பகிர்வு -Comment[tg]=Истифодаи Муштараки Мизи Корӣ -Comment[th]=ใช้งานพื้นที่ทำงานร่วมกัน -Comment[tr]=Masaüstü Paylaşımı -Comment[ug]=ئۈستەلئۈستىنى ھەمبەھىرلەش -Comment[uk]=Спільні стільниці -Comment[xh]=Ulwahlulelano lwe Desktop -Comment[x-test]=xxDesktop Sharingxx -Comment[zh_CN]=桌面共享 -Comment[zh_HK]=桌面分享 -Comment[zh_TW]=桌面分享 - -[krfb/UserAcceptsConnection] -Name=User Accepts Connection -Name[ar]=المستخدم يقبل الاتصال -Name[ast]=L'usuariu aceuta la conexón -Name[bg]=Потребителят приема връзката -Name[bs]=Korisnik prihvata vezu -Name[ca]=L'usuari accepta la connexió -Name[ca@valencia]=L'usuari accepta la connexió -Name[cs]=Uživatel přijímá spojení -Name[da]=Bruger accepterer forbindelse -Name[de]=Benutzer akzeptiert Verbindung -Name[el]=Ο χρήστης δέχεται τη σύνδεση -Name[en_GB]=User Accepts Connection -Name[eo]=Uzanto akceptas la konekton -Name[es]=El usuario acepta la conexión -Name[et]=Kasutaja nõustub ühendusega -Name[eu]=Erabiltzaileak konexioa onartu du -Name[fi]=Käyttäjä hyväksyy yhteyden -Name[fr]=L'utilisateur accepte la connexion -Name[ga]=Glacann an tÚsáideoir Le Ceangal -Name[gl]=O usuario acepta a conexión -Name[hi]=उपयोक्ता ने कनेक्शन स्वीकारा -Name[hne]=कमइया हर कनेक्सन स्वीकारा -Name[hr]=Korisnik prihvaća vezu -Name[hu]=A felhasználó engedélyezi a csatlakozást -Name[ia]=Usator da acceptation a connexion -Name[is]=Notandi samþykkir tengingar -Name[it]=L'utente accetta la connessione -Name[ja]=ユーザが接続を許可 -Name[kk]=Пайдаланушы қосылымды қабылдайды -Name[km]=អ្នក​ប្រើ​ទទួល​យក​ការ​ត​ភ្ជាប់ -Name[ko]=사용자가 연결을 수락함 -Name[lt]=Naudotojas priėmė kvietimą -Name[lv]=Lietotājs atļauj savienojumu -Name[ml]=ഉപയോക്താവ് ബന്ധം സ്വീകരിക്കുന്നു -Name[mr]=वापरकर्ता जुळवणी स्वीकारतो -Name[nb]=Bruker godtar tilkobling -Name[nds]=Bruker lett tokoppeln to -Name[nl]=Gebruiker accepteert de verbinding -Name[nn]=Brukar godtek tilkopling -Name[pa]=ਯੂਜ਼ਰ ਨੇ ਕੁਨੈਕਸ਼ਨ ਮਨਜ਼ੂਰ ਕੀਤਾ -Name[pl]=Połączenie zaakceptowane przez użytkownika -Name[pt]=O Utilizador Aceita a Ligação -Name[pt_BR]=O usuário aceita a conexão -Name[ro]=Utilizatorul acceptă conexiunea -Name[ru]=Пользователь принимает соединения -Name[si]=සබැඳිය පරිශීලකයා තහවුරු කරයි -Name[sk]=Užívateľ akceptuje pripojenie -Name[sl]=Uporabnik sprejema povezavo -Name[sr]=Корисник прихвата везу -Name[sr@ijekavian]=Корисник прихвата везу -Name[sr@ijekavianlatin]=Korisnik prihvata vezu -Name[sr@latin]=Korisnik prihvata vezu -Name[sv]=Användaren accepterar anslutning -Name[th]=ผู้ใช้ยอมรับการเชื่อมต่อ -Name[tr]=Kullanıcı Bağlantıyı Kabul Etti -Name[ug]=ئىشلەتكۈچى باغلىنىشقا قوشۇلدى -Name[uk]=Користувач приймає з’єднання -Name[x-test]=xxUser Accepts Connectionxx -Name[zh_CN]=用户接受连接 -Name[zh_TW]=使用者接受連線 -Comment=User accepts connection -Comment[af]=Gebruiker aanvaar verbinding -Comment[ar]=المستخدم يقبل الاتصال -Comment[ast]=L'usuariu aceuta la conexón -Comment[bg]=Потребителят приема връзката -Comment[bn]=ব্যবহারকারী সংযোগ গ্রহণ করে -Comment[bs]=Korisnik prihvata vezu -Comment[ca]=L'usuari accepta la connexió -Comment[ca@valencia]=L'usuari accepta la connexió -Comment[cs]=Uživatel přijímá spojení -Comment[cy]=Mae'r defnyddiwr yn derbyn y cysylltiad -Comment[da]=Bruger accepterer forbindelse -Comment[de]=Der Benutzer akzeptiert die Verbindung -Comment[el]=Ο χρήστης δέχεται τη σύνδεση -Comment[en_GB]=User accepts connection -Comment[eo]=Uzanto akceptas la konekton -Comment[es]=El usuario acepta la conexión -Comment[et]=Kasutaja nõustub ühendusega -Comment[eu]=Erabiltzaileak konexioa onartu du -Comment[fi]=Käyttäjä hyväksyy yhteyden -Comment[fr]=L'utilisateur accepte la connexion -Comment[ga]=Glacann úsáideoir le ceangal -Comment[gl]=O usuario acepta a conexión -Comment[he]=המשתמש מקבל את החיבור -Comment[hi]=उपयोक्ता ने कनेक्शन स्वीकारा -Comment[hne]=कमइया हर कनेक्सन स्वीकारा -Comment[hr]=Korisnik prihvaća vezu -Comment[hu]=A felhasználó engedélyezi a csatlakozást -Comment[ia]=Usator da acceptation a connexion -Comment[is]=Notandi samþykkir tengingu -Comment[it]=L'utente accetta la connessione -Comment[ja]=ユーザが接続を許可 -Comment[kk]=Пайдаланушы қосылымды қабылдайды -Comment[km]=អ្នក​ប្រើ​ទទួល​យក​ការ​ត​ភ្ជាប់ -Comment[ko]=사용자가 연결을 수락함 -Comment[lt]=Naudotojas priėmė kvietimą -Comment[lv]=Lietotājs atļauj savienojumu -Comment[mk]=Корисникот прифаќа поврзување -Comment[ml]=ഉപയോക്താവ് ബന്ധം സ്വീകരിക്കുന്നു -Comment[mr]=वापरकर्ता जुळवणी स्वीकारतो -Comment[ms]= Pengguna menerima sambungan -Comment[nb]=Bruker godtar tilkobling -Comment[nds]=Bruker nimmt Tokoppelanfraag an -Comment[nl]=Gebruiker accepteert de verbinding -Comment[nn]=Brukaren godtek tilkoplinga -Comment[pa]=ਯੂਜ਼ਰ ਨੇ ਕੁਨੈਕਸ਼ਨ ਮੰਨਿਆ -Comment[pl]=Użytkownik akceptuje połączenie -Comment[pt]=O utilizador aceita a ligação -Comment[pt_BR]=O usuário aceita a conexão -Comment[ro]=Utilizatorul acceptă conexiunea -Comment[ru]=Пользователь принимает соединения -Comment[si]=සබැඳිය පරිශීලකයා තහවුරු කරයි -Comment[sk]=Užívateľ akceptuje pripojenie -Comment[sl]=Uporabnik sprejema povezavo -Comment[sr]=Корисник прихвата везу -Comment[sr@ijekavian]=Корисник прихвата везу -Comment[sr@ijekavianlatin]=Korisnik prihvata vezu -Comment[sr@latin]=Korisnik prihvata vezu -Comment[sv]=Användaren accepterar anslutning -Comment[ta]=பயனர் இணைப்பு ஏற்றுக்கொள்ளப்பட்டது -Comment[tg]=Корванд пайвастшавиро қабул мекунад -Comment[th]=ผู้ใช้ยอมรับการเชื่อมต่อ -Comment[tr]=Kullanıcı bağlantıyı kabul etti -Comment[ug]=ئىشلەتكۈچى باغلىنىشقا قوشۇلدى -Comment[uk]=Користувач приймає з’єднання -Comment[xh]=Umsebenzisi wamkela uxhulumaniso -Comment[x-test]=xxUser accepts connectionxx -Comment[zh_CN]=用户接受连接 -Comment[zh_HK]=用戶接受連線 -Comment[zh_TW]=使用者接受連線 -Actions=Popup - -[krfb/UserRefusesConnection] -Name=User Refuses Connection -Name[ar]=المستخدم يرفض الاتصال -Name[ast]=L'usuariu refuga la conexón -Name[bg]=Потребителят отказва връзката -Name[bs]=Korisnik odbija vezu -Name[ca]=L'usuari refusa la connexió -Name[ca@valencia]=L'usuari refusa la connexió -Name[cs]=Uživatel odmítá spojení -Name[da]=Bruger afslår forbindelse -Name[de]=Benutzer verweigert Verbindung -Name[el]=Ο χρήστης απέρριψε τη σύνδεση -Name[en_GB]=User Refuses Connection -Name[eo]=Uzanto rifuzas la konekton -Name[es]=El usuario rechaza la conexión -Name[et]=Kasutaja keeldub ühendusest -Name[eu]=Erabiltzaileak konexioa ukatu du -Name[fi]=Käyttäjä hylkää yhteyden -Name[fr]=L'utilisateur refuse la connexion -Name[ga]=Diúltaíonn an tÚsáideoir Le Ceangal -Name[gl]=O usuario rexeita a conexión -Name[hi]=उपयोक्ता ने कनेक्शन अस्वीकारा -Name[hne]=कमइया हर कनेक्सन अस्वीकारा -Name[hr]=Korisnik odbija vezu -Name[hu]=A felhasználó elutasítja a csatlakozást -Name[ia]=Usator refuta connexion -Name[is]=Notandi hafnar tengingum -Name[it]=L'utente rifiuta la connessione -Name[ja]=ユーザが接続を拒否 -Name[kk]=Пайдаланушы қосылымдан бас тартады -Name[km]=អ្នក​ប្រើ​បដិសេធ​ការ​ត​ភ្ជាប់ -Name[ko]=사용자가 연결을 거부함 -Name[lt]=Naudotojas atmetė kvietimą -Name[lv]=Lietotājs noraida savienojumu -Name[ml]=ഉപയോക്താവ് ബന്ധം തിരസ്കരിക്കുന്നു -Name[mr]=वापरकर्ता जुळवणी अस्वीकारतो -Name[nb]=Bruker nekter tilkobling -Name[nds]=Bruker wiest tokoppeln af -Name[nl]=Gebruiker weigert de verbinding -Name[nn]=Brukar avslår tilkopling -Name[pa]=ਯੂਜ਼ਰ ਨੇ ਕੁਨੈਕਸ਼ਨ ਤੋਂ ਇਨਕਾਰ ਕੀਤਾ -Name[pl]=Połączenie odrzucone przez użytkownika -Name[pt]=O Utilizador Recusa a Ligação -Name[pt_BR]=O usuário rejeita a conexão -Name[ro]=Utilizatorul refuză conexiunea -Name[ru]=Пользователь отклоняет соединения -Name[si]=සබැඳිය පරිශීලකයා තහවුරු නොකරයි -Name[sk]=Užívateľ odmieta pripojenie -Name[sl]=Uporabnik zavrača povezavo -Name[sr]=Корисник одбија везу -Name[sr@ijekavian]=Корисник одбија везу -Name[sr@ijekavianlatin]=Korisnik odbija vezu -Name[sr@latin]=Korisnik odbija vezu -Name[sv]=Användaren vägrar anslutning -Name[th]=ผู้ใช้ปฏิเสธการเชื่อมต่อ -Name[tr]=Kullanıcı Bağlantıyı Reddetti -Name[ug]=ئىشلەتكۈچى باغلىنىشنى رەت قىلدى -Name[uk]=Користувач не приймає з’єднання -Name[x-test]=xxUser Refuses Connectionxx -Name[zh_CN]=用户拒绝连接 -Name[zh_TW]=使用者拒絕連線 -Comment=User refuses connection -Comment[af]=Gebruiker weier verbinding -Comment[ar]=المستخدم يرفض الاتصال -Comment[ast]=L'usuariu refuga la conexón -Comment[bg]=Потребителят отказва връзката -Comment[bn]=ব্যবহারকারী সংযোগ অস্বীকার করে -Comment[bs]=Korisnik odbija vezu -Comment[ca]=L'usuari refusa la connexió -Comment[ca@valencia]=L'usuari refusa la connexió -Comment[cs]=Uživatel odmítá spojení -Comment[cy]=Mae'r defnyddiwr yn gwrthod y cysylltiad -Comment[da]=Bruger afslår forbindelse -Comment[de]=Der Benutzer verweigert die Verbindung -Comment[el]=Ο χρήστης απέρριψε τη σύνδεση -Comment[en_GB]=User refuses connection -Comment[eo]=Uzanto rifuzas konektojn -Comment[es]=El usuario rechaza la conexión -Comment[et]=Kasutaja keeldub ühendusest -Comment[eu]=Erabiltzaileak konexioa ukatu du -Comment[fi]=Käyttäjä hylkää yhteyden -Comment[fr]=L'utilisateur refuse la connexion -Comment[ga]=Diúltaíonn úsáideoir ceangal -Comment[gl]=O usuario rexeita a conexión -Comment[he]=המשתמש מסרב לחיבור -Comment[hi]=उपयोक्ता ने कनेक्शन अस्वीकारा -Comment[hne]=कमइया हर कनेक्सन अस्वीकारा -Comment[hr]=Korisnik odbija vezu -Comment[hu]=A felhasználó elutasítja a csatlakozást -Comment[ia]=Usator refuta connexion -Comment[is]=Notandi hafnar tengingu -Comment[it]=L'utente rifiuta la connessione -Comment[ja]=ユーザが接続を拒否 -Comment[kk]=Пайдаланушы қосылымды қабылдамайды -Comment[km]=អ្នក​ប្រើ​បដិសេធ​ការ​ត​ភ្ជាប់ -Comment[ko]=사용자가 연결을 거부함 -Comment[lt]=Naudotojas atmetė kvietimą -Comment[lv]=Lietotājs noraida savienojumu -Comment[mk]=Корисникот одбива поврзување -Comment[ml]=ഉപയോക്താവ് ബന്ധം തിരസ്കരിക്കുന്നു -Comment[mr]=वापरकर्ता जुळवणी अस्वीकारतो -Comment[ms]=Pengguna menolak sambungan -Comment[nb]=Bruker nekter tilkobling -Comment[nds]=Bruker wiest Tokoppelanfraag af -Comment[nl]=Gebruiker weigert de verbinding -Comment[nn]=Brukaren avslår tilkoplinga -Comment[pa]=ਯੂਜ਼ਰ ਨੇ ਕੁਨੈਕਸ਼ਨ ਤੋਂ ਇਨਕਾਰ ਕੀਤਾ -Comment[pl]=Użytkownik odrzuca połączenie -Comment[pt]=O utilizador recusa a ligação -Comment[pt_BR]=O usuário rejeita a conexão -Comment[ro]=Utilizatorul refuză conexiunea -Comment[ru]=Пользователь отклоняет соединения -Comment[si]=සබැඳිය පරිශීලකයා තහවුරු නොකරයි -Comment[sk]=Užívateľ odmieta pripojenie -Comment[sl]=Uporabnik zavrača povezavo -Comment[sr]=Корисник одбија везу -Comment[sr@ijekavian]=Корисник одбија везу -Comment[sr@ijekavianlatin]=Korisnik odbija vezu -Comment[sr@latin]=Korisnik odbija vezu -Comment[sv]=Användaren vägrar anslutning -Comment[ta]=பயனர் இணைப்பு ஏற்க மறுக்கப்பட்டது -Comment[tg]=Корванд пайвастшавиро рад мекунад -Comment[th]=ผู้ใช้ปฏิเสธการเชื่อมต่อ -Comment[tr]=Kullanıcı bağlantıyı reddetti -Comment[ug]=ئىشلەتكۈچى باغلىنىشنى رەت قىلدى -Comment[uk]=Користувач не приймає з’єднання -Comment[xh]=Umsebenzisi wala uxhulumaniso -Comment[x-test]=xxUser refuses connectionxx -Comment[zh_CN]=用户拒绝连接 -Comment[zh_HK]=用戶拒絕連線 -Comment[zh_TW]=使用者拒絕連線使用者 -Actions=Popup - -[krfb/ConnectionClosed] -Name=Connection Closed -Name[ar]=الاتصال أغلق -Name[ast]=Conexón zarrada -Name[bg]=Връзката е прекъсната -Name[bs]=Konekcija zatvorena -Name[ca]=Connexió tancada -Name[ca@valencia]=Connexió tancada -Name[cs]=Spojení ukončeno -Name[da]=Forbindelse lukket -Name[de]=Verbindung geschlossen -Name[el]=Η σύνδεση έκλεισε -Name[en_GB]=Connection Closed -Name[eo]=Konekto fermita -Name[es]=Conexión cerrada -Name[et]=Ühendus suletud -Name[eu]=Konexioa itxi da -Name[fi]=Yhteys suljettu -Name[fr]=Connexion fermée -Name[ga]=Ceangal Dúnta -Name[gl]=Conexión fechada -Name[hi]=कनेक्शन बन्द -Name[hne]=कनेक्सन बन्द -Name[hr]=Veza prekinuta -Name[hu]=A kapcsolat megszűnt -Name[ia]=Connexion claudite -Name[is]=Tengingu lokað -Name[it]=Connessione chiusa -Name[ja]=接続切断 -Name[kk]=Қосылымдан жабылды -Name[km]=បាន​បិទ​ការ​ត​ភ្ជាប់ -Name[ko]=연결이 닫힘 -Name[lt]=Ryšys baigtas -Name[lv]=Savienojums slēgts -Name[mai]=संबंधन बन्न भ' गेल -Name[ml]=ബന്ധം അടച്ചു -Name[mr]=जुळवणी बंद केली -Name[nb]=Forbindelsen lukket -Name[nds]=Afkoppelt -Name[nl]=Verbinding gesloten -Name[nn]=Tilkopling vart avslutta -Name[pa]=ਕੁਨੈਕਸ਼ਨ ਬੰਦ ਕੀਤਾ -Name[pl]=Połączenia zakończone -Name[pt]=Ligação Fechada -Name[pt_BR]=Conexão encerrada -Name[ro]=Conexiune închisă -Name[ru]=Соединение закрыто -Name[si]=සබඳතාව වසා දැමිනි -Name[sk]=Pripojenie bolo ukončené -Name[sl]=Povezava zaprta -Name[sq]=Lidhja u Mbyll -Name[sr]=Веза затворена -Name[sr@ijekavian]=Веза затворена -Name[sr@ijekavianlatin]=Veza zatvorena -Name[sr@latin]=Veza zatvorena -Name[sv]=Anslutning stängd -Name[th]=การเชื่อมต่อยุติ -Name[tr]=Bağlantı Kapatıldı -Name[ug]=باغلىنىش يېپىلدى -Name[uk]=З'єднання закрито -Name[x-test]=xxConnection Closedxx -Name[zh_CN]=连接关闭 -Name[zh_TW]=連線已關閉 -Comment=Connection closed -Comment[af]=Verbinding gesluit -Comment[ar]=تمّ غلق الاتصال -Comment[ast]=Conexón zarrada -Comment[bg]=Връзката е прекъсната -Comment[bn]=সংযোগ বন্ধ করা হল -Comment[br]=Serret eo ar gevreadenn -Comment[bs]=Veza je zatvorena -Comment[ca]=Connexió tancada -Comment[ca@valencia]=Connexió tancada -Comment[cs]=Spojení ukončeno -Comment[cy]=Mae'r cysylltiad ar gau -Comment[da]=Forbindelse lukket -Comment[de]=Verbindung geschlossen -Comment[el]=Η σύνδεση έκλεισε -Comment[en_GB]=Connection closed -Comment[eo]=Konekto fermita -Comment[es]=Conexión cerrada -Comment[et]=Ühendus suletud -Comment[eu]=Konexioa itxi da -Comment[fi]=Yhteys suljettu -Comment[fr]=Connexion fermée -Comment[ga]=Ceangal dúnta -Comment[gl]=A conexión está fechada -Comment[he]=החיבור נסגר -Comment[hi]=कनेक्शन बन्द -Comment[hne]=कनेक्सन बन्द -Comment[hr]=Veza prekinuta -Comment[hu]=A kapcsolat megszűnt -Comment[ia]=Connexion claudite -Comment[is]=Tengingu lokað -Comment[it]=Connessione chiusa -Comment[ja]=接続が閉じられました -Comment[kk]=Қосылым жабылды -Comment[km]=បាន​បិទ​ការ​ត​ភ្ជាប់ -Comment[ko]=연결이 닫힘 -Comment[lt]=Ryšys baigtas -Comment[lv]=Savienojums tika slēgts -Comment[mk]=Поврзувањето е затворено -Comment[ml]=ബന്ധം അടച്ചു -Comment[mr]=जुळवणी बंद केली -Comment[ms]=Sambungan ditutup -Comment[nb]=Forbindelsen lukket -Comment[nds]=Afkoppelt -Comment[nl]=Verbinding gesloten -Comment[nn]=Tilkoplinga vart avslutta -Comment[pa]=ਕੁਨੈਕਸ਼ਨ ਬੰਦ ਕੀਤਾ -Comment[pl]=Połączenie zakończone -Comment[pt]=A ligação foi encerrada -Comment[pt_BR]=Conexão encerrada -Comment[ro]=Conexiune închisă -Comment[ru]=Соединение закрыто -Comment[si]=සබඳතාව වසාදැමිනි -Comment[sk]=Pripojenie bolo ukončené -Comment[sl]=Povezava zaprta -Comment[sq]=Lidhja u mbyll -Comment[sr]=Веза је затворена -Comment[sr@ijekavian]=Веза је затворена -Comment[sr@ijekavianlatin]=Veza je zatvorena -Comment[sr@latin]=Veza je zatvorena -Comment[sv]=Anslutning stängd -Comment[ta]=இணைப்புகள் மூடப்பட்டது -Comment[tg]=Пайвастшавӣ пӯшида аст -Comment[th]=การเชื่อมต่อยุติ -Comment[tr]=Bağlantı kapatıldı -Comment[ug]=باغلىنىش تاقالدى -Comment[uk]=З'єднання закрито -Comment[uz]=Aloqa uzildi -Comment[uz@cyrillic]=Алоқа узилди -Comment[xh]=Uxhulumaniso luvaliwe -Comment[x-test]=xxConnection closedxx -Comment[zh_CN]=连接关闭 -Comment[zh_HK]=連線已關閉 -Comment[zh_TW]=連線已關閉 -Actions=Popup - -[krfb/InvalidPassword] -Name=Invalid Password -Name[ar]=كلمة المرور غير صحيحة -Name[ast]=Contraseña incorreuta -Name[bg]=Неправилна парола -Name[bs]=Neispravna šifra -Name[ca]=Contrasenya no vàlida -Name[ca@valencia]=Contrasenya no vàlida -Name[cs]=Neplatné heslo -Name[da]=Ugyldig adgangskode -Name[de]=Passwort ungültig -Name[el]=Μη έγκυρος κωδικός πρόσβασης -Name[en_GB]=Invalid Password -Name[eo]=Nevalida pasvorto -Name[es]=Contraseña incorrecta -Name[et]=Vale parool -Name[eu]=Baliogabeko pasahitza -Name[fi]=Virheellinen salasana -Name[fr]=Mot de passe non valable -Name[ga]=Focal Faire Neamhbhailí -Name[gl]=O contrasinal non é válido -Name[hi]=अवैध पासवर्ड -Name[hne]=अवैध पासवर्ड -Name[hr]=Nevažeća zaporka -Name[hu]=Érvénytelen jelszó -Name[ia]=Contrasigno invalide -Name[is]=Ógilt lykilorð -Name[it]=Password non valida -Name[ja]=無効なパスワード -Name[kk]=Жарамсыз паролі -Name[km]=ពាក្យ​សម្ងាត់​មិន​ត្រឹមត្រូវ -Name[ko]=잘못된 암호 -Name[lt]=Neteisingas slaptažodžis -Name[lv]=Nederīga parole -Name[ml]=അസാധുവായ അടയാളവാക്ക് -Name[mr]=अवैध गुप्तशब्द -Name[nb]=Ugyldig passord -Name[nds]=Leeg Passwoort -Name[nl]=Ongeldig wachtwoord -Name[nn]=Ugyldig passord -Name[pa]=ਗਲਤ ਪਾਸਵਰਡ -Name[pl]=Błędne hasło -Name[pt]=Senha Inválida -Name[pt_BR]=Senha inválida -Name[ro]=Parolă nevalidă -Name[ru]=Неверный пароль -Name[si]=වැරදි මුරපදය -Name[sk]=Neplatné heslo -Name[sl]=Neveljavno geslo -Name[sq]=Fjalëkalim i Pavlefshëm -Name[sr]=Неисправна лозинка -Name[sr@ijekavian]=Неисправна лозинка -Name[sr@ijekavianlatin]=Neispravna lozinka -Name[sr@latin]=Neispravna lozinka -Name[sv]=Ogiltigt lösenord -Name[th]=รหัสผ่านไม่ถูกต้อง -Name[tr]=Geçersiz Parola -Name[ug]=ئىناۋەتسىز ئىم -Name[uk]=Неправильний пароль -Name[wa]=Sicret nén valåbe -Name[x-test]=xxInvalid Passwordxx -Name[zh_CN]=无效密码 -Name[zh_TW]=不正確的密碼 -Comment=Invalid password -Comment[af]=Ongeldige wagwoord -Comment[ar]=كلمة المرور غير صحيحة -Comment[ast]=Contraseña incorreuta -Comment[bg]=Неправилна парола -Comment[bn]=অবৈধ পাসওয়ার্ড -Comment[br]=Tremenger siek -Comment[bs]=Neispravna šifra -Comment[ca]=Contrasenya no vàlida -Comment[ca@valencia]=Contrasenya no vàlida -Comment[cs]=Neplatné heslo -Comment[cy]=Cyfrinair annilys -Comment[da]=Ugyldig adgangskode -Comment[de]=Passwort ungültig -Comment[el]=Μη έγκυρος κωδικός πρόσβασης -Comment[en_GB]=Invalid password -Comment[eo]=Nevalida pasvorto -Comment[es]=Contraseña incorrecta -Comment[et]=Vale parool -Comment[eu]=Baliogabeko pasahitza -Comment[fi]=Virheellinen salasana -Comment[fr]=Mot de passe non valable -Comment[ga]=Focal faire neamhbhailí -Comment[gl]=Este contrasinal non é válido -Comment[he]=הסיסמה שגויה -Comment[hi]=अवैध पासवर्ड -Comment[hne]=अवैध पासवर्ड -Comment[hr]=Nevažeća šifra -Comment[hu]=Érvénytelen jelszó -Comment[ia]=Contrasigno invalide -Comment[is]=Lykilorð ógilt -Comment[it]=Password non valida -Comment[ja]=無効なパスワード -Comment[kk]=Паролі дұрыс емес -Comment[km]=ពាក្យ​សម្ងាត់​មិន​ត្រឹមត្រូវ -Comment[ko]=잘못된 암호 -Comment[lt]=Neteisingas slaptažodis -Comment[lv]=Parole nav derīga -Comment[mai]=अवैध कूटशब्द -Comment[mk]=Невалидна лозинка -Comment[ml]=അസാധുവായ അടയാളവാക്ക് -Comment[mr]=अवैध गुप्तशब्द -Comment[ms]=Kata laluan tidak sah -Comment[nb]=Ugyldig passord -Comment[nds]=Leeg Passwoort -Comment[nl]=Ongeldig wachtwoord -Comment[nn]=Passordet var ugyldig -Comment[oc]=Mot de pas invalid -Comment[pa]=ਗਲਤ ਪਾਸਵਰਡ -Comment[pl]=Błędne hasło -Comment[pt]=A senha é inválida -Comment[pt_BR]=Senha inválida -Comment[ro]=Parolă nevalidă -Comment[ru]=Неверный пароль -Comment[si]=වැරදි මුරපදය -Comment[sk]=Neplatné heslo -Comment[sl]=Neveljavno geslo -Comment[sq]=Fjalëkalim i pavlefshëm -Comment[sr]=Неисправна лозинка -Comment[sr@ijekavian]=Неисправна лозинка -Comment[sr@ijekavianlatin]=Neispravna lozinka -Comment[sr@latin]=Neispravna lozinka -Comment[sv]=Ogiltigt lösenord -Comment[ta]=செல்லாத கடவுச்சொல் -Comment[tg]=Гузарвожаи нодуруст -Comment[th]=รหัสผ่านไม่ถูกต้อง -Comment[tr]=Geçersiz parola -Comment[ug]=ئىناۋەتسىز ئىم -Comment[uk]=Неправильний пароль -Comment[uz]=Maxfiy soʻz haqiqiy emas -Comment[uz@cyrillic]=Махфий сўз ҳақиқий эмас -Comment[wa]=Sicret nén valide -Comment[xh]=Igama lokugqitha elingasebenziyo -Comment[x-test]=xxInvalid passwordxx -Comment[zh_CN]=无效密码 -Comment[zh_HK]=無效的密碼 -Comment[zh_TW]=不正確的密碼 -Actions=Popup - -[krfb/InvalidPasswordInvitations] -Name=Invalid Password Invitations -Name[ar]=كلمة المرور الدعوات غير صحيحة -Name[ast]=Contraseñas d'invitaciones incorreutes -Name[bg]=Неправилна парола за покана -Name[bs]=Neispravna šifra pozivnice -Name[ca]=Contrasenya de les invitacions no vàlides -Name[ca@valencia]=Contrasenya de les invitacions no vàlides -Name[cs]=Neplatné hesla výzev -Name[da]=Ugyldige adgangskodeinvitationer -Name[de]=Ungültiges Einladungs-Passwort -Name[el]=Μη έγκυρος κωδικός πρόσβασης πρόσκλησης -Name[en_GB]=Invalid Password Invitations -Name[eo]=Nevalidaj pasvortaj invitoj -Name[es]=Contraseñas de invitaciones incorrectas -Name[et]=Kutsutu vale parool -Name[eu]=Gonbitearen pasahitza baliogabea -Name[fi]=Virheellinen salasana kutsuun -Name[fr]=Invitations de mots de passe non valables -Name[ga]=Cuirí Neamhbhailí Focal Faire -Name[gl]=O contrasinal de convidado non válido -Name[hi]=अवैध पासवर्ड निमंत्रण -Name[hne]=अवैध पासवर्ड निमंत्रन -Name[hr]=Pozivnice s nevažećim zaporkama -Name[hu]=Érvénytelen jelszavas meghívó -Name[ia]=Invitationes de contrasigno invalide -Name[is]=Ógild lykilorðsboð -Name[it]=Password di invito non valida -Name[ja]=招待に対する無効なパスワード -Name[kk]=Жарамсыз паролімен шақыру -Name[km]=ការ​អញ្ជើញ​ពាក្យ​សម្ងាត់​មិន​ត្រឹមត្រូវ -Name[ko]=잘못된 암호 초대장 -Name[lt]=Neteisingas kvietimo slaptažodis -Name[lv]=Nepareiza parole ar ielūgumu -Name[ml]=അസാധുവായ അടയാളവാക്ക് ക്ഷണങ്ങള്‍ -Name[mr]=अवैध गुप्तशब्द निमंत्रण -Name[nb]=Ugyldig invitasjonspassord -Name[nds]=Leeg Passwoort bi Inladen -Name[nl]=Ongeldig wachtwoord uitnodiging -Name[nn]=Ugyldig invitasjonspassord -Name[pa]=ਗਲਤ ਪਾਸਵਰਡ ਸੱਦਾ -Name[pl]=Informacja o błędnym haśle -Name[pt]=Convites de Senha Inválidos -Name[pt_BR]=Avisos de senha inválida -Name[ro]=Parolă nevalidă Invitații -Name[ru]=Неверный пароль приглашения -Name[si]=වැරදි මුරපද ආරාධනාවක් -Name[sk]=Neplatné heslo pozvánky -Name[sl]=Povabila z neveljavnimi gesli -Name[sr]=Неисправна лозинка позивнице -Name[sr@ijekavian]=Неисправна лозинка позивнице -Name[sr@ijekavianlatin]=Neispravna lozinka pozivnice -Name[sr@latin]=Neispravna lozinka pozivnice -Name[sv]=Ogiltigt lösenord vid inbjudan -Name[th]=รหัสผ่านของการเชื้อเชิญไม่ถูกต้อง -Name[tr]=Geçersiz Parola Daveti -Name[ug]=ئىناۋەتسىز ئىم تەكلىپلىرى -Name[uk]=Запрошення з некоректними паролями -Name[x-test]=xxInvalid Password Invitationsxx -Name[zh_CN]=无效密码邀请 -Name[zh_TW]=不合法的密碼邀請 -Comment=The invited party sent an invalid password. Connection refused. -Comment[af]=Die uitgenooi party gestuur 'n ongeldige wagwoord. Verbinding geweier. -Comment[ar]=المدعو أرسل كلمة مرور غير صحيحة. رفض الإتصال. -Comment[ast]=L'invitáu unvió una contraseña incorreuta. Conexón refugada. -Comment[bg]=Поканената страна изпрати неправилна парола. Връзката е отказана. -Comment[bn]=আমন্ত্রিত দল একটি অবৈধ পাসওয়ার্ড পাঠাল। সংযোগ অস্বীকার করা হল। -Comment[bs]=Pozvana strana je poslala pogrešnu šifru. Veza je odbijena. -Comment[ca]=La part invitada ha enviat una contrasenya no vàlida. Connexió refusada. -Comment[ca@valencia]=La part invitada ha enviat una contrasenya no vàlida. Connexió refusada. -Comment[cs]=Pozvaná strana poslala neplatné heslo. Spojení odmítnuto. -Comment[cy]=Anfonodd y person gwahodd cyfrinair annilys. Gwrthodwyd y cysylltiad. -Comment[da]=Den inviterede part sendte en ugyldig adgangskode. Forbindelse afslået. -Comment[de]=Die eingeladene Person hat ein ungültiges Passwort gesendet: Verbindung abgelehnt. -Comment[el]=Η πρόσκληση περιέχει μη έγκυρο κωδικό πρόσβασης. Η σύνδεση απορρίφθηκε. -Comment[en_GB]=The invited party sent an invalid password. Connection refused. -Comment[eo]=La invitita kliento sendis nevalidan pasvorton. Konekto rifuzita. -Comment[es]=El invitado envió una contraseña incorrecta. Conexión rechazada. -Comment[et]=Kutsutu saatis vigase parooli. Ühendusest keelduti. -Comment[eu]=Gonbidatutako parekoak baliogabeko pasahitza bidali du. Konexioa ukatuta. -Comment[fi]=Kutsuttu taho lähetti virheellisen salasanan. Yhteys hylättiin. -Comment[fr]=La partie invitée a envoyé un mot de passe non valable. Connexion refusée. -Comment[ga]=Sheol an duine le cuireadh focal faire neamhbhailí. Diúltaíodh an ceangal. -Comment[gl]=A parte convidada envioulle un contrasinal non válido. A conexión foi rexeitada. -Comment[he]=הצד המוזמן שלח סיסמה שגויה. החיבור נדחה. -Comment[hi]=निमंत्रित पार्टी ने अवैध पासवर्ड भेजा. कनेक्शन अस्वीकृत. -Comment[hne]=निमंत्रित पार्टी हर अवैध पासवर्ड भेजिस. कनेक्सन अस्वीकृत. -Comment[hr]=Stranka koju ste pozvali je poslala nevažeću šifru. Veza odbijena. -Comment[hu]=A meghívott fél érvénytelen jelszót küldött. A csatlakozási kérés elutasítva. -Comment[ia]=Le partita invitate inviava un contrasigno invalide. Connexion refusate. -Comment[is]=Boðinn aðili sendi ógilt lykilorð. Tengingu hafnað -Comment[it]=La parte invitata ha inviato una password non valida. Connessione rifiutata. -Comment[ja]=招待された人が無効なパスワードを送ってきました。接続を拒否しました。 -Comment[kk]=Шқырылған жақ дұрыс емес парольді жіберді. Қосылымдан бас тартылды.. -Comment[km]=ភាគី​ដែល​បាន​អញ្ជើញ បាន​ផ្ញើ​ពាក្យ​សម្ងាត់​មិន​ត្រឹមត្រូវ ។ ការ​តភ្ជាប់​ត្រូវ​បាន​បដិសេធ ។ -Comment[ko]=초대한 사람이 잘못된 암호를 보냈습니다. 연결이 잘못되었습니다. -Comment[lt]=Pakviestoji pusė atsiuntė neteisingą slaptažodį. Ryšys nutrauktas. -Comment[lv]=Ielūgtā persona nosūtīja nepareizu paroli. Savienojums noraidīts. -Comment[mk]=Поканетата страна испрати невалидна лозинка. Поврзувањето е одбиено. -Comment[ml]=ക്ഷണിച്ച പാര്‍ട്ടി അസാധുവായ അടയാളവാക്കാണ് അയച്ചത്. ബന്ധം നിഷേധിച്ചു. -Comment[ms]=Pihak yang dijemput telah menghantar kata laluan yang salah. Sambungan ditolak. -Comment[nb]=Den inviterte brukeren sendte et ugyldig passord. Tilkobling nektet. -Comment[nds]=De inlaadt Deel hett en leeg Passwoort angeven. Tokoppeln torüchwiest. -Comment[nl]=De uitgenodigde partij stuurde een ongeldig wachtwoord. De verbinding is geweigerd. -Comment[nn]=Ugyldig passordsvar på invitasjon. Tilkoplinga vart avslått. -Comment[pl]=Z drugiej strony podano błędne hasło. Połączenie odrzucone. -Comment[pt]=O utilizador convidado enviou uma senha inválida. A ligação foi recusada. -Comment[pt_BR]=A parte "convidada" enviou uma senha inválida. Conexão recusada. -Comment[ro]=Partea care invită a trimis o parolă nevalidă. Conexiune refuzată. -Comment[ru]=Приглашённый пользователь ввёл неправильный пароль. Соединение отклонено. -Comment[si]=ආරාධිත පාර්‍ශවය වැරදි මුරපදයක් එවන ලද බැවින් සබඳතාව ප්‍රතික්‍ෂේප විය. -Comment[sk]=Pozvaná strana poslala neplatné heslo. Pripojenie bolo odmietnuté. -Comment[sl]=Povabljena stranka je poslala neveljavno geslo. Povezava zavrnjena. -Comment[sr]=Позвана страна је послала погрешну лозинку. Веза је одбијена. -Comment[sr@ijekavian]=Позвана страна је послала погрешну лозинку. Веза је одбијена. -Comment[sr@ijekavianlatin]=Pozvana strana je poslala pogrešnu lozinku. Veza je odbijena. -Comment[sr@latin]=Pozvana strana je poslala pogrešnu lozinku. Veza je odbijena. -Comment[sv]=Den inbjudna personen skickade ett ogiltigt lösenord. Anslutning vägrades. -Comment[ta]=அழைத்த நபர் தவறான கடவுச்சொல்லை அனுப்பியுள்ளார். இணைப்பு நிராகரிக்கப்பட்டது. -Comment[tg]=Корванди дурдаст гузарвожаи нодурустро фиристод. Пайвастшавӣ манъ шудааст. -Comment[th]=ผู้เข้าร่วมการเชิญชวนส่งรหัสผ่านมาไม่ถูกต้อง ทำการปฏิเสธการเชื่อมต่อ -Comment[tr]=Davet edilenden gönderilmiş geçersiz parola. Bağlantı reddedildi. -Comment[ug]=تەكلىپ قىلغۇچى ئەۋەتكەن ئىم ئىناۋەتسىز. باغلىنىش رەت قىلىندى. -Comment[uk]=Запрошений учасник надіслав некоректний пароль. У з’єднанні відмовлено. -Comment[xh]=Umhlangano omenyiweyo uthumele igama lokugqitha elisebenzayo. Uxhulumano lwa liwe. -Comment[x-test]=xxThe invited party sent an invalid password. Connection refused.xx -Comment[zh_CN]=受邀请方发送的密码不对。连接被拒绝。 -Comment[zh_HK]=被邀請的一方送出無效的密碼。已拒絕連線。 -Comment[zh_TW]=邀請的人送出了不合法的密碼邀請。連線已拒絕。 -Actions=Popup - -[krfb/NewConnectionOnHold] -Name=New Connection on Hold -Name[ar]=اتصال جديد على التوقف -Name[ast]=Conexón nueva a la espera -Name[bg]=Изчакване на новата връзка -Name[bs]=Nova veza je na čekanju -Name[ca]=Nova connexió en espera -Name[ca@valencia]=Nova connexió en espera -Name[cs]=Nové spojení pozdrženo -Name[da]=Ny forbindelse sat til at vente -Name[de]=Neue Verbindung wartet -Name[el]=Νέα σύνδεση σε αναμονή -Name[en_GB]=New Connection on Hold -Name[eo]=Nova konekto atendante -Name[es]=Conexión nueva a la espera -Name[et]=Uus ühendus ootel -Name[eu]=Konexio berria itxarote moduan -Name[fi]=Uusi yhteys odottaa -Name[fr]=Nouvelle connexion en attente -Name[ga]=Ceangal Nua Ag Fanacht -Name[gl]=Nova conexión en espera -Name[hi]=नया कनेक्शन होल्ड पर रखा -Name[hne]=नवा कनेक्सन होल्ड मं रखा -Name[hr]=Nova veza na čekanju -Name[hu]=Új kapcsolat tartva -Name[ia]=Nove connexion in pausa -Name[is]=Ný tenging á bið -Name[it]=Nuova connessione in attesa -Name[ja]=保留中の新しい接続 -Name[kk]=Жаңа қосылым күтілуде -Name[km]=ការ​តភ្ជាប់​ថ្មី កំពុង​ស្ថិត​នៅ​ក្នុង​ការ​រង់ចាំ -Name[ko]=새 연결 대기 중 -Name[lt]=Naujas kvietimas ryšiui sulaikytas -Name[lv]=Jauns savienojums gaida -Name[ml]=പുതിയ ബന്ധം തത്കാലം നിര്‍ത്തിയിരിയ്ക്കുന്നു -Name[mr]=नवीन जुळवणी थांबविलेली आहे -Name[nb]=Ny tilkobling venter -Name[nds]=Nieg Verbinnen töövt -Name[nl]=Nieuwe verbinding in de wacht -Name[nn]=Ny tilkopling ventar -Name[pa]=ਨਵਾਂ ਕੁਨੈਕਸ਼ਨ ਹੋਲਡ ਉੱਤੇ ਹੈ -Name[pl]=Nowe połączenie wstrzymane -Name[pt]=Ligação Nova em Espera -Name[pt_BR]=Nova conexão ativa -Name[ro]=Conexiune nouă în așteptare -Name[ru]=Новое соединение приостановлено -Name[si]=නව සබඳතාවක් රඳවා ඇත -Name[sk]=Nové pripojenie bolo pozdržané -Name[sl]=Nova povezava na čakanju -Name[sr]=Нова веза је на чекању -Name[sr@ijekavian]=Нова веза је на чекању -Name[sr@ijekavianlatin]=Nova veza je na čekanju -Name[sr@latin]=Nova veza je na čekanju -Name[sv]=Ny anslutning väntar -Name[th]=การเชื่อมต่อใหม่ถูกพักรอไว้ก่อน -Name[tr]=Yeni Açık Bağlantı -Name[uk]=Очікування на нове з’єднання -Name[x-test]=xxNew Connection on Holdxx -Name[zh_CN]=新连接已搁置 -Name[zh_TW]=新連線等待處理 -Comment=Connection requested, user must accept -Comment[af]=Verbinding versoekte, gebruiker moet aanvaar -Comment[ar]=الاتصال طلب، يجب موافقة المستخدم -Comment[ast]=Conexón solicitada, l'usuario tien d'aceutala -Comment[bg]=Поискана е връзка, следва потребителят да приеме -Comment[bn]=সংযোগ অনুরোধ করা হল, ব্যবহারকারীকে অবশ্যই স্বীকার করতে হবে -Comment[bs]=Veza je zahtijevana, korinik mora da je prihvati -Comment[ca]=Connexió sol·licitada, l'usuari ha d'acceptar-la -Comment[ca@valencia]=Connexió sol·licitada, l'usuari ha d'acceptar-la -Comment[cs]=Vyžadováno spojení, uživatel musí přijmout -Comment[cy]=Cais wedi'i wneud am gysylltiad,rhaid i'r ddefnyddiwr ei dderbyn -Comment[da]=Forbindelse forespurgt, bruger skal acceptere -Comment[de]=Verbindungsanfrage, Benutzer muss bestätigen -Comment[el]=Αίτηση για σύνδεση, απαιτείται παρέμβαση του χρήστη -Comment[en_GB]=Connection requested, user must accept -Comment[eo]=Konekto pridemandita, la uzanto devas akcepti -Comment[es]=Conexión solicitada, el usuario debe aceptarla -Comment[et]=Nõutakse ühendust, kasutaja peab seda lubama -Comment[eu]=Konexioa eskatuta, erabiltzaileak onartu behar du -Comment[fi]=Pyydettiin yhteyttä, käyttäjän tulee hyväksyä -Comment[fr]=Connexion demandée. L'utilisateur doit accepter -Comment[ga]=Ceangal iarrtha; ní mór don úsáideoir glacadh leis -Comment[gl]=Pediuse a conexión; o usuario debe aceptar -Comment[he]=נתבקש חיבור, על המשתמש לקבלו -Comment[hi]=कनेक्शन निवेदित. उपयोक्ता को स्वीकार होना चाहिए -Comment[hne]=कनेक्सन निवेदित. कमइया ल स्वीकार होना चाही -Comment[hr]=Veza je zatražena, korisnik mora prihvatiti -Comment[hu]=Csatlakozási kérés, a felhasználónak el kell fogadnia -Comment[ia]=Connexion requirite, usator debe dar acceptation -Comment[is]=Beiðni um tengingu, notandi verður að samþykkja -Comment[it]=Connessione richiesta, l'utente deve accettare -Comment[ja]=接続が要求されています。ユーザが許可しなければなりません。 -Comment[kk]=Қосылым сұралды, пайдаланушы жауап беруге тиіс -Comment[km]=បាន​ស្នើ​ការ​ត​ភ្ជាប់​​ អ្នក​ប្រើ​ត្រូវ​តែ​ទទួល​យក -Comment[ko]=연결 요청됨, 사용자가 수락해야 함 -Comment[lt]=Kvietimas ryšiui išsiųstas, naudotojas turi priimti kvietimą -Comment[lv]=Ir pieprasīts jauns savienojums, kurš lietotājam ir jāapstiprina -Comment[mk]=Побарано е поврзување, корисникот мора да прифати -Comment[ml]=ബന്ധം ആവശ്യ‌പ്പെട്ടിട്ടുണ്ട്, ഉപയോക്താവ് സ്വീകരിക്കണം -Comment[ms]=Sambungan diminta, pengguna mesti menerima -Comment[nb]=Anmodning om tilkobling, bruker må godta -Comment[nds]=Tokoppeln anfraagt, Bruker mutt verlöven -Comment[nl]=Verbindingsverzoek, gebruiker dient toe te stemmen -Comment[nn]=Ei tilkopling er førespurd. Brukaren må godta. -Comment[pa]=ਕੁਨੈਕਸ਼ਨ ਦੀ ਮੰਗ ਕੀਤੀ ਗਈ, ਯੂਜ਼ਰ ਵਲੋਂ ਮਨਜ਼ੂਰ ਲਾਜ਼ਮੀ -Comment[pl]=Próba połączenia, musi być zaakceptowana przez użytkownika -Comment[pt]=Foi pedida uma ligação que o utilizador deverá aceitar -Comment[pt_BR]=Conexão requisitada; o usuário deve aceitar -Comment[ro]=Conexiune cerută, utilizatorul trebuie să accepte -Comment[ru]=Запрос на соединение, требуется подтверждение пользователя -Comment[si]=සබඳතාව ඉල්ලා ඇත, පරිශීලක තහවුරු කල යුතුයි -Comment[sk]=Vyžiadané pripojenie, užívateľ ho musí akceptovať -Comment[sl]=Povezava zahtevana, uporabnik mora sprejeti -Comment[sr]=Захтевана је веза, корисник мора да је прихвати -Comment[sr@ijekavian]=Захтијевана је веза, корисник мора да је прихвати -Comment[sr@ijekavianlatin]=Zahtijevana je veza, korisnik mora da je prihvati -Comment[sr@latin]=Zahtevana je veza, korisnik mora da je prihvati -Comment[sv]=Anslutning begärd, användaren måste acceptera -Comment[ta]=இணைப்பு கோரப்பட்டது, பயனர் கண்டிப்பாக ஏற்றுக்கொள்ள வேண்டும் -Comment[tg]=Пайвастшавӣ дархоста шудааст, корванд бояд қабул кунад -Comment[th]=มีการร้องขอเชื่อมต่อมา ผู้ใช้ต้องทำการยอมรับก่อน -Comment[tr]=Bağlantı isteği, kullanıcı kabul etmeli -Comment[ug]=باغلىنىش ئىلتىماس قىلىندى، ئىشلەتكۈچى قوشۇلۇشى كېرەك -Comment[uk]=Отримано запит на з’єднання, користувач має його прийняти -Comment[xh]=Uxhulumaniso luceliwe, umsebenzisi kufanele amkele -Comment[x-test]=xxConnection requested, user must acceptxx -Comment[zh_CN]=连接已请求,用户必须接受 -Comment[zh_HK]=已請求連線,用戶必須接受 -Comment[zh_TW]=連線已要求,必須等使用者接受 -Actions=Popup - -[krfb/NewConnectionAutoAccepted] -Name=New Connection Auto Accepted -Name[ar]=اتصال جديد مقبول تلقائيا -Name[ast]=Conexón nueva aceutada automáticamente -Name[bg]=Автоматично приемане на новата връзка -Name[bs]=Nova veza je automatski prihvaćena -Name[ca]=Nova connexió acceptada automàticament -Name[ca@valencia]=Nova connexió acceptada automàticament -Name[cs]=Nové spojení automaticky přijato -Name[da]=Ny forbindelse automatisk accepteret -Name[de]=Neue Verbindung automatisch angenommen -Name[el]=Αυτόματη αποδοχή νέας σύνδεσης -Name[en_GB]=New Connection Auto Accepted -Name[eo]=Nova konekto aŭtomate akceptita -Name[es]=Conexión nueva aceptada automáticamente -Name[et]=Uue ühendusega automaatselt nõus -Name[eu]=Konexio berria automatikoki onartuta -Name[fi]=Uusi yhteys hyväksyttiin automaattisesti -Name[fr]=Nouvelle connexion acceptée automatiquement -Name[ga]=Ceangal nua bunaithe go huathoibríoch -Name[gl]=Nova conexión aceptada automaticamente -Name[hi]=नय कनेक्शन स्वचालित स्वीकारा -Name[hne]=नय कनेक्सन अपने अपन स्वीकारा -Name[hr]=Nova veza automatski prihvaćena -Name[hu]=Új kapcsolat automatikusan engedélyezve -Name[ia]=Nove connexion con acceptation automatic -Name[is]=Ný tenging sjálfvirkt samþykkt -Name[it]=Nuova connessione accettata automaticamente -Name[ja]=新しい接続の自動受け入れ -Name[kk]=Жаңа қосылым автоқабылданды -Name[km]=បាន​ទទួល​យក​ការ​តភ្ជាប់​ថ្មី​ដោយ​ស្វ័យ​ប្រវត្តិ -Name[ko]=새 연결 자동 수락 -Name[lt]=Naujas kvietimas ryšiui automatiškai priimtas -Name[lv]=Automātiski pieņemts jauns savienojums -Name[ml]=പുതിയ ബന്ധം തനിയെ സ്വീകരിക്കപ്പെട്ടു -Name[nb]=Ny tilkobling automatisk godtatt -Name[nds]=Nieg Verbinnen automaatsch tolaten -Name[nl]=Nieuwe verbinding automatisch accepteren -Name[nn]=Ny tilkopling automatisk godteken -Name[pa]=ਨਵਾਂ ਕੁਨੈਕਸ਼ਨ ਆਟੋ ਮਨਜ਼ੂਰ -Name[pl]=Nowe połączenie automatycznie przyjęte -Name[pt]=Nova Ligação Aceite Automaticamente -Name[pt_BR]=Nova conexão com aceitação automática -Name[ro]=Conexiune nouă acceptată automat -Name[ru]=Новое соединение принимается автоматически -Name[si]=නව සබඳතාව ස්වයංක්‍රීයව පිළිගැණිනි -Name[sk]=Nové pripojenie bolo automaticky akceptované -Name[sl]=Nova povezava samodejno sprejeta -Name[sr]=Нова веза је аутоматски прихваћена -Name[sr@ijekavian]=Нова веза је аутоматски прихваћена -Name[sr@ijekavianlatin]=Nova veza je automatski prihvaćena -Name[sr@latin]=Nova veza je automatski prihvaćena -Name[sv]=Ny anslutning accepterades automatiskt -Name[th]=รับการเชื่อมต่อใหม่โดยอัตโนมัติ -Name[tr]=Yeni Bağlantı Otomatik olarak Kabul Edildi -Name[ug]=يېڭى باغلىنىش ئۆزلۈكىدىن قوشۇلدى -Name[uk]=Нове з’єднання автоматично прийнято -Name[x-test]=xxNew Connection Auto Acceptedxx -Name[zh_CN]=新连接自动接受 -Name[zh_TW]=新連線自動接受 -Comment=New connection automatically established -Comment[af]=Nuwe verbinding automaties vasgestel -Comment[ar]=اتصال جديد مفعل تلقائيا -Comment[ast]=Conexón nueva afitada automáticamente -Comment[bg]=Новата връзка е автоматично приета -Comment[bn]=নতুন সংযোগ স্বয়ংক্রীয়ভাবে স্থাপন করা হল -Comment[bs]=Nova veza je automatski uspostavljena -Comment[ca]=Nova connexió establerta automàticament -Comment[ca@valencia]=Nova connexió establerta automàticament -Comment[cs]=Automaticky navázáno nové spojení -Comment[cy]=Sefydlwyd cysylltiad newydd yn awtomatig -Comment[da]=Ny forbindelse automatisk etableret -Comment[de]=Neue Verbindung automatisch hergestellt -Comment[el]=Μια νέα σύνδεση δημιουργήθηκε αυτόματα -Comment[en_GB]=New connection automatically established -Comment[eo]=Nova konekto aŭtomate establita -Comment[es]=Conexión nueva establecida automáticamente -Comment[et]=Uus ühendus automaatselt loodud -Comment[eu]=Konexio berria automatikoki ezarrita -Comment[fi]=Uusi yhteys muodostettiin automaattisesti -Comment[fr]=Nouvelle connexion établie automatiquement -Comment[ga]=Ceangal nua bunaithe go huathoibríoch -Comment[gl]=Estabeleceuse automaticamente unha conexión nova -Comment[he]=נוצר חיבור חדש באופן אוטומטי -Comment[hi]=नया कनेक्शन स्वचलित स्थापित -Comment[hne]=नवा कनेक्सन अपने अपन स्थापित -Comment[hr]=Nova veza automatski prihvaćena -Comment[hu]=Automatikusan létrejött egy új kapcsolat -Comment[ia]=Nove connexion establite automaticamente -Comment[is]=Nýjar tengingar sjálfkrafa samþykktar -Comment[it]=Nuova connessione stabilita automaticamente -Comment[ja]=新しい接続を自動的に確立しました -Comment[kk]=Жаңа қосылым автоматты түрде орнатылды -Comment[km]=បាន​បង្កើត​ការ​ត​ភ្ជាប់​ថ្មី​ដោយ​ស្វ័យ​ប្រវត្តិ -Comment[ko]=새 연결이 자동으로 성립됨 -Comment[lt]=Naujas ryšys užmegztas automatiškai -Comment[lv]=Automātiski izveidots jauns savienojums -Comment[mk]=Автоматски е воспоставено ново поврзување -Comment[ml]=പുതിയ ബന്ധം യാന്ത്രികമായി സ്ഥാപിക്കപ്പെട്ടു -Comment[ms]=Sambungan baru secara automatik terjalin -Comment[nb]=En ny tilkobling er automatisk opprettet -Comment[nds]=Nieg Verbinnen automaatsch inricht -Comment[nl]=Nieuwe verbinding automatisch opgebouwd -Comment[nn]=Ei ny tilkopling vart automatisk starta -Comment[pa]=ਨਵਾਂ ਕੁਨੈਕਸ਼ਨ ਆਟੋਮੈਟਿਕ ਹੀ ਬਣਾਇਆ ਗਿਆ -Comment[pl]=Nowe połączenie ustanowiono automatycznie -Comment[pt]=Foi estabelecida automaticamente uma nova ligação -Comment[pt_BR]=Nova conexão estabelecida automaticamente -Comment[ro]=Conexiune nouă stabilită automat -Comment[ru]=Новое соединение устанавливается автоматически -Comment[si]=නව සබඳතාව ස්වයංක්‍රීයව සැකසිනි -Comment[sk]=Nové pripojenie bolo automaticky nadviazané -Comment[sl]=Nova povezava samodejno vzpostavljena -Comment[sr]=Нова веза је аутоматски успостављена -Comment[sr@ijekavian]=Нова веза је аутоматски успостављена -Comment[sr@ijekavianlatin]=Nova veza je automatski uspostavljena -Comment[sr@latin]=Nova veza je automatski uspostavljena -Comment[sv]=Ny anslutning automatiskt upprättad -Comment[ta]=இணைப்புகள் தானாக உருவாக்கப்பட்டது -Comment[tg]=Пайвастшавии нав ба таври худкор барпо мегардад -Comment[th]=การเชื่อมต่อใหม่จะถูกทำการเชื่อมต่อโดยอัตโนมัติ -Comment[tr]=Yeni bağlantı otomatik olarak kuruldu -Comment[ug]=يېڭى باغلىنىش ئۆزلۈكىدىن قۇرۇلدى -Comment[uk]=Автоматично встановлено нове з’єднання -Comment[xh]=Uxhulumaniso olutsha lufunyenwe ngokuzenzekelayo -Comment[x-test]=xxNew connection automatically establishedxx -Comment[zh_CN]=自动建立新连接 -Comment[zh_HK]=已自動建立新連線 -Comment[zh_TW]=新連線自動建立 -Actions=Popup - -[krfb/TooManyConnections] -Name=Too Many Connections -Name[ar]=اتصالات عديدة -Name[ast]=Abondes conexones -Name[bg]=Твърде много връзки -Name[bs]=Previše veza -Name[ca]=Massa connexions -Name[ca@valencia]=Massa connexions -Name[cs]=Příliš mnoho spojení -Name[da]=For mange forbindelser -Name[de]=Zu viele Verbindungen -Name[el]=Πάρα πολλές συνδέσεις -Name[en_GB]=Too Many Connections -Name[eo]=Tro multaj konektoj -Name[es]=Demasiadas conexiones -Name[et]=Liiga palju ühendusi -Name[eu]=Konexio gehiegi -Name[fi]=Liikaa yhteyksiä -Name[fr]=Trop de connexions -Name[ga]=An Iomarca Ceangal -Name[gl]=Demasiadas conexións -Name[hi]=बहुत सारे कनेक्शन -Name[hne]=बहुत अकन कनेक्सन -Name[hr]=Previše veza -Name[hu]=Túl sok kapcsolat -Name[ia]=Nimie connexiones -Name[is]=Of margar tengingar -Name[it]=Troppe connessioni -Name[ja]=多すぎる接続 -Name[kk]=Тым көп қосылым -Name[km]=ការ​តភ្ជាប់​ច្រើន​ពេក -Name[ko]=너무 많은 연결 -Name[lt]=Per daug užmegztų ryšių -Name[lv]=Pārāk daudz savienojumu -Name[ml]=വളരെ അധികം ബന്ധങ്ങള്‍ -Name[nb]=For mange tilkoblinger -Name[nds]=To vele Verbinnen -Name[nl]=Teveel verbindingen -Name[nn]=For mange tilkoplingar -Name[pa]=ਬਹੁਤ ਸਾਰੇ ਕੁਨੈਕਸ਼ਨ -Name[pl]=Zbyt wiele połączeń -Name[pt]=Demasiadas Ligações -Name[pt_BR]=Conexões em excesso -Name[ro]=Prea multe conexiuni -Name[ru]=Слишком много соединений -Name[si]=වඩා වැඩි සබඳතා ගණනක් -Name[sk]=Príliš veľa pripojení -Name[sl]=Preveč povezav -Name[sr]=Исувише веза -Name[sr@ijekavian]=Исувише веза -Name[sr@ijekavianlatin]=Isuviše veza -Name[sr@latin]=Isuviše veza -Name[sv]=För många anslutningar -Name[th]=มีการเชื่อมต่อมากเกินไป -Name[tr]=Çok Fazla Bağlantı -Name[ug]=باغلىنىش بەك كۆپ -Name[uk]=Забагато з’єднань -Name[x-test]=xxToo Many Connectionsxx -Name[zh_CN]=连接过多 -Name[zh_TW]=太多連線 -Comment=Busy, connection refused -Comment[af]=Besig, verbinding geweier -Comment[ar]=مشغول، الإتصال رفض -Comment[ast]=Ocupáu, conexón refugada -Comment[bg]=Заето. Връзката е отказана. -Comment[bn]=ব্যস্ত, সংযোগ অস্বীকার করল -Comment[br]=Dalc'het, kevreadenn disteuleret -Comment[bs]=Zauzeto, veza je odbijena -Comment[ca]=Ocupat, connexió rebutjada -Comment[ca@valencia]=Ocupat, connexió rebutjada -Comment[cs]=Zaneprázdněn, spojení odmítnuto -Comment[cy]=Prysur, gwrthodwyd y cysylltiad -Comment[da]=Optaget, forbindelse afslået -Comment[de]=Beschäftigt, Verbindung abgelehnt -Comment[el]=Απασχολημένος, η σύνδεση απορρίφθηκε -Comment[en_GB]=Busy, connection refused -Comment[eo]=Okupata, konekto rifuzita -Comment[es]=Ocupado, conexión rechazada -Comment[et]=Hõivatud, ühendusest keelduti -Comment[eu]=Lanpetuta, konexioa ukatu da -Comment[fi]=Varattu, yhteys hylättiin -Comment[fr]=Occupé. Connexion refusée -Comment[ga]=Gnóthach; ceangal diúltaithe -Comment[gl]=Ocupado; a conexión foi rexeitada -Comment[he]=תפוס, החיבור נדחה -Comment[hi]=व्यस्त, कनेक्शन अस्वीकृत -Comment[hne]=व्यस्त, कनेक्सन अस्वीकृत -Comment[hr]=Zauzeto, veza odbijena -Comment[hu]=A csatlakozási kérés elutasítva túlterhelés miatt -Comment[ia]=Occupate, connexion refusate -Comment[is]=Uptekinn, tengingu hafnað -Comment[it]=Occupato, connessione rifiutata -Comment[ja]=ビジーです、接続を拒否しました -Comment[kk]=Бос емес, қосылым болмады -Comment[km]=រវល់ បដិសេធ​ការ​ត​ភ្ជាប់ -Comment[ko]=바쁨, 연결 거부됨 -Comment[lt]=Užimta, kvietimas ryšiui atmestas -Comment[lv]=Aizņemts, savienojums noraidīts -Comment[mk]=Зафатено, поврзувањето е одбиено -Comment[ml]=തിരക്കിലാണ്, ബന്ധം നിഷേധിച്ചു -Comment[ms]=Sibuk, sambungan ditolak -Comment[nb]=Opptatt, tilkobling nektet -Comment[nds]=Bunnen, Verbinnen torüchwiest -Comment[nl]=Bezet, verbinding geweigerd -Comment[nn]=Oppteken, så tilkoplinga vart avslått -Comment[pa]=ਬਿਜ਼ੀ, ਕੁਨੈਕਸ਼ਨ ਤੋਂ ਇਨਕਾਰ -Comment[pl]=Zajęte, połączenie odrzucone -Comment[pt]=Ocupado, pelo a ligação foi recusada -Comment[pt_BR]=Ocupado; conexão recusada -Comment[ro]=Ocupat, conexiune refuzată -Comment[ru]=Занят, соединение отклонено -Comment[si]=කාර්‍යබහුලයි, සබඳතාව නොපිළිගැණිනි -Comment[sk]=Zaneprázdnený, pripojenie bolo odmietnuté -Comment[sl]=Zaposlen, povezava zavrnjena -Comment[sr]=Заузето, веза је одбијена -Comment[sr@ijekavian]=Заузето, веза је одбијена -Comment[sr@ijekavianlatin]=Zauzeto, veza je odbijena -Comment[sr@latin]=Zauzeto, veza je odbijena -Comment[sv]=Upptagen, anslutning vägras -Comment[ta]=வேலையில் உள்ளது, இணைப்பு நிராகரிக்கப்பட்டது -Comment[tg]=Банд, пайвастшавӣ рад гардидааст -Comment[th]=ยังไม่ว่าง ทำการปฏิเสธการเชื่อมต่อ -Comment[tr]=Meşgul, bağlantı reddedildi -Comment[ug]=ئالدىراش، باغلىنىش رەت قىلىندى -Comment[uk]=Зайнято, у з’єднанні відмовлено -Comment[uz]=Band, aloqa rad etildi -Comment[uz@cyrillic]=Банд, алоқа рад этилди -Comment[xh]=Uxhulumaniso, olu xakekileyo lwaliwe -Comment[x-test]=xxBusy, connection refusedxx -Comment[zh_CN]=对方处于忙碌状态,连接被拒绝 -Comment[zh_HK]=忙碌,已拒絕連線 -Comment[zh_TW]=忙碌,連線被拒 -Actions=Popup - -[krfb/UnexpectedConnection] -Name=Unexpected Connection -Name[ar]=الاتصال غير متوقّع -Name[ast]=Conexón inesperada -Name[bg]=Неочаквана връзка -Name[bs]=Neočekivana veza -Name[ca]=Connexió inesperada -Name[ca@valencia]=Connexió inesperada -Name[cs]=Neočekávané spojení -Name[da]=Uventet forbindelse -Name[de]=Unerwartete Verbindung -Name[el]=Μη αναμενόμενη σύνδεση -Name[en_GB]=Unexpected Connection -Name[eo]=Neatendita konekto -Name[es]=Conexión inesperada -Name[et]=Ootamatu ühendus -Name[eu]=Ustekabeko konexioa -Name[fi]=Odottamaton yhteys -Name[fr]=Connexion inattendue -Name[ga]=Ceangal Gan Choinne -Name[gl]=Conexión non agardada -Name[hi]=अप्रत्याशित कनेक्शन -Name[hne]=अप्रत्यासित कनेक्सन -Name[hr]=Neočekivana veza -Name[hu]=Nem várt kapcsolat -Name[ia]=Connexion impreviste -Name[is]=Óvænt Tenging -Name[it]=Connessione inattesa -Name[ja]=予期しない接続 -Name[kk]=Күтпеген қосылым -Name[km]=ការ​តភ្ជាប់​ដែល​មិន​បាន​រំពឹង​ទុក -Name[ko]=예상하지 않은 연결 -Name[lt]=Netikėtas kvietimas ryšiui -Name[lv]=Negaidīts savienojums -Name[ml]=അപ്രതീക്ഷിതമായ ബന്ധം -Name[nb]=Uventet tilkobling -Name[nds]=Nich verwacht Tokoppeln -Name[nl]=Onverwachte verbinding -Name[nn]=Uventa tilkopling -Name[pa]=ਅਣਜਾਣ ਕੁਨੈਕਸ਼ਨ -Name[pl]=Niespodziewane połączenie -Name[pt]=Ligação Inesperada -Name[pt_BR]=Conexão inesperada -Name[ro]=Conexiune neașteptată -Name[ru]=Неожиданное соединение -Name[si]=බලාපොරොත්තු රහිත සබඳතාවක් -Name[sk]=Neočakávané pripojenie -Name[sl]=Nepričakovana povezava -Name[sq]=Lidhje e Papritur -Name[sr]=Неочекивана веза -Name[sr@ijekavian]=Неочекивана веза -Name[sr@ijekavianlatin]=Neočekivana veza -Name[sr@latin]=Neočekivana veza -Name[sv]=Oväntad anslutning -Name[th]=เกิดการเชื่อมต่อที่ไม่คาดคิด -Name[tr]=Beklenmeyen Bağlantı -Name[ug]=كۈتۈلمىگەن باغلىنىش -Name[uk]=Неочікуване з’єднання -Name[x-test]=xxUnexpected Connectionxx -Name[zh_CN]=未预料的连接 -Name[zh_TW]=未知的連線 -Comment=Received unexpected connection, abort -Comment[af]=Ontvang onverwagte verbinding, staak -Comment[ar]=استقبال اتصال غير متوقع، إنهاء -Comment[ast]=Recibióse conexón inesperada, albortando -Comment[bg]=Получена е неочаквана връзка. Прекъсване. -Comment[bn]=অপ্রত্যাশিত সংযোগ গ্রহণ করল, বাতিল করুন -Comment[bs]=Primljena je neočekivana veza, prekini -Comment[ca]=Rebuda una connexió inesperada, avortant -Comment[ca@valencia]=Rebuda una connexió inesperada, avortant -Comment[cs]=Obdrženo neočekávané spojení, přerušeno -Comment[cy]=Derbynwyd cysylltiad annisgwyl,terfynu -Comment[da]=Modtog uventet forbindelse, afbrød -Comment[de]=Unerwartete Verbindung hergestellt, Abbruch -Comment[el]=Λήφθηκε μια μη αναμενόμενη σύνδεση· εγκατάλειψη -Comment[en_GB]=Received unexpected connection, abort -Comment[eo]=Ricevis neatenditan konekton, ĉesi -Comment[es]=Recibida conexión inesperada, interrumpir -Comment[et]=Saadi ootamatu ühendus, loobuti -Comment[eu]=Ustekabeko konexioa jaso da, abortatzen -Comment[fi]=Vastaanotettiin odottamaton yhteys, lopeta -Comment[fr]=Connexion inattendue reçue. Annulation -Comment[ga]=Fuarthas ceangal gan choinne, á thobscor -Comment[gl]=Recibiuse unha conexión non agardada; cancélase -Comment[he]=נתקבל חיבור בלתי צפוי, בוטל -Comment[hi]=अप्रत्याशित कनेक्शन प्राप्त. छोड़ा -Comment[hne]=अप्रत्यासित कनेक्सन प्राप्त. छोड़ा -Comment[hr]=Primio sam neočekivanu vezu, prekid -Comment[hu]=Nem várt csatlakozási kérés érkezett, megszakítás -Comment[ia]=On recipeva connexion impreviste, aborta -Comment[is]=Tók á móti óvæntri tengingu, hætti -Comment[it]=Ricevuta connessione inattesa, terminata -Comment[ja]=予期しない接続を受信しました。廃棄します。 -Comment[kk]=Күтпеген қосылым ұсынысы, доғарылды -Comment[km]=បាន​ទទួល​យក​ការ​តភ្ជាប់​ដែល​មិន​បាន​រំពឹង​ទុក ​បោះបង់ -Comment[ko]=예상하지 않은 연결을 받았습니다, 중지합니다 -Comment[lt]=Sulaukta netikėto kvietimo ryšiui, nutraukiama -Comment[lv]=Saņemts negaidīts savienojums, pārtraukts -Comment[mk]=Примено е неочекувано поврзување, се прекинува -Comment[ml]=അപ്രതീക്ഷിതമായ ബന്ധം ലഭിച്ചു, നിരസിക്കുക -Comment[ms]=Menerima sambungan luar jangka, menamatkan -Comment[nb]=Mottok uventet tilkobling, avbrutt -Comment[nds]=Unverwacht Verbinnen kregen, afbraken -Comment[nl]=Ontving een onverwachte verbinding, afgebroken -Comment[nn]=Fekk ei uventa tilkopling, så avbryt no -Comment[pl]=Otrzymano niespodziewane połączenie. Przerwane. -Comment[pt]=Foi recebida uma ligação inesperada, pelo que foi interrompida -Comment[pt_BR]=Conexão recebida inesperadamente; abortar -Comment[ro]=Conexiune neașteptată recepționată, abandonare -Comment[ru]=Получено неожиданное соединение. Отключение -Comment[si]=බලාපොරොත්තු රහිත සබඳතාවක් ලැබිනි, පිටවෙමින් -Comment[sk]=Prijaté neočakávané pripojenie, prerušené -Comment[sl]=Prejeta nepričakovana povezava, prekinjeno -Comment[sr]=Примљена је неочекивана веза, прекидам -Comment[sr@ijekavian]=Примљена је неочекивана веза, прекидам -Comment[sr@ijekavianlatin]=Primljena je neočekivana veza, prekidam -Comment[sr@latin]=Primljena je neočekivana veza, prekidam -Comment[sv]=Tog emot oväntad anslutning, avbryter -Comment[ta]=எதிர்பாராத இணைப்பு, நிறுத்தப்பட்டது -Comment[tg]=Пайвастшавии ғайричашмдош қабул гардид, кандашавӣ -Comment[th]=ได้รับการเชื่อมต่อมาอย่างไม่คาดคิด ทำการยกเลิก -Comment[tr]=Beklenmeyen bir bağlantı alındı, vazgeçiliyor -Comment[ug]=ئويلاشمىغان باغلىنىشنى تاپشۇرۇۋالدى، توختات -Comment[uk]=Отримано з’єднання, яке не очікувалось, припиняється -Comment[xh]=Ufumene uxhulumaniso olungalindelekanga, lahla -Comment[x-test]=xxReceived unexpected connection, abortxx -Comment[zh_CN]=收到意外连接,已中止 -Comment[zh_HK]=接收到非預期的連線,中止 -Comment[zh_TW]=已接收到未知的連線,中止。 -Actions=Popup diff --git a/krfb/krfb/krfbconfig.kcfgc b/krfb/krfb/krfbconfig.kcfgc deleted file mode 100644 index 7bbb14fa..00000000 --- a/krfb/krfb/krfbconfig.kcfgc +++ /dev/null @@ -1,3 +0,0 @@ -File=krfb.kcfg -ClassName=KrfbConfig -Singleton=true diff --git a/krfb/krfb/main.cpp b/krfb/krfb/main.cpp deleted file mode 100644 index 831dccb8..00000000 --- a/krfb/krfb/main.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/*************************************************************************** - main.cpp - ------------------- - begin : Sat Dec 8 03:23:02 CET 2001 - copyright : (C) 2001-2003 by Tim Jansen - email : tim@tjansen.de - ***************************************************************************/ - -/*************************************************************************** - * * - * 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. * - * * - ***************************************************************************/ - -#include "mainwindow.h" -#include "trayicon.h" -#include "invitationsrfbserver.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -static const char description[] = I18N_NOOP("VNC-compatible server to share " - "KDE desktops"); - -static bool checkX11Capabilities() -{ - int bp1, bp2, majorv, minorv; - Bool r = XTestQueryExtension(QX11Info::display(), &bp1, &bp2, - &majorv, &minorv); - - if ((!r) || (((majorv * 1000) + minorv) < 2002)) { - KMessageBox::error(0, - i18n("Your X11 Server does not support the required XTest extension " - "version 2.2. Sharing your desktop is not possible."), - i18n("Desktop Sharing Error")); - return false; - } - - return true; -} - -int main(int argc, char *argv[]) -{ - KAboutData aboutData("krfb", 0, ki18n("Desktop Sharing"), KDE_VERSION_STRING, - ki18n(description), KAboutData::License_GPL, - ki18n("(c) 2009-2010, Collabora Ltd.\n" - "(c) 2007, Alessandro Praduroux\n" - "(c) 2001-2003, Tim Jansen\n" - "(c) 2001, Johannes E. Schindelin\n" - "(c) 2000-2001, Const Kaplinsky\n" - "(c) 2000, Tridia Corporation\n" - "(c) 1999, AT&T Laboratories Boston\n")); - aboutData.addAuthor(ki18n("George Kiagiadakis"), - KLocalizedString(), - "george.kiagiadakis@collabora.co.uk"); - aboutData.addAuthor(ki18n("Alessandro Praduroux"), ki18n("KDE4 porting"), "pradu@pradu.it"); - aboutData.addAuthor(ki18n("Tim Jansen"), ki18n("Original author"), "tim@tjansen.de"); - aboutData.addCredit(ki18n("Johannes E. Schindelin"), - ki18n("libvncserver")); - aboutData.addCredit(ki18n("Const Kaplinsky"), - ki18n("TightVNC encoder")); - aboutData.addCredit(ki18n("Tridia Corporation"), - ki18n("ZLib encoder")); - aboutData.addCredit(ki18n("AT&T Laboratories Boston"), - ki18n("original VNC encoders and " - "protocol design")); - KCmdLineArgs::init(argc, argv, &aboutData); - - KCmdLineOptions options; - options.add("nodialog", ki18n("Do not show the invitations management dialog at startup")); - KCmdLineArgs::addCmdLineOptions(options); - - KUniqueApplication app; - app.setQuitOnLastWindowClosed(false); - - if (!checkX11Capabilities()) { - return 1; - } - - //init the core - InvitationsRfbServer::init(); - - //init the GUI - MainWindow mainWindow; - TrayIcon trayicon(&mainWindow); - - if (app.isSessionRestored() && KMainWindow::canBeRestored(1)) { - mainWindow.restore(1, false); - } else if (KCmdLineArgs::parsedArgs()->isSet("dialog")) { - mainWindow.show(); - } - - sigset_t sigs; - sigemptyset(&sigs); - sigaddset(&sigs, SIGPIPE); - sigprocmask(SIG_BLOCK, &sigs, 0); - - return app.exec(); -} - diff --git a/krfb/krfb/mainwidget.ui b/krfb/krfb/mainwidget.ui deleted file mode 100644 index 0f2cc7e2..00000000 --- a/krfb/krfb/mainwidget.ui +++ /dev/null @@ -1,538 +0,0 @@ - - - MainWidget - - - - 0 - 0 - 600 - 340 - - - - - 0 - 0 - - - - - 600 - 340 - - - - - 16777215 - 16777215 - - - - - - - - 128 - 128 - - - - - 128 - 128 - - - - - - - - QLayout::SetMaximumSize - - - - - - 0 - 0 - - - - - 400 - 20 - - - - - 16777215 - 40 - - - - - 75 - true - - - - KDE Desktop Sharing - - - KDE Desktop Sharing - - - Qt::AlignCenter - - - - - - - - 0 - 0 - - - - - 400 - 40 - - - - - 16777215 - 80 - - - - KDE Desktop Sharing - - - KDE Desktop Sharing allows you to grant permission to someone at a remote location for viewing and possibly controlling your desktop. - - - true - - - - - - - - 0 - 0 - - - - - 400 - 20 - - - - - 16777215 - 40 - - - - Starts/Stops Remote Desktop Sharing - - - &Enable Desktop Sharing - - - - - - - false - - - - 0 - 0 - - - - - 0 - 100 - - - - Connection Details - - - - - - QLayout::SetMaximumSize - - - QFormLayout::ExpandingFieldsGrow - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - 0 - 0 - - - - &Address - - - addressAboutButton - - - - - - - QLayout::SetMaximumSize - - - - - - 0 - 0 - - - - More about this address - - - About - - - - - - - - - - - - - 0 - 0 - - - - Address required by remote users to connect to your desktop. Click about button on the right for more info. - - - 127.0.0.1 : 5900 - - - Qt::AlignCenter - - - - - - - - - - - QLayout::SetMaximumSize - - - QFormLayout::ExpandingFieldsGrow - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - 0 - 0 - - - - &Password - - - passwordEditButton - - - - - - - QLayout::SetMaximumSize - - - - - - 0 - 0 - - - - Edit/Save Desktop Sharing Password - - - Edit - - - - - - - - - - - - - 0 - 0 - - - - Password required by remote users to connect to your desktop. Click the edit button on the right to change password. - - - TemporaryPassword - - - Qt::AlignCenter - - - - - - - - - - - - - - false - - - - 0 - 0 - - - - Unattended Access allows a remote user with the password to gain control to your desktop without your explicit confirmation. - - - Unattended Access - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - 0 - 0 - - - - - 16777215 - 80 - - - - Unattended Access allows a remote user with the password to gain control to your desktop without your explicit confirmation. Click "About" button on right to know more. - - - Unattended Access allows a remote user with the password to gain control to your desktop without your explicit confirmation. - - - true - - - - - - - - 0 - 0 - - - - Know more about Unattended Access - - - About - - - - - - - - - - - - - - 0 - - - 10 - - - 0 - - - 10 - - - - - - 0 - 0 - - - - - 16777215 - 80 - - - - Starts/Stops unattended access to your desktop. Click on button on right to change password, and "About" button to know more. - - - Enable &Unattended Access - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 320 - 80 - - - - Change password for Unattended Access - - - &Change Unattended Password - - - - - - - - - - - - - - QLayout::SetMinimumSize - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
- - KPixmapWidget - QWidget -
kpixmapwidget.h
-
-
- - enableSharingCheckBox - addressAboutButton - passwordEditButton - enableUnattendedCheckBox - unattendedPasswordButton - - - - enableSharingCheckBox - toggled(bool) - detailsGroupBox - setEnabled(bool) - - - 382 - 87 - - - 245 - 140 - - - - - enableSharingCheckBox - toggled(bool) - unattendedGroupBox - setEnabled(bool) - - - 320 - 76 - - - 325 - 214 - - - - -
diff --git a/krfb/krfb/mainwindow.cpp b/krfb/krfb/mainwindow.cpp deleted file mode 100644 index e0786bb9..00000000 --- a/krfb/krfb/mainwindow.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2013 Amandeep Singh - - 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. -*/ -#include "mainwindow.h" -#include "invitationsrfbserver.h" - -#include "krfbconfig.h" -#include "ui_configtcp.h" -#include "ui_configsecurity.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -class TCP: public QWidget, public Ui::TCP -{ -public: - TCP(QWidget *parent = 0) : QWidget(parent) { - setupUi(this); - } -}; - -class Security: public QWidget, public Ui::Security -{ -public: - Security(QWidget *parent = 0) : QWidget(parent) { - setupUi(this); - } -}; - - -MainWindow::MainWindow(QWidget *parent) - : KXmlGuiWindow(parent) -{ - setAttribute(Qt::WA_DeleteOnClose, false); - - m_passwordEditable = false; - m_passwordLineEdit = new KLineEdit(this); - m_passwordLineEdit->setVisible(false); - m_passwordLineEdit->setAlignment(Qt::AlignHCenter); - - QWidget *mainWidget = new QWidget; - m_ui.setupUi(mainWidget); - m_ui.krfbIconWidget->setPixmap(KIcon("krfb").pixmap(128)); - m_ui.enableUnattendedCheckBox->setChecked( - InvitationsRfbServer::instance->allowUnattendedAccess()); - - setCentralWidget(mainWidget); - - connect(m_ui.passwordEditButton,SIGNAL(clicked()), - this,SLOT(editPassword())); - connect(m_ui.enableSharingCheckBox,SIGNAL(toggled(bool)), - this, SLOT(toggleDesktopSharing(bool))); - connect(m_ui.enableUnattendedCheckBox, SIGNAL(toggled(bool)), - InvitationsRfbServer::instance, SLOT(toggleUnattendedAccess(bool))); - connect(m_ui.unattendedPasswordButton, SIGNAL(clicked()), - this, SLOT(editUnattendedPassword())); - connect(m_ui.addressAboutButton, SIGNAL(clicked()), - this, SLOT(aboutConnectionAddress())); - connect(m_ui.unattendedAboutButton, SIGNAL(clicked()), - this, SLOT(aboutUnattendedMode())); - connect(InvitationsRfbServer::instance, SIGNAL(passwordChanged(const QString&)), - this, SLOT(passwordChanged(const QString&))); - - // Figure out the address - int port = KrfbConfig::port(); - QList interfaceList = QNetworkInterface::allInterfaces(); - foreach(const QNetworkInterface & interface, interfaceList) { - if(interface.flags() & QNetworkInterface::IsLoopBack) - continue; - - if(interface.flags() & QNetworkInterface::IsRunning && - !interface.addressEntries().isEmpty()) - m_ui.addressDisplayLabel->setText(QString("%1 : %2") - .arg(interface.addressEntries().first().ip().toString()) - .arg(port)); - } - - //Figure out the password - m_ui.passwordDisplayLabel->setText( - InvitationsRfbServer::instance->desktopPassword()); - - KStandardAction::quit(QCoreApplication::instance(), SLOT(quit()), actionCollection()); - KStandardAction::preferences(this, SLOT(showConfiguration()), actionCollection()); - - setupGUI(); - - setAutoSaveSettings(); -} - -MainWindow::~MainWindow() -{ -} - -void MainWindow::editPassword() -{ - if(m_passwordEditable) { - m_passwordEditable = false; - m_ui.passwordEditButton->setIcon(KIcon("document-properties")); - m_ui.passwordGridLayout->removeWidget(m_passwordLineEdit); - InvitationsRfbServer::instance->setDesktopPassword( - m_passwordLineEdit->text()); - m_ui.passwordDisplayLabel->setText( - InvitationsRfbServer::instance->desktopPassword()); - m_passwordLineEdit->setVisible(false); - } else { - m_passwordEditable = true; - m_ui.passwordEditButton->setIcon(KIcon("document-save")); - m_ui.passwordGridLayout->addWidget(m_passwordLineEdit,0,0); - m_passwordLineEdit->setText( - InvitationsRfbServer::instance->desktopPassword()); - m_passwordLineEdit->setVisible(true); - m_passwordLineEdit->setFocus(Qt::MouseFocusReason); - } -} - -void MainWindow::editUnattendedPassword() -{ - KNewPasswordDialog dialog(this); - dialog.setPrompt(i18n("Enter a new password for Unattended Access")); - if(dialog.exec()) { - InvitationsRfbServer::instance->setUnattendedPassword(dialog.password()); - } -} - -void MainWindow::toggleDesktopSharing(bool enable) -{ - if(enable) { - if(!InvitationsRfbServer::instance->start()) { - KMessageBox::error(this, - i18n("Failed to start the krfb server. Desktop sharing " - "will not work. Try setting another port in the settings " - "and restart krfb.")); - } - } else { - InvitationsRfbServer::instance->stop(); - if(m_passwordEditable) { - m_passwordEditable = false; - m_passwordLineEdit->setVisible(false); - m_ui.passwordEditButton->setIcon(KIcon("document-properties")); - } - } -} - -void MainWindow::passwordChanged(const QString& password) -{ - m_passwordLineEdit->setText(password); - m_ui.passwordDisplayLabel->setText(password); -} - -void MainWindow::aboutConnectionAddress() -{ - KMessageBox::about(this, - i18n("This field contains the address of your computer and the port number, separated by a colon.\n\nThe address is just a hint - you can use any address that can reach your computer.\n\nDesktop Sharing tries to guess your address from your network configuration, but does not always succeed in doing so.\n\nIf your computer is behind a firewall it may have a different address or be unreachable for other computers."), - i18n("KDE Desktop Sharing")); -} - -void MainWindow::aboutUnattendedMode() -{ - KMessageBox::about(this, - i18n("Any remote user with normal desktop sharing password will have to be authenticated.\n\nIf unattended access is on, and the remote user provides unattended mode password, desktop sharing access will be granted without explicit confirmation."), - i18n("KDE Desktop Sharing")); -} - -void MainWindow::showConfiguration() -{ - if (KConfigDialog::showDialog("settings")) { - return; - } - - KConfigDialog *dialog = new KConfigDialog(this, "settings", KrfbConfig::self()); - dialog->addPage(new TCP, i18n("Network"), "network-workgroup"); - dialog->addPage(new Security, i18n("Security"), "security-high"); - dialog->setHelp(QString(), "krfb"); - dialog->show(); -} - -void MainWindow::readProperties(const KConfigGroup& group) -{ - if (group.readEntry("Visible", true)) { - show(); - } - KMainWindow::readProperties(group); -} - -void MainWindow::saveProperties(KConfigGroup& group) -{ - group.writeEntry("Visible", isVisible()); - KMainWindow::saveProperties(group); -} - -#include "moc_mainwindow.cpp" diff --git a/krfb/krfb/mainwindow.h b/krfb/krfb/mainwindow.h deleted file mode 100644 index 987891ca..00000000 --- a/krfb/krfb/mainwindow.h +++ /dev/null @@ -1,49 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2013 Amandeep Singh - - 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. -*/ - -#ifndef MANAGEINVITATIONSDIALOG_H -#define MANAGEINVITATIONSDIALOG_H - -#include "ui_mainwidget.h" - -#include - -class KLineEdit; - -class MainWindow : public KXmlGuiWindow -{ - Q_OBJECT - - public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); - - public Q_SLOTS: - void showConfiguration(); - - protected: - virtual void readProperties(const KConfigGroup & group); - virtual void saveProperties(KConfigGroup & group); - - private Q_SLOTS: - void editPassword(); - void editUnattendedPassword(); - void toggleDesktopSharing(bool enable); - void passwordChanged(const QString&); - void aboutConnectionAddress(); - void aboutUnattendedMode(); - - private: - Ui::MainWidget m_ui; - bool m_passwordEditable; - KLineEdit *m_passwordLineEdit; -}; - -#endif diff --git a/krfb/krfb/rfb.h b/krfb/krfb/rfb.h deleted file mode 100644 index fa94edad..00000000 --- a/krfb/krfb/rfb.h +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file should always be included instead of because otherwise it's redefinition - * of TRUE and FALSE plays havoc with other things. - */ - -#ifndef KRFB_RFB_H -#define KRFB_RFB_H - -#include "rfb/rfb.h" - -#undef TRUE -#undef FALSE - -#endif // Header guard - diff --git a/krfb/krfb/rfbclient.cpp b/krfb/krfb/rfbclient.cpp deleted file mode 100644 index f35bd76a..00000000 --- a/krfb/krfb/rfbclient.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "rfbclient.h" -#include "connectiondialog.h" -#include "krfbconfig.h" -#include "sockethelpers.h" -#include "events.h" -#include -#include -#include -#include //for bzero() - -struct RfbClient::Private -{ - Private(rfbClientPtr client) : - controlEnabled(KrfbConfig::allowDesktopControl()), - client(client) - {} - - bool controlEnabled; - rfbClientPtr client; - QSocketNotifier *notifier; - QString remoteAddressString; -}; - -RfbClient::RfbClient(rfbClientPtr client, QObject* parent) - : QObject(parent), d(new Private(client)) -{ - d->remoteAddressString = peerAddress(d->client->sock) + ":" + - QString::number(peerPort(d->client->sock)); - - d->notifier = new QSocketNotifier(client->sock, QSocketNotifier::Read, this); - d->notifier->setEnabled(false); - connect(d->notifier, SIGNAL(activated(int)), this, SLOT(onSocketActivated())); -} - -RfbClient::~RfbClient() -{ - kDebug(); - delete d; -} - -QString RfbClient::name() const -{ - return d->remoteAddressString; -} - -//static -bool RfbClient::controlCanBeEnabled() -{ - return KrfbConfig::allowDesktopControl(); -} - -bool RfbClient::controlEnabled() const -{ - return d->controlEnabled; -} - -void RfbClient::setControlEnabled(bool enabled) -{ - if (controlCanBeEnabled() && d->controlEnabled != enabled) { - d->controlEnabled = enabled; - Q_EMIT controlEnabledChanged(enabled); - } -} - -bool RfbClient::isOnHold() const -{ - return d->client->onHold ? true : false; -} - -void RfbClient::setOnHold(bool onHold) -{ - if (isOnHold() != onHold) { - d->client->onHold = onHold; - d->notifier->setEnabled(!onHold); - Q_EMIT holdStatusChanged(onHold); - } -} - -void RfbClient::closeConnection() -{ - d->notifier->setEnabled(false); - rfbCloseClient(d->client); - rfbClientConnectionGone(d->client); -} - -rfbClientPtr RfbClient::getRfbClientPtr() -{ - return d->client; -} - -void RfbClient::handleKeyboardEvent(bool down, rfbKeySym keySym) -{ - if (d->controlEnabled) { - EventHandler::handleKeyboard(down, keySym); - } -} - -void RfbClient::handleMouseEvent(int buttonMask, int x, int y) -{ - if (d->controlEnabled) { - EventHandler::handlePointer(buttonMask, x, y); - } -} - -void RfbClient::onSocketActivated() -{ - //Process not only one, but all pending messages. - //poll() idea/code copied from vino: - // Copyright (C) 2003 Sun Microsystems, Inc. - // License: GPL v2 or later - struct pollfd pollfd = { d->client->sock, POLLIN|POLLPRI, 0 }; - - while(poll(&pollfd, 1, 0) == 1) { - rfbProcessClientMessage(d->client); - - //This is how we handle disconnection. - //if rfbProcessClientMessage() finds out that it can't read the socket, - //it closes it and sets it to -1. So, we just have to check this here - //and call rfbClientConnectionGone() if necessary. This will call - //the clientGoneHook which in turn will remove this RfbClient instance - //from the server manager and will call deleteLater() to delete it - if (d->client->sock == -1) { - kDebug() << "disconnected from socket signal"; - d->notifier->setEnabled(false); - rfbClientConnectionGone(d->client); - break; - } - } -} - -void RfbClient::clientGoneHookNoop(rfbClientPtr cl) -{ - Q_UNUSED(cl); -} - -void RfbClient::update() -{ - rfbUpdateClient(d->client); - - //This is how we handle disconnection. - //if rfbUpdateClient() finds out that it can't write to the socket, - //it closes it and sets it to -1. So, we just have to check this here - //and call rfbClientConnectionGone() if necessary. This will call - //the clientGoneHook which in turn will remove this RfbClient instance - //from the server manager and will call deleteLater() to delete it - if (d->client->sock == -1) { - kDebug() << "disconnected during update"; - d->notifier->setEnabled(false); - rfbClientConnectionGone(d->client); - } -} - -//************* - -PendingRfbClient::PendingRfbClient(rfbClientPtr client, QObject *parent) - : QObject(parent), m_rfbClient(client) -{ - m_rfbClient->clientData = this; -} - -PendingRfbClient::~PendingRfbClient() -{} - -void PendingRfbClient::accept(RfbClient *newClient) -{ - kDebug() << "accepted connection"; - - m_rfbClient->clientData = newClient; - newClient->setOnHold(false); - - Q_EMIT finished(newClient); - deleteLater(); -} - -void PendingRfbClient::reject() -{ - kDebug() << "refused connection"; - - //override the clientGoneHook that was previously set by RfbServer - m_rfbClient->clientGoneHook = RfbClient::clientGoneHookNoop; - rfbCloseClient(m_rfbClient); - rfbClientConnectionGone(m_rfbClient); - - Q_EMIT finished(NULL); - deleteLater(); -} - -bool PendingRfbClient::checkPassword(const QByteArray & encryptedPassword) -{ - Q_UNUSED(encryptedPassword); - - return m_rfbClient->screen->authPasswdData == (void*)0; -} - -bool PendingRfbClient::vncAuthCheckPassword(const QByteArray& password, const QByteArray& encryptedPassword) const -{ - if (password.isEmpty() && encryptedPassword.isEmpty()) { - return true; - } - - char passwd[MAXPWLEN]; - unsigned char challenge[CHALLENGESIZE]; - - memcpy(challenge, m_rfbClient->authChallenge, CHALLENGESIZE); - bzero(passwd, MAXPWLEN); - - if (!password.isEmpty()) { - strncpy(passwd, password, - (MAXPWLEN <= password.size()) ? MAXPWLEN : password.size()); - } - - rfbEncryptBytes(challenge, passwd); - return memcmp(challenge, encryptedPassword, encryptedPassword.size()) == 0; -} - -#include "moc_rfbclient.cpp" diff --git a/krfb/krfb/rfbclient.h b/krfb/krfb/rfbclient.h deleted file mode 100644 index d6e49248..00000000 --- a/krfb/krfb/rfbclient.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#ifndef RFBCLIENT_H -#define RFBCLIENT_H - -#include "rfb.h" -#include - -class RfbClient : public QObject -{ - Q_OBJECT - Q_PROPERTY(bool controlEnabled READ controlEnabled WRITE setControlEnabled NOTIFY controlEnabledChanged) - Q_PROPERTY(bool onHold READ isOnHold WRITE setOnHold NOTIFY holdStatusChanged) -public: - RfbClient(rfbClientPtr client, QObject *parent = 0); - virtual ~RfbClient(); - - /** Returns a name for the client, to be shown to the user */ - virtual QString name() const; - - static bool controlCanBeEnabled(); - bool controlEnabled() const; - bool isOnHold() const; - -public Q_SLOTS: - void setControlEnabled(bool enabled); - void setOnHold(bool onHold); - void closeConnection(); - -Q_SIGNALS: - void controlEnabledChanged(bool enabled); - void holdStatusChanged(bool onHold); - -protected: - friend class RfbServer; //the following event handling methods are called by RfbServer - - rfbClientPtr getRfbClientPtr(); - virtual void handleKeyboardEvent(bool down, rfbKeySym keySym); - virtual void handleMouseEvent(int buttonMask, int x, int y); - -private Q_SLOTS: - void onSocketActivated(); - -protected: - static void clientGoneHookNoop(rfbClientPtr cl); - friend class PendingInvitationsRfbClient; - friend class PendingRfbClient; - -private: - ///called by RfbServerManager to send framebuffer updates - ///and check for possible disconnection - void update(); - friend class RfbServerManager; - - struct Private; - Private *const d; -}; - - -class PendingRfbClient : public QObject -{ - Q_OBJECT -public: - PendingRfbClient(rfbClientPtr client, QObject *parent = 0); - virtual ~PendingRfbClient(); - -Q_SIGNALS: - void finished(RfbClient *client); - -protected Q_SLOTS: - virtual void processNewClient() = 0; - - void accept(RfbClient *newClient); - void reject(); - -protected: - - friend class RfbServer; //Following two methods are handled by RfbServer - - /** This method is supposed to check if the provided \a encryptedPassword - * matches the criteria for authenticating the client. - * The default implementation returns false if a password is required. - * Reimplement to do more useful stuff. - */ - virtual bool checkPassword(const QByteArray & encryptedPassword); - - /** This method checks if the \a encryptedPassword that was sent from the remote - * user matches the \a password that you have specified localy to be the password - * for this connection. This assumes that the standard VNC authentication mechanism - * is used. Returns true if the password matches or false otherwise. - */ - bool vncAuthCheckPassword(const QByteArray & password, const QByteArray & encryptedPassword) const; - - rfbClientPtr m_rfbClient; -}; - -#endif // RFBCLIENT_H diff --git a/krfb/krfb/rfbserver.cpp b/krfb/krfb/rfbserver.cpp deleted file mode 100644 index a66d802b..00000000 --- a/krfb/krfb/rfbserver.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "rfbserver.h" -#include "rfbservermanager.h" -#include -#include -#include -#include - -struct RfbServer::Private -{ - QByteArray listeningAddress; - int listeningPort; - bool passwordRequired; - rfbScreenInfoPtr screen; - QSocketNotifier *notifier; -}; - -RfbServer::RfbServer(QObject *parent) - : QObject(parent), d(new Private) -{ - d->listeningAddress = "0.0.0.0"; - d->listeningPort = 0; - d->passwordRequired = true; - d->screen = NULL; - d->notifier = NULL; - - RfbServerManager::instance()->registerServer(this); -} - -RfbServer::~RfbServer() -{ - if (d->screen) { - rfbScreenCleanup(d->screen); - } - delete d; - - RfbServerManager::instance()->unregisterServer(this); -} - -QByteArray RfbServer::listeningAddress() const -{ - return d->listeningAddress; -} - -int RfbServer::listeningPort() const -{ - return d->listeningPort; -} - -bool RfbServer::passwordRequired() const -{ - return d->passwordRequired; -} - -void RfbServer::setListeningAddress(const QByteArray& address) -{ - d->listeningAddress = address; -} - -void RfbServer::setListeningPort(int port) -{ - d->listeningPort = port; -} - -void RfbServer::setPasswordRequired(bool passwordRequired) -{ - d->passwordRequired = passwordRequired; -} - -bool RfbServer::start() -{ - if (!d->screen) { - d->screen = RfbServerManager::instance()->newScreen(); - if (!d->screen) { - return false; - } - - // server hooks - d->screen->screenData = this; - d->screen->newClientHook = newClientHook; - d->screen->kbdAddEvent = keyboardHook; - d->screen->ptrAddEvent = pointerHook; - d->screen->passwordCheck = passwordCheck; - d->screen->setXCutText = clipboardHook; - } else { - //if we already have a screen, stop listening first - rfbShutdownServer(d->screen, false); - } - - if (listeningAddress() != "0.0.0.0") { - strncpy(d->screen->thisHost, listeningAddress().data(), 254); - } - - if (listeningPort() == 0) { - d->screen->autoPort = 1; - } - - d->screen->port = listeningPort(); - - // Disable/Enable password checking - if (passwordRequired()) { - d->screen->authPasswdData = (void *)1; - } else { - d->screen->authPasswdData = (void *)0; - } - - kDebug() << "Starting server. Listen port:" << listeningPort() - << "Listen Address:" << listeningAddress() - << "Password enabled:" << passwordRequired(); - - rfbInitServer(d->screen); - - if (!rfbIsActive(d->screen)) { - kDebug() << "Failed to start server"; - rfbShutdownServer(d->screen, false); - return false; - }; - - d->notifier = new QSocketNotifier(d->screen->listenSock, QSocketNotifier::Read, this); - d->notifier->setEnabled(true); - connect(d->notifier, SIGNAL(activated(int)), this, SLOT(onListenSocketActivated())); - connect(QApplication::clipboard(), SIGNAL(dataChanged()), - this, SLOT(krfbSendServerCutText())); - - return true; -} - -void RfbServer::stop(bool disconnectClients) -{ - if (d->screen) { - rfbShutdownServer(d->screen, disconnectClients); - if (d->notifier) { - d->notifier->setEnabled(false); - d->notifier->deleteLater(); - d->notifier = NULL; - } - } -} - -void RfbServer::updateScreen(const QList & modifiedTiles) -{ - if (d->screen) { - QList::const_iterator it = modifiedTiles.constBegin(); - for(; it != modifiedTiles.constEnd(); ++it) { - rfbMarkRectAsModified(d->screen, it->x(), it->y(), it->right(), it->bottom()); - } - } -} - -/* - * Code copied from vino's bundled libvncserver: - * Copyright (C) 2000, 2001 Const Kaplinsky. All Rights Reserved. - * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. - * License: GPL v2 or later - */ -void krfb_rfbSetCursorPosition(rfbScreenInfoPtr screen, rfbClientPtr client, int x, int y) -{ - rfbClientIteratorPtr iterator; - rfbClientPtr cl; - - if (x == screen->cursorX || y == screen->cursorY) - return; - - LOCK(screen->cursorMutex); - screen->cursorX = x; - screen->cursorY = y; - UNLOCK(screen->cursorMutex); - - /* Inform all clients about this cursor movement. */ - iterator = rfbGetClientIterator(screen); - while ((cl = rfbClientIteratorNext(iterator)) != NULL) { - cl->cursorWasMoved = true; - } - rfbReleaseClientIterator(iterator); - - /* The cursor was moved by this client, so don't send CursorPos. */ - if (client) { - client->cursorWasMoved = false; - } -} - -void RfbServer::updateCursorPosition(const QPoint & position) -{ - if (d->screen) { - krfb_rfbSetCursorPosition(d->screen, NULL, position.x(), position.y()); - } -} - -void RfbServer::krfbSendServerCutText() -{ - if(d->screen) { - QString text = QApplication::clipboard()->text(); - rfbSendServerCutText(d->screen, - text.toLocal8Bit().data(),text.length()); - } -} - -void RfbServer::onListenSocketActivated() -{ - rfbProcessNewConnection(d->screen); -} - -void RfbServer::pendingClientFinished(RfbClient *client) -{ - kDebug(); - if (client) { - RfbServerManager::instance()->addClient(client); - client->getRfbClientPtr()->clientGoneHook = clientGoneHook; - } -} - -//static -rfbNewClientAction RfbServer::newClientHook(rfbClientPtr cl) -{ - kDebug() << "New client"; - RfbServer *server = static_cast(cl->screen->screenData); - - PendingRfbClient *pendingClient = server->newClient(cl); - connect(pendingClient, SIGNAL(finished(RfbClient*)), - server, SLOT(pendingClientFinished(RfbClient*))); - - return RFB_CLIENT_ON_HOLD; -} - -//static -void RfbServer::clientGoneHook(rfbClientPtr cl) -{ - kDebug() << "client gone"; - RfbClient *client = static_cast(cl->clientData); - - RfbServerManager::instance()->removeClient(client); - client->deleteLater(); -} - -//static -rfbBool RfbServer::passwordCheck(rfbClientPtr cl, const char *encryptedPassword, int len) -{ - PendingRfbClient *client = static_cast(cl->clientData); - Q_ASSERT(client); - return client->checkPassword(QByteArray::fromRawData(encryptedPassword, len)); -} - -//static -void RfbServer::keyboardHook(rfbBool down, rfbKeySym keySym, rfbClientPtr cl) -{ - RfbClient *client = static_cast(cl->clientData); - client->handleKeyboardEvent(down ? true : false, keySym); -} - -//static -void RfbServer::pointerHook(int bm, int x, int y, rfbClientPtr cl) -{ - RfbClient *client = static_cast(cl->clientData); - client->handleMouseEvent(bm, x, y); -} - -//static -void RfbServer::clipboardHook(char *str, int len, rfbClientPtr cl) -{ - QApplication::clipboard()->setText(QString::fromLocal8Bit(str,len)); -} - -#include "moc_rfbserver.cpp" diff --git a/krfb/krfb/rfbserver.h b/krfb/krfb/rfbserver.h deleted file mode 100644 index 6a9fe397..00000000 --- a/krfb/krfb/rfbserver.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#ifndef RFBSERVER_H -#define RFBSERVER_H - -#include "rfb.h" -#include "rfbclient.h" -#include - -class RfbServer : public QObject -{ - Q_OBJECT -public: - RfbServer(QObject *parent = 0); - virtual ~RfbServer(); - - QByteArray listeningAddress() const; - int listeningPort() const; - bool passwordRequired() const; - - void setListeningAddress(const QByteArray & address); - void setListeningPort(int port); - void setPasswordRequired(bool passwordRequired); - -public Q_SLOTS: - virtual bool start(); - virtual void stop(bool disconnectClients = true); - - void updateScreen(const QList & modifiedTiles); - void updateCursorPosition(const QPoint & position); - -private Q_SLOTS: - void krfbSendServerCutText(); - void onListenSocketActivated(); - void pendingClientFinished(RfbClient *client); - -protected: - virtual PendingRfbClient *newClient(rfbClientPtr client) = 0; - -private: - static rfbNewClientAction newClientHook(rfbClientPtr cl); - static void clientGoneHook(rfbClientPtr cl); - - static rfbBool passwordCheck(rfbClientPtr cl, const char *encryptedPassword, int len); - static void keyboardHook(rfbBool down, rfbKeySym keySym, rfbClientPtr cl); - static void pointerHook(int bm, int x, int y, rfbClientPtr cl); - static void clipboardHook(char *str, int len, rfbClientPtr cl); - - Q_DISABLE_COPY(RfbServer) - - struct Private; - Private *const d; -}; - -#endif // RFBSERVER_H diff --git a/krfb/krfb/rfbservermanager.cpp b/krfb/krfb/rfbservermanager.cpp deleted file mode 100644 index a59ae8ae..00000000 --- a/krfb/krfb/rfbservermanager.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "rfbservermanager.h" -#include "rfbserver.h" -#include "framebuffer.h" -#include "framebuffermanager.h" -#include "sockethelpers.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char *cur = - " " - " x " - " xx " - " xxx " - " xxxx " - " xxxxx " - " xxxxxx " - " xxxxxxx " - " xxxxxxxx " - " xxxxxxxxx " - " xxxxxxxxxx " - " xxxxx " - " xx xxx " - " x xxx " - " xxx " - " xxx " - " xxx " - " xxx " - " "; - -static const char *mask = - "xx " - "xxx " - "xxxx " - "xxxxx " - "xxxxxx " - "xxxxxxx " - "xxxxxxxx " - "xxxxxxxxx " - "xxxxxxxxxx " - "xxxxxxxxxxx " - "xxxxxxxxxxxx " - "xxxxxxxxxx " - "xxxxxxxx " - "xxxxxxxx " - "xx xxxxx " - " xxxxx " - " xxxxx " - " xxxxx " - " xxx "; - - -class RfbServerManagerStatic -{ -public: - RfbServerManager server; -}; - -K_GLOBAL_STATIC(RfbServerManagerStatic, s_instance) - -RfbServerManager* RfbServerManager::instance() -{ - return &s_instance->server; -} - - -struct RfbServerManager::Private -{ - QSharedPointer fb; - rfbCursorPtr myCursor; - QByteArray desktopName; - QTimer rfbUpdateTimer; - QSet servers; - QSet clients; -}; - - -RfbServerManager::RfbServerManager() - : QObject(), d(new Private) -{ - init(); -} - -RfbServerManager::~RfbServerManager() -{ - delete d; -} - -void RfbServerManager::init() -{ - kDebug(); - - d->fb = FrameBufferManager::instance()->frameBuffer(QApplication::desktop()->winId()); - d->myCursor = rfbMakeXCursor(19, 19, (char *) cur, (char *) mask); - d->myCursor->cleanup = false; - d->desktopName = QString("%1@%2 (shared desktop)") //FIXME check if we can use utf8 - .arg(KUser().loginName(),QHostInfo::localHostName()).toLatin1(); - - connect(&d->rfbUpdateTimer, SIGNAL(timeout()), SLOT(updateScreens())); - connect(qApp, SIGNAL(aboutToQuit()), SLOT(cleanup())); -} - -void RfbServerManager::updateScreens() -{ - QList rects = d->fb->modifiedTiles(); - QPoint currentCursorPos = QCursor::pos(); - - Q_FOREACH(RfbServer *server, d->servers) { - server->updateScreen(rects); - server->updateCursorPosition(currentCursorPos); - } - - //update() might disconnect some of the clients, which will synchronously - //call the removeClient() method and will change d->clients, so we need - //to copy the set here to avoid problems. - QSet clients = d->clients; - Q_FOREACH(RfbClient *client, clients) { - client->update(); - } -} - -void RfbServerManager::cleanup() -{ - kDebug(); - - //copy because d->servers is going to be modified while we delete the servers - QSet servers = d->servers; - Q_FOREACH(RfbServer *server, servers) { - delete server; - } - - Q_ASSERT(d->servers.isEmpty()); - Q_ASSERT(d->clients.isEmpty()); - - d->myCursor->cleanup = true; - rfbFreeCursor(d->myCursor); - d->fb.clear(); -} - -void RfbServerManager::registerServer(RfbServer* server) -{ - d->servers.insert(server); -} - -void RfbServerManager::unregisterServer(RfbServer* server) -{ - d->servers.remove(server); -} - -rfbScreenInfoPtr RfbServerManager::newScreen() -{ - rfbScreenInfoPtr screen = NULL; - - if (!d->fb.isNull()) { - int w = d->fb->width(); - int h = d->fb->height(); - int depth = d->fb->depth(); - int bpp = depth >> 3; - - if (bpp != 1 && bpp != 2 && bpp != 4) { - bpp = 4; - } - - kDebug() << "bpp: " << bpp; - - rfbLogEnable(0); - - screen = rfbGetScreen(0, 0, w, h, 8, 3, bpp); - screen->paddedWidthInBytes = d->fb->paddedWidth(); - d->fb->getServerFormat(screen->serverFormat); - screen->frameBuffer = d->fb->data(); - - screen->desktopName = d->desktopName.constData(); - screen->cursor = d->myCursor; - } - - return screen; -} - -void RfbServerManager::addClient(RfbClient* cc) -{ - if (d->clients.size() == 0) { - kDebug() << "Starting framebuffer monitor"; - d->fb->startMonitor(); - d->rfbUpdateTimer.start(50); - } - d->clients.insert(cc); - - KNotification::event( - "krfb/UserAcceptsConnection", - QString(), - i18n("The remote user %1 is now connected.", cc->name()) - ); - - Q_EMIT clientConnected(cc); -} - -void RfbServerManager::removeClient(RfbClient* cc) -{ - d->clients.remove(cc); - if (d->clients.size() == 0) { - kDebug() << "Stopping framebuffer monitor"; - d->fb->stopMonitor(); - d->rfbUpdateTimer.stop(); - } - - KNotification::event( - "krfb/ConnectionClosed", - QString(), - i18n("The remote user %1 disconnected.", cc->name()) - ); - - Q_EMIT clientDisconnected(cc); -} - -#include "moc_rfbservermanager.cpp" diff --git a/krfb/krfb/rfbservermanager.h b/krfb/krfb/rfbservermanager.h deleted file mode 100644 index 7790458c..00000000 --- a/krfb/krfb/rfbservermanager.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (C) 2009-2010 Collabora Ltd - @author George Goldberg - @author George Kiagiadakis - Copyright (C) 2007 Alessandro Praduroux - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#ifndef RFBSERVERMANAGER_H -#define RFBSERVERMANAGER_H - -#include "rfb.h" -#include - -class RfbClient; -class RfbServerManagerStatic; -class RfbServer; - -class RfbServerManager : public QObject -{ - Q_OBJECT -public: - static RfbServerManager *instance(); - -Q_SIGNALS: - void clientConnected(RfbClient *cc); - void clientDisconnected(RfbClient *cc); - -private Q_SLOTS: - void init(); - void updateScreens(); - void cleanup(); - -private: - void registerServer(RfbServer *server); - void unregisterServer(RfbServer *server); - - rfbScreenInfoPtr newScreen(); - - void addClient(RfbClient *cc); - void removeClient(RfbClient *cc); - - RfbServerManager(); - virtual ~RfbServerManager(); - Q_DISABLE_COPY(RfbServerManager) - - friend class RfbServer; - friend class RfbServerManagerStatic; - - struct Private; - Private *const d; -}; - -#endif // RFBSERVERMANAGER_H diff --git a/krfb/krfb/sockethelpers.cpp b/krfb/krfb/sockethelpers.cpp deleted file mode 100644 index 97fcc87b..00000000 --- a/krfb/krfb/sockethelpers.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "sockethelpers.h" - -#include -#include -#include - -QString peerAddress(int sock) -{ - - const int ADDR_SIZE = 50; - struct sockaddr sa; - socklen_t salen = sizeof(struct sockaddr); - - if (getpeername(sock, &sa, &salen) == 0) { - if (sa.sa_family == AF_INET) { - struct sockaddr_in *si = (struct sockaddr_in *)&sa; - return QString(inet_ntoa(si->sin_addr)); - } - - if (sa.sa_family == AF_INET6) { - char inetbuf[ADDR_SIZE]; - inet_ntop(sa.sa_family, &sa, inetbuf, ADDR_SIZE); - return QString(inetbuf); - } - - return QString("not a network address"); - } - - return QString("unable to determine..."); -} - -unsigned short peerPort(int sock) -{ - - struct sockaddr sa; - socklen_t salen = sizeof(struct sockaddr); - - if (getpeername(sock, &sa, &salen) == 0) { - struct sockaddr_in *si = (struct sockaddr_in *)&sa; - return ntohs(si->sin_port); - } - - return 0; -} - -QString localAddress(int sock) -{ - - const int ADDR_SIZE = 50; - struct sockaddr sa; - socklen_t salen = sizeof(struct sockaddr); - - if (getsockname(sock, &sa, &salen) == 0) { - if (sa.sa_family == AF_INET) { - struct sockaddr_in *si = (struct sockaddr_in *)&sa; - return QString(inet_ntoa(si->sin_addr)); - } - - if (sa.sa_family == AF_INET6) { - char inetbuf[ADDR_SIZE]; - inet_ntop(sa.sa_family, &sa, inetbuf, ADDR_SIZE); - return QString(inetbuf); - } - - return QString("not a network address"); - } - - return QString("unable to determine..."); -} - -unsigned short localPort(int sock) -{ - - struct sockaddr sa; - socklen_t salen = sizeof(struct sockaddr); - - if (getsockname(sock, &sa, &salen) == 0) { - struct sockaddr_in *si = (struct sockaddr_in *)&sa; - return ntohs(si->sin_port); - } - - return 0; -} - diff --git a/krfb/krfb/sockethelpers.h b/krfb/krfb/sockethelpers.h deleted file mode 100644 index dae2dccd..00000000 --- a/krfb/krfb/sockethelpers.h +++ /dev/null @@ -1,30 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2009 Collabora Ltd - @author George Goldberg - Copyright (C) 2007 Alessandro Praduroux - Copyright (C) 2001-2003 by Tim Jansen - - 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; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include - -QString peerAddress(int sock); -unsigned short peerPort(int sock); - -QString localAddress(int sock); -unsigned short localPort(int sock); - diff --git a/krfb/krfb/trayicon.cpp b/krfb/krfb/trayicon.cpp deleted file mode 100644 index 60f5daae..00000000 --- a/krfb/krfb/trayicon.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - Copyright (C) 2010 Collabora Ltd - @author George Kiagiadakis - Copyright (C) 2001-2002 Tim Jansen - - 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 Lesser General Public License - along with this program. If not, see . -*/ -#include "trayicon.h" - -#include "mainwindow.h" -#include "rfbservermanager.h" -#include "rfbclient.h" - -#include -#include -#include -#include -#include -#include -#include -#include - - -class ClientActions -{ -public: - ClientActions(RfbClient *client, KMenu *menu, QAction *before); - virtual ~ClientActions(); - -private: - KMenu *m_menu; - QAction *m_title; - QAction *m_disconnectAction; - QAction *m_enableControlAction; - QAction *m_separator; -}; - -ClientActions::ClientActions(RfbClient* client, KMenu* menu, QAction* before) - : m_menu(menu) -{ - m_title = m_menu->addTitle(client->name(), before); - - m_disconnectAction = new KAction(i18n("Disconnect"), m_menu); - m_menu->insertAction(before, m_disconnectAction); - - QObject::connect(m_disconnectAction, SIGNAL(triggered()), client, SLOT(closeConnection())); - - if (client->controlCanBeEnabled()) { - m_enableControlAction = new KToggleAction(i18n("Enable Remote Control"), m_menu); - m_enableControlAction->setChecked(client->controlEnabled()); - m_menu->insertAction(before, m_enableControlAction); - - QObject::connect(m_enableControlAction, SIGNAL(triggered(bool)), - client, SLOT(setControlEnabled(bool))); - QObject::connect(client, SIGNAL(controlEnabledChanged(bool)), - m_enableControlAction, SLOT(setChecked(bool))); - } else { - m_enableControlAction = NULL; - } - - m_separator = m_menu->insertSeparator(before); -} - -ClientActions::~ClientActions() -{ - kDebug(); - - m_menu->removeAction(m_title); - delete m_title; - - m_menu->removeAction(m_disconnectAction); - delete m_disconnectAction; - - if (m_enableControlAction) { - m_menu->removeAction(m_enableControlAction); - delete m_enableControlAction; - } - - m_menu->removeAction(m_separator); - delete m_separator; -} - -//********** - -TrayIcon::TrayIcon(QWidget *mainWindow) - : KStatusNotifierItem(mainWindow) -{ - setIconByPixmap(KIcon("krfb").pixmap(22, 22, KIcon::Disabled)); - - setToolTipTitle(i18n("Desktop Sharing - disconnected")); - setCategory(KStatusNotifierItem::ApplicationStatus); - - connect(RfbServerManager::instance(), SIGNAL(clientConnected(RfbClient*)), - this, SLOT(onClientConnected(RfbClient*))); - connect(RfbServerManager::instance(), SIGNAL(clientDisconnected(RfbClient*)), - this, SLOT(onClientDisconnected(RfbClient*))); - - m_aboutAction = KStandardAction::aboutApp(this, SLOT(showAbout()), actionCollection()); - contextMenu()->addAction(m_aboutAction); -} - -void TrayIcon::onClientConnected(RfbClient* client) -{ - kDebug(); - - if (m_clientActions.isEmpty()) { //first client connected - setIconByName("krfb"); - setToolTipTitle(i18n("Desktop Sharing - connected with %1", client->name())); - setStatus(KStatusNotifierItem::Active); - } else { //Nth client connected, N != 1 - setToolTipTitle(i18n("Desktop Sharing - connected")); - } - - m_clientActions[client] = new ClientActions(client, contextMenu(), m_aboutAction); -} - -void TrayIcon::onClientDisconnected(RfbClient* client) -{ - kDebug(); - - ClientActions *actions = m_clientActions.take(client); - delete actions; - - if (m_clientActions.isEmpty()) { - setIconByPixmap(KIcon("krfb").pixmap(22, 22, KIcon::Disabled)); - setToolTipTitle(i18n("Desktop Sharing - disconnected")); - setStatus(KStatusNotifierItem::Passive); - } else if (m_clientActions.size() == 1) { //clients number dropped back to 1 - RfbClient *client = m_clientActions.constBegin().key(); - setToolTipTitle(i18n("Desktop Sharing - connected with %1", client->name())); - } -} - -void TrayIcon::showAbout() -{ - KDialog *dlg = new KAboutApplicationDialog(KGlobal::mainComponent().aboutData()); - dlg->setAttribute(Qt::WA_DeleteOnClose, true); - dlg->show(); -} - -#include "moc_trayicon.cpp" diff --git a/krfb/krfb/trayicon.h b/krfb/krfb/trayicon.h deleted file mode 100644 index 499893d3..00000000 --- a/krfb/krfb/trayicon.h +++ /dev/null @@ -1,49 +0,0 @@ -/*************************************************************************** - trayicon.h - description - ------------------- - begin : Tue Dec 11 2001 - copyright : (C) 2001-2002 by Tim Jansen - email : tim@tjansen.de - ***************************************************************************/ - -/*************************************************************************** - * * - * 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. * - * * - ***************************************************************************/ - -#ifndef TRAYICON_H -#define TRAYICON_H - -#include -#include - -class KDialog; -class RfbClient; -class ClientActions; - -/** - * Implements the trayicon. - * @author Tim Jansen - */ - -class TrayIcon : public KStatusNotifierItem -{ - Q_OBJECT -public: - TrayIcon(QWidget *mainWindow); - -public Q_SLOTS: - void onClientConnected(RfbClient *client); - void onClientDisconnected(RfbClient *client); - void showAbout(); - -private: - KAction *m_aboutAction; - QHash m_clientActions; -}; - -#endif diff --git a/kvkbd/CMakeLists.txt b/kvkbd/CMakeLists.txt deleted file mode 100644 index ea7d2733..00000000 --- a/kvkbd/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -project( kvkbd ) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - include(FeatureSummary) - - find_package(KDELibs4 4.23.0 REQUIRED) - - include_directories(${KDE4_INCLUDES}) - add_definitions(${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -endif() - -add_subdirectory( src ) -add_subdirectory( colors ) -add_subdirectory( themes ) - -if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) - feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) -endif() diff --git a/kvkbd/LICENSE b/kvkbd/LICENSE deleted file mode 100644 index bde60ceb..00000000 --- a/kvkbd/LICENSE +++ /dev/null @@ -1,165 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. \ No newline at end of file diff --git a/kvkbd/README b/kvkbd/README deleted file mode 100644 index ed6736db..00000000 --- a/kvkbd/README +++ /dev/null @@ -1,13 +0,0 @@ -Kvkbd - A virtual keyboard for KDE4 -=============================================================================== -Installations instructions: -See INSTALL - -Known issues: -- The mod keys(ctrl, alt, alt gr, pg up, pg down, ...) may not work if you're -not using Xserver >= 1.5 with evdev enabled due to changes in the keys mapping. -Hopefully, new releases of Kvkbd will detect which mapping is used and behave -accordingly. -- The Loginhelper mode(see manual) does not work currently with KDM, you can either -apply the patch for KDM available here: , -wait for your distribution or for KDE to include the patch, or use XDM. diff --git a/kvkbd/colors/CMakeLists.txt b/kvkbd/colors/CMakeLists.txt deleted file mode 100644 index dda25d78..00000000 --- a/kvkbd/colors/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -install( FILES dark.css legacy.css light.css simple.css DESTINATION ${KDE4_DATA_INSTALL_DIR}/kvkbd/colors) diff --git a/kvkbd/colors/dark.css b/kvkbd/colors/dark.css deleted file mode 100644 index 257bc779..00000000 --- a/kvkbd/colors/dark.css +++ /dev/null @@ -1,43 +0,0 @@ -QWidget[name="main"] { - background-color:rgba(0,0,0,30%); - border-radius: 5px 5px 5px 5px; -} - -VButton { - margin:1px; - padding:0px; - border-style: outset; - border-radius: 5px; - border-width: 1px; - - font-size:13px; - font-weight:bold; - - border-color: #000000; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #000000, stop: 1 #555555); - - color:#cccccc; -} - -VButton:pressed { - border-style: inset; -} -VButton:checked { - - border-style: inset; - border-width: 2px; - border-color: #999999; -} -VButton:hover { - border-width:2px; - border-color: #555555; -} - -VButton[action="toggleExtension"] { - background-color:gray; - border-color: gray; -} -VButton[action="toggleVisibility"] { - background-color:red; - border-color:red; -} \ No newline at end of file diff --git a/kvkbd/colors/legacy.css b/kvkbd/colors/legacy.css deleted file mode 100644 index b9f1e594..00000000 --- a/kvkbd/colors/legacy.css +++ /dev/null @@ -1,13 +0,0 @@ -QWidget[name="main"] { - background-color:rgba(0,0,0,30%); - border-radius: 5px 5px 5px 5px; -} - -VButton[action="toggleExtension"] { - background-color:gray; - border-color: gray; -} -VButton[action="toggleVisibility"] { - background-color:red; - border-color:red; -} \ No newline at end of file diff --git a/kvkbd/colors/light.css b/kvkbd/colors/light.css deleted file mode 100644 index 3f81be2b..00000000 --- a/kvkbd/colors/light.css +++ /dev/null @@ -1,40 +0,0 @@ -QWidget[name="main"] { - background-color:rgba(255,255,255,30%); - border-radius: 5px 5px 5px 5px; -} - -VButton { - margin:1px; - padding:0px; - border-style: outset; - border-radius: 5px; - border-width: 1px; - - font-size:13px; - font-weight:bold; - - border-color: #000000; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #FFFFFF, stop: 1 #999999 ); - - color:black; -} - -VButton:pressed { - border-style: inset; -} -VButton:checked { - border-style: inset; - border-width:2px; -} -VButton:hover { - border-width:2px; - border-color: #555555; -} -VButton[action="toggleExtension"] { - background-color:gray; - border-color: gray; -} -VButton[action="toggleVisibility"] { - background-color:red; - border-color:red; -} diff --git a/kvkbd/colors/simple.css b/kvkbd/colors/simple.css deleted file mode 100644 index 8a05c2a8..00000000 --- a/kvkbd/colors/simple.css +++ /dev/null @@ -1,42 +0,0 @@ -QWidget[name="main"] { - background-color:rgba(255,255,255,30%); -} - -VButton { - margin:2px; - padding:0px; - border-style: outset; - - border-width: 1px; - - font-size:13px; - font-weight:bold; - background-color:rgba(172,172,172,70%); - border-color: #000000; -/* background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #FFFFFF, stop: 1 #999999 ); */ - - color:black; -} - -VButton:pressed { - border-style: inset; - border-color: #333333; -} -VButton:checked { -/* border-style: inset; */ - border-width:2px; - border-color: #333333; -} -VButton:hover { - border-width:2px; - border-color: #333333; - -} -VButton[action="toggleExtension"] { - background-color:gray; - border-color: gray; -} -VButton[action="toggleVisibility"] { - background-color:red; - border-color:red; -} diff --git a/kvkbd/kvkbd.kdev4 b/kvkbd/kvkbd.kdev4 deleted file mode 100644 index 64c21dcd..00000000 --- a/kvkbd/kvkbd.kdev4 +++ /dev/null @@ -1,3 +0,0 @@ -[Project] -Manager=KDevCMakeManager -Name=kvkbd diff --git a/kvkbd/src/CMakeLists.txt b/kvkbd/src/CMakeLists.txt deleted file mode 100644 index 18f8058d..00000000 --- a/kvkbd/src/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -include_directories(${KDE4_INCLUDES} ${QT_INCLUDES}) - -set(kvkbd_SRCS vkeyboard.cpp - x11keyboard.cpp - dragwidget.cpp - mainwidget.cpp - vbutton.cpp - main.cpp - resizabledragwidget.cpp - keysymconvert.cpp - kbddock.cpp - kvkbdapp.cpp - kbdtray.cpp - themeloader.cpp -) - -QT4_ADD_DBUS_ADAPTOR(kvkbd_SRCS org.kde.kvkbd.Kvkbd.xml - mainwidget.h MainWidget) - -QT4_ADD_DBUS_ADAPTOR(kvkbd_SRCS org.kde.kvkbd.Dock.xml - kbddock.h KbdDock) - -add_executable(kvkbd ${kvkbd_SRCS}) - -target_link_libraries(kvkbd - KDE4::kdecore - KDE4::kdeui - ${QT_QTDBUS_LIBRARY} - ${QT_QTXML_LIBRARY} - ${X11_X11_LIB} - ${X11_XTest_LIB} -) - -install( - TARGETS kvkbd - DESTINATION ${KDE4_BIN_INSTALL_DIR} -) - -install( - FILES kvkbd.desktop - DESTINATION ${KDE4_XDG_APPS_INSTALL_DIR} -) diff --git a/kvkbd/src/Messages.sh b/kvkbd/src/Messages.sh deleted file mode 100755 index 49b2cc9f..00000000 --- a/kvkbd/src/Messages.sh +++ /dev/null @@ -1,2 +0,0 @@ -#! /bin/sh -$XGETTEXT *.cpp -o $podir/kvkbd.pot diff --git a/kvkbd/src/dragwidget.cpp b/kvkbd/src/dragwidget.cpp deleted file mode 100644 index a6b55940..00000000 --- a/kvkbd/src/dragwidget.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include "dragwidget.h" - -#include -#include -#include -#include - -#include -#include -#include - - -DragWidget::DragWidget(QWidget *parent) : - QWidget(parent), dragged(false), moved(false), locked(false) -{ - setAttribute(Qt::WA_TranslucentBackground); -} - -DragWidget::~DragWidget() -{ -} - -void DragWidget::blurBackground(bool blurEnabled) -{ - setProperty("blurBackground", QVariant(blurEnabled)); - repaint(); -} - -void DragWidget::setLocked(bool locked) -{ - this->locked = locked; -} -bool DragWidget::isLocked() -{ - return locked; -} - -void DragWidget::mousePressEvent(QMouseEvent *e) -{ - if (locked) { - return; - } - - gpress = e->globalPos(); - dragged = true; - dragPoint = e->pos(); -} - -void DragWidget::mouseMoveEvent(QMouseEvent *ev) -{ - if (!dragged) { - return; - } - - moved = true; - - QPoint curr(ev->globalPos().x() - dragPoint.x(), ev->globalPos().y() - dragPoint.y()); - move(curr); - -} - -void DragWidget::mouseReleaseEvent(QMouseEvent *) -{ - dragged = false; - moved = false; -} - -void DragWidget::paintEvent(QPaintEvent *) -{ - QStyleOption opt; - opt.initFrom(this); - QStylePainter p(this); - p.drawPrimitive(QStyle::PE_Widget, opt); -} - -void DragWidget::toggleVisibility() -{ - if (isMinimized()) { - showNormal(); - show(); - raise(); - } else { - showMinimized(); - hide(); - lower(); - } - -} diff --git a/kvkbd/src/dragwidget.h b/kvkbd/src/dragwidget.h deleted file mode 100644 index 479c522b..00000000 --- a/kvkbd/src/dragwidget.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef DRAGWIDGET_H -#define DRAGWIDGET_H - -#include -#include -#include - -class DragWidget : public QWidget -{ - Q_OBJECT - -public: - DragWidget(QWidget *parent = 0); - ~DragWidget(); - -public slots: - void toggleVisibility(); - void blurBackground(bool blurEnabled); - void setLocked(bool mode); - bool isLocked(); - -protected: - virtual void mouseMoveEvent(QMouseEvent * e); - virtual void mousePressEvent(QMouseEvent * e); - virtual void mouseReleaseEvent(QMouseEvent * e); - - virtual void paintEvent(QPaintEvent *e); - - QPoint dragPoint; - QPoint gpress; - - bool dragged; - bool moved; - bool locked; - -signals: - void widgetShown(); -}; - - -#endif // DRAGWIDGET_H diff --git a/kvkbd/src/kbddock.cpp b/kvkbd/src/kbddock.cpp deleted file mode 100644 index 3e5a642e..00000000 --- a/kvkbd/src/kbddock.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kbddock.h" - -#include -#include -#include -#include - -#include -#include - -#include "dockadaptor.h" - -#define DEFAULT_WIDTH 105 -#define DEFAULT_HEIGHT 35 - -KbdDock::KbdDock(const WId& window) - : DragWidget(0), wID(window) -{ - setAttribute(Qt::WA_AlwaysShowToolTips); - setAttribute(Qt::WA_DeleteOnClose, false); - setWindowFlags( Qt::ToolTip | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint ); - setFocusPolicy(Qt::NoFocus); - setToolTip(i18nc("@info:tooltip Displayed on the movable dock", "Toggle keyboard visibility")); - - resize(DEFAULT_WIDTH, DEFAULT_HEIGHT); - raise(); -} -#undef DEFAULT_WIDTH -#undef DEFAULT_HEIGHT - -KbdDock::~KbdDock() -{ -} - -void KbdDock::paintEvent(QPaintEvent *) -{ - QPixmap pix = QPixmap::grabWindow(wID); - QPainter p(this); - p.drawPixmap(0, 0, pix.scaled(width(), height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); -} - - - -void KbdDock::mouseReleaseEvent(QMouseEvent *ev) -{ - if (dragged && !moved) { - emit requestVisibility(); - } - - DragWidget::mouseReleaseEvent(ev); - raise(); -} diff --git a/kvkbd/src/kbddock.h b/kvkbd/src/kbddock.h deleted file mode 100644 index a2e651d9..00000000 --- a/kvkbd/src/kbddock.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KBDDOCK_H -#define KBDDOCK_H - -#include "dragwidget.h" - -#include -#include - - -class KbdDock : public DragWidget -{ - Q_OBJECT - -public: - KbdDock(const WId& window); - ~KbdDock(); - - void paintEvent(QPaintEvent *); - void setPixmap(const QPixmap& pm); - -signals: - void requestVisibility(); - -protected: - void mouseReleaseEvent(QMouseEvent *ev); - WId wID; - - QPixmap pm; -}; - -#endif // KBDDOCK_H diff --git a/kvkbd/src/kbdtray.cpp b/kvkbd/src/kbdtray.cpp deleted file mode 100644 index a060cd70..00000000 --- a/kvkbd/src/kbdtray.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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 3 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, see . - * - */ - -#include "kbdtray.h" - -KbdTray::KbdTray(QWidget* parent) - : KStatusNotifierItem(parent) -{ - setTitle("Kvkbd"); - setIconByName("input-keyboard"); - - connect(this, SIGNAL(activateRequested(bool,QPoint)), this, SIGNAL(requestVisibility())); -} - diff --git a/kvkbd/src/kbdtray.h b/kvkbd/src/kbdtray.h deleted file mode 100644 index c3416426..00000000 --- a/kvkbd/src/kbdtray.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2007-2014 Todor Gyumyushev - * - * 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 3 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, see . - * - */ - -#ifndef KBDTRAY_H -#define KBDTRAY_H - -#include -#include - -class KbdTray : public KStatusNotifierItem -{ - Q_OBJECT -public: - explicit KbdTray(QWidget *parent = nullptr); - -Q_SIGNALS: - void requestVisibility(); -}; - - -#endif // KBDTRAY_H diff --git a/kvkbd/src/keysymconvert.cpp b/kvkbd/src/keysymconvert.cpp deleted file mode 100644 index b04dc592..00000000 --- a/kvkbd/src/keysymconvert.cpp +++ /dev/null @@ -1,863 +0,0 @@ -/* $XFree86$ - * This module converts keysym values into the corresponding ISO 10646 - * (UCS, Unicode) values. - * - * The array keysymtab[] contains pairs of X11 keysym values for graphical - * characters and the corresponding Unicode value. The function - * keysym2ucs() maps a keysym onto a Unicode value using a binary search, - * therefore keysymtab[] must remain SORTED by keysym value. - * - * The keysym -> UTF-8 conversion will hopefully one day be provided - * by Xlib via XmbLookupString() and should ideally not have to be - * done in X applications. But we are not there yet. - * - * We allow to represent any UCS character in the range U-00000000 to - * U-00FFFFFF by a keysym value in the range 0x01000000 to 0x01ffffff. - * This admittedly does not cover the entire 31-bit space of UCS, but - * it does cover all of the characters up to U-10FFFF, which can be - * represented by UTF-16, and more, and it is very unlikely that higher - * UCS codes will ever be assigned by ISO. So to get Unicode character - * U+ABCD you can directly use keysym 0x0100abcd. - * - * NOTE: The comments in the table below contain the actual character - * encoded in UTF-8, so for viewing and editing best use an editor in - * UTF-8 mode. - * - * Author: Markus G. Kuhn , - * University of Cambridge, April 2001 - * - * Special thanks to Richard Verhoeven for preparing - * an initial draft of the mapping table. - * - * This software is in the public domain. Share and enjoy! - * - * AUTOMATICALLY GENERATED FILE, DO NOT EDIT !!! (unicode/convmap.pl) - */ - -#include "keysymconvert.h" - -struct codepair { - unsigned short keysym; - unsigned short ucs; -} keysymtab[] = { - { 0x01a1, 0x0104 }, /* Aogonek Ą LATIN CAPITAL LETTER A WITH OGONEK */ - { 0x01a2, 0x02d8 }, /* breve ˘ BREVE */ - { 0x01a3, 0x0141 }, /* Lstroke Ł LATIN CAPITAL LETTER L WITH STROKE */ - { 0x01a5, 0x013d }, /* Lcaron Ľ LATIN CAPITAL LETTER L WITH CARON */ - { 0x01a6, 0x015a }, /* Sacute Ś LATIN CAPITAL LETTER S WITH ACUTE */ - { 0x01a9, 0x0160 }, /* Scaron Š LATIN CAPITAL LETTER S WITH CARON */ - { 0x01aa, 0x015e }, /* Scedilla Ş LATIN CAPITAL LETTER S WITH CEDILLA */ - { 0x01ab, 0x0164 }, /* Tcaron Ť LATIN CAPITAL LETTER T WITH CARON */ - { 0x01ac, 0x0179 }, /* Zacute Ź LATIN CAPITAL LETTER Z WITH ACUTE */ - { 0x01ae, 0x017d }, /* Zcaron Ž LATIN CAPITAL LETTER Z WITH CARON */ - { 0x01af, 0x017b }, /* Zabovedot Ż LATIN CAPITAL LETTER Z WITH DOT ABOVE */ - { 0x01b1, 0x0105 }, /* aogonek ą LATIN SMALL LETTER A WITH OGONEK */ - { 0x01b2, 0x02db }, /* ogonek ˛ OGONEK */ - { 0x01b3, 0x0142 }, /* lstroke ł LATIN SMALL LETTER L WITH STROKE */ - { 0x01b5, 0x013e }, /* lcaron ľ LATIN SMALL LETTER L WITH CARON */ - { 0x01b6, 0x015b }, /* sacute ś LATIN SMALL LETTER S WITH ACUTE */ - { 0x01b7, 0x02c7 }, /* caron ˇ CARON */ - { 0x01b9, 0x0161 }, /* scaron š LATIN SMALL LETTER S WITH CARON */ - { 0x01ba, 0x015f }, /* scedilla ş LATIN SMALL LETTER S WITH CEDILLA */ - { 0x01bb, 0x0165 }, /* tcaron ť LATIN SMALL LETTER T WITH CARON */ - { 0x01bc, 0x017a }, /* zacute ź LATIN SMALL LETTER Z WITH ACUTE */ - { 0x01bd, 0x02dd }, /* doubleacute ˝ DOUBLE ACUTE ACCENT */ - { 0x01be, 0x017e }, /* zcaron ž LATIN SMALL LETTER Z WITH CARON */ - { 0x01bf, 0x017c }, /* zabovedot ż LATIN SMALL LETTER Z WITH DOT ABOVE */ - { 0x01c0, 0x0154 }, /* Racute Ŕ LATIN CAPITAL LETTER R WITH ACUTE */ - { 0x01c3, 0x0102 }, /* Abreve Ă LATIN CAPITAL LETTER A WITH BREVE */ - { 0x01c5, 0x0139 }, /* Lacute Ĺ LATIN CAPITAL LETTER L WITH ACUTE */ - { 0x01c6, 0x0106 }, /* Cacute Ć LATIN CAPITAL LETTER C WITH ACUTE */ - { 0x01c8, 0x010c }, /* Ccaron Č LATIN CAPITAL LETTER C WITH CARON */ - { 0x01ca, 0x0118 }, /* Eogonek Ę LATIN CAPITAL LETTER E WITH OGONEK */ - { 0x01cc, 0x011a }, /* Ecaron Ě LATIN CAPITAL LETTER E WITH CARON */ - { 0x01cf, 0x010e }, /* Dcaron Ď LATIN CAPITAL LETTER D WITH CARON */ - { 0x01d0, 0x0110 }, /* Dstroke Đ LATIN CAPITAL LETTER D WITH STROKE */ - { 0x01d1, 0x0143 }, /* Nacute Ń LATIN CAPITAL LETTER N WITH ACUTE */ - { 0x01d2, 0x0147 }, /* Ncaron Ň LATIN CAPITAL LETTER N WITH CARON */ - { 0x01d5, 0x0150 }, /* Odoubleacute Ő LATIN CAPITAL LETTER O WITH DOUBLE ACUTE */ - { 0x01d8, 0x0158 }, /* Rcaron Ř LATIN CAPITAL LETTER R WITH CARON */ - { 0x01d9, 0x016e }, /* Uring Ů LATIN CAPITAL LETTER U WITH RING ABOVE */ - { 0x01db, 0x0170 }, /* Udoubleacute Ű LATIN CAPITAL LETTER U WITH DOUBLE ACUTE */ - { 0x01de, 0x0162 }, /* Tcedilla Ţ LATIN CAPITAL LETTER T WITH CEDILLA */ - { 0x01e0, 0x0155 }, /* racute ŕ LATIN SMALL LETTER R WITH ACUTE */ - { 0x01e3, 0x0103 }, /* abreve ă LATIN SMALL LETTER A WITH BREVE */ - { 0x01e5, 0x013a }, /* lacute ĺ LATIN SMALL LETTER L WITH ACUTE */ - { 0x01e6, 0x0107 }, /* cacute ć LATIN SMALL LETTER C WITH ACUTE */ - { 0x01e8, 0x010d }, /* ccaron č LATIN SMALL LETTER C WITH CARON */ - { 0x01ea, 0x0119 }, /* eogonek ę LATIN SMALL LETTER E WITH OGONEK */ - { 0x01ec, 0x011b }, /* ecaron ě LATIN SMALL LETTER E WITH CARON */ - { 0x01ef, 0x010f }, /* dcaron ď LATIN SMALL LETTER D WITH CARON */ - { 0x01f0, 0x0111 }, /* dstroke đ LATIN SMALL LETTER D WITH STROKE */ - { 0x01f1, 0x0144 }, /* nacute ń LATIN SMALL LETTER N WITH ACUTE */ - { 0x01f2, 0x0148 }, /* ncaron ň LATIN SMALL LETTER N WITH CARON */ - { 0x01f5, 0x0151 }, /* odoubleacute ő LATIN SMALL LETTER O WITH DOUBLE ACUTE */ - { 0x01f8, 0x0159 }, /* rcaron ř LATIN SMALL LETTER R WITH CARON */ - { 0x01f9, 0x016f }, /* uring ů LATIN SMALL LETTER U WITH RING ABOVE */ - { 0x01fb, 0x0171 }, /* udoubleacute ű LATIN SMALL LETTER U WITH DOUBLE ACUTE */ - { 0x01fe, 0x0163 }, /* tcedilla ţ LATIN SMALL LETTER T WITH CEDILLA */ - { 0x01ff, 0x02d9 }, /* abovedot ˙ DOT ABOVE */ - { 0x02a1, 0x0126 }, /* Hstroke Ħ LATIN CAPITAL LETTER H WITH STROKE */ - { 0x02a6, 0x0124 }, /* Hcircumflex Ĥ LATIN CAPITAL LETTER H WITH CIRCUMFLEX */ - { 0x02a9, 0x0130 }, /* Iabovedot İ LATIN CAPITAL LETTER I WITH DOT ABOVE */ - { 0x02ab, 0x011e }, /* Gbreve Ğ LATIN CAPITAL LETTER G WITH BREVE */ - { 0x02ac, 0x0134 }, /* Jcircumflex Ĵ LATIN CAPITAL LETTER J WITH CIRCUMFLEX */ - { 0x02b1, 0x0127 }, /* hstroke ħ LATIN SMALL LETTER H WITH STROKE */ - { 0x02b6, 0x0125 }, /* hcircumflex ĥ LATIN SMALL LETTER H WITH CIRCUMFLEX */ - { 0x02b9, 0x0131 }, /* idotless ı LATIN SMALL LETTER DOTLESS I */ - { 0x02bb, 0x011f }, /* gbreve ğ LATIN SMALL LETTER G WITH BREVE */ - { 0x02bc, 0x0135 }, /* jcircumflex ĵ LATIN SMALL LETTER J WITH CIRCUMFLEX */ - { 0x02c5, 0x010a }, /* Cabovedot Ċ LATIN CAPITAL LETTER C WITH DOT ABOVE */ - { 0x02c6, 0x0108 }, /* Ccircumflex Ĉ LATIN CAPITAL LETTER C WITH CIRCUMFLEX */ - { 0x02d5, 0x0120 }, /* Gabovedot Ġ LATIN CAPITAL LETTER G WITH DOT ABOVE */ - { 0x02d8, 0x011c }, /* Gcircumflex Ĝ LATIN CAPITAL LETTER G WITH CIRCUMFLEX */ - { 0x02dd, 0x016c }, /* Ubreve Ŭ LATIN CAPITAL LETTER U WITH BREVE */ - { 0x02de, 0x015c }, /* Scircumflex Ŝ LATIN CAPITAL LETTER S WITH CIRCUMFLEX */ - { 0x02e5, 0x010b }, /* cabovedot ċ LATIN SMALL LETTER C WITH DOT ABOVE */ - { 0x02e6, 0x0109 }, /* ccircumflex ĉ LATIN SMALL LETTER C WITH CIRCUMFLEX */ - { 0x02f5, 0x0121 }, /* gabovedot ġ LATIN SMALL LETTER G WITH DOT ABOVE */ - { 0x02f8, 0x011d }, /* gcircumflex ĝ LATIN SMALL LETTER G WITH CIRCUMFLEX */ - { 0x02fd, 0x016d }, /* ubreve ŭ LATIN SMALL LETTER U WITH BREVE */ - { 0x02fe, 0x015d }, /* scircumflex ŝ LATIN SMALL LETTER S WITH CIRCUMFLEX */ - { 0x03a2, 0x0138 }, /* kra ĸ LATIN SMALL LETTER KRA */ - { 0x03a3, 0x0156 }, /* Rcedilla Ŗ LATIN CAPITAL LETTER R WITH CEDILLA */ - { 0x03a5, 0x0128 }, /* Itilde Ĩ LATIN CAPITAL LETTER I WITH TILDE */ - { 0x03a6, 0x013b }, /* Lcedilla Ļ LATIN CAPITAL LETTER L WITH CEDILLA */ - { 0x03aa, 0x0112 }, /* Emacron Ē LATIN CAPITAL LETTER E WITH MACRON */ - { 0x03ab, 0x0122 }, /* Gcedilla Ģ LATIN CAPITAL LETTER G WITH CEDILLA */ - { 0x03ac, 0x0166 }, /* Tslash Ŧ LATIN CAPITAL LETTER T WITH STROKE */ - { 0x03b3, 0x0157 }, /* rcedilla ŗ LATIN SMALL LETTER R WITH CEDILLA */ - { 0x03b5, 0x0129 }, /* itilde ĩ LATIN SMALL LETTER I WITH TILDE */ - { 0x03b6, 0x013c }, /* lcedilla ļ LATIN SMALL LETTER L WITH CEDILLA */ - { 0x03ba, 0x0113 }, /* emacron ē LATIN SMALL LETTER E WITH MACRON */ - { 0x03bb, 0x0123 }, /* gcedilla ģ LATIN SMALL LETTER G WITH CEDILLA */ - { 0x03bc, 0x0167 }, /* tslash ŧ LATIN SMALL LETTER T WITH STROKE */ - { 0x03bd, 0x014a }, /* ENG Ŋ LATIN CAPITAL LETTER ENG */ - { 0x03bf, 0x014b }, /* eng ŋ LATIN SMALL LETTER ENG */ - { 0x03c0, 0x0100 }, /* Amacron Ā LATIN CAPITAL LETTER A WITH MACRON */ - { 0x03c7, 0x012e }, /* Iogonek Į LATIN CAPITAL LETTER I WITH OGONEK */ - { 0x03cc, 0x0116 }, /* Eabovedot Ė LATIN CAPITAL LETTER E WITH DOT ABOVE */ - { 0x03cf, 0x012a }, /* Imacron Ī LATIN CAPITAL LETTER I WITH MACRON */ - { 0x03d1, 0x0145 }, /* Ncedilla Ņ LATIN CAPITAL LETTER N WITH CEDILLA */ - { 0x03d2, 0x014c }, /* Omacron Ō LATIN CAPITAL LETTER O WITH MACRON */ - { 0x03d3, 0x0136 }, /* Kcedilla Ķ LATIN CAPITAL LETTER K WITH CEDILLA */ - { 0x03d9, 0x0172 }, /* Uogonek Ų LATIN CAPITAL LETTER U WITH OGONEK */ - { 0x03dd, 0x0168 }, /* Utilde Ũ LATIN CAPITAL LETTER U WITH TILDE */ - { 0x03de, 0x016a }, /* Umacron Ū LATIN CAPITAL LETTER U WITH MACRON */ - { 0x03e0, 0x0101 }, /* amacron ā LATIN SMALL LETTER A WITH MACRON */ - { 0x03e7, 0x012f }, /* iogonek į LATIN SMALL LETTER I WITH OGONEK */ - { 0x03ec, 0x0117 }, /* eabovedot ė LATIN SMALL LETTER E WITH DOT ABOVE */ - { 0x03ef, 0x012b }, /* imacron ī LATIN SMALL LETTER I WITH MACRON */ - { 0x03f1, 0x0146 }, /* ncedilla ņ LATIN SMALL LETTER N WITH CEDILLA */ - { 0x03f2, 0x014d }, /* omacron ō LATIN SMALL LETTER O WITH MACRON */ - { 0x03f3, 0x0137 }, /* kcedilla ķ LATIN SMALL LETTER K WITH CEDILLA */ - { 0x03f9, 0x0173 }, /* uogonek ų LATIN SMALL LETTER U WITH OGONEK */ - { 0x03fd, 0x0169 }, /* utilde ũ LATIN SMALL LETTER U WITH TILDE */ - { 0x03fe, 0x016b }, /* umacron ū LATIN SMALL LETTER U WITH MACRON */ - { 0x047e, 0x203e }, /* overline ‾ OVERLINE */ - { 0x04a1, 0x3002 }, /* kana_fullstop 。 IDEOGRAPHIC FULL STOP */ - { 0x04a2, 0x300c }, /* kana_openingbracket 「 LEFT CORNER BRACKET */ - { 0x04a3, 0x300d }, /* kana_closingbracket 」 RIGHT CORNER BRACKET */ - { 0x04a4, 0x3001 }, /* kana_comma 、 IDEOGRAPHIC COMMA */ - { 0x04a5, 0x30fb }, /* kana_conjunctive ・ KATAKANA MIDDLE DOT */ - { 0x04a6, 0x30f2 }, /* kana_WO ヲ KATAKANA LETTER WO */ - { 0x04a7, 0x30a1 }, /* kana_a ァ KATAKANA LETTER SMALL A */ - { 0x04a8, 0x30a3 }, /* kana_i ィ KATAKANA LETTER SMALL I */ - { 0x04a9, 0x30a5 }, /* kana_u ゥ KATAKANA LETTER SMALL U */ - { 0x04aa, 0x30a7 }, /* kana_e ェ KATAKANA LETTER SMALL E */ - { 0x04ab, 0x30a9 }, /* kana_o ォ KATAKANA LETTER SMALL O */ - { 0x04ac, 0x30e3 }, /* kana_ya ャ KATAKANA LETTER SMALL YA */ - { 0x04ad, 0x30e5 }, /* kana_yu ュ KATAKANA LETTER SMALL YU */ - { 0x04ae, 0x30e7 }, /* kana_yo ョ KATAKANA LETTER SMALL YO */ - { 0x04af, 0x30c3 }, /* kana_tsu ッ KATAKANA LETTER SMALL TU */ - { 0x04b0, 0x30fc }, /* prolongedsound ー KATAKANA-HIRAGANA PROLONGED SOUND MARK */ - { 0x04b1, 0x30a2 }, /* kana_A ア KATAKANA LETTER A */ - { 0x04b2, 0x30a4 }, /* kana_I イ KATAKANA LETTER I */ - { 0x04b3, 0x30a6 }, /* kana_U ウ KATAKANA LETTER U */ - { 0x04b4, 0x30a8 }, /* kana_E エ KATAKANA LETTER E */ - { 0x04b5, 0x30aa }, /* kana_O オ KATAKANA LETTER O */ - { 0x04b6, 0x30ab }, /* kana_KA カ KATAKANA LETTER KA */ - { 0x04b7, 0x30ad }, /* kana_KI キ KATAKANA LETTER KI */ - { 0x04b8, 0x30af }, /* kana_KU ク KATAKANA LETTER KU */ - { 0x04b9, 0x30b1 }, /* kana_KE ケ KATAKANA LETTER KE */ - { 0x04ba, 0x30b3 }, /* kana_KO コ KATAKANA LETTER KO */ - { 0x04bb, 0x30b5 }, /* kana_SA サ KATAKANA LETTER SA */ - { 0x04bc, 0x30b7 }, /* kana_SHI シ KATAKANA LETTER SI */ - { 0x04bd, 0x30b9 }, /* kana_SU ス KATAKANA LETTER SU */ - { 0x04be, 0x30bb }, /* kana_SE セ KATAKANA LETTER SE */ - { 0x04bf, 0x30bd }, /* kana_SO ソ KATAKANA LETTER SO */ - { 0x04c0, 0x30bf }, /* kana_TA タ KATAKANA LETTER TA */ - { 0x04c1, 0x30c1 }, /* kana_CHI チ KATAKANA LETTER TI */ - { 0x04c2, 0x30c4 }, /* kana_TSU ツ KATAKANA LETTER TU */ - { 0x04c3, 0x30c6 }, /* kana_TE テ KATAKANA LETTER TE */ - { 0x04c4, 0x30c8 }, /* kana_TO ト KATAKANA LETTER TO */ - { 0x04c5, 0x30ca }, /* kana_NA ナ KATAKANA LETTER NA */ - { 0x04c6, 0x30cb }, /* kana_NI ニ KATAKANA LETTER NI */ - { 0x04c7, 0x30cc }, /* kana_NU ヌ KATAKANA LETTER NU */ - { 0x04c8, 0x30cd }, /* kana_NE ネ KATAKANA LETTER NE */ - { 0x04c9, 0x30ce }, /* kana_NO ノ KATAKANA LETTER NO */ - { 0x04ca, 0x30cf }, /* kana_HA ハ KATAKANA LETTER HA */ - { 0x04cb, 0x30d2 }, /* kana_HI ヒ KATAKANA LETTER HI */ - { 0x04cc, 0x30d5 }, /* kana_FU フ KATAKANA LETTER HU */ - { 0x04cd, 0x30d8 }, /* kana_HE ヘ KATAKANA LETTER HE */ - { 0x04ce, 0x30db }, /* kana_HO ホ KATAKANA LETTER HO */ - { 0x04cf, 0x30de }, /* kana_MA マ KATAKANA LETTER MA */ - { 0x04d0, 0x30df }, /* kana_MI ミ KATAKANA LETTER MI */ - { 0x04d1, 0x30e0 }, /* kana_MU ム KATAKANA LETTER MU */ - { 0x04d2, 0x30e1 }, /* kana_ME メ KATAKANA LETTER ME */ - { 0x04d3, 0x30e2 }, /* kana_MO モ KATAKANA LETTER MO */ - { 0x04d4, 0x30e4 }, /* kana_YA ヤ KATAKANA LETTER YA */ - { 0x04d5, 0x30e6 }, /* kana_YU ユ KATAKANA LETTER YU */ - { 0x04d6, 0x30e8 }, /* kana_YO ヨ KATAKANA LETTER YO */ - { 0x04d7, 0x30e9 }, /* kana_RA ラ KATAKANA LETTER RA */ - { 0x04d8, 0x30ea }, /* kana_RI リ KATAKANA LETTER RI */ - { 0x04d9, 0x30eb }, /* kana_RU ル KATAKANA LETTER RU */ - { 0x04da, 0x30ec }, /* kana_RE レ KATAKANA LETTER RE */ - { 0x04db, 0x30ed }, /* kana_RO ロ KATAKANA LETTER RO */ - { 0x04dc, 0x30ef }, /* kana_WA ワ KATAKANA LETTER WA */ - { 0x04dd, 0x30f3 }, /* kana_N ン KATAKANA LETTER N */ - { 0x04de, 0x309b }, /* voicedsound ゛ KATAKANA-HIRAGANA VOICED SOUND MARK */ - { 0x04df, 0x309c }, /* semivoicedsound ゜ KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */ - { 0x05ac, 0x060c }, /* Arabic_comma ، ARABIC COMMA */ - { 0x05bb, 0x061b }, /* Arabic_semicolon ؛ ARABIC SEMICOLON */ - { 0x05bf, 0x061f }, /* Arabic_question_mark ؟ ARABIC QUESTION MARK */ - { 0x05c1, 0x0621 }, /* Arabic_hamza ء ARABIC LETTER HAMZA */ - { 0x05c2, 0x0622 }, /* Arabic_maddaonalef آ ARABIC LETTER ALEF WITH MADDA ABOVE */ - { 0x05c3, 0x0623 }, /* Arabic_hamzaonalef أ ARABIC LETTER ALEF WITH HAMZA ABOVE */ - { 0x05c4, 0x0624 }, /* Arabic_hamzaonwaw ؤ ARABIC LETTER WAW WITH HAMZA ABOVE */ - { 0x05c5, 0x0625 }, /* Arabic_hamzaunderalef إ ARABIC LETTER ALEF WITH HAMZA BELOW */ - { 0x05c6, 0x0626 }, /* Arabic_hamzaonyeh ئ ARABIC LETTER YEH WITH HAMZA ABOVE */ - { 0x05c7, 0x0627 }, /* Arabic_alef ا ARABIC LETTER ALEF */ - { 0x05c8, 0x0628 }, /* Arabic_beh ب ARABIC LETTER BEH */ - { 0x05c9, 0x0629 }, /* Arabic_tehmarbuta ة ARABIC LETTER TEH MARBUTA */ - { 0x05ca, 0x062a }, /* Arabic_teh ت ARABIC LETTER TEH */ - { 0x05cb, 0x062b }, /* Arabic_theh ث ARABIC LETTER THEH */ - { 0x05cc, 0x062c }, /* Arabic_jeem ج ARABIC LETTER JEEM */ - { 0x05cd, 0x062d }, /* Arabic_hah ح ARABIC LETTER HAH */ - { 0x05ce, 0x062e }, /* Arabic_khah خ ARABIC LETTER KHAH */ - { 0x05cf, 0x062f }, /* Arabic_dal د ARABIC LETTER DAL */ - { 0x05d0, 0x0630 }, /* Arabic_thal ذ ARABIC LETTER THAL */ - { 0x05d1, 0x0631 }, /* Arabic_ra ر ARABIC LETTER REH */ - { 0x05d2, 0x0632 }, /* Arabic_zain ز ARABIC LETTER ZAIN */ - { 0x05d3, 0x0633 }, /* Arabic_seen س ARABIC LETTER SEEN */ - { 0x05d4, 0x0634 }, /* Arabic_sheen ش ARABIC LETTER SHEEN */ - { 0x05d5, 0x0635 }, /* Arabic_sad ص ARABIC LETTER SAD */ - { 0x05d6, 0x0636 }, /* Arabic_dad ض ARABIC LETTER DAD */ - { 0x05d7, 0x0637 }, /* Arabic_tah ط ARABIC LETTER TAH */ - { 0x05d8, 0x0638 }, /* Arabic_zah ظ ARABIC LETTER ZAH */ - { 0x05d9, 0x0639 }, /* Arabic_ain ع ARABIC LETTER AIN */ - { 0x05da, 0x063a }, /* Arabic_ghain غ ARABIC LETTER GHAIN */ - { 0x05e0, 0x0640 }, /* Arabic_tatweel ـ ARABIC TATWEEL */ - { 0x05e1, 0x0641 }, /* Arabic_feh ف ARABIC LETTER FEH */ - { 0x05e2, 0x0642 }, /* Arabic_qaf ق ARABIC LETTER QAF */ - { 0x05e3, 0x0643 }, /* Arabic_kaf ك ARABIC LETTER KAF */ - { 0x05e4, 0x0644 }, /* Arabic_lam ل ARABIC LETTER LAM */ - { 0x05e5, 0x0645 }, /* Arabic_meem م ARABIC LETTER MEEM */ - { 0x05e6, 0x0646 }, /* Arabic_noon ن ARABIC LETTER NOON */ - { 0x05e7, 0x0647 }, /* Arabic_ha ه ARABIC LETTER HEH */ - { 0x05e8, 0x0648 }, /* Arabic_waw و ARABIC LETTER WAW */ - { 0x05e9, 0x0649 }, /* Arabic_alefmaksura ى ARABIC LETTER ALEF MAKSURA */ - { 0x05ea, 0x064a }, /* Arabic_yeh ي ARABIC LETTER YEH */ - { 0x05eb, 0x064b }, /* Arabic_fathatan ً ARABIC FATHATAN */ - { 0x05ec, 0x064c }, /* Arabic_dammatan ٌ ARABIC DAMMATAN */ - { 0x05ed, 0x064d }, /* Arabic_kasratan ٍ ARABIC KASRATAN */ - { 0x05ee, 0x064e }, /* Arabic_fatha َ ARABIC FATHA */ - { 0x05ef, 0x064f }, /* Arabic_damma ُ ARABIC DAMMA */ - { 0x05f0, 0x0650 }, /* Arabic_kasra ِ ARABIC KASRA */ - { 0x05f1, 0x0651 }, /* Arabic_shadda ّ ARABIC SHADDA */ - { 0x05f2, 0x0652 }, /* Arabic_sukun ْ ARABIC SUKUN */ - { 0x06a1, 0x0452 }, /* Serbian_dje ђ CYRILLIC SMALL LETTER DJE */ - { 0x06a2, 0x0453 }, /* Macedonia_gje ѓ CYRILLIC SMALL LETTER GJE */ - { 0x06a3, 0x0451 }, /* Cyrillic_io ё CYRILLIC SMALL LETTER IO */ - { 0x06a4, 0x0454 }, /* Ukrainian_ie є CYRILLIC SMALL LETTER UKRAINIAN IE */ - { 0x06a5, 0x0455 }, /* Macedonia_dse ѕ CYRILLIC SMALL LETTER DZE */ - { 0x06a6, 0x0456 }, /* Ukrainian_i і CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */ - { 0x06a7, 0x0457 }, /* Ukrainian_yi ї CYRILLIC SMALL LETTER YI */ - { 0x06a8, 0x0458 }, /* Cyrillic_je ј CYRILLIC SMALL LETTER JE */ - { 0x06a9, 0x0459 }, /* Cyrillic_lje љ CYRILLIC SMALL LETTER LJE */ - { 0x06aa, 0x045a }, /* Cyrillic_nje њ CYRILLIC SMALL LETTER NJE */ - { 0x06ab, 0x045b }, /* Serbian_tshe ћ CYRILLIC SMALL LETTER TSHE */ - { 0x06ac, 0x045c }, /* Macedonia_kje ќ CYRILLIC SMALL LETTER KJE */ - { 0x06ad, 0x0491 }, /* Ukrainian_ghe_with_upturn ґ CYRILLIC SMALL LETTER GHE WITH UPTURN */ - { 0x06ae, 0x045e }, /* Byelorussian_shortu ў CYRILLIC SMALL LETTER SHORT U */ - { 0x06af, 0x045f }, /* Cyrillic_dzhe џ CYRILLIC SMALL LETTER DZHE */ - { 0x06b0, 0x2116 }, /* numerosign № NUMERO SIGN */ - { 0x06b1, 0x0402 }, /* Serbian_DJE Ђ CYRILLIC CAPITAL LETTER DJE */ - { 0x06b2, 0x0403 }, /* Macedonia_GJE Ѓ CYRILLIC CAPITAL LETTER GJE */ - { 0x06b3, 0x0401 }, /* Cyrillic_IO Ё CYRILLIC CAPITAL LETTER IO */ - { 0x06b4, 0x0404 }, /* Ukrainian_IE Є CYRILLIC CAPITAL LETTER UKRAINIAN IE */ - { 0x06b5, 0x0405 }, /* Macedonia_DSE Ѕ CYRILLIC CAPITAL LETTER DZE */ - { 0x06b6, 0x0406 }, /* Ukrainian_I І CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */ - { 0x06b7, 0x0407 }, /* Ukrainian_YI Ї CYRILLIC CAPITAL LETTER YI */ - { 0x06b8, 0x0408 }, /* Cyrillic_JE Ј CYRILLIC CAPITAL LETTER JE */ - { 0x06b9, 0x0409 }, /* Cyrillic_LJE Љ CYRILLIC CAPITAL LETTER LJE */ - { 0x06ba, 0x040a }, /* Cyrillic_NJE Њ CYRILLIC CAPITAL LETTER NJE */ - { 0x06bb, 0x040b }, /* Serbian_TSHE Ћ CYRILLIC CAPITAL LETTER TSHE */ - { 0x06bc, 0x040c }, /* Macedonia_KJE Ќ CYRILLIC CAPITAL LETTER KJE */ - { 0x06bd, 0x0490 }, /* Ukrainian_GHE_WITH_UPTURN Ґ CYRILLIC CAPITAL LETTER GHE WITH UPTURN */ - { 0x06be, 0x040e }, /* Byelorussian_SHORTU Ў CYRILLIC CAPITAL LETTER SHORT U */ - { 0x06bf, 0x040f }, /* Cyrillic_DZHE Џ CYRILLIC CAPITAL LETTER DZHE */ - { 0x06c0, 0x044e }, /* Cyrillic_yu ю CYRILLIC SMALL LETTER YU */ - { 0x06c1, 0x0430 }, /* Cyrillic_a а CYRILLIC SMALL LETTER A */ - { 0x06c2, 0x0431 }, /* Cyrillic_be б CYRILLIC SMALL LETTER BE */ - { 0x06c3, 0x0446 }, /* Cyrillic_tse ц CYRILLIC SMALL LETTER TSE */ - { 0x06c4, 0x0434 }, /* Cyrillic_de д CYRILLIC SMALL LETTER DE */ - { 0x06c5, 0x0435 }, /* Cyrillic_ie е CYRILLIC SMALL LETTER IE */ - { 0x06c6, 0x0444 }, /* Cyrillic_ef ф CYRILLIC SMALL LETTER EF */ - { 0x06c7, 0x0433 }, /* Cyrillic_ghe г CYRILLIC SMALL LETTER GHE */ - { 0x06c8, 0x0445 }, /* Cyrillic_ha х CYRILLIC SMALL LETTER HA */ - { 0x06c9, 0x0438 }, /* Cyrillic_i и CYRILLIC SMALL LETTER I */ - { 0x06ca, 0x0439 }, /* Cyrillic_shorti й CYRILLIC SMALL LETTER SHORT I */ - { 0x06cb, 0x043a }, /* Cyrillic_ka к CYRILLIC SMALL LETTER KA */ - { 0x06cc, 0x043b }, /* Cyrillic_el л CYRILLIC SMALL LETTER EL */ - { 0x06cd, 0x043c }, /* Cyrillic_em м CYRILLIC SMALL LETTER EM */ - { 0x06ce, 0x043d }, /* Cyrillic_en н CYRILLIC SMALL LETTER EN */ - { 0x06cf, 0x043e }, /* Cyrillic_o о CYRILLIC SMALL LETTER O */ - { 0x06d0, 0x043f }, /* Cyrillic_pe п CYRILLIC SMALL LETTER PE */ - { 0x06d1, 0x044f }, /* Cyrillic_ya я CYRILLIC SMALL LETTER YA */ - { 0x06d2, 0x0440 }, /* Cyrillic_er р CYRILLIC SMALL LETTER ER */ - { 0x06d3, 0x0441 }, /* Cyrillic_es с CYRILLIC SMALL LETTER ES */ - { 0x06d4, 0x0442 }, /* Cyrillic_te т CYRILLIC SMALL LETTER TE */ - { 0x06d5, 0x0443 }, /* Cyrillic_u у CYRILLIC SMALL LETTER U */ - { 0x06d6, 0x0436 }, /* Cyrillic_zhe ж CYRILLIC SMALL LETTER ZHE */ - { 0x06d7, 0x0432 }, /* Cyrillic_ve в CYRILLIC SMALL LETTER VE */ - { 0x06d8, 0x044c }, /* Cyrillic_softsign ь CYRILLIC SMALL LETTER SOFT SIGN */ - { 0x06d9, 0x044b }, /* Cyrillic_yeru ы CYRILLIC SMALL LETTER YERU */ - { 0x06da, 0x0437 }, /* Cyrillic_ze з CYRILLIC SMALL LETTER ZE */ - { 0x06db, 0x0448 }, /* Cyrillic_sha ш CYRILLIC SMALL LETTER SHA */ - { 0x06dc, 0x044d }, /* Cyrillic_e э CYRILLIC SMALL LETTER E */ - { 0x06dd, 0x0449 }, /* Cyrillic_shcha щ CYRILLIC SMALL LETTER SHCHA */ - { 0x06de, 0x0447 }, /* Cyrillic_che ч CYRILLIC SMALL LETTER CHE */ - { 0x06df, 0x044a }, /* Cyrillic_hardsign ъ CYRILLIC SMALL LETTER HARD SIGN */ - { 0x06e0, 0x042e }, /* Cyrillic_YU Ю CYRILLIC CAPITAL LETTER YU */ - { 0x06e1, 0x0410 }, /* Cyrillic_A А CYRILLIC CAPITAL LETTER A */ - { 0x06e2, 0x0411 }, /* Cyrillic_BE Б CYRILLIC CAPITAL LETTER BE */ - { 0x06e3, 0x0426 }, /* Cyrillic_TSE Ц CYRILLIC CAPITAL LETTER TSE */ - { 0x06e4, 0x0414 }, /* Cyrillic_DE Д CYRILLIC CAPITAL LETTER DE */ - { 0x06e5, 0x0415 }, /* Cyrillic_IE Е CYRILLIC CAPITAL LETTER IE */ - { 0x06e6, 0x0424 }, /* Cyrillic_EF Ф CYRILLIC CAPITAL LETTER EF */ - { 0x06e7, 0x0413 }, /* Cyrillic_GHE Г CYRILLIC CAPITAL LETTER GHE */ - { 0x06e8, 0x0425 }, /* Cyrillic_HA Х CYRILLIC CAPITAL LETTER HA */ - { 0x06e9, 0x0418 }, /* Cyrillic_I И CYRILLIC CAPITAL LETTER I */ - { 0x06ea, 0x0419 }, /* Cyrillic_SHORTI Й CYRILLIC CAPITAL LETTER SHORT I */ - { 0x06eb, 0x041a }, /* Cyrillic_KA К CYRILLIC CAPITAL LETTER KA */ - { 0x06ec, 0x041b }, /* Cyrillic_EL Л CYRILLIC CAPITAL LETTER EL */ - { 0x06ed, 0x041c }, /* Cyrillic_EM М CYRILLIC CAPITAL LETTER EM */ - { 0x06ee, 0x041d }, /* Cyrillic_EN Н CYRILLIC CAPITAL LETTER EN */ - { 0x06ef, 0x041e }, /* Cyrillic_O О CYRILLIC CAPITAL LETTER O */ - { 0x06f0, 0x041f }, /* Cyrillic_PE П CYRILLIC CAPITAL LETTER PE */ - { 0x06f1, 0x042f }, /* Cyrillic_YA Я CYRILLIC CAPITAL LETTER YA */ - { 0x06f2, 0x0420 }, /* Cyrillic_ER Р CYRILLIC CAPITAL LETTER ER */ - { 0x06f3, 0x0421 }, /* Cyrillic_ES С CYRILLIC CAPITAL LETTER ES */ - { 0x06f4, 0x0422 }, /* Cyrillic_TE Т CYRILLIC CAPITAL LETTER TE */ - { 0x06f5, 0x0423 }, /* Cyrillic_U У CYRILLIC CAPITAL LETTER U */ - { 0x06f6, 0x0416 }, /* Cyrillic_ZHE Ж CYRILLIC CAPITAL LETTER ZHE */ - { 0x06f7, 0x0412 }, /* Cyrillic_VE В CYRILLIC CAPITAL LETTER VE */ - { 0x06f8, 0x042c }, /* Cyrillic_SOFTSIGN Ь CYRILLIC CAPITAL LETTER SOFT SIGN */ - { 0x06f9, 0x042b }, /* Cyrillic_YERU Ы CYRILLIC CAPITAL LETTER YERU */ - { 0x06fa, 0x0417 }, /* Cyrillic_ZE З CYRILLIC CAPITAL LETTER ZE */ - { 0x06fb, 0x0428 }, /* Cyrillic_SHA Ш CYRILLIC CAPITAL LETTER SHA */ - { 0x06fc, 0x042d }, /* Cyrillic_E Э CYRILLIC CAPITAL LETTER E */ - { 0x06fd, 0x0429 }, /* Cyrillic_SHCHA Щ CYRILLIC CAPITAL LETTER SHCHA */ - { 0x06fe, 0x0427 }, /* Cyrillic_CHE Ч CYRILLIC CAPITAL LETTER CHE */ - { 0x06ff, 0x042a }, /* Cyrillic_HARDSIGN Ъ CYRILLIC CAPITAL LETTER HARD SIGN */ - { 0x07a1, 0x0386 }, /* Greek_ALPHAaccent Ά GREEK CAPITAL LETTER ALPHA WITH TONOS */ - { 0x07a2, 0x0388 }, /* Greek_EPSILONaccent Έ GREEK CAPITAL LETTER EPSILON WITH TONOS */ - { 0x07a3, 0x0389 }, /* Greek_ETAaccent Ή GREEK CAPITAL LETTER ETA WITH TONOS */ - { 0x07a4, 0x038a }, /* Greek_IOTAaccent Ί GREEK CAPITAL LETTER IOTA WITH TONOS */ - { 0x07a5, 0x03aa }, /* Greek_IOTAdiaeresis Ϊ GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */ - { 0x07a7, 0x038c }, /* Greek_OMICRONaccent Ό GREEK CAPITAL LETTER OMICRON WITH TONOS */ - { 0x07a8, 0x038e }, /* Greek_UPSILONaccent Ύ GREEK CAPITAL LETTER UPSILON WITH TONOS */ - { 0x07a9, 0x03ab }, /* Greek_UPSILONdieresis Ϋ GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */ - { 0x07ab, 0x038f }, /* Greek_OMEGAaccent Ώ GREEK CAPITAL LETTER OMEGA WITH TONOS */ - { 0x07ae, 0x0385 }, /* Greek_accentdieresis ΅ GREEK DIALYTIKA TONOS */ - { 0x07af, 0x2015 }, /* Greek_horizbar ― HORIZONTAL BAR */ - { 0x07b1, 0x03ac }, /* Greek_alphaaccent ά GREEK SMALL LETTER ALPHA WITH TONOS */ - { 0x07b2, 0x03ad }, /* Greek_epsilonaccent έ GREEK SMALL LETTER EPSILON WITH TONOS */ - { 0x07b3, 0x03ae }, /* Greek_etaaccent ή GREEK SMALL LETTER ETA WITH TONOS */ - { 0x07b4, 0x03af }, /* Greek_iotaaccent ί GREEK SMALL LETTER IOTA WITH TONOS */ - { 0x07b5, 0x03ca }, /* Greek_iotadieresis ϊ GREEK SMALL LETTER IOTA WITH DIALYTIKA */ - { 0x07b6, 0x0390 }, /* Greek_iotaaccentdieresis ΐ GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */ - { 0x07b7, 0x03cc }, /* Greek_omicronaccent ό GREEK SMALL LETTER OMICRON WITH TONOS */ - { 0x07b8, 0x03cd }, /* Greek_upsilonaccent ύ GREEK SMALL LETTER UPSILON WITH TONOS */ - { 0x07b9, 0x03cb }, /* Greek_upsilondieresis ϋ GREEK SMALL LETTER UPSILON WITH DIALYTIKA */ - { 0x07ba, 0x03b0 }, /* Greek_upsilonaccentdieresis ΰ GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */ - { 0x07bb, 0x03ce }, /* Greek_omegaaccent ώ GREEK SMALL LETTER OMEGA WITH TONOS */ - { 0x07c1, 0x0391 }, /* Greek_ALPHA Α GREEK CAPITAL LETTER ALPHA */ - { 0x07c2, 0x0392 }, /* Greek_BETA Β GREEK CAPITAL LETTER BETA */ - { 0x07c3, 0x0393 }, /* Greek_GAMMA Γ GREEK CAPITAL LETTER GAMMA */ - { 0x07c4, 0x0394 }, /* Greek_DELTA Δ GREEK CAPITAL LETTER DELTA */ - { 0x07c5, 0x0395 }, /* Greek_EPSILON Ε GREEK CAPITAL LETTER EPSILON */ - { 0x07c6, 0x0396 }, /* Greek_ZETA Ζ GREEK CAPITAL LETTER ZETA */ - { 0x07c7, 0x0397 }, /* Greek_ETA Η GREEK CAPITAL LETTER ETA */ - { 0x07c8, 0x0398 }, /* Greek_THETA Θ GREEK CAPITAL LETTER THETA */ - { 0x07c9, 0x0399 }, /* Greek_IOTA Ι GREEK CAPITAL LETTER IOTA */ - { 0x07ca, 0x039a }, /* Greek_KAPPA Κ GREEK CAPITAL LETTER KAPPA */ - { 0x07cb, 0x039b }, /* Greek_LAMBDA Λ GREEK CAPITAL LETTER LAMDA */ - { 0x07cc, 0x039c }, /* Greek_MU Μ GREEK CAPITAL LETTER MU */ - { 0x07cd, 0x039d }, /* Greek_NU Ν GREEK CAPITAL LETTER NU */ - { 0x07ce, 0x039e }, /* Greek_XI Ξ GREEK CAPITAL LETTER XI */ - { 0x07cf, 0x039f }, /* Greek_OMICRON Ο GREEK CAPITAL LETTER OMICRON */ - { 0x07d0, 0x03a0 }, /* Greek_PI Π GREEK CAPITAL LETTER PI */ - { 0x07d1, 0x03a1 }, /* Greek_RHO Ρ GREEK CAPITAL LETTER RHO */ - { 0x07d2, 0x03a3 }, /* Greek_SIGMA Σ GREEK CAPITAL LETTER SIGMA */ - { 0x07d4, 0x03a4 }, /* Greek_TAU Τ GREEK CAPITAL LETTER TAU */ - { 0x07d5, 0x03a5 }, /* Greek_UPSILON Υ GREEK CAPITAL LETTER UPSILON */ - { 0x07d6, 0x03a6 }, /* Greek_PHI Φ GREEK CAPITAL LETTER PHI */ - { 0x07d7, 0x03a7 }, /* Greek_CHI Χ GREEK CAPITAL LETTER CHI */ - { 0x07d8, 0x03a8 }, /* Greek_PSI Ψ GREEK CAPITAL LETTER PSI */ - { 0x07d9, 0x03a9 }, /* Greek_OMEGA Ω GREEK CAPITAL LETTER OMEGA */ - { 0x07e1, 0x03b1 }, /* Greek_alpha α GREEK SMALL LETTER ALPHA */ - { 0x07e2, 0x03b2 }, /* Greek_beta β GREEK SMALL LETTER BETA */ - { 0x07e3, 0x03b3 }, /* Greek_gamma γ GREEK SMALL LETTER GAMMA */ - { 0x07e4, 0x03b4 }, /* Greek_delta δ GREEK SMALL LETTER DELTA */ - { 0x07e5, 0x03b5 }, /* Greek_epsilon ε GREEK SMALL LETTER EPSILON */ - { 0x07e6, 0x03b6 }, /* Greek_zeta ζ GREEK SMALL LETTER ZETA */ - { 0x07e7, 0x03b7 }, /* Greek_eta η GREEK SMALL LETTER ETA */ - { 0x07e8, 0x03b8 }, /* Greek_theta θ GREEK SMALL LETTER THETA */ - { 0x07e9, 0x03b9 }, /* Greek_iota ι GREEK SMALL LETTER IOTA */ - { 0x07ea, 0x03ba }, /* Greek_kappa κ GREEK SMALL LETTER KAPPA */ - { 0x07eb, 0x03bb }, /* Greek_lambda λ GREEK SMALL LETTER LAMDA */ - { 0x07ec, 0x03bc }, /* Greek_mu μ GREEK SMALL LETTER MU */ - { 0x07ed, 0x03bd }, /* Greek_nu ν GREEK SMALL LETTER NU */ - { 0x07ee, 0x03be }, /* Greek_xi ξ GREEK SMALL LETTER XI */ - { 0x07ef, 0x03bf }, /* Greek_omicron ο GREEK SMALL LETTER OMICRON */ - { 0x07f0, 0x03c0 }, /* Greek_pi π GREEK SMALL LETTER PI */ - { 0x07f1, 0x03c1 }, /* Greek_rho ρ GREEK SMALL LETTER RHO */ - { 0x07f2, 0x03c3 }, /* Greek_sigma σ GREEK SMALL LETTER SIGMA */ - { 0x07f3, 0x03c2 }, /* Greek_finalsmallsigma ς GREEK SMALL LETTER FINAL SIGMA */ - { 0x07f4, 0x03c4 }, /* Greek_tau τ GREEK SMALL LETTER TAU */ - { 0x07f5, 0x03c5 }, /* Greek_upsilon υ GREEK SMALL LETTER UPSILON */ - { 0x07f6, 0x03c6 }, /* Greek_phi φ GREEK SMALL LETTER PHI */ - { 0x07f7, 0x03c7 }, /* Greek_chi χ GREEK SMALL LETTER CHI */ - { 0x07f8, 0x03c8 }, /* Greek_psi ψ GREEK SMALL LETTER PSI */ - { 0x07f9, 0x03c9 }, /* Greek_omega ω GREEK SMALL LETTER OMEGA */ - { 0x08a1, 0x23b7 }, /* leftradical ⎷ RADICAL SYMBOL BOTTOM */ - { 0x08a2, 0x250c }, /* topleftradical ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT */ - { 0x08a3, 0x2500 }, /* horizconnector ─ BOX DRAWINGS LIGHT HORIZONTAL */ - { 0x08a4, 0x2320 }, /* topintegral ⌠ TOP HALF INTEGRAL */ - { 0x08a5, 0x2321 }, /* botintegral ⌡ BOTTOM HALF INTEGRAL */ - { 0x08a6, 0x2502 }, /* vertconnector │ BOX DRAWINGS LIGHT VERTICAL */ - { 0x08a7, 0x23a1 }, /* topleftsqbracket ⎡ LEFT SQUARE BRACKET UPPER CORNER */ - { 0x08a8, 0x23a3 }, /* botleftsqbracket ⎣ LEFT SQUARE BRACKET LOWER CORNER */ - { 0x08a9, 0x23a4 }, /* toprightsqbracket ⎤ RIGHT SQUARE BRACKET UPPER CORNER */ - { 0x08aa, 0x23a6 }, /* botrightsqbracket ⎦ RIGHT SQUARE BRACKET LOWER CORNER */ - { 0x08ab, 0x239b }, /* topleftparens ⎛ LEFT PARENTHESIS UPPER HOOK */ - { 0x08ac, 0x239d }, /* botleftparens ⎝ LEFT PARENTHESIS LOWER HOOK */ - { 0x08ad, 0x239e }, /* toprightparens ⎞ RIGHT PARENTHESIS UPPER HOOK */ - { 0x08ae, 0x23a0 }, /* botrightparens ⎠ RIGHT PARENTHESIS LOWER HOOK */ - { 0x08af, 0x23a8 }, /* leftmiddlecurlybrace ⎨ LEFT CURLY BRACKET MIDDLE PIECE */ - { 0x08b0, 0x23ac }, /* rightmiddlecurlybrace ⎬ RIGHT CURLY BRACKET MIDDLE PIECE */ - /* 0x08b1 topleftsummation ? ??? */ - /* 0x08b2 botleftsummation ? ??? */ - /* 0x08b3 topvertsummationconnector ? ??? */ - /* 0x08b4 botvertsummationconnector ? ??? */ - /* 0x08b5 toprightsummation ? ??? */ - /* 0x08b6 botrightsummation ? ??? */ - /* 0x08b7 rightmiddlesummation ? ??? */ - { 0x08bc, 0x2264 }, /* lessthanequal ≤ LESS-THAN OR EQUAL TO */ - { 0x08bd, 0x2260 }, /* notequal ≠ NOT EQUAL TO */ - { 0x08be, 0x2265 }, /* greaterthanequal ≥ GREATER-THAN OR EQUAL TO */ - { 0x08bf, 0x222b }, /* integral ∫ INTEGRAL */ - { 0x08c0, 0x2234 }, /* therefore ∴ THEREFORE */ - { 0x08c1, 0x221d }, /* variation ∝ PROPORTIONAL TO */ - { 0x08c2, 0x221e }, /* infinity ∞ INFINITY */ - { 0x08c5, 0x2207 }, /* nabla ∇ NABLA */ - { 0x08c8, 0x223c }, /* approximate ∼ TILDE OPERATOR */ - { 0x08c9, 0x2243 }, /* similarequal ≃ ASYMPTOTICALLY EQUAL TO */ - { 0x08cd, 0x21d4 }, /* ifonlyif ⇔ LEFT RIGHT DOUBLE ARROW */ - { 0x08ce, 0x21d2 }, /* implies ⇒ RIGHTWARDS DOUBLE ARROW */ - { 0x08cf, 0x2261 }, /* identical ≡ IDENTICAL TO */ - { 0x08d6, 0x221a }, /* radical √ SQUARE ROOT */ - { 0x08da, 0x2282 }, /* includedin ⊂ SUBSET OF */ - { 0x08db, 0x2283 }, /* includes ⊃ SUPERSET OF */ - { 0x08dc, 0x2229 }, /* intersection ∩ INTERSECTION */ - { 0x08dd, 0x222a }, /* union ∪ UNION */ - { 0x08de, 0x2227 }, /* logicaland ∧ LOGICAL AND */ - { 0x08df, 0x2228 }, /* logicalor ∨ LOGICAL OR */ - { 0x08ef, 0x2202 }, /* partialderivative ∂ PARTIAL DIFFERENTIAL */ - { 0x08f6, 0x0192 }, /* function ƒ LATIN SMALL LETTER F WITH HOOK */ - { 0x08fb, 0x2190 }, /* leftarrow ← LEFTWARDS ARROW */ - { 0x08fc, 0x2191 }, /* uparrow ↑ UPWARDS ARROW */ - { 0x08fd, 0x2192 }, /* rightarrow → RIGHTWARDS ARROW */ - { 0x08fe, 0x2193 }, /* downarrow ↓ DOWNWARDS ARROW */ - { 0x09df, 0x2422 }, /* blank ␢ BLANK SYMBOL */ - { 0x09e0, 0x25c6 }, /* soliddiamond ◆ BLACK DIAMOND */ - { 0x09e1, 0x2592 }, /* checkerboard ▒ MEDIUM SHADE */ - { 0x09e2, 0x2409 }, /* ht ␉ SYMBOL FOR HORIZONTAL TABULATION */ - { 0x09e3, 0x240c }, /* ff ␌ SYMBOL FOR FORM FEED */ - { 0x09e4, 0x240d }, /* cr ␍ SYMBOL FOR CARRIAGE RETURN */ - { 0x09e5, 0x240a }, /* lf ␊ SYMBOL FOR LINE FEED */ - { 0x09e8, 0x2424 }, /* nl ␤ SYMBOL FOR NEWLINE */ - { 0x09e9, 0x240b }, /* vt ␋ SYMBOL FOR VERTICAL TABULATION */ - { 0x09ea, 0x2518 }, /* lowrightcorner ┘ BOX DRAWINGS LIGHT UP AND LEFT */ - { 0x09eb, 0x2510 }, /* uprightcorner ┐ BOX DRAWINGS LIGHT DOWN AND LEFT */ - { 0x09ec, 0x250c }, /* upleftcorner ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT */ - { 0x09ed, 0x2514 }, /* lowleftcorner └ BOX DRAWINGS LIGHT UP AND RIGHT */ - { 0x09ee, 0x253c }, /* crossinglines ┼ BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */ - { 0x09ef, 0x23ba }, /* horizlinescan1 ⎺ HORIZONTAL SCAN LINE-1 */ - { 0x09f0, 0x23bb }, /* horizlinescan3 ⎻ HORIZONTAL SCAN LINE-3 */ - { 0x09f1, 0x2500 }, /* horizlinescan5 ─ BOX DRAWINGS LIGHT HORIZONTAL */ - { 0x09f2, 0x23bc }, /* horizlinescan7 ⎼ HORIZONTAL SCAN LINE-7 */ - { 0x09f3, 0x23bd }, /* horizlinescan9 ⎽ HORIZONTAL SCAN LINE-9 */ - { 0x09f4, 0x251c }, /* leftt ├ BOX DRAWINGS LIGHT VERTICAL AND RIGHT */ - { 0x09f5, 0x2524 }, /* rightt ┤ BOX DRAWINGS LIGHT VERTICAL AND LEFT */ - { 0x09f6, 0x2534 }, /* bott ┴ BOX DRAWINGS LIGHT UP AND HORIZONTAL */ - { 0x09f7, 0x252c }, /* topt ┬ BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */ - { 0x09f8, 0x2502 }, /* vertbar │ BOX DRAWINGS LIGHT VERTICAL */ - { 0x0aa1, 0x2003 }, /* emspace   EM SPACE */ - { 0x0aa2, 0x2002 }, /* enspace   EN SPACE */ - { 0x0aa3, 0x2004 }, /* em3space   THREE-PER-EM SPACE */ - { 0x0aa4, 0x2005 }, /* em4space   FOUR-PER-EM SPACE */ - { 0x0aa5, 0x2007 }, /* digitspace   FIGURE SPACE */ - { 0x0aa6, 0x2008 }, /* punctspace   PUNCTUATION SPACE */ - { 0x0aa7, 0x2009 }, /* thinspace   THIN SPACE */ - { 0x0aa8, 0x200a }, /* hairspace   HAIR SPACE */ - { 0x0aa9, 0x2014 }, /* emdash — EM DASH */ - { 0x0aaa, 0x2013 }, /* endash – EN DASH */ - { 0x0aac, 0x2423 }, /* signifblank ␣ OPEN BOX */ - { 0x0aae, 0x2026 }, /* ellipsis … HORIZONTAL ELLIPSIS */ - { 0x0aaf, 0x2025 }, /* doubbaselinedot ‥ TWO DOT LEADER */ - { 0x0ab0, 0x2153 }, /* onethird ⅓ VULGAR FRACTION ONE THIRD */ - { 0x0ab1, 0x2154 }, /* twothirds ⅔ VULGAR FRACTION TWO THIRDS */ - { 0x0ab2, 0x2155 }, /* onefifth ⅕ VULGAR FRACTION ONE FIFTH */ - { 0x0ab3, 0x2156 }, /* twofifths ⅖ VULGAR FRACTION TWO FIFTHS */ - { 0x0ab4, 0x2157 }, /* threefifths ⅗ VULGAR FRACTION THREE FIFTHS */ - { 0x0ab5, 0x2158 }, /* fourfifths ⅘ VULGAR FRACTION FOUR FIFTHS */ - { 0x0ab6, 0x2159 }, /* onesixth ⅙ VULGAR FRACTION ONE SIXTH */ - { 0x0ab7, 0x215a }, /* fivesixths ⅚ VULGAR FRACTION FIVE SIXTHS */ - { 0x0ab8, 0x2105 }, /* careof ℅ CARE OF */ - { 0x0abb, 0x2012 }, /* figdash ‒ FIGURE DASH */ - { 0x0abc, 0x2329 }, /* leftanglebracket 〈 LEFT-POINTING ANGLE BRACKET */ - { 0x0abd, 0x002e }, /* decimalpoint . FULL STOP */ - { 0x0abe, 0x232a }, /* rightanglebracket 〉 RIGHT-POINTING ANGLE BRACKET */ - /* 0x0abf marker ? ??? */ - { 0x0ac3, 0x215b }, /* oneeighth ⅛ VULGAR FRACTION ONE EIGHTH */ - { 0x0ac4, 0x215c }, /* threeeighths ⅜ VULGAR FRACTION THREE EIGHTHS */ - { 0x0ac5, 0x215d }, /* fiveeighths ⅝ VULGAR FRACTION FIVE EIGHTHS */ - { 0x0ac6, 0x215e }, /* seveneighths ⅞ VULGAR FRACTION SEVEN EIGHTHS */ - { 0x0ac9, 0x2122 }, /* trademark ™ TRADE MARK SIGN */ - { 0x0aca, 0x2613 }, /* signaturemark ☓ SALTIRE */ - /* 0x0acb trademarkincircle ? ??? */ - { 0x0acc, 0x25c1 }, /* leftopentriangle ◁ WHITE LEFT-POINTING TRIANGLE */ - { 0x0acd, 0x25b7 }, /* rightopentriangle ▷ WHITE RIGHT-POINTING TRIANGLE */ - { 0x0ace, 0x25cb }, /* emopencircle ○ WHITE CIRCLE */ - { 0x0acf, 0x25af }, /* emopenrectangle ▯ WHITE VERTICAL RECTANGLE */ - { 0x0ad0, 0x2018 }, /* leftsinglequotemark ‘ LEFT SINGLE QUOTATION MARK */ - { 0x0ad1, 0x2019 }, /* rightsinglequotemark ’ RIGHT SINGLE QUOTATION MARK */ - { 0x0ad2, 0x201c }, /* leftdoublequotemark “ LEFT DOUBLE QUOTATION MARK */ - { 0x0ad3, 0x201d }, /* rightdoublequotemark ” RIGHT DOUBLE QUOTATION MARK */ - { 0x0ad4, 0x211e }, /* prescription ℞ PRESCRIPTION TAKE */ - { 0x0ad5, 0x2030 }, /* permille ‰ PER MILLE SIGN */ - { 0x0ad6, 0x2032 }, /* minutes ′ PRIME */ - { 0x0ad7, 0x2033 }, /* seconds ″ DOUBLE PRIME */ - { 0x0ad9, 0x271d }, /* latincross ✝ LATIN CROSS */ - /* 0x0ada hexagram ? ??? */ - { 0x0adb, 0x25ac }, /* filledrectbullet ▬ BLACK RECTANGLE */ - { 0x0adc, 0x25c0 }, /* filledlefttribullet ◀ BLACK LEFT-POINTING TRIANGLE */ - { 0x0add, 0x25b6 }, /* filledrighttribullet ▶ BLACK RIGHT-POINTING TRIANGLE */ - { 0x0ade, 0x25cf }, /* emfilledcircle ● BLACK CIRCLE */ - { 0x0adf, 0x25ae }, /* emfilledrect ▮ BLACK VERTICAL RECTANGLE */ - { 0x0ae0, 0x25e6 }, /* enopencircbullet ◦ WHITE BULLET */ - { 0x0ae1, 0x25ab }, /* enopensquarebullet ▫ WHITE SMALL SQUARE */ - { 0x0ae2, 0x25ad }, /* openrectbullet ▭ WHITE RECTANGLE */ - { 0x0ae3, 0x25b3 }, /* opentribulletup △ WHITE UP-POINTING TRIANGLE */ - { 0x0ae4, 0x25bd }, /* opentribulletdown ▽ WHITE DOWN-POINTING TRIANGLE */ - { 0x0ae5, 0x2606 }, /* openstar ☆ WHITE STAR */ - { 0x0ae6, 0x2022 }, /* enfilledcircbullet • BULLET */ - { 0x0ae7, 0x25aa }, /* enfilledsqbullet ▪ BLACK SMALL SQUARE */ - { 0x0ae8, 0x25b2 }, /* filledtribulletup ▲ BLACK UP-POINTING TRIANGLE */ - { 0x0ae9, 0x25bc }, /* filledtribulletdown ▼ BLACK DOWN-POINTING TRIANGLE */ - { 0x0aea, 0x261c }, /* leftpointer ☜ WHITE LEFT POINTING INDEX */ - { 0x0aeb, 0x261e }, /* rightpointer ☞ WHITE RIGHT POINTING INDEX */ - { 0x0aec, 0x2663 }, /* club ♣ BLACK CLUB SUIT */ - { 0x0aed, 0x2666 }, /* diamond ♦ BLACK DIAMOND SUIT */ - { 0x0aee, 0x2665 }, /* heart ♥ BLACK HEART SUIT */ - { 0x0af0, 0x2720 }, /* maltesecross ✠ MALTESE CROSS */ - { 0x0af1, 0x2020 }, /* dagger † DAGGER */ - { 0x0af2, 0x2021 }, /* doubledagger ‡ DOUBLE DAGGER */ - { 0x0af3, 0x2713 }, /* checkmark ✓ CHECK MARK */ - { 0x0af4, 0x2717 }, /* ballotcross ✗ BALLOT X */ - { 0x0af5, 0x266f }, /* musicalsharp ♯ MUSIC SHARP SIGN */ - { 0x0af6, 0x266d }, /* musicalflat ♭ MUSIC FLAT SIGN */ - { 0x0af7, 0x2642 }, /* malesymbol ♂ MALE SIGN */ - { 0x0af8, 0x2640 }, /* femalesymbol ♀ FEMALE SIGN */ - { 0x0af9, 0x260e }, /* telephone ☎ BLACK TELEPHONE */ - { 0x0afa, 0x2315 }, /* telephonerecorder ⌕ TELEPHONE RECORDER */ - { 0x0afb, 0x2117 }, /* phonographcopyright ℗ SOUND RECORDING COPYRIGHT */ - { 0x0afc, 0x2038 }, /* caret ‸ CARET */ - { 0x0afd, 0x201a }, /* singlelowquotemark ‚ SINGLE LOW-9 QUOTATION MARK */ - { 0x0afe, 0x201e }, /* doublelowquotemark „ DOUBLE LOW-9 QUOTATION MARK */ - /* 0x0aff cursor ? ??? */ - { 0x0ba3, 0x003c }, /* leftcaret < LESS-THAN SIGN */ - { 0x0ba6, 0x003e }, /* rightcaret > GREATER-THAN SIGN */ - { 0x0ba8, 0x2228 }, /* downcaret ∨ LOGICAL OR */ - { 0x0ba9, 0x2227 }, /* upcaret ∧ LOGICAL AND */ - { 0x0bc0, 0x00af }, /* overbar ¯ MACRON */ - { 0x0bc2, 0x22a4 }, /* downtack ⊤ DOWN TACK */ - { 0x0bc3, 0x2229 }, /* upshoe ∩ INTERSECTION */ - { 0x0bc4, 0x230a }, /* downstile ⌊ LEFT FLOOR */ - { 0x0bc6, 0x005f }, /* underbar _ LOW LINE */ - { 0x0bca, 0x2218 }, /* jot ∘ RING OPERATOR */ - { 0x0bcc, 0x2395 }, /* quad ⎕ APL FUNCTIONAL SYMBOL QUAD */ - { 0x0bce, 0x22a5 }, /* uptack ⊥ UP TACK */ - { 0x0bcf, 0x25cb }, /* circle ○ WHITE CIRCLE */ - { 0x0bd3, 0x2308 }, /* upstile ⌈ LEFT CEILING */ - { 0x0bd6, 0x222a }, /* downshoe ∪ UNION */ - { 0x0bd8, 0x2283 }, /* rightshoe ⊃ SUPERSET OF */ - { 0x0bda, 0x2282 }, /* leftshoe ⊂ SUBSET OF */ - { 0x0bdc, 0x22a3 }, /* lefttack ⊣ LEFT TACK */ - { 0x0bfc, 0x22a2 }, /* righttack ⊢ RIGHT TACK */ - { 0x0cdf, 0x2017 }, /* hebrew_doublelowline ‗ DOUBLE LOW LINE */ - { 0x0ce0, 0x05d0 }, /* hebrew_aleph א HEBREW LETTER ALEF */ - { 0x0ce1, 0x05d1 }, /* hebrew_bet ב HEBREW LETTER BET */ - { 0x0ce2, 0x05d2 }, /* hebrew_gimel ג HEBREW LETTER GIMEL */ - { 0x0ce3, 0x05d3 }, /* hebrew_dalet ד HEBREW LETTER DALET */ - { 0x0ce4, 0x05d4 }, /* hebrew_he ה HEBREW LETTER HE */ - { 0x0ce5, 0x05d5 }, /* hebrew_waw ו HEBREW LETTER VAV */ - { 0x0ce6, 0x05d6 }, /* hebrew_zain ז HEBREW LETTER ZAYIN */ - { 0x0ce7, 0x05d7 }, /* hebrew_chet ח HEBREW LETTER HET */ - { 0x0ce8, 0x05d8 }, /* hebrew_tet ט HEBREW LETTER TET */ - { 0x0ce9, 0x05d9 }, /* hebrew_yod י HEBREW LETTER YOD */ - { 0x0cea, 0x05da }, /* hebrew_finalkaph ך HEBREW LETTER FINAL KAF */ - { 0x0ceb, 0x05db }, /* hebrew_kaph כ HEBREW LETTER KAF */ - { 0x0cec, 0x05dc }, /* hebrew_lamed ל HEBREW LETTER LAMED */ - { 0x0ced, 0x05dd }, /* hebrew_finalmem ם HEBREW LETTER FINAL MEM */ - { 0x0cee, 0x05de }, /* hebrew_mem מ HEBREW LETTER MEM */ - { 0x0cef, 0x05df }, /* hebrew_finalnun ן HEBREW LETTER FINAL NUN */ - { 0x0cf0, 0x05e0 }, /* hebrew_nun נ HEBREW LETTER NUN */ - { 0x0cf1, 0x05e1 }, /* hebrew_samech ס HEBREW LETTER SAMEKH */ - { 0x0cf2, 0x05e2 }, /* hebrew_ayin ע HEBREW LETTER AYIN */ - { 0x0cf3, 0x05e3 }, /* hebrew_finalpe ף HEBREW LETTER FINAL PE */ - { 0x0cf4, 0x05e4 }, /* hebrew_pe פ HEBREW LETTER PE */ - { 0x0cf5, 0x05e5 }, /* hebrew_finalzade ץ HEBREW LETTER FINAL TSADI */ - { 0x0cf6, 0x05e6 }, /* hebrew_zade צ HEBREW LETTER TSADI */ - { 0x0cf7, 0x05e7 }, /* hebrew_qoph ק HEBREW LETTER QOF */ - { 0x0cf8, 0x05e8 }, /* hebrew_resh ר HEBREW LETTER RESH */ - { 0x0cf9, 0x05e9 }, /* hebrew_shin ש HEBREW LETTER SHIN */ - { 0x0cfa, 0x05ea }, /* hebrew_taw ת HEBREW LETTER TAV */ - { 0x0da1, 0x0e01 }, /* Thai_kokai ก THAI CHARACTER KO KAI */ - { 0x0da2, 0x0e02 }, /* Thai_khokhai ข THAI CHARACTER KHO KHAI */ - { 0x0da3, 0x0e03 }, /* Thai_khokhuat ฃ THAI CHARACTER KHO KHUAT */ - { 0x0da4, 0x0e04 }, /* Thai_khokhwai ค THAI CHARACTER KHO KHWAI */ - { 0x0da5, 0x0e05 }, /* Thai_khokhon ฅ THAI CHARACTER KHO KHON */ - { 0x0da6, 0x0e06 }, /* Thai_khorakhang ฆ THAI CHARACTER KHO RAKHANG */ - { 0x0da7, 0x0e07 }, /* Thai_ngongu ง THAI CHARACTER NGO NGU */ - { 0x0da8, 0x0e08 }, /* Thai_chochan จ THAI CHARACTER CHO CHAN */ - { 0x0da9, 0x0e09 }, /* Thai_choching ฉ THAI CHARACTER CHO CHING */ - { 0x0daa, 0x0e0a }, /* Thai_chochang ช THAI CHARACTER CHO CHANG */ - { 0x0dab, 0x0e0b }, /* Thai_soso ซ THAI CHARACTER SO SO */ - { 0x0dac, 0x0e0c }, /* Thai_chochoe ฌ THAI CHARACTER CHO CHOE */ - { 0x0dad, 0x0e0d }, /* Thai_yoying ญ THAI CHARACTER YO YING */ - { 0x0dae, 0x0e0e }, /* Thai_dochada ฎ THAI CHARACTER DO CHADA */ - { 0x0daf, 0x0e0f }, /* Thai_topatak ฏ THAI CHARACTER TO PATAK */ - { 0x0db0, 0x0e10 }, /* Thai_thothan ฐ THAI CHARACTER THO THAN */ - { 0x0db1, 0x0e11 }, /* Thai_thonangmontho ฑ THAI CHARACTER THO NANGMONTHO */ - { 0x0db2, 0x0e12 }, /* Thai_thophuthao ฒ THAI CHARACTER THO PHUTHAO */ - { 0x0db3, 0x0e13 }, /* Thai_nonen ณ THAI CHARACTER NO NEN */ - { 0x0db4, 0x0e14 }, /* Thai_dodek ด THAI CHARACTER DO DEK */ - { 0x0db5, 0x0e15 }, /* Thai_totao ต THAI CHARACTER TO TAO */ - { 0x0db6, 0x0e16 }, /* Thai_thothung ถ THAI CHARACTER THO THUNG */ - { 0x0db7, 0x0e17 }, /* Thai_thothahan ท THAI CHARACTER THO THAHAN */ - { 0x0db8, 0x0e18 }, /* Thai_thothong ธ THAI CHARACTER THO THONG */ - { 0x0db9, 0x0e19 }, /* Thai_nonu น THAI CHARACTER NO NU */ - { 0x0dba, 0x0e1a }, /* Thai_bobaimai บ THAI CHARACTER BO BAIMAI */ - { 0x0dbb, 0x0e1b }, /* Thai_popla ป THAI CHARACTER PO PLA */ - { 0x0dbc, 0x0e1c }, /* Thai_phophung ผ THAI CHARACTER PHO PHUNG */ - { 0x0dbd, 0x0e1d }, /* Thai_fofa ฝ THAI CHARACTER FO FA */ - { 0x0dbe, 0x0e1e }, /* Thai_phophan พ THAI CHARACTER PHO PHAN */ - { 0x0dbf, 0x0e1f }, /* Thai_fofan ฟ THAI CHARACTER FO FAN */ - { 0x0dc0, 0x0e20 }, /* Thai_phosamphao ภ THAI CHARACTER PHO SAMPHAO */ - { 0x0dc1, 0x0e21 }, /* Thai_moma ม THAI CHARACTER MO MA */ - { 0x0dc2, 0x0e22 }, /* Thai_yoyak ย THAI CHARACTER YO YAK */ - { 0x0dc3, 0x0e23 }, /* Thai_rorua ร THAI CHARACTER RO RUA */ - { 0x0dc4, 0x0e24 }, /* Thai_ru ฤ THAI CHARACTER RU */ - { 0x0dc5, 0x0e25 }, /* Thai_loling ล THAI CHARACTER LO LING */ - { 0x0dc6, 0x0e26 }, /* Thai_lu ฦ THAI CHARACTER LU */ - { 0x0dc7, 0x0e27 }, /* Thai_wowaen ว THAI CHARACTER WO WAEN */ - { 0x0dc8, 0x0e28 }, /* Thai_sosala ศ THAI CHARACTER SO SALA */ - { 0x0dc9, 0x0e29 }, /* Thai_sorusi ษ THAI CHARACTER SO RUSI */ - { 0x0dca, 0x0e2a }, /* Thai_sosua ส THAI CHARACTER SO SUA */ - { 0x0dcb, 0x0e2b }, /* Thai_hohip ห THAI CHARACTER HO HIP */ - { 0x0dcc, 0x0e2c }, /* Thai_lochula ฬ THAI CHARACTER LO CHULA */ - { 0x0dcd, 0x0e2d }, /* Thai_oang อ THAI CHARACTER O ANG */ - { 0x0dce, 0x0e2e }, /* Thai_honokhuk ฮ THAI CHARACTER HO NOKHUK */ - { 0x0dcf, 0x0e2f }, /* Thai_paiyannoi ฯ THAI CHARACTER PAIYANNOI */ - { 0x0dd0, 0x0e30 }, /* Thai_saraa ะ THAI CHARACTER SARA A */ - { 0x0dd1, 0x0e31 }, /* Thai_maihanakat ั THAI CHARACTER MAI HAN-AKAT */ - { 0x0dd2, 0x0e32 }, /* Thai_saraaa า THAI CHARACTER SARA AA */ - { 0x0dd3, 0x0e33 }, /* Thai_saraam ำ THAI CHARACTER SARA AM */ - { 0x0dd4, 0x0e34 }, /* Thai_sarai ิ THAI CHARACTER SARA I */ - { 0x0dd5, 0x0e35 }, /* Thai_saraii ี THAI CHARACTER SARA II */ - { 0x0dd6, 0x0e36 }, /* Thai_saraue ึ THAI CHARACTER SARA UE */ - { 0x0dd7, 0x0e37 }, /* Thai_sarauee ื THAI CHARACTER SARA UEE */ - { 0x0dd8, 0x0e38 }, /* Thai_sarau ุ THAI CHARACTER SARA U */ - { 0x0dd9, 0x0e39 }, /* Thai_sarauu ู THAI CHARACTER SARA UU */ - { 0x0dda, 0x0e3a }, /* Thai_phinthu ฺ THAI CHARACTER PHINTHU */ - /* 0x0dde Thai_maihanakat_maitho ? ??? */ - { 0x0ddf, 0x0e3f }, /* Thai_baht ฿ THAI CURRENCY SYMBOL BAHT */ - { 0x0de0, 0x0e40 }, /* Thai_sarae เ THAI CHARACTER SARA E */ - { 0x0de1, 0x0e41 }, /* Thai_saraae แ THAI CHARACTER SARA AE */ - { 0x0de2, 0x0e42 }, /* Thai_sarao โ THAI CHARACTER SARA O */ - { 0x0de3, 0x0e43 }, /* Thai_saraaimaimuan ใ THAI CHARACTER SARA AI MAIMUAN */ - { 0x0de4, 0x0e44 }, /* Thai_saraaimaimalai ไ THAI CHARACTER SARA AI MAIMALAI */ - { 0x0de5, 0x0e45 }, /* Thai_lakkhangyao ๅ THAI CHARACTER LAKKHANGYAO */ - { 0x0de6, 0x0e46 }, /* Thai_maiyamok ๆ THAI CHARACTER MAIYAMOK */ - { 0x0de7, 0x0e47 }, /* Thai_maitaikhu ็ THAI CHARACTER MAITAIKHU */ - { 0x0de8, 0x0e48 }, /* Thai_maiek ่ THAI CHARACTER MAI EK */ - { 0x0de9, 0x0e49 }, /* Thai_maitho ้ THAI CHARACTER MAI THO */ - { 0x0dea, 0x0e4a }, /* Thai_maitri ๊ THAI CHARACTER MAI TRI */ - { 0x0deb, 0x0e4b }, /* Thai_maichattawa ๋ THAI CHARACTER MAI CHATTAWA */ - { 0x0dec, 0x0e4c }, /* Thai_thanthakhat ์ THAI CHARACTER THANTHAKHAT */ - { 0x0ded, 0x0e4d }, /* Thai_nikhahit ํ THAI CHARACTER NIKHAHIT */ - { 0x0df0, 0x0e50 }, /* Thai_leksun ๐ THAI DIGIT ZERO */ - { 0x0df1, 0x0e51 }, /* Thai_leknung ๑ THAI DIGIT ONE */ - { 0x0df2, 0x0e52 }, /* Thai_leksong ๒ THAI DIGIT TWO */ - { 0x0df3, 0x0e53 }, /* Thai_leksam ๓ THAI DIGIT THREE */ - { 0x0df4, 0x0e54 }, /* Thai_leksi ๔ THAI DIGIT FOUR */ - { 0x0df5, 0x0e55 }, /* Thai_lekha ๕ THAI DIGIT FIVE */ - { 0x0df6, 0x0e56 }, /* Thai_lekhok ๖ THAI DIGIT SIX */ - { 0x0df7, 0x0e57 }, /* Thai_lekchet ๗ THAI DIGIT SEVEN */ - { 0x0df8, 0x0e58 }, /* Thai_lekpaet ๘ THAI DIGIT EIGHT */ - { 0x0df9, 0x0e59 }, /* Thai_lekkao ๙ THAI DIGIT NINE */ - { 0x0ea1, 0x3131 }, /* Hangul_Kiyeog ㄱ HANGUL LETTER KIYEOK */ - { 0x0ea2, 0x3132 }, /* Hangul_SsangKiyeog ㄲ HANGUL LETTER SSANGKIYEOK */ - { 0x0ea3, 0x3133 }, /* Hangul_KiyeogSios ㄳ HANGUL LETTER KIYEOK-SIOS */ - { 0x0ea4, 0x3134 }, /* Hangul_Nieun ㄴ HANGUL LETTER NIEUN */ - { 0x0ea5, 0x3135 }, /* Hangul_NieunJieuj ㄵ HANGUL LETTER NIEUN-CIEUC */ - { 0x0ea6, 0x3136 }, /* Hangul_NieunHieuh ㄶ HANGUL LETTER NIEUN-HIEUH */ - { 0x0ea7, 0x3137 }, /* Hangul_Dikeud ㄷ HANGUL LETTER TIKEUT */ - { 0x0ea8, 0x3138 }, /* Hangul_SsangDikeud ㄸ HANGUL LETTER SSANGTIKEUT */ - { 0x0ea9, 0x3139 }, /* Hangul_Rieul ㄹ HANGUL LETTER RIEUL */ - { 0x0eaa, 0x313a }, /* Hangul_RieulKiyeog ㄺ HANGUL LETTER RIEUL-KIYEOK */ - { 0x0eab, 0x313b }, /* Hangul_RieulMieum ㄻ HANGUL LETTER RIEUL-MIEUM */ - { 0x0eac, 0x313c }, /* Hangul_RieulPieub ㄼ HANGUL LETTER RIEUL-PIEUP */ - { 0x0ead, 0x313d }, /* Hangul_RieulSios ㄽ HANGUL LETTER RIEUL-SIOS */ - { 0x0eae, 0x313e }, /* Hangul_RieulTieut ㄾ HANGUL LETTER RIEUL-THIEUTH */ - { 0x0eaf, 0x313f }, /* Hangul_RieulPhieuf ㄿ HANGUL LETTER RIEUL-PHIEUPH */ - { 0x0eb0, 0x3140 }, /* Hangul_RieulHieuh ㅀ HANGUL LETTER RIEUL-HIEUH */ - { 0x0eb1, 0x3141 }, /* Hangul_Mieum ㅁ HANGUL LETTER MIEUM */ - { 0x0eb2, 0x3142 }, /* Hangul_Pieub ㅂ HANGUL LETTER PIEUP */ - { 0x0eb3, 0x3143 }, /* Hangul_SsangPieub ㅃ HANGUL LETTER SSANGPIEUP */ - { 0x0eb4, 0x3144 }, /* Hangul_PieubSios ㅄ HANGUL LETTER PIEUP-SIOS */ - { 0x0eb5, 0x3145 }, /* Hangul_Sios ㅅ HANGUL LETTER SIOS */ - { 0x0eb6, 0x3146 }, /* Hangul_SsangSios ㅆ HANGUL LETTER SSANGSIOS */ - { 0x0eb7, 0x3147 }, /* Hangul_Ieung ㅇ HANGUL LETTER IEUNG */ - { 0x0eb8, 0x3148 }, /* Hangul_Jieuj ㅈ HANGUL LETTER CIEUC */ - { 0x0eb9, 0x3149 }, /* Hangul_SsangJieuj ㅉ HANGUL LETTER SSANGCIEUC */ - { 0x0eba, 0x314a }, /* Hangul_Cieuc ㅊ HANGUL LETTER CHIEUCH */ - { 0x0ebb, 0x314b }, /* Hangul_Khieuq ㅋ HANGUL LETTER KHIEUKH */ - { 0x0ebc, 0x314c }, /* Hangul_Tieut ㅌ HANGUL LETTER THIEUTH */ - { 0x0ebd, 0x314d }, /* Hangul_Phieuf ㅍ HANGUL LETTER PHIEUPH */ - { 0x0ebe, 0x314e }, /* Hangul_Hieuh ㅎ HANGUL LETTER HIEUH */ - { 0x0ebf, 0x314f }, /* Hangul_A ㅏ HANGUL LETTER A */ - { 0x0ec0, 0x3150 }, /* Hangul_AE ㅐ HANGUL LETTER AE */ - { 0x0ec1, 0x3151 }, /* Hangul_YA ㅑ HANGUL LETTER YA */ - { 0x0ec2, 0x3152 }, /* Hangul_YAE ㅒ HANGUL LETTER YAE */ - { 0x0ec3, 0x3153 }, /* Hangul_EO ㅓ HANGUL LETTER EO */ - { 0x0ec4, 0x3154 }, /* Hangul_E ㅔ HANGUL LETTER E */ - { 0x0ec5, 0x3155 }, /* Hangul_YEO ㅕ HANGUL LETTER YEO */ - { 0x0ec6, 0x3156 }, /* Hangul_YE ㅖ HANGUL LETTER YE */ - { 0x0ec7, 0x3157 }, /* Hangul_O ㅗ HANGUL LETTER O */ - { 0x0ec8, 0x3158 }, /* Hangul_WA ㅘ HANGUL LETTER WA */ - { 0x0ec9, 0x3159 }, /* Hangul_WAE ㅙ HANGUL LETTER WAE */ - { 0x0eca, 0x315a }, /* Hangul_OE ㅚ HANGUL LETTER OE */ - { 0x0ecb, 0x315b }, /* Hangul_YO ㅛ HANGUL LETTER YO */ - { 0x0ecc, 0x315c }, /* Hangul_U ㅜ HANGUL LETTER U */ - { 0x0ecd, 0x315d }, /* Hangul_WEO ㅝ HANGUL LETTER WEO */ - { 0x0ece, 0x315e }, /* Hangul_WE ㅞ HANGUL LETTER WE */ - { 0x0ecf, 0x315f }, /* Hangul_WI ㅟ HANGUL LETTER WI */ - { 0x0ed0, 0x3160 }, /* Hangul_YU ㅠ HANGUL LETTER YU */ - { 0x0ed1, 0x3161 }, /* Hangul_EU ㅡ HANGUL LETTER EU */ - { 0x0ed2, 0x3162 }, /* Hangul_YI ㅢ HANGUL LETTER YI */ - { 0x0ed3, 0x3163 }, /* Hangul_I ㅣ HANGUL LETTER I */ - { 0x0ed4, 0x11a8 }, /* Hangul_J_Kiyeog ᆨ HANGUL JONGSEONG KIYEOK */ - { 0x0ed5, 0x11a9 }, /* Hangul_J_SsangKiyeog ᆩ HANGUL JONGSEONG SSANGKIYEOK */ - { 0x0ed6, 0x11aa }, /* Hangul_J_KiyeogSios ᆪ HANGUL JONGSEONG KIYEOK-SIOS */ - { 0x0ed7, 0x11ab }, /* Hangul_J_Nieun ᆫ HANGUL JONGSEONG NIEUN */ - { 0x0ed8, 0x11ac }, /* Hangul_J_NieunJieuj ᆬ HANGUL JONGSEONG NIEUN-CIEUC */ - { 0x0ed9, 0x11ad }, /* Hangul_J_NieunHieuh ᆭ HANGUL JONGSEONG NIEUN-HIEUH */ - { 0x0eda, 0x11ae }, /* Hangul_J_Dikeud ᆮ HANGUL JONGSEONG TIKEUT */ - { 0x0edb, 0x11af }, /* Hangul_J_Rieul ᆯ HANGUL JONGSEONG RIEUL */ - { 0x0edc, 0x11b0 }, /* Hangul_J_RieulKiyeog ᆰ HANGUL JONGSEONG RIEUL-KIYEOK */ - { 0x0edd, 0x11b1 }, /* Hangul_J_RieulMieum ᆱ HANGUL JONGSEONG RIEUL-MIEUM */ - { 0x0ede, 0x11b2 }, /* Hangul_J_RieulPieub ᆲ HANGUL JONGSEONG RIEUL-PIEUP */ - { 0x0edf, 0x11b3 }, /* Hangul_J_RieulSios ᆳ HANGUL JONGSEONG RIEUL-SIOS */ - { 0x0ee0, 0x11b4 }, /* Hangul_J_RieulTieut ᆴ HANGUL JONGSEONG RIEUL-THIEUTH */ - { 0x0ee1, 0x11b5 }, /* Hangul_J_RieulPhieuf ᆵ HANGUL JONGSEONG RIEUL-PHIEUPH */ - { 0x0ee2, 0x11b6 }, /* Hangul_J_RieulHieuh ᆶ HANGUL JONGSEONG RIEUL-HIEUH */ - { 0x0ee3, 0x11b7 }, /* Hangul_J_Mieum ᆷ HANGUL JONGSEONG MIEUM */ - { 0x0ee4, 0x11b8 }, /* Hangul_J_Pieub ᆸ HANGUL JONGSEONG PIEUP */ - { 0x0ee5, 0x11b9 }, /* Hangul_J_PieubSios ᆹ HANGUL JONGSEONG PIEUP-SIOS */ - { 0x0ee6, 0x11ba }, /* Hangul_J_Sios ᆺ HANGUL JONGSEONG SIOS */ - { 0x0ee7, 0x11bb }, /* Hangul_J_SsangSios ᆻ HANGUL JONGSEONG SSANGSIOS */ - { 0x0ee8, 0x11bc }, /* Hangul_J_Ieung ᆼ HANGUL JONGSEONG IEUNG */ - { 0x0ee9, 0x11bd }, /* Hangul_J_Jieuj ᆽ HANGUL JONGSEONG CIEUC */ - { 0x0eea, 0x11be }, /* Hangul_J_Cieuc ᆾ HANGUL JONGSEONG CHIEUCH */ - { 0x0eeb, 0x11bf }, /* Hangul_J_Khieuq ᆿ HANGUL JONGSEONG KHIEUKH */ - { 0x0eec, 0x11c0 }, /* Hangul_J_Tieut ᇀ HANGUL JONGSEONG THIEUTH */ - { 0x0eed, 0x11c1 }, /* Hangul_J_Phieuf ᇁ HANGUL JONGSEONG PHIEUPH */ - { 0x0eee, 0x11c2 }, /* Hangul_J_Hieuh ᇂ HANGUL JONGSEONG HIEUH */ - { 0x0eef, 0x316d }, /* Hangul_RieulYeorinHieuh ㅭ HANGUL LETTER RIEUL-YEORINHIEUH */ - { 0x0ef0, 0x3171 }, /* Hangul_SunkyeongeumMieum ㅱ HANGUL LETTER KAPYEOUNMIEUM */ - { 0x0ef1, 0x3178 }, /* Hangul_SunkyeongeumPieub ㅸ HANGUL LETTER KAPYEOUNPIEUP */ - { 0x0ef2, 0x317f }, /* Hangul_PanSios ㅿ HANGUL LETTER PANSIOS */ - { 0x0ef3, 0x3181 }, /* Hangul_KkogjiDalrinIeung ㆁ HANGUL LETTER YESIEUNG */ - { 0x0ef4, 0x3184 }, /* Hangul_SunkyeongeumPhieuf ㆄ HANGUL LETTER KAPYEOUNPHIEUPH */ - { 0x0ef5, 0x3186 }, /* Hangul_YeorinHieuh ㆆ HANGUL LETTER YEORINHIEUH */ - { 0x0ef6, 0x318d }, /* Hangul_AraeA ㆍ HANGUL LETTER ARAEA */ - { 0x0ef7, 0x318e }, /* Hangul_AraeAE ㆎ HANGUL LETTER ARAEAE */ - { 0x0ef8, 0x11eb }, /* Hangul_J_PanSios ᇫ HANGUL JONGSEONG PANSIOS */ - { 0x0ef9, 0x11f0 }, /* Hangul_J_KkogjiDalrinIeung ᇰ HANGUL JONGSEONG YESIEUNG */ - { 0x0efa, 0x11f9 }, /* Hangul_J_YeorinHieuh ᇹ HANGUL JONGSEONG YEORINHIEUH */ - { 0x0eff, 0x20a9 }, /* Korean_Won ₩ WON SIGN */ - { 0x13a4, 0x20ac }, /* Euro € EURO SIGN */ - { 0x13bc, 0x0152 }, /* OE Œ LATIN CAPITAL LIGATURE OE */ - { 0x13bd, 0x0153 }, /* oe œ LATIN SMALL LIGATURE OE */ - { 0x13be, 0x0178 }, /* Ydiaeresis Ÿ LATIN CAPITAL LETTER Y WITH DIAERESIS */ - { 0x20a0, 0x20a0 }, /* EcuSign ₠ EURO-CURRENCY SIGN */ - { 0x20a1, 0x20a1 }, /* ColonSign ₡ COLON SIGN */ - { 0x20a2, 0x20a2 }, /* CruzeiroSign ₢ CRUZEIRO SIGN */ - { 0x20a3, 0x20a3 }, /* FFrancSign ₣ FRENCH FRANC SIGN */ - { 0x20a4, 0x20a4 }, /* LiraSign ₤ LIRA SIGN */ - { 0x20a5, 0x20a5 }, /* MillSign ₥ MILL SIGN */ - { 0x20a6, 0x20a6 }, /* NairaSign ₦ NAIRA SIGN */ - { 0x20a7, 0x20a7 }, /* PesetaSign ₧ PESETA SIGN */ - { 0x20a8, 0x20a8 }, /* RupeeSign ₨ RUPEE SIGN */ - { 0x20a9, 0x20a9 }, /* WonSign ₩ WON SIGN */ - { 0x20aa, 0x20aa }, /* NewSheqelSign ₪ NEW SHEQEL SIGN */ - { 0x20ab, 0x20ab }, /* DongSign ₫ DONG SIGN */ - { 0x20ac, 0x20ac }, /* EuroSign € EURO SIGN */ -}; - -long KeySymConvert::convert(KeySym keysym) -{ - int min = 0; - int max = sizeof(keysymtab) / sizeof(struct codepair) - 1; - int mid; - - /* first check for Latin-1 characters (1:1 mapping) */ - if ((keysym >= 0x0020 && keysym <= 0x007e) || - (keysym >= 0x00a0 && keysym <= 0x00ff)) - return keysym; - - /* also check for directly encoded 24-bit UCS characters */ - if ((keysym & 0xff000000) == 0x01000000) - return keysym & 0x00ffffff; - - /* binary search in table */ - while (max >= min) { - mid = (min + max) / 2; - if (keysymtab[mid].keysym < keysym) - min = mid + 1; - else if (keysymtab[mid].keysym > keysym) - max = mid - 1; - else { - /* found it */ - return keysymtab[mid].ucs; - } - } - - /* no matching Unicode value found */ - return -1; -} diff --git a/kvkbd/src/keysymconvert.h b/kvkbd/src/keysymconvert.h deleted file mode 100644 index 2577be59..00000000 --- a/kvkbd/src/keysymconvert.h +++ /dev/null @@ -1,18 +0,0 @@ -/* $XFree86: xc/programs/xterm/keysym2ucs.h,v 1.1 1999/06/12 15:37:18 dawes Exp $ */ -/* - * This module converts keysym values into the corresponding ISO 10646-1 - * (UCS, Unicode) values. - */ - -#ifndef KEYSYM2UCS_H -#define KEYSYM2UCS_H - -#include - -class KeySymConvert -{ -public: - long convert(KeySym keysym); -}; - -#endif // KEYSYM2UCS_H diff --git a/kvkbd/src/kvkbd.desktop b/kvkbd/src/kvkbd.desktop deleted file mode 100644 index abc0c2eb..00000000 --- a/kvkbd/src/kvkbd.desktop +++ /dev/null @@ -1,46 +0,0 @@ -[Desktop Entry] -Name=Kvkbd -Name[cs]=Kvkbd -Name[de]=Kvkbd -Name[es]=Kvkbd -Name[fi]=Kvkbd -Name[hu]=Kvkbd -Name[nl]=Kvkbd -Name[pl]=Kvkbd -Name[pt]=Kvkbd -Name[pt_BR]=Kvkbd -Name[sk]=Kvkbd -Name[uk]=Kvkbd -Name[x-test]=xxKvkbdxx -Exec=kvkbd --icon '%i' --caption '%c' -Icon=preferences-desktop-keyboard -Type=Application -Comment=A virtual keyboard for KDE -Comment[cs]=Virtuální klávesnice pro KDE -Comment[de]=Eine virtuelle Tastatur für KDE -Comment[es]=Un teclado virtual para KDE -Comment[fi]=KDE:n virtuaalinäppäimistö -Comment[hu]=Virtuális billentyűzet a KDE-hez -Comment[nl]=Een virtueel toetsenbord voor KDE -Comment[pl]=Wirtualna klawiatura dla KDE -Comment[pt]=Um teclado virtual para o KDE -Comment[pt_BR]=Um teclado virtual para o KDE -Comment[sk]=Virtuálna klávesnica pre KDE -Comment[uk]=Віртуальна клавіатура для KDE -Comment[x-test]=xxA virtual keyboard for KDExx -GenericName=Virtual Keyboard -GenericName[cs]=Virtuální klávesnice -GenericName[de]=Virtuelle Tastatur -GenericName[es]=Teclado virtual -GenericName[fi]=Virtuaalinäppäimistö -GenericName[hu]=Virtuális billentyűzet -GenericName[nl]=Virtueel toetsenbord -GenericName[pl]=Wirtualna klawiatura -GenericName[pt]=Teclado Virtual -GenericName[pt_BR]=Teclado virtual -GenericName[sk]=Virtuálna klávesnica -GenericName[uk]=Віртуальна клавіатура -GenericName[x-test]=xxVirtual Keyboardxx -Categories=Qt;KDE;Utility;Accessibility; -Terminal=false -StartupNotify=true diff --git a/kvkbd/src/kvkbdapp.cpp b/kvkbd/src/kvkbdapp.cpp deleted file mode 100644 index e3ec2852..00000000 --- a/kvkbd/src/kvkbdapp.cpp +++ /dev/null @@ -1,394 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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 3 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, see . - * - */ - -#include "kvkbdapp.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define DEFAULT_WIDTH 640 -#define DEFAULT_HEIGHT 210 - -#include "x11keyboard.h" - -QList modKeys; - - -KvkbdApp::KvkbdApp(bool loginhelper) : KUniqueApplication(), is_login(loginhelper) -// : KApplication() -{ - - signalMapper = new QSignalMapper(this); - connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(buttonAction(const QString &))); - - widget = new ResizableDragWidget(0); - widget->setContentsMargins(10,10,10,10); - widget->setProperty("name", "main"); - - KConfigGroup cfg = KGlobal::config()->group(""); - - if (!is_login) { - widget->setAttribute(Qt::WA_ShowWithoutActivating); - widget->setAttribute(Qt::WA_DeleteOnClose, false); - } - - widget->setWindowFlags( Qt::ToolTip | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint ); - - dock = new KbdDock(widget->winId()); - connect(dock, SIGNAL(requestVisibility()), widget, SLOT(toggleVisibility())); - - tray = new KbdTray(widget); - connect(tray, SIGNAL(requestVisibility()), widget, SLOT(toggleVisibility())); - - - layout = new QGridLayout(widget); - layout->setContentsMargins(0,0,0,0); - widget->setLayout(layout); - - xkbd = new X11Keyboard(this); - - themeLoader = new ThemeLoader(widget); - - connect(themeLoader, SIGNAL(partLoaded(MainWidget*, int, int)), this, SLOT(partLoaded(MainWidget*, int, int))); - connect(themeLoader, SIGNAL(buttonLoaded(VButton*)), this, SLOT(buttonLoaded(VButton*))); - - KMenu *cmenu = tray->contextMenu(); - - KAction *chooseFontAction = new KAction(KIcon("preferences-desktop-font"), i18nc("@action:inmenu", "Choose Font..."), this); - connect(chooseFontAction, SIGNAL(triggered(bool)), this, SLOT(chooseFont()) ); - cmenu->addAction(chooseFontAction); - - KToggleAction *autoResizeAction = new KToggleAction(i18nc("@action:inmenu", "Auto Resize Font"), this); - bool autoResizeEnabled = cfg.readEntry("autoresfont",true); - autoResizeAction->setChecked(autoResizeEnabled); - widget->setProperty("autoresfont", autoResizeEnabled); - cmenu->addAction(autoResizeAction); - connect(autoResizeAction, SIGNAL(triggered(bool)), this, SLOT(autoResizeFont(bool))); - - bool blur = cfg.readEntry("blurBackground", QVariant(true)).toBool(); - - KToggleAction *blurBackgroundAction = new KToggleAction(i18nc("@action:inmenu", "Blur Background"), this); - blurBackgroundAction->setChecked(blur); - cmenu->addAction(blurBackgroundAction); - widget->blurBackground(blur); - connect(blurBackgroundAction, SIGNAL(triggered(bool)), widget, SLOT(blurBackground(bool))); - dock->blurBackground(blur); - connect(blurBackgroundAction, SIGNAL(triggered(bool)), dock, SLOT(blurBackground(bool))); - widget->blurBackground(blur); - dock->blurBackground(blur); - - bool dockVisible = cfg.readEntry("showdock", QVariant(false)).toBool(); - KToggleAction *showDockAction = new KToggleAction(i18nc("@action:inmenu", "Show Dock"), this); - showDockAction->setChecked(dockVisible); - cmenu->addAction(showDockAction); - connect(showDockAction, SIGNAL(triggered(bool)), dock, SLOT(setVisible(bool))); - - bool isLocked = cfg.readEntry("locked", QVariant(false)).toBool(); - KToggleAction *lockOnScreenAction = new KToggleAction(i18nc("@action:inmenu", "Lock on Screen"), this); - lockOnScreenAction->setChecked(isLocked); - cmenu->addAction(lockOnScreenAction); - connect(lockOnScreenAction, SIGNAL(triggered(bool)), widget, SLOT(setLocked(bool))); - - bool stickyModKeys = cfg.readEntry("stickyModKeys", QVariant(false)).toBool(); - KToggleAction *stickyModKeysAction = new KToggleAction(i18nc("@action:inmenu", "Sticky Modifier Keys"), this); - stickyModKeysAction->setChecked(stickyModKeys); - cmenu->addAction(stickyModKeysAction); - connect(stickyModKeysAction, SIGNAL(triggered(bool)), this, SLOT(setStickyModKeys(bool))); - widget->setProperty("stickyModKeys", stickyModKeys); - - QFont font = cfg.readEntry("font", widget->font()); - widget->setFont(font); - - QString colorsFilename = cfg.readEntry("colors"); - QMenu *colors = new QMenu(widget); - themeLoader->findColorStyles(colors, colorsFilename); - cmenu->addMenu(colors); - connect(themeLoader, SIGNAL(colorStyleChanged()), widget, SLOT(repaint())); - connect(themeLoader, SIGNAL(colorStyleChanged()), dock, SLOT(repaint())); - connect(blurBackgroundAction, SIGNAL(triggered(bool)), themeLoader, SLOT(reloadColorStyle())); - - KHelpMenu *helpMenu = new KHelpMenu(widget, KCmdLineArgs::aboutData()); - cmenu->addMenu((QMenu*)helpMenu->menu()); - - QString themeName = cfg.readEntry("layout", "standart"); - themeLoader->loadTheme(themeName); - widget->setProperty("layout", themeName); - - QSize defaultSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); - QDesktopWidget *pDesktop = QApplication::desktop(); - - QRect screenGeometry = pDesktop->availableGeometry(pDesktop->underMouse()); - qDebug() << "ScreenGeometry: " << screenGeometry; - - QPoint bottomRight = screenGeometry.bottomRight()-QPoint(defaultSize.width(), defaultSize.height()); - - QRect widgetGeometry(bottomRight, defaultSize); - qDebug() << "widgetGeometry: " << widgetGeometry; - - QRect c_geometry = cfg.readEntry("geometry", widgetGeometry); - if (!screenGeometry.contains(c_geometry, true)) { - c_geometry = widgetGeometry; - } - widget->setGeometry(c_geometry); - - QPoint pos = c_geometry.topLeft(); - pos.setY(pos.y()-dock->height()); - - QRect dockGeometry(pos, dock->size()); - - QRect c_dock_geometry = cfg.readEntry("dockGeometry", dockGeometry); - if (!screenGeometry.contains(c_dock_geometry, true)) { - c_dock_geometry = dockGeometry; - } - dock->setGeometry(c_dock_geometry); - - widget->show(); - - bool extensionVisible = cfg.readEntry("extentVisible", QVariant(true)).toBool(); - if (!extensionVisible) { - toggleExtension(); - } - - setQuitOnLastWindowClosed (is_login); - - connect(this, SIGNAL(aboutToQuit()), this, SLOT(storeConfig())); - emit fontUpdated(widget->font()); - - if (dockVisible && !is_login) { - dock->show(); - } - - xkbd->start(); - - if (!is_login) { - bool vis = cfg.readEntry("visible", QVariant(true)).toBool(); - if (!vis ) { - widget->showMinimized(); - } - widget->setWindowTitle("kvkbd"); - tray->setStatus(KStatusNotifierItem::Active); - } else { - QTimer *timer = new QTimer(this); - timer->setInterval(1000); - connect(timer, SIGNAL(timeout()), widget, SLOT(raise())); - timer->start(); - widget->setWindowTitle("kvkbd.login"); - } -} -#undef DEFAULT_WIDTH -#undef DEFAULT_HEIGHT - -KvkbdApp::~KvkbdApp() -{ -} - -void KvkbdApp::storeConfig() -{ - KConfigGroup cfg = KGlobal::config()->group(""); - - cfg.writeEntry("visible", widget->isVisible()); - cfg.writeEntry("geometry", widget->geometry()); - cfg.writeEntry("locked", widget->isLocked()); - cfg.writeEntry("stickyModKeys", widget->property("stickyModKeys")); - - cfg.writeEntry("showdock", dock->isVisible()); - cfg.writeEntry("dockGeometry", dock->geometry()); - - cfg.writeEntry("layout", widget->property("layout")); - cfg.writeEntry("colors", widget->property("colors")); - cfg.writeEntry("font", widget->font()); - cfg.writeEntry("autoresfont", widget->property("autoresfont").toBool()); - cfg.writeEntry("blurBackground", widget->property("blurBackground").toBool()); - - MainWidget *prt = parts.value("extension"); - if (prt) { - cfg.writeEntry("extentVisible", prt->isVisible()); - } - - cfg.sync(); - -} - - -void KvkbdApp::autoResizeFont(bool mode) -{ - widget->setProperty("autoresfont", QVariant(mode)); - emit fontUpdated(widget->font()); - -} -void KvkbdApp::setStickyModKeys(bool mode) -{ - widget->setProperty("stickyModKeys", QVariant(mode)); -} - -void KvkbdApp::chooseFont() -{ - bool restore = false; - - if (widget->isVisible()) { - widget->hide(); - restore = true; - } - - QFont widgetFont = widget->font(); - - int result = KFontDialog::getFont(widgetFont, KFontChooser::NoDisplayFlags, widget); - if (result == KFontDialog::Accepted) { - - widget->setFont(widgetFont); - emit fontUpdated(widgetFont); - - } - - if (restore) { - widget->show(); - } - - -} - - - - -void KvkbdApp::buttonLoaded(VButton *btn) -{ - if (btn->property("modifier").toBool() == true) { - modKeys.append(btn); - } else { - QObject::connect(btn, SIGNAL(keyClick(unsigned int)), xkbd, SLOT(processKeyPress(unsigned int)) ); - } - QString bAction = btn->property("action").toString(); - - if (bAction.length()>0) { - connect(btn, SIGNAL(clicked()), signalMapper, SLOT(map())); - signalMapper->setMapping(btn, bAction); - actionButtons.insertMulti(bAction, btn); - } - - QString tooltip = btn->property("tooltip").toString(); - if (tooltip.length()>0) { - btn->setToolTip(tooltip); - - } - -} -void KvkbdApp::partLoaded(MainWidget *vPart, int total_rows, int total_cols) -{ - // std::cout << "Col Strech: " << total_cols << std::endl; - // std::cout << "Row Strech: " << total_rows << std::endl; - - QString partName = vPart->property("part").toString(); - - int row_pos = 0; - int col_pos = 0; - - if (layoutPosition.count()>0) { - QString partName = layoutPosition.keys().at(0); - QRect lp = layoutPosition.value(partName); - col_pos = lp.width(); - } - - layout->addWidget(vPart,row_pos,col_pos,total_rows,total_cols); - // std::cout << "Insert to layout: " << qPrintable(partName) << " RowStart: " << row_pos << " ColStart: " << col_pos << " RowSpan: " << total_rows << " ColSpan: " << total_cols << std::endl; - parts.insert(partName, vPart); - layoutPosition.insert(partName, QRect(col_pos,row_pos,total_cols,total_rows)); - - QObject::connect(xkbd, SIGNAL(layoutUpdated(int,QString)), vPart, SLOT(updateLayout(int,QString))); - QObject::connect(xkbd, SIGNAL(groupStateChanged(const ModifierGroupStateMap&)), vPart, SLOT(updateGroupState(const ModifierGroupStateMap&))); - QObject::connect(xkbd, SIGNAL(keyProcessComplete(unsigned int)), this, SLOT(keyProcessComplete(unsigned int))); - - QObject::connect(this, SIGNAL(textSwitch(bool)), vPart, SLOT(textSwitch(bool))); - QObject::connect(this, SIGNAL(fontUpdated(const QFont&)), vPart, SLOT(updateFont(const QFont&))); - - - -} -void KvkbdApp::keyProcessComplete(unsigned int) -{ - if (widget->property("stickyModKeys").toBool()) return; - - QListIterator itr(modKeys); - while (itr.hasNext()) { - VButton *mod = itr.next(); - if (mod->isChecked()) { - mod->click(); - } - } -} - -void KvkbdApp::buttonAction(const QString &action) -{ - - if (QString::compare(action , "toggleVisibility")==0) { - if (!is_login) { - widget->toggleVisibility(); - } - } - else if (QString::compare(action , "toggleExtension")==0) { - - toggleExtension(); - } - else if (QString::compare(action, "shiftText")==0) { - if (actionButtons.contains(action)) { - QList buttons = actionButtons.values(action); - QListIterator itr(buttons); - bool setShift = false; - while (itr.hasNext()) { - VButton *btn = itr.next(); - if (btn->isCheckable() && btn->isChecked()) setShift=true; - } - emit textSwitch(setShift); - } - } -} -void KvkbdApp::toggleExtension() -{ - MainWidget *prt = parts.value("extension"); - if (prt->isVisible()) { - prt->hide(); - layout->removeWidget(prt); - } - else { - QString partName = prt->property("part").toString(); - QRect span = layoutPosition.value(partName); - layout->addWidget(prt,span.y(),span.x(), span.height(), span.width()); - prt->show(); - } -} - -#include "moc_kvkbdapp.cpp" diff --git a/kvkbd/src/kvkbdapp.h b/kvkbd/src/kvkbdapp.h deleted file mode 100644 index fa60a341..00000000 --- a/kvkbd/src/kvkbdapp.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * - * 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 3 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, see . - * - */ - -#ifndef KVKBDAPP_H -#define KVKBDAPP_H - -#include -#include -#include -#include - -#include "resizabledragwidget.h" -#include "mainwidget.h" -#include "kbdtray.h" -#include "vbutton.h" -#include "themeloader.h" -#include "kbddock.h" -#include "vkeyboard.h" - -class KvkbdApp : public KUniqueApplication -{ - Q_OBJECT - -public: - KvkbdApp(bool loginhelper=false); - ~KvkbdApp(); - -public slots: - void keyProcessComplete(unsigned int); - - void buttonAction(const QString& action); - void storeConfig(); - void toggleExtension(); - - void chooseFont(); - void autoResizeFont(bool mode); - void setStickyModKeys(bool mode); - - void partLoaded(MainWidget *vPart, int total_rows, int total_cols); - void buttonLoaded(VButton *btn); - -protected: - - ResizableDragWidget *widget; - - KbdTray *tray; - - - QMap colorMap; - QMap parts; - QMap layoutPosition; - - QSignalMapper *signalMapper; - - - QGridLayout *layout; - - - QMap actionButtons; - - ThemeLoader *themeLoader; - - KbdDock *dock; - - VKeyboard *xkbd; - - bool is_login; - -signals: - void textSwitch(bool); - void fontUpdated(const QFont& font); - void startupCompleted(); -}; - -#endif // KVKBDAPP_H diff --git a/kvkbd/src/main.cpp b/kvkbd/src/main.cpp deleted file mode 100644 index db872352..00000000 --- a/kvkbd/src/main.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - - - -#include "kvkbdapp.h" -#include -#include - -static const char description[] = - I18N_NOOP("A virtual keyboard for KDE"); - -static const char version[] = "0.7.2"; - -#include - -void findLoginWindow() -{ - unsigned int numkids, i, scrn; - Window r, p; - Window *kids=0; - //XWindowAttributes attr; - Window root; - Display *dipsy=0; - char *win_name=0; - - dipsy = XOpenDisplay(0); - if (!dipsy) return; - - scrn = DefaultScreen(dipsy); - root = RootWindow(dipsy, scrn); - - XQueryTree(dipsy, root, &r, &p, &kids, &numkids); - - for (i = 0; i < numkids; ++i) { - XFetchName(dipsy, kids[i], &win_name); - QString c(win_name); - if (c=="kvkbd.login") { - long wid = kids[i]; - XDestroyWindow(dipsy,wid); - XFlush(dipsy); - i=numkids; - } - XFree(win_name); - } - XCloseDisplay(dipsy); -} - -int main(int argc, char **argv) -{ - setenv("KSNI_NO_DBUSMENU", "1", 1); - - KAboutData about("kvkbd", 0, ki18n("Kvkbd"), version, ki18n(description), - KAboutData::License_LGPL_V3, ki18n("(C) 2007-2014 The Kvkbd Developers")); - about.addAuthor(ki18n("Todor Gyumyushev"), ki18n("Original Author"), "yodor1@gmail.com"); - about.addAuthor(ki18n("Guillaume Martres"), ki18n("KDE4 port"), "smarter@ubuntu.com"); - about.setProgramIconName("preferences-desktop-keyboard"); - - KCmdLineArgs::init(argc, argv, &about); - KCmdLineOptions options; - - options.add("loginhelper", ki18n("Stand alone version for use with KDM or XDM.\n" - "See Kvkbd Handbook for information on how to use this option.")); - KCmdLineArgs::addCmdLineOptions(options); - - const bool is_login = KCmdLineArgs::parsedArgs()->isSet("loginhelper"); - if (!is_login) { - findLoginWindow(); - } - - KvkbdApp app(is_login); - - return app.exec(); -} - - - diff --git a/kvkbd/src/mainwidget.cpp b/kvkbd/src/mainwidget.cpp deleted file mode 100644 index 26b9b26b..00000000 --- a/kvkbd/src/mainwidget.cpp +++ /dev/null @@ -1,141 +0,0 @@ -#include "mainwidget.h" - -#include -#include - -#include "vbutton.h" - - -MainWidget::MainWidget(QWidget *parent) : QWidget(parent) -{ - -} - -void MainWidget::setBaseSize(int w, int h) -{ - bsize.setWidth(w); - bsize.setHeight(h); - -} -void MainWidget::updateGroupState(const ModifierGroupStateMap& stateMap) -{ - QObjectList buttons = this->children(); - ModifierGroupStateMapIterator itr(stateMap); - QList text; - - while (itr.hasNext()) { - itr.next(); - QString group_name = itr.key(); - bool state = itr.value(); - - for (int a=0; aproperty("group_toggle").toString(); - QString btn_group_name = btn->property("group_name").toString(); - QString group_label = btn->property("group_label").toString(); - QString label = btn->property("label").toString(); - - if (QString::compare(group_toggle,group_name)==0) { - - if (group_label.length()>0 && label.length()>0) { - if (state) { - btn->setText(group_label); - } - else { - btn->setText(label); - } - } - - } - else if (QString::compare(group_name,"capslock")==0) { - - btn->setCaps(state); - btn->updateText(); - } - - if (QString::compare(btn_group_name, group_name)==0) { - btn->setChecked(state); - } - - } - - } - -} - -void MainWidget::textSwitch(bool setShift) -{ - QObjectList buttons = this->children(); - - for (int a=0; asetShift(setShift); - btn->updateText(); - } - -} -void MainWidget::updateLayout(int index, QString layout_name) -{ - QObjectList buttons = this->children(); - - VKeyboard *vkbd = (VKeyboard*)QObject::sender(); - - for (int a=0; aproperty("label").toString().length()<1) { - ButtonText text; - - vkbd->textForKeyCode(btn->getKeyCode(), text); - btn->setButtonText(text); - btn->updateText(); - - } - - if (btn->objectName()=="currentLayout") { - btn->setText(layout_name); - } - } - -} - - -void MainWidget::resizeEvent(QResizeEvent *ev) -{ - - const QSize& size = ev->size(); - - double dw = (double)size.width() / (double)bsize.width(); - double dh = (double)size.height() / (double)bsize.height(); - - QObjectList buttons = this->children(); - for (int a=0; aVRect(); - - btn->setGeometry((geom.x() * dw), (geom.y() * dh), (geom.width() * dw), (geom.height() * dh)); - - } - - updateFont(this->parentWidget()->font()); - -} - -void MainWidget::updateFont(const QFont& widgetFont) -{ - - int fontSize = widgetFont.pointSize(); - if ( parentWidget()->property("autoresfont").toBool() ) { - fontSize = (8.0 / 500.0) * this->parentWidget()->size().width(); - } - QString buttonStyle = QString("VButton { font-family:'%1'; font-size: %2px; font-weight:%3; font-style: %4; }").arg(widgetFont.family()).arg(fontSize).arg(widgetFont.bold() ? "bold" : "normal").arg(widgetFont.italic() ? "italic" : "normal"); - this->setStyleSheet(buttonStyle); - -} -#include "moc_mainwidget.cpp" diff --git a/kvkbd/src/mainwidget.h b/kvkbd/src/mainwidget.h deleted file mode 100644 index a62d4033..00000000 --- a/kvkbd/src/mainwidget.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef MAINWIDGET_H -#define MAINWIDGET_H - -#include -#include -#include -#include -#include - -#include "vkeyboard.h" - - -class MainWidget : public QWidget -{ - Q_OBJECT - -public: - explicit MainWidget(QWidget *parent = 0); - void setBaseSize(int w, int h); - -signals: - -public slots: - void textSwitch(bool); - void updateLayout(int index, QString layout_name); - void updateGroupState(const ModifierGroupStateMap&); - void updateFont(const QFont& widgetFont); - -protected: - virtual void resizeEvent(QResizeEvent *ev); - QSize bsize; - -}; - -#endif // MAINWIDGET_H diff --git a/kvkbd/src/org.kde.kvkbd.Dock.xml b/kvkbd/src/org.kde.kvkbd.Dock.xml deleted file mode 100644 index a554dfe5..00000000 --- a/kvkbd/src/org.kde.kvkbd.Dock.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/kvkbd/src/org.kde.kvkbd.Kvkbd.xml b/kvkbd/src/org.kde.kvkbd.Kvkbd.xml deleted file mode 100644 index dcc16cbb..00000000 --- a/kvkbd/src/org.kde.kvkbd.Kvkbd.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - diff --git a/kvkbd/src/resizabledragwidget.cpp b/kvkbd/src/resizabledragwidget.cpp deleted file mode 100644 index e7a9e43e..00000000 --- a/kvkbd/src/resizabledragwidget.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of the Kvkbd project. - * Copyright (C) 2007-2014 Todor Gyumyushev - * Copyright (C) 2008 Guillaume Martres - * - * 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 3 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, see . - * - */ - -#include "resizabledragwidget.h" - -#include -#include -#include - -#include - -ResizableDragWidget::ResizableDragWidget(QWidget *parent) : - DragWidget(parent), doResize(false) -{ -} - -ResizableDragWidget::~ResizableDragWidget() -{ -} - -void ResizableDragWidget::mousePressEvent(QMouseEvent * ev) -{ - // std::cout << "ResizableDragWidget::mousePressEvent" << std::endl; - - DragWidget::mousePressEvent(ev); - - if (dragPoint.x() > width() - 20 && dragPoint.x() < width() && dragPoint.y() > height() - 20 && dragPoint.y() < height()) { - - dragPoint = QPoint(width() - ev->pos().x(), height() - ev->pos().y()); - - dragged = false; - doResize = true; - } - -} - -void ResizableDragWidget::mouseMoveEvent(QMouseEvent * ev) -{ - // std::cout << "ResizableDragWidget::mouseMoveEvent | Resize: " << doResize << " | Dragged: " << dragged << std::endl; - - - DragWidget::mouseMoveEvent(ev); - - if (!doResize) return; - - QPoint curr(ev->globalPos().x(), ev->globalPos().y()); - QPoint pos = QWidget::pos(); - int nw = curr.x() - pos.x() + dragPoint.x(); - int nh = curr.y() - pos.y() + dragPoint.y(); - - resize(nw, nh); - -} - -void ResizableDragWidget::mouseReleaseEvent(QMouseEvent * e) -{ - DragWidget::mouseReleaseEvent(e); - - doResize = false; - -} - -void ResizableDragWidget::paintEvent(QPaintEvent *ev) -{ - - DragWidget::paintEvent(ev); - - QPainter p(this); - - for (int a = 0; a < 20; a += 4) { - - p.setPen(QColor(170, 170, 170)); - p.drawLine(width() - 20 + a, height() - 2, width() - 2, height() - 20 + a); - p.setPen(QColor(200, 200, 200)); - p.drawLine(width() - 19 + a, height() - 2, width() - 2, height() - 19 + a); - } - -} - - - -#include "moc_resizabledragwidget.cpp" diff --git a/kvkbd/src/resizabledragwidget.h b/kvkbd/src/resizabledragwidget.h deleted file mode 100644 index 492f92d5..00000000 --- a/kvkbd/src/resizabledragwidget.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef RESIZABLEDRAGWIDGET_H -#define RESIZABLEDRAGWIDGET_H - -#include "dragwidget.h" - -class ResizableDragWidget : public DragWidget -{ - Q_OBJECT - -public: - explicit ResizableDragWidget(QWidget *parent = 0); - ~ResizableDragWidget(); - -protected: - virtual void mouseMoveEvent(QMouseEvent * e); - virtual void mousePressEvent(QMouseEvent * e); - virtual void mouseReleaseEvent(QMouseEvent * e); - virtual void paintEvent(QPaintEvent *e); - - bool doResize; -}; - - - -#endif // RESIZABLEDRAGWIDGET_H diff --git a/kvkbd/src/themeloader.cpp b/kvkbd/src/themeloader.cpp deleted file mode 100644 index 00540986..00000000 --- a/kvkbd/src/themeloader.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor - * - * 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 3 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, see . - * - */ - -#include "themeloader.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -int defaultWidth = 25; -int defaultHeight = 25; - -ThemeLoader::ThemeLoader(QWidget *parent) : QObject(parent) -{ - defaultcss = KStandardDirs::locate("data", QString::fromLatin1("kvkbd/themes/standart.css")); - if (defaultcss.isEmpty()) { - kWarning() << "Could not locate standard theme CSS file"; - } - themespath = QFileInfo(defaultcss).path(); - // qDebug() << Q_FUNC_INFO << defaultcss << themespath; -} - -ThemeLoader::~ThemeLoader() -{ -} - -void ThemeLoader::loadTheme(QString& themeName) -{ - QString themePath = QString::fromLatin1("%1/%2").arg(themespath).arg(themeName); - int ret = loadLayout(themePath); - - if (ret != 0) { - kapp->quit(); - } -} - -void ThemeLoader::loadColorFile(const QString& fileName) -{ - lastcolorstyle = fileName; - - QFile themeFile; - - themeFile.setFileName(fileName); - - if (!themeFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - QMessageBox::information(0, "Error", QString("Unable to open css file: %1").arg(themeFile.fileName())); - return; - } - - QString themeData = themeFile.readAll(); - if (!(QWidget*)parent()->property("blurBackground").toBool()) { - themeData = themeData.replace(",30%);", ");"); - } - - ((QWidget*)parent())->setStyleSheet(themeData); - ((QWidget*)parent())->setProperty("colors", fileName); - themeFile.close(); - - ((QWidget*)parent())->repaint(); - - emit colorStyleChanged(); -} - -void ThemeLoader::loadColorStyle() -{ - QAction *action = (QAction*)QObject::sender(); - - QFileInfo info(action->data().toString()); - - loadColorFile(info.absoluteFilePath()); -} - -void ThemeLoader::reloadColorStyle() -{ - loadColorFile(lastcolorstyle); -} - -void ThemeLoader::findColorStyles(QMenu *colors, const QString& configSelectedStyle) -{ - KStandardDirs kdirs; - QStringList dirs = kdirs.findDirs("data", "kvkbd"); - - QActionGroup *color_group = new QActionGroup(colors); - color_group->setExclusive(true); - - - QAction *item = new QAction(colors); - item->setCheckable(true); - item->setText("standart"); - item->setData(defaultcss); - colors->addAction(item); - color_group->addAction(item); - - colors->setTitle("Color Style"); - colors->setIcon(KIcon("preferences-desktop-color")); - QListIterator itr(dirs); - while (itr.hasNext()) { - QString data_path = itr.next() + "colors"; - - QFileInfo info(data_path); - if (info.isDir() && info.isReadable()) { - QDir colors_dir(info.absoluteFilePath(), "*.css"); - QFileInfoList list = colors_dir.entryInfoList(); - - QListIterator itr(list); - while (itr.hasNext()) { - QFileInfo fileInfo = itr.next(); - //std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10) - // .arg(fileInfo.fileName())); - //std::cout << std::endl; - - QAction *item = new QAction(this); - item->setCheckable(true); - - item->setText(fileInfo.baseName()); - item->setData(fileInfo.absoluteFilePath()); - colors->addAction(item); - color_group->addAction(item); - - - } - - } - - } - - QString selectedStyle = configSelectedStyle; - if (selectedStyle.length() < 1) { - selectedStyle = defaultcss; - } - QAction *selectedAction = 0; - - QListIterator itrActions(color_group->actions()); - while (itrActions.hasNext()) { - QAction *item = itrActions.next(); - - if (item->data().toString() == selectedStyle) { - item->setChecked(true); - selectedAction = item; - } - - connect(item, SIGNAL(triggered(bool)), this, SLOT(loadColorStyle())); - } - - if (selectedAction) { - selectedAction->trigger(); - } - -} - - -int ThemeLoader::loadLayout(const QString& themeName) -{ - QFile themeFile; - - QDomDocument doc; - - themeFile.setFileName(QString::fromLatin1("%1.xml").arg(themeName)); - - if (!themeFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - QMessageBox::information(0, "Error", QString("Unable to open theme xml file: %1").arg(themeFile.fileName())); - return -1; - } - if (!doc.setContent(&themeFile)) { - QMessageBox::information(0, "Error", QString("Unable to parse theme xml file: %1").arg(themeFile.fileName())); - return -2; - } - themeFile.close(); - - - QDomElement docElem = doc.documentElement(); - - QDomNodeList wList = docElem.elementsByTagName("buttonWidth"); - QDomNode wNode = wList.at(0); - - //read default button width - defaultWidth = wNode.attributes().namedItem("width").toAttr().value().toInt(); - - QDomNodeList nList = (wNode.toElement()).elementsByTagName("item"); - for (int a=0; a"<< width << std::endl; - } - - wList = docElem.elementsByTagName("buttonHeight"); - wNode = wList.at(0); - nList = (wNode.toElement()).elementsByTagName("item"); - for (int a=0; a"<< height << std::endl; - } - - wList = docElem.elementsByTagName("spacingHints"); - wNode = wList.at(0); - nList = (wNode.toElement()).elementsByTagName("item"); - for (int a=0; a"<< width << std::endl; - } - - wList = docElem.elementsByTagName("part"); - wNode = wList.at(0); - - //insert main part to widget - QString partName = wNode.attributes().namedItem("name").toAttr().value(); - - MainWidget *part = new MainWidget((QWidget*)parent()); - part->setProperty("part", "main"); - - - loadKeys(part, wNode); - - wList = wNode.childNodes(); - - for (int a=0; asetProperty("part", "extension"); - loadKeys(widget1, wNode); - break; - } - } - - return 0; -} -bool ThemeLoader::applyProperty(VButton *btn, const QString& attributeName, QDomNamedNodeMap *attributes, QVariant defaultValue) -{ - bool ret = false; - - QString attributeValue = attributes->namedItem(attributeName).toAttr().value(); - if (attributeValue.length()>0) { - btn->setProperty(qPrintable(attributeName), attributeValue); - ret = true; - } else { - if (defaultValue.toString().length()>0) { - btn->setProperty(qPrintable(attributeName), defaultValue); - ret = true; - } - } - return ret; -} -void ThemeLoader::loadKeys(MainWidget *vPart, const QDomNode& wNode) -{ - int max_sx = 0; - int max_sy = 0; - - int sx = 0; - int sy = 0; - int rowMarginLeft = 0; - int rowSpacingY = 0; - int rowSpacingX = 0; - - int total_cols = 0; - int total_rows = 0; - - QDomNodeList nList = wNode.childNodes(); - - //(wNode.toElement()).elementsByTagName("row"); - - for (int a=0; a0) { - btn->setObjectName(button_name); - } - - - if (applyProperty(btn, "label", &attributes)) { - btn->setText(btn->property("label").toString()); - } - - applyProperty(btn, "group_label", &attributes); - - applyProperty(btn, "group_toggle", &attributes); - - applyProperty(btn, "group_name", &attributes); - - applyProperty(btn, "colorGroup", &attributes, "normal"); - - applyProperty(btn, "tooltip", &attributes); - - QString modifier = attributes.namedItem("modifier").toAttr().value(); - if (modifier.toInt()>0) { - btn->setProperty("modifier", true); - btn->setCheckable(true); - } - - unsigned int key_code = attributes.namedItem("code").toAttr().value().toInt(); - if (key_code>0) { - btn->setKeyCode(key_code); - } - - if (applyProperty(btn, "action", &attributes)) { - btn->setProperty("action", btn->property("action").toString()); - - } - - - int is_checkable = attributes.namedItem("checkable").toAttr().value().toInt(); - if (is_checkable>0) { - btn->setCheckable(true); - btn->setChecked(false); - } - - btn->move(sx,sy); - btn->resize(buttonWidth, buttonHeight); - btn->storeSize(); - -// btn->setNode(node); - // std::cout << "ColorGroup: " << qPrintable(colorGroup) << std::endl; - - sx+=buttonWidth+rowSpacingX; - - emit buttonLoaded(btn); - } else if (node.toElement().tagName()=="spacing") { - - QString widthHint = attributes.namedItem("width").toAttr().value(); - QString heightHint = attributes.namedItem("height").toAttr().value(); - - - if (spacingMap.contains(widthHint)) { - int spacingWidth = spacingMap.value(widthHint); - - sx+=spacingWidth; - - - } - if (heightMap.contains(heightHint)) { - int spacingHeight = heightMap.value(heightHint); - - if (spacingHeight>rowHeight) rowHeight = spacingHeight; - - } - - } - - //std::cout << "X=>"<"<max_sx)max_sx = sx; - - sy+=(rowHeight+rowSpacingY); - sx=0+rowMarginLeft; - - if (row_buttons>total_cols)total_cols=row_buttons; - - } - if (sy>max_sy) max_sy = sy; - - vPart->setBaseSize(max_sx, max_sy); - - emit partLoaded(vPart, total_rows, total_cols); -} - -#include "moc_themeloader.cpp" diff --git a/kvkbd/src/themeloader.h b/kvkbd/src/themeloader.h deleted file mode 100644 index bd95b5f1..00000000 --- a/kvkbd/src/themeloader.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor - * - * 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 3 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, see . - * - */ - -#ifndef THEMELOADER_H -#define THEMELOADER_H - -#include - -#include -#include -#include -#include - -#include "mainwidget.h" -#include "vbutton.h" - - -class ThemeLoader : public QObject -{ - Q_OBJECT - -public: - ThemeLoader(QWidget *parent); - ~ThemeLoader(); - - void loadTheme(QString& themeName); - - void loadColorFile(const QString& fileName); - - int loadLayout(const QString& themeName); - - void findColorStyles(QMenu *parent, const QString& selectedStyle); - -protected: - void loadKeys(MainWidget *vPart, const QDomNode& wNode); - bool applyProperty(VButton *btn, const QString& attributeName, QDomNamedNodeMap *attributes, QVariant defaultValue=""); - - QMap widthMap; - QMap heightMap; - QMap spacingMap; - -public slots: - void loadColorStyle(); - void reloadColorStyle(); - -signals: - void partLoaded(MainWidget *vPart, int total_rows, int total_cols); - void buttonLoaded(VButton *btn); - void colorStyleChanged(); - -private: - QString lastcolorstyle; - QString defaultcss; - QString themespath; -}; - -#endif // THEMELOADER_H diff --git a/kvkbd/src/vbutton.cpp b/kvkbd/src/vbutton.cpp deleted file mode 100644 index 7f7cead4..00000000 --- a/kvkbd/src/vbutton.cpp +++ /dev/null @@ -1,179 +0,0 @@ -#include "vbutton.h" -#include - -#define TIMER_INTERVAL_SHORT 40 -#define TIMER_INTERVAL_LONG 200 - -int VButton::RepeatShortDelay = TIMER_INTERVAL_SHORT; -int VButton::RepeatLongDelay = TIMER_INTERVAL_LONG; - - -VButton::VButton(QWidget *parent) : - QPushButton(parent) -{ - - setFocusPolicy(Qt::NoFocus); - setAttribute(Qt::WA_AlwaysShowToolTips); - - keyCode = 0; - - rightClicked = false; - mTextIndex = 0; - isCaps = false; - - keyTimer = new QTimer(this); - - connect(keyTimer, SIGNAL(timeout()), this, SLOT(repeatKey())); - -} - -void VButton::storeSize() -{ - vpos = geometry(); - -} - -QRect VButton::VRect() -{ - return vpos; - -} - -void VButton::setKeyCode(unsigned int keyCode) -{ - this->keyCode = keyCode; -} - -unsigned int VButton::getKeyCode() -{ - return this->keyCode; - -} - -void VButton::setButtonText(const ButtonText& text) -{ - this->mButtonText = text; -} - -ButtonText VButton::buttonText() const -{ - return this->mButtonText; -} - -void VButton::setTextIndex(int index) -{ - this->mTextIndex = index; -} - -int VButton::textIndex() -{ - return this->mTextIndex; - -} - -void VButton::nextText() -{ - if (mButtonText.count()<1)return; - - mTextIndex++; - int textCount = mButtonText.count()-1; - if (mTextIndex>textCount) mTextIndex=0; - - - updateText(); - - -} - -void VButton::setCaps(bool mode) -{ - if (mButtonText.count()<1)return; - - isCaps = mode; - - - -} -void VButton::setShift(bool mode) -{ - if (mButtonText.count()<1)return; - if (mode) { - this->mTextIndex = 1; - } - else { - this->mTextIndex = 0; - - } - isShift = mode; -} -void VButton::updateText() -{ - if (mButtonText.count()<1)return; - - QString text = mButtonText.at(this->mTextIndex); - if (text == "&") { - text+="&"; - } - - bool doCaps = isCaps ; - if (isShift) doCaps = !doCaps; - - if (doCaps) { - text = text.toUpper(); - } - else { - text = text.toLower(); - } - - this->setText(text); - -} - -void VButton::sendKey() -{ - emit keyClick(this->keyCode); -} - -void VButton::mousePressEvent(QMouseEvent *e) -{ - - rightClicked = false; - if (e->button() == Qt::RightButton) { - - rightClicked = true; - - } - QPushButton::mousePressEvent(e); - - if (this->keyCode>0) { - sendKey(); - - if (!isCheckable()) { - if (!keyTimer->isActive()) { - //200 ms is a bit more that the time needed for a single click - keyTimer->start(VButton::RepeatLongDelay); - - } - - } - } -} - -void VButton::mouseReleaseEvent(QMouseEvent *e) -{ - - if (keyTimer->isActive())keyTimer->stop(); - QPushButton::mouseReleaseEvent(e); -} - -void VButton::repeatKey() -{ - //if the user is still pressing the button after 200 ms, we assume - //he wants the key to be quickly repeated and we decrease the interval - if (keyTimer->interval() == VButton::RepeatLongDelay) { - //TODO: make this configurable? - keyTimer->setInterval(VButton::RepeatShortDelay); - } - - sendKey(); -} diff --git a/kvkbd/src/vbutton.h b/kvkbd/src/vbutton.h deleted file mode 100644 index 56898411..00000000 --- a/kvkbd/src/vbutton.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef VBUTTON_H -#define VBUTTON_H - -#include -#include -#include -#include -#include -#include -#include "x11keyboard.h" - -class VButton : public QPushButton -{ - Q_OBJECT - -public: - explicit VButton(QWidget *parent = 0); - - void storeSize(); - - void reposition(const QSize &baseSize, const QSize &size); - QRect VRect(); - - unsigned int getKeyCode(); - void setKeyCode(unsigned int keyCode); - - void setButtonText(const ButtonText& text); - ButtonText buttonText() const; - - void setTextIndex(int index); - int textIndex(); - void updateText(); - void nextText(); - void setCaps(bool mode); - void setShift(bool mode); - -signals: - void keyClick(unsigned int); - void buttonAction(const QString& action); - -public slots: - void sendKey(); - -protected: - unsigned int keyCode; - QRect vpos; - - bool rightClicked; - QTimer *keyTimer; - - - ButtonText mButtonText; - int mTextIndex; - - bool isCaps; - bool isShift; - - static int RepeatShortDelay; - static int RepeatLongDelay; - -protected slots: - void mousePressEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void repeatKey(); - - -}; - -#endif // VBUTTON_H diff --git a/kvkbd/src/vkeyboard.cpp b/kvkbd/src/vkeyboard.cpp deleted file mode 100644 index 94c1e9a8..00000000 --- a/kvkbd/src/vkeyboard.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor Gyumyushev - * - * 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 3 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, see . - * - */ - -#include "vkeyboard.h" - -VKeyboard::VKeyboard(QObject *parent) : QObject(parent) -{ - -} - -VKeyboard::~VKeyboard() -{ -} - -#include "moc_vkeyboard.cpp" diff --git a/kvkbd/src/vkeyboard.h b/kvkbd/src/vkeyboard.h deleted file mode 100644 index f8b2a8d7..00000000 --- a/kvkbd/src/vkeyboard.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor - * - * 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 3 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, see . - * - */ - -#ifndef VKEYBOARD_H -#define VKEYBOARD_H - -#include -#include -#include -#include -#include - -//caps state, numlock state -typedef QMap ModifierGroupStateMap; -typedef QMapIterator ModifierGroupStateMapIterator; -//normal text, shift text -typedef QList ButtonText; - -class VKeyboard : public QObject -{ - Q_OBJECT - -public: - VKeyboard(QObject *parent=0); - virtual ~VKeyboard(); - - virtual void textForKeyCode(unsigned int keyCode, ButtonText& text)=0; - -public slots: - virtual void processKeyPress(unsigned int)=0; - virtual void queryModState()=0; - virtual void layoutChanged()=0; - virtual void start()=0; - -signals: - //key sent successfully - void keyProcessComplete(unsigned int); - - void groupStateChanged(const ModifierGroupStateMap& modifier_state); - - //layout index in list, layout caption - void layoutUpdated(int, QString); -}; - -#endif // VKEYBOARD_H diff --git a/kvkbd/src/x11keyboard.cpp b/kvkbd/src/x11keyboard.cpp deleted file mode 100644 index 078d6efc..00000000 --- a/kvkbd/src/x11keyboard.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor Gyumyushev - * - * 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 3 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, see . - * - */ - -#include "x11keyboard.h" - -#include -#include -#include - -#include -#include -#include - -#include "vbutton.h" - -extern QList modKeys; - -X11Keyboard::X11Keyboard(QObject *parent) - : VKeyboard(parent), - kkeyboardlayout(this), - layout_index(0) -{ - connect(&kkeyboardlayout, SIGNAL(layoutChanged()), this, SLOT(layoutChanged())); - - groupTimer = new QTimer(parent); - groupTimer->setInterval(250); - - - groupState.insert("capslock", this->queryModKeyState(XK_Caps_Lock)); - groupState.insert("numlock", this->queryModKeyState(XK_Num_Lock)); - - connect(groupTimer, SIGNAL(timeout()), this, SLOT(queryModState())); -} - -X11Keyboard::~X11Keyboard() -{ -} - -void X11Keyboard::start() -{ - layoutChanged(); - emit groupStateChanged(groupState); - groupTimer->start(); -} - -void X11Keyboard::processKeyPress(unsigned int keyCode) -{ - groupTimer->stop(); - sendKey(keyCode); - emit keyProcessComplete(keyCode); - groupTimer->start(); - -} -void X11Keyboard::sendKey(unsigned int keycode) -{ - Window currentFocus; - int revertTo; - - Display *display = QX11Info::display(); - XGetInputFocus(display, ¤tFocus, &revertTo); - - QListIterator itr(modKeys); - while (itr.hasNext()) { - VButton *mod = itr.next(); - if (mod->isChecked()) { - XTestFakeKeyEvent(display, mod->getKeyCode(), true, 2); - } - } - - XTestFakeKeyEvent(display, keycode, true, 2); - XTestFakeKeyEvent(display, keycode, false, 2); - - itr.toFront(); - while (itr.hasNext()) { - VButton *mod = itr.next(); - if (mod->isChecked()) { - XTestFakeKeyEvent(display, mod->getKeyCode(), false, 2); - } - } - - XFlush(display); - -} - -bool X11Keyboard::queryModKeyState(KeySym iKey) -{ - int iKeyMask = 0; - Window wDummy1, wDummy2; - int iDummy3, iDummy4, iDummy5, iDummy6; - unsigned int iMask; - - Display* display = QX11Info::display(); - - XModifierKeymap* map = XGetModifierMapping(display); - KeyCode keyCode = XKeysymToKeycode(display, iKey); - if (keyCode == NoSymbol) return false; - for (int i = 0; i < 8; ++i) { - if (map->modifiermap[map->max_keypermod * i] == keyCode) { - iKeyMask = 1 << i; - } - } - XQueryPointer(display, DefaultRootWindow(display), &wDummy1, &wDummy2, &iDummy3, &iDummy4, &iDummy5, &iDummy6, &iMask); - XFreeModifiermap(map); - return ((iMask & iKeyMask) != 0); -} - -void X11Keyboard::queryModState() -{ - - bool curr_caps_state = this->queryModKeyState(XK_Caps_Lock); - bool curr_num_state = this->queryModKeyState(XK_Num_Lock); - - bool caps_state = groupState.value("capslock"); - bool num_state = groupState.value("numlock"); - - groupState.insert("capslock", curr_caps_state); - groupState.insert("numlock", curr_num_state); - - if (curr_caps_state != caps_state || curr_num_state != num_state) { - - emit groupStateChanged(groupState); - } - -} - - -void X11Keyboard::layoutChanged() -{ - - //std::cerr << "LayoutChanged" << std::endl; - - QString current_layout = kkeyboardlayout.layouts().first().layout; - emit layoutUpdated(layout_index, current_layout); - -} -void X11Keyboard::textForKeyCode(unsigned int keyCode, ButtonText& text) -{ - if (keyCode==0) { - text.clear(); - return; - } - - KeyCode button_code = keyCode; - - int keysyms_per_keycode = 0; - - KeySym *keysym = XGetKeyboardMapping (QX11Info::display(), button_code, 1, &keysyms_per_keycode); - - int index_normal = layout_index * 2; - int index_shift = index_normal + 1; - - KeySym normal = keysym[index_normal]; - KeySym shift = keysym[index_shift]; - - - long int ret = kconvert.convert(normal); - long int shiftRet = kconvert.convert(shift); - - QChar normalText = QChar((uint)ret); - QChar shiftText = QChar((uint)shiftRet); - - //cout << "Normal Text " << normalText.toAscii() << " Shift Text: " << shiftText.toAscii() << std::endl; - - text.clear(); - text.append(normalText); - text.append(shiftText); - - XFree ((char *) keysym); - -} - - diff --git a/kvkbd/src/x11keyboard.h b/kvkbd/src/x11keyboard.h deleted file mode 100644 index 008e740e..00000000 --- a/kvkbd/src/x11keyboard.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright (C) 2014 Todor Gyumyushev - * - * 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 3 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, see . - * - */ - -#ifndef X11KEYBOARD_H -#define X11KEYBOARD_H - -#include "keysymconvert.h" -#include - -#include "vkeyboard.h" - -#include -#include -#include -#include -#include -#include - -class X11Keyboard : public VKeyboard -{ - Q_OBJECT - -public: - X11Keyboard(QObject *parent=0); - virtual ~X11Keyboard(); - void textForKeyCode(unsigned int keyCode, ButtonText& text); - -public slots: - virtual void processKeyPress(unsigned int); - virtual void queryModState(); - virtual void layoutChanged(); - virtual void start(); - -protected: - - void sendKey(unsigned int keycode); - - int layout_index; - KKeyboardLayout kkeyboardlayout; - - KeySymConvert kconvert; - - bool queryModKeyState(KeySym keyCode); - ModifierGroupStateMap groupState; - QTimer *groupTimer; - -}; - -#endif // X11KEYBOARD_H diff --git a/kvkbd/themes/CMakeLists.txt b/kvkbd/themes/CMakeLists.txt deleted file mode 100644 index 6fa30476..00000000 --- a/kvkbd/themes/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -install( - FILES - standart.xml - standart.css - DESTINATION ${KDE4_DATA_INSTALL_DIR}/kvkbd/themes -) diff --git a/kvkbd/themes/standart.css b/kvkbd/themes/standart.css deleted file mode 100644 index 5df6d61c..00000000 --- a/kvkbd/themes/standart.css +++ /dev/null @@ -1,70 +0,0 @@ -QWidget[name="main"] { - background-color:rgba(0,0,0,30%); -} - -VButton { - margin:1px; - padding:0px; - border-style: outset; - border-radius: 5px; - border-width: 1px; - - font-size:13px; - font-weight:bold; -} - -VButton:pressed { - border-style: inset; -} -VButton:checked { - border-style: inset; - border-width:2px; -} -VButton:hover { - border-width:2px; -} - -VButton[colorGroup="normal"] { - border-color: #97c5d5; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #97c5d5, stop: 1 #c7f5f5); -} -VButton[colorGroup="system"] { - border-color: #e8a8a5; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #e8a8a5, stop: 1 #f8c8c5); -} -VButton[colorGroup="application"] { - border-color: #a97ca9; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #a97ca9, stop: 1 #a97ca9); -} -VButton[colorGroup="function"] { - border-color: #edc07d; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #edc07d, stop: 1 #edc07d); -} -VButton[colorGroup="enter"] { - border-color: #f1efbe; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #f1efbe, stop: 1 #f1efbe); -} -VButton[colorGroup="cursor"] { - border-color: #a8d1b1; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #a8d1b1, stop: 1 #a8d1b1); -} -VButton[colorGroup="other"] { - border-color: #999999; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #ffffff, stop: 1 #fefefe); -} -VButton[colorGroup="numeric"] { - border-color: #9faaca; - background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, stop: 0 #9faaca, stop: 1 #9faaca); -} -VButton[action="toggleExtension"] { - background-color:gray; - border-color: gray; -} -VButton[action="toggleVisibility"] { - background-color:red; - border-color:red; -} -VButton[colorGroup="nextLayout"] { - background-color:none; - border:none; -} diff --git a/kvkbd/themes/standart.xml b/kvkbd/themes/standart.xml deleted file mode 100644 index 7b66c89d..00000000 --- a/kvkbd/themes/standart.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/okular/shell/okular.desktop b/okular/shell/okular.desktop index 69956d7e..d39b3d15 100755 --- a/okular/shell/okular.desktop +++ b/okular/shell/okular.desktop @@ -131,4 +131,3 @@ InitialPreference=7 Categories=Qt;KDE;Graphics;Office;Viewer; MimeType=application/vnd.kde.okular-archive; StartupNotify=true -X-KDE-HasTrayOption=true