diff --git a/CMakeLists.txt b/CMakeLists.txt --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,8 @@ project(alkimia VERSION 7.0.80) +option(BUILD_QT4 "Build for Qt4" ON) + find_package(ECM 0.0.11 REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) @@ -15,21 +17,67 @@ # check for PkgConfig, Qt and MPIR/GMP find_package(PkgConfig) if(BUILD_QT4) - find_package(Qt4 REQUIRED COMPONENTS QtCore QtDBus QtTest) + find_package(Qt4 REQUIRED COMPONENTS QtCore QtGui QtDBus QtTest QtWebKit QtDeclarative) set(QT_USE_LIBSPREFIX Qt4::Qt) set(ALKIMIA_LIB_SUFFIX "") set(ALKIMIA_INCLUDE_SUFFIX "Qt4") set(ALKIMIA_PATH_SUFFIX) set(PC_TARGET_QTPREFIX Qt) set(PC_TARGET_SUFFIX) + set(_kde4_uninstall_rule_created 1) + find_package(KDE4 REQUIRED) + include(KDE4Defaults) + set(KDE_LIBRARIES ${KDE4_KDECORE_LIBS} ${KDE4_KIO_LIBS}) + include_directories(${KDE4_INCLUDES}) + macro(ki18n_wrap_ui) + kde4_add_ui_files(${ARGN}) + endmacro(ki18n_wrap_ui) + macro(kconfig_add_kcfg_files) + kde4_add_kcfg_files(${ARGN}) + endmacro(kconfig_add_kcfg_files) + macro(ecm_add_executable) + kde4_add_executable(${ARGN}) + endmacro(ecm_add_executable) + + macro(ecm_mark_nongui_executable) + foreach(_target ${ARGN}) + set_target_properties(${_target} + PROPERTIES + WIN32_EXECUTABLE FALSE + MACOSX_BUNDLE FALSE + ) + endforeach() + endmacro(ecm_mark_nongui_executable) else() - find_package(Qt5 REQUIRED COMPONENTS Core DBus Test) + find_package(Qt5 REQUIRED COMPONENTS + Core + Test + WebKitWidgets + Qml + ) + # search packages used by KDE + find_package(KF5 REQUIRED COMPONENTS + Config + CoreAddons + KDELibs4Support + #I18n + #WebKit + Package + Plasma + NewStuff + ) set(QT_USE_LIBSPREFIX Qt5::) set(ALKIMIA_LIB_SUFFIX "5") set(ALKIMIA_INCLUDE_SUFFIX "Qt5") set(ALKIMIA_PATH_SUFFIX 5) set(PC_TARGET_QTPREFIX Qt5) set(PC_TARGET_SUFFIX 5) + macro(ecm_add_executable) + add_executable(${ARGN}) + endmacro(ecm_add_executable) + if(CMAKE_COMPILER_IS_GNUCC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations") + endif() endif() # figure out which multi-precision library to use @@ -55,8 +103,24 @@ feature_summary(WHAT ALL) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) + add_definitions(-DQT_USE_FAST_CONCATENATION -DQT_USE_FAST_OPERATOR_PLUS) -include_directories(${MP_INCLUDE_DIR}) +include_directories( + ${MP_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/src + ${CMAKE_BINARY_DIR}/src +) add_subdirectory(src) add_subdirectory(autotests) +add_subdirectory(qml) +if(BUILD_QT4) + add_subdirectory(plasma/applets/onlinequote) +else() + add_subdirectory(plasma/applets/ForeignCurrencies) +endif() +add_subdirectory(tests) +add_subdirectory(tools) diff --git a/Messages.sh b/Messages.sh new file mode 100644 --- /dev/null +++ b/Messages.sh @@ -0,0 +1,12 @@ +#!/bin/sh + +# invoke the extractrc script on all .ui, .rc, and .kcfg files in the sources +# the results are stored in a pseudo .cpp file to be picked up by xgettext. +$EXTRACTRC `find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` >> rc.cpp +# invoke the grantlee extract script for translatable string from Grantlee themes +$EXTRACT_GRANTLEE_TEMPLATE_STRINGS `find . -name \*.html` >> html.cpp +# if your application contains tips-of-the-day, call preparetips as well. +$PREPARETIPS > tips.cpp +# call xgettext on all source files. If your sources have other filename +# extensions besides .cc, .cpp, and .h, just add them in the find call. +$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h -name \*.qml` -o $podir/alkimia.pot diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt --- a/autotests/CMakeLists.txt +++ b/autotests/CMakeLists.txt @@ -1,15 +1,32 @@ include(ECMAddTests) +set(TEST_LIB + alkimia + alkimia-internal + ${QT_USE_LIBSPREFIX}Test + ${QT_USE_LIBSPREFIX}Core + ${QT_USE_LIBSPREFIX}DBus + ${QT_USE_LIBSPREFIX}WebKit + ${MP_LIBRARIES} +) if(BUILD_QT4) - set(TEST_LIB ${QT_QTTEST_LIBRARY}) + list(APPEND TEST_LIB ${KDE_LIBRARIES}) else() - set(TEST_LIB Qt5::Test) + list(APPEND TEST_LIB ${QT_USE_LIBSPREFIX}WebKitWidgets) endif() ecm_add_tests( alkvaluetest.cpp alkquoteitemtest.cpp alkcompanytest.cpp + alkexceptiontest.cpp LINK_LIBRARIES alkimia ${TEST_LIB} ) + +ecm_add_test( + alkonlinequotetest.cpp + ../src/alkquotereceiver.cpp + LINK_LIBRARIES ${TEST_LIB} + TEST_NAME alkonlinequotestest +) diff --git a/src/alkcompany.h b/autotests/alkexceptiontest.h copy from src/alkcompany.h copy to autotests/alkexceptiontest.h --- a/src/alkcompany.h +++ b/autotests/alkexceptiontest.h @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2002 Thomas Baumgart tbaumgart@kde.org * * * * This file is part of libalkimia. * * * @@ -17,65 +17,23 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H +#ifndef ALKEXCEPTIONTEST_H +#define ALKEXCEPTIONTEST_H -#include "alk_export.h" +#include "alkexception.h" -#include -#include -#include -#include +#include -class ALK_EXPORT AlkCompany : public QObject +class AlkExceptionTest : public QObject { Q_OBJECT -public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); - /** - * Financial symbol - */ - const QString &symbol() const; +private slots: + void init(); + void cleanup(); - /** - * Name of the equity - */ - const QString &name() const; + void testDefaultConstructor(); - /** - * Type of the equity - */ - const QString &type() const; - - /** - * Exchange market of the equity - */ - const QString &exchange() const; - - /** - * Internal id - */ - const QString &recordId() const; - - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); - -private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private *const d; + void testConstructor(); }; - -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); - -Q_DECLARE_METATYPE(AlkCompany) - #endif diff --git a/autotests/alkexceptiontest.cpp b/autotests/alkexceptiontest.cpp new file mode 100644 --- /dev/null +++ b/autotests/alkexceptiontest.cpp @@ -0,0 +1,48 @@ +/*************************************************************************** + * Copyright 2002 Thomas Baumgart tbaumgart@kde.org * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkexceptiontest.h" + +#include + +QTEST_MAIN(AlkExceptionTest) + +void AlkExceptionTest::init() +{ +} + +void AlkExceptionTest::cleanup() +{ +} + +void AlkExceptionTest::testDefaultConstructor() +{ + const AlkException &e = ALKEXCEPTION("Message"); + QVERIFY(e.what() == "Message"); + QVERIFY(e.line() == __LINE__ - 2); + QVERIFY(e.file() == __FILE__); +} + +void AlkExceptionTest::testConstructor() +{ + AlkException e("New message", "Joe's file", 1234); + QVERIFY(e.what() == "New message"); + QVERIFY(e.line() == 1234); + QVERIFY(e.file() == "Joe's file"); +} diff --git a/src/alkcompany.h b/autotests/alkonlinequotetest.h copy from src/alkcompany.h copy to autotests/alkonlinequotetest.h --- a/src/alkcompany.h +++ b/autotests/alkonlinequotetest.h @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * * * * This file is part of libalkimia. * * * @@ -17,65 +17,24 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H +#ifndef ALKONLINEQUOTETEST_H +#define ALKONLINEQUOTETEST_H -#include "alk_export.h" +#include -#include -#include -#include -#include +class AlkOnlineQuotesProfile; -class ALK_EXPORT AlkCompany : public QObject +class AlkOnlineQuoteTest : public QObject { Q_OBJECT -public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); - - /** - * Financial symbol - */ - const QString &symbol() const; - - /** - * Name of the equity - */ - const QString &name() const; - - /** - * Type of the equity - */ - const QString &type() const; - - /** - * Exchange market of the equity - */ - const QString &exchange() const; - - /** - * Internal id - */ - const QString &recordId() const; - - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); +private slots: + void init(); + void cleanup(); + void testQuoteSources(); + void testLaunch(); private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private *const d; + AlkOnlineQuotesProfile *m_profile; }; -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); - -Q_DECLARE_METATYPE(AlkCompany) - -#endif +#endif // ALKONLINEQUOTETEST_H diff --git a/autotests/alkonlinequotetest.cpp b/autotests/alkonlinequotetest.cpp new file mode 100644 --- /dev/null +++ b/autotests/alkonlinequotetest.cpp @@ -0,0 +1,58 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequotetest.h" + +#include "alkonlinequote.h" +#include "alkonlinequotesprofile.h" +#include "alkquotereceiver.h" + +#include +#include + +QTEST_MAIN(AlkOnlineQuoteTest) + +void AlkOnlineQuoteTest::init() +{ + m_profile = new AlkOnlineQuotesProfile("alkimia",AlkOnlineQuotesProfile::Type::KMyMoney); +} + +void AlkOnlineQuoteTest::cleanup() +{ + delete m_profile; +} + +void AlkOnlineQuoteTest::testQuoteSources() +{ + QStringList sources = m_profile->quoteSources(); + qDebug() << sources; + QVERIFY(sources.size() > 0); +} + +void AlkOnlineQuoteTest::testLaunch() +{ + AlkOnlineQuote quote(m_profile); + convertertest::AlkQuoteReceiver receiver("e); + QWebView *view = new QWebView; + quote.setWebView(view); + receiver.setVerbose(true); + + QVERIFY(quote.launch("EUR USD", "EUR USD", m_profile->quoteSources().first())); + delete view; +} diff --git a/autotests/alkvaluetest.cpp b/autotests/alkvaluetest.cpp --- a/autotests/alkvaluetest.cpp +++ b/autotests/alkvaluetest.cpp @@ -18,7 +18,8 @@ ***************************************************************************/ #include "alkvaluetest.h" -#include "alkvalue.h" + +#include "alkimia/alkvalue.h" #include diff --git a/doc/design.xmi b/doc/design.xmi new file mode 100644 --- /dev/null +++ b/doc/design.xmi @@ -0,0 +1,2327 @@ + + + + + umbrello uml modeller http://umbrello.kde.org + 1.6.17 + UnicodeUTF8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plasma/applets/ForeignCurrencies/CMakeLists.txt b/plasma/applets/ForeignCurrencies/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/CMakeLists.txt @@ -0,0 +1,15 @@ +# Locate plasma_install_package macro. +find_package(KF5Plasma REQUIRED) + +set(APPLET_NAME org.wincak.foreigncurrencies2) + +plasma_install_package(. ${APPLET_NAME}) + +#set(TRACE "QML_IMPORT_TRACE=1") + +add_custom_target(foreigncurrencies-test + COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/${APPLET_NAME} + COMMAND ${CMAKE_COMMAND} -E + env "QML2_IMPORT_PATH=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}:${CMAKE_CURRENT_BINARY_DIR} ${TRACE}" + plasmoidviewer --applet ${APPLET_NAME} +) diff --git a/plasma/applets/ForeignCurrencies/LICENSE b/plasma/applets/ForeignCurrencies/LICENSE new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + CurrencyConverter + Copyright (C) 2018 wincak + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/plasma/applets/ForeignCurrencies/README b/plasma/applets/ForeignCurrencies/README new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/README @@ -0,0 +1,18 @@ +Displays currency pair price on your plasma desktop. + +This is a fork of Foreign currencies plasmoid by bravenec2nd +https://store.kde.org/p/1170603 +that stopped working along with yahoo API + +Prices are downloaded from http://free.currencyconverterapi.com/api/v5/ +Prices are updated every 15 minutes. +When you click to the line with the price then the browser with Finance Yahoo with selected currency pair is opened. + +Pair names examples: +- USD_EUR = USD to EUR price +- EUR_CZK = USD to CZK price +- XAU_USD = USD to Gold price +- XAG_USD = USD to Silver price +- XAU_CZK = CZK to Gold price +- XAG_CZK = CZK to Silver price + diff --git a/plasma/applets/ForeignCurrencies/contents/config/config.qml b/plasma/applets/ForeignCurrencies/contents/config/config.qml new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/config/config.qml @@ -0,0 +1,11 @@ +import QtQuick 2.2 +import org.kde.plasma.configuration 2.0 + +ConfigModel { + ConfigCategory { + name: i18n('General') + icon: Qt.resolvedUrl('../icons/currency.svg').replace('file://', '') + source: 'config/ConfigGeneral.qml' + } +} + diff --git a/plasma/applets/ForeignCurrencies/contents/config/config.qmlc b/plasma/applets/ForeignCurrencies/contents/config/config.qmlc new file mode 100644 index 0000000000000000000000000000000000000000..38b76b9315bf188fb6593282633a33f9e1bbeaab GIT binary patch literal 1588 zc$}3}J&Y1T6n+D@u*;qtoS2-+CDQ06#;|(`7qHO;qlKDiqESn3e-3iX&jCl&Skl^= zSZHA`v9htc!pg$J!otqRSkY^Yg@wua&FlcPn2YBlA8+QH_vU@?4eSg{j$0qpPZAL` zHR_HVFC0cxN)T;Syke#3m)C8#?3X>SRJDEI-L%WL?N@EjuAVP$RvgbKY0u7WeEYKW z^+|4YaqsQt#Z%X6`)BrFKfn9v$6n)=S4bxja~xQS6UE@)$-ED9{*&SlV9W3vB8P?k zJDbH^Vl=gTKo&^I{Y}L)>G_>T7^7rHZ9!S{yE=((GHaUp*+r(CT1r#vod)!O)HC6e zN355W^>W8dJ-cKYYiXSsSY}NlOJ-^V-k!qf{Q79=ri;S2MrMMX|)4k z^V$#dOxbsZ?o33v+MtF=O-9f9`@ec|W&cLr$;}Yovo2D^-{2*XXQ2{qiHM#g&L?l6 z$#c~bIG_9`TwEOhBj7zS1{Tmn4!8{521dYB;3F^wegeONRa|}@aDm5~TA%0^4S-#0 zl0(~)Uj;hUqb(|cbIF76Qb2X;Qw!e(#CE7nKC-ru+XFYinseOvZ>y$6+`yXO63F}0 zbLTaY?_tHOJ```$2G;_|jsHhIdH@YQ_&z>itvvF1Mm`c9zHL)#JX*dQ9lk;zd)}FY zj1}zFj;)CLtB7a=dvKMQJ7+o{&U5Vnm + + + + + + [{"symbol":"USD EUR"}] + + + + diff --git a/plasma/applets/ForeignCurrencies/contents/icons/currency.svg b/plasma/applets/ForeignCurrencies/contents/icons/currency.svg new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/icons/currency.svg @@ -0,0 +1,120 @@ + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + € + + diff --git a/plasma/applets/ForeignCurrencies/contents/ui/Currency.qml b/plasma/applets/ForeignCurrencies/contents/ui/Currency.qml new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/ui/Currency.qml @@ -0,0 +1,77 @@ +import QtQuick 2.0 +import QtQuick.Layouts 1.2 +import QtQuick.Controls 1.4 +import org.kde.plasma.plasmoid 2.0 +import org.kde.plasma.core 2.0 as PlasmaCore +import org.kde.alkimia 1.0 + +Item { + id: root; + property string symbol: "USD EUR"; + property string source: "Alkimia Currency"; + // one hour + property int timeout: 1000*60*60; + property double price; + Layout.fillWidth: true; + Layout.fillHeight: true; + + Text { + id: currencyLabel; + text: root.symbol; + font.pixelSize: 18; + color: theme.textColor; + height: font.pixelsize*1.1; + width: parent.width * 0.5; + horizontalAlignment: Text.AlignLeft; + verticalAlignment: Text.AlignVCenter; + anchors.top: parent.top; + anchors.bottom: parent.bottom; + anchors.left: parent.left; + } + + Text { + id: priceLabel; + text: "unknown"; + font.pixelSize: 18; + color: theme.textColor; + height: font.pixelsize*1.1; + width: parent.width * 0.5; + horizontalAlignment: Text.AlignRight; + verticalAlignment: Text.AlignVCenter; + anchors.top: parent.top; + anchors.bottom: parent.bottom; + anchors.right: parent.right; + anchors.left: currency.right; + } + + AlkOnlineQuote { + id: quote + onError: { + console.log(s) + } + onStatus: { + console.log(s) + } + onQuote: { + //root.date = date + priceLabel.text = price + } + } + + Timer { + id: timer; + interval: 1000; + running: true; + repeat: true; + onTriggered: { + console.log("=== timer ==="); + if (root.symbol == "") { + timer.interval = 10000; + return; + } + quote.launch(root.symbol, "", root.source) + timer.interval = root.timeout + } + } +} + diff --git a/plasma/applets/ForeignCurrencies/contents/ui/Okno.qml b/plasma/applets/ForeignCurrencies/contents/ui/Okno.qml new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/ui/Okno.qml @@ -0,0 +1,34 @@ +import QtQuick 2.0 +import QtQuick.Layouts 1.2 + +ColumnLayout { + Layout.minimumWidth: units.gridUnit * 10 + Layout.minimumHeight: units.gridUnit * 5 + Layout.preferredWidth: units.gridUnit * 20 + Layout.preferredHeight: units.gridUnit * 50 + + id: root + anchors.fill: parent; + + Component.onCompleted: { + createLines(); + } + + Connections { + target: plasmoid.configuration; + onCurrenciesChanged: { createLines(); } + } + + function createLines() { + for (var i=root.children.length-1; i >= 0; i--) { + root.children[i].destroy(); + } + var currencies = JSON.parse(plasmoid.configuration.currencies) + currencies.forEach(function (line) { + var component = Qt.createComponent("Currency.qml"); + var chart = component.createObject(root, { symbol: line.symbol }); + }) + + } +} + diff --git a/plasma/applets/ForeignCurrencies/contents/ui/config/ConfigGeneral.qml b/plasma/applets/ForeignCurrencies/contents/ui/config/ConfigGeneral.qml new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/ui/config/ConfigGeneral.qml @@ -0,0 +1,161 @@ +import QtQuick 2.2 +import QtQuick.Controls 1.3 +import QtQuick.Layouts 1.1 +import QtQuick.Dialogs 1.2 +import org.kde.plasma.core 2.0 as PlasmaCore + +Item { + + property string cfg_currencies + + ListModel { + id: currenciesModel + } + + Component.onCompleted: { + var currencies = JSON.parse(plasmoid.configuration.currencies) + currencies.forEach(function (line) { + currenciesModel.append({ + symbol: line.symbol + }) + }) + } + + + function currenciesModelChanged() { + var newCurrenciesArray = [] + for (var i = 0; i < currenciesModel.count; i++) { + newCurrenciesArray.push({ + symbol: currenciesModel.get(i).symbol + }) + } + cfg_currencies = JSON.stringify(newCurrenciesArray) + } + + + Dialog { + id: addCurrencyDialog + title: i18n('Add Currency Pair') + + width: 300 + + standardButtons: StandardButton.Ok | StandardButton.Cancel + + onAccepted: { + if (symbolField.text !== "") { + console.log("symbol: " + symbolField.text); + currenciesModel.append({ symbol: symbolField.text }); + currenciesModelChanged() + close() + } + } + + TextField { + id: symbolField + placeholderText: i18n('Paste currency pair symbol here') + width: parent.width + } + + } + + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + + Label { + text: i18n('Currency Pairs') + font.bold: true + Layout.alignment: Qt.AlignLeft + } + + Item { } + + TableView { + id: currenciesTable + width: parent.width + + TableViewColumn { + id: symbolIdCol + role: 'symbolId' + title: i18n('Symbol') + // width: parent.width * 0.6 + + delegate: Label { + text: styleData.value + elide: Text.ElideRight + anchors.left: parent ? parent.left : undefined + anchors.leftMargin: 5 + anchors.right: parent ? parent.right : undefined + anchors.rightMargin: 5 + } + } + + + TableViewColumn { + title: i18n('Action') + // width: parent.width * 0.2 + + delegate: Item { + + GridLayout { + height: parent.height + columns: 3 + rowSpacing: 0 + + Button { + iconName: 'go-up' + Layout.fillHeight: true + onClicked: { + currenciesModel.move(styleData.row, styleData.row - 1, 1) + currenciesModelChanged() + } + enabled: styleData.row > 0 + } + + Button { + iconName: 'go-down' + Layout.fillHeight: true + onClicked: { + currenciesModel.move(styleData.row, styleData.row + 1, 1) + currenciesModelChanged() + } + enabled: styleData.row < currenciesModel.count - 1 + } + + Button { + iconName: 'list-remove' + Layout.fillHeight: true + onClicked: { + currenciesModel.remove(styleData.row) + currenciesModelChanged() + } + } + } + } + + } + model: currenciesModel + Layout.preferredHeight: 150 + Layout.preferredWidth: parent.width + Layout.columnSpan: 2 + } + + Row { + Layout.columnSpan: 2 + + Button { + iconName: 'list-add' + text: 'Add Currency Pair' + onClicked: { + addCurrencyDialog.open(); + symbolField.text = '' + symbolField.focus = true + } + } + + } + + } + +} diff --git a/plasma/applets/ForeignCurrencies/contents/ui/main.qml b/plasma/applets/ForeignCurrencies/contents/ui/main.qml new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/contents/ui/main.qml @@ -0,0 +1,10 @@ +import QtQuick 2.0 +import QtQuick.Layouts 1.1 +import org.kde.plasma.plasmoid 2.0 +import org.kde.plasma.core 2.0 as PlasmaCore + + +Item { + Plasmoid.fullRepresentation: Okno { } + Plasmoid.compactRepresentation: Okno { } +} diff --git a/plasma/applets/ForeignCurrencies/metadata.desktop b/plasma/applets/ForeignCurrencies/metadata.desktop new file mode 100644 --- /dev/null +++ b/plasma/applets/ForeignCurrencies/metadata.desktop @@ -0,0 +1,17 @@ +[Desktop Entry] +Encoding=UTF-8 +Name=Foreign Currencies +Comment=Plasmoid showing current foreign currencies prices. Fork of Foreign Currencies plasmoid by bravenec2nd. +Type=Service +Icon=applications-internet +X-Plasma-MainScript=ui/main.qml +X-Plasma-API=declarativeappletscript + +X-KDE-PluginInfo-Author=Petr Bravenec, wincak +X-KDE-PluginInfo-Email=petr@bravenec.eu, wincak@seznam.cz +X-KDE-PluginInfo-License=GPL2 +X-KDE-PluginInfo-Version=1.1 +X-KDE-PluginInfo-Website=https://gitlab.com/wincak/ForeignCurrencies +X-KDE-PluginInfo-Name=org.wincak.foreigncurrencies2 +X-KDE-PluginInfo-Category=Online Services +X-KDE-ServiceTypes=Plasma/Applet diff --git a/plasma/applets/onlinequote/CMakeLists.txt b/plasma/applets/onlinequote/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/plasma/applets/onlinequote/CMakeLists.txt @@ -0,0 +1,31 @@ +# We add our source code here +set(SOURCES plasma-onlinequote.cpp) + +set(UI configwidget.ui) + +ki18n_wrap_ui(SOURCES ${UI}) + +# Now make sure all files get to the right place +kde4_add_plugin(plasma_applet_onlinequote ${SOURCES}) +target_link_libraries(plasma_applet_onlinequote + alkimia +) +if(BUILD_QT4) + target_link_libraries(plasma_applet_onlinequote + ${KDE4_PLASMA_LIBS} + ${KDE4_KDEUI_LIBS} + ) + set(PLUGIN_INSTALL_DIR "${KDE4_LIB_INSTALL_DIR}/kde4") + set(SERVICES_INSTALL_DIR ${KDE4_SERVICES_INSTALL_DIR}) +else() + target_link_libraries(plasma_applet_onlinequote + KF5::Package + KF5::Plasma + ) +endif() + +install(TARGETS plasma_applet_onlinequote + DESTINATION ${PLUGIN_INSTALL_DIR}) + +install(FILES plasma-applet-onlinequote.desktop + DESTINATION ${SERVICES_INSTALL_DIR}) diff --git a/plasma/applets/onlinequote/configwidget.ui b/plasma/applets/onlinequote/configwidget.ui new file mode 100644 --- /dev/null +++ b/plasma/applets/onlinequote/configwidget.ui @@ -0,0 +1,78 @@ + + + ConfigWidget + + + + 0 + 0 + 400 + 300 + + + + Dialog + + + + + + + + + + + Symbol + + + + + + + Interval[min] + + + + + + + + + + Online Quote + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Profile + + + + + + + + + + + + + diff --git a/plasma/applets/onlinequote/plasma-applet-onlinequote.desktop b/plasma/applets/onlinequote/plasma-applet-onlinequote.desktop new file mode 100644 --- /dev/null +++ b/plasma/applets/onlinequote/plasma-applet-onlinequote.desktop @@ -0,0 +1,16 @@ +[Desktop Entry] +Name=Online Quote +Comment=Plasma applet for an online quote +Type=Service +ServiceTypes=Plasma/Applet + +X-KDE-Library=plasma_applet_onlinequote +X-KDE-PluginInfo-Name=OnlineQuote +X-KDE-PluginInfo-Category=Finance +X-KDE-PluginInfo-Author=Ralf Habacker +X-KDE-PluginInfo-Email=ralf.habacker@freenet.de +X-KDE-PluginInfo-Version=0.1 +X-KDE-PluginInfo-Website=http://plasma.kde.org/ +X-KDE-PluginInfo-Depends= +X-KDE-PluginInfo-License=GPL +X-KDE-PluginInfo-EnabledByDefault=true diff --git a/plasma/applets/onlinequote/plasma-onlinequote.h b/plasma/applets/onlinequote/plasma-onlinequote.h new file mode 100644 --- /dev/null +++ b/plasma/applets/onlinequote/plasma-onlinequote.h @@ -0,0 +1,48 @@ +#ifndef PLASMA_APPLET_ONLINEQUOTE_HEADER +#define PLASMA_APPLET_ONLINEQUOTE_HEADER + +#include +// Here we avoid loading the header multiple times +#include +#include + +class QSizeF; + +class MyWidget; +class AlkOnlineQuotesProfile; + +// KF5 +class KConfigDialog; +class QStyleOptionGraphicsItem; + +// Define our plasma Applet +class PlasmaOnlineQuote : public Plasma::Applet +{ + Q_OBJECT +public: + // Basic Create/Destroy + PlasmaOnlineQuote(QObject *parent, const QVariantList &args); + ~PlasmaOnlineQuote(); + +protected slots: + void slotConfigAccepted(); + void slotFetchQuote(); + void slotReceivedQuote(const QString &id, const QString &symbol, const QDate &data, const double &price); + void slotLogStatus(const QString &s); + void slotLogError(const QString &s); + void slotLogFailed(const QString &id, const QString &symbol); + void slotProfileChanged(const QString &name); +protected: + // The paintInterface procedure paints the applet to screen + void paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect& contentsRect); + void init(); + void configChanged(); + void createConfigurationInterface(KConfigDialog *parent); + Plasma::Svg m_svg; + KIcon m_icon; + MyWidget *m_widget; + QDate m_date; + double m_price; + AlkOnlineQuotesProfile *m_profile; +}; +#endif diff --git a/plasma/applets/onlinequote/plasma-onlinequote.cpp b/plasma/applets/onlinequote/plasma-onlinequote.cpp new file mode 100644 --- /dev/null +++ b/plasma/applets/onlinequote/plasma-onlinequote.cpp @@ -0,0 +1,216 @@ +#include "plasma-onlinequote.h" + +#include "alkonlinequote.h" +#include "alkonlinequotesprofile.h" +#include "alkonlinequotesprofilemanager.h" +#include "ui_configwidget.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + + +class MyWidget : public QWidget, public Ui::ConfigWidget +{ +public: + MyWidget() + { + setupUi((QWidget *)this); + } +}; + +PlasmaOnlineQuote::PlasmaOnlineQuote(QObject *parent, const QVariantList &args) + : Plasma::Applet(parent, args) + , m_svg(this) + , m_icon("preferences-system-network") + , m_widget(0) + , m_price(0) + , m_profile(nullptr) +{ + setHasConfigurationInterface(true); + m_svg.setImagePath("widgets/background"); +#if QT_VERSION < 0x050000 + // this will get us the standard applet background, for free! + setBackgroundHints(DefaultBackground); + resize(200, 200); +#endif + AlkOnlineQuotesProfileManager &manager = AlkOnlineQuotesProfileManager::instance(); + // manager is shared between plasmoids + if(AlkOnlineQuotesProfileManager::instance().profiles().size() == 0) { + manager.addProfile(new AlkOnlineQuotesProfile("alkimia", AlkOnlineQuotesProfile::Type::KMyMoney)); + manager.addProfile(new AlkOnlineQuotesProfile("kmymoney", AlkOnlineQuotesProfile::Type::KMyMoney)); + } +} + +PlasmaOnlineQuote::~PlasmaOnlineQuote() +{ +#if QT_VERSION < 0x050000 + if (hasFailedToLaunch()) { + // Do some cleanup here + } else +#endif + { + // Save settings + config().sync(); + } +} + +void PlasmaOnlineQuote::init() +{ +#if QT_VERSION < 0x050000 + // A small demonstration of the setFailedToLaunch function + if (m_icon.isNull()) { + setFailedToLaunch(true, "No world to say hello"); + } +#endif + QString currentProfile = config().readEntry("profile"); + qDebug() << "reading current profile" << currentProfile; + if (currentProfile.isEmpty()) + currentProfile = AlkOnlineQuotesProfileManager::instance().profiles().first()->name(); + qDebug() << "setup current profile" << currentProfile; + m_profile = AlkOnlineQuotesProfileManager::instance().profile(currentProfile); + QTimer::singleShot(100, this, SLOT(slotFetchQuote())); +} + +void PlasmaOnlineQuote::configChanged() +{ + qDebug() << "configChanged()"; +} + +void PlasmaOnlineQuote::createConfigurationInterface(KConfigDialog *parent) +{ + m_widget = new MyWidget; + QStringList profiles = AlkOnlineQuotesProfileManager::instance().profileNames(); + m_widget->m_profile->addItems(profiles); + QString currentProfile = m_profile->name(); + int index = profiles.indexOf(currentProfile); + m_widget->m_profile->setCurrentIndex(index); + connect(m_widget->m_profile, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotProfileChanged(QString))); + + QStringList sources = m_profile->quoteSources(); + m_widget->m_onlineQuote->addItems(sources); + index = sources.indexOf(config().readEntry("onlinequote")); + m_widget->m_onlineQuote->setCurrentIndex(index); + + m_widget->m_symbol->setText(config().readEntry("symbol")); + m_widget->m_interval->setValue(config().readEntry("interval", 60)); + parent->addPage(dynamic_cast(m_widget), "Online Source"); + connect(parent, SIGNAL(applyClicked()), this, SLOT(slotConfigAccepted())); + connect(parent, SIGNAL(okClicked()), this, SLOT(slotConfigAccepted())); +} + +void PlasmaOnlineQuote::slotProfileChanged(const QString &name) +{ + AlkOnlineQuotesProfile *profile = AlkOnlineQuotesProfileManager::instance().profile(name); + if (!profile) { + qWarning() << "profile" << name << "not present"; + return; + } + m_profile = profile; + QStringList sources = m_profile->quoteSources(); + m_widget->m_onlineQuote->clear(); + m_widget->m_onlineQuote->addItems(sources); + int index = sources.indexOf(config().readEntry("onlinequote")); + m_widget->m_onlineQuote->setCurrentIndex(index); +} + +void PlasmaOnlineQuote::slotConfigAccepted() +{ + config().writeEntry("profile", m_widget->m_profile->currentText()); + config().writeEntry("onlinequote", m_widget->m_onlineQuote->currentText()); + config().writeEntry("symbol", m_widget->m_symbol->text()); + config().writeEntry("interval", m_widget->m_interval->value()); + config().sync(); + emit configNeedsSaving(); + slotFetchQuote(); + qDebug() << "configAccepted()"; +} + +void PlasmaOnlineQuote::slotFetchQuote() +{ + if (config().readEntry("symbol").isEmpty() || config().readEntry("interval").toInt() == 0) { + qDebug() << __FUNCTION__ << "no configuration found"; + return; + } + AlkOnlineQuote quote(m_profile); + connect("e, SIGNAL(status(QString)), this, SLOT(slotLogStatus(QString))); + connect("e, SIGNAL(error(QString)), this, SLOT(slotLogError(QString))); + connect("e, SIGNAL(failed(QString,QString)), this, SLOT(slotLogFailed(QString,QString))); + connect("e, SIGNAL(quote(QString,QString,QDate,double)), this, SLOT(slotReceivedQuote(QString,QString,QDate,double))); + quote.launch(config().readEntry("symbol"), "", config().readEntry("onlinequote")); + int interval = config().readEntry("interval").toInt()*1000; + qDebug() << "setting timer to " << interval << "ms"; + QTimer::singleShot(interval, this, SLOT(slotFetchQuote())); +} + +void PlasmaOnlineQuote::slotLogStatus(const QString &s) +{ + qDebug() << s; +} + +void PlasmaOnlineQuote::slotLogError(const QString &s) +{ + slotLogStatus("Error:" + s); +} + +void PlasmaOnlineQuote::slotLogFailed(const QString &id, const QString &symbol) +{ + slotLogStatus(QString("Failed: %1 %2").arg(id, symbol)); +} + +void PlasmaOnlineQuote::slotReceivedQuote(const QString &id, const QString &symbol, const QDate &date, const double &price) +{ + Q_UNUSED(id) + Q_UNUSED(symbol) + qDebug() << "got quote" << date << price; + m_date = date; + m_price = price; +#if QT_VERSION < 0x050000 + update(); +#else +#warning how to update ui ? +#endif +} + +void PlasmaOnlineQuote::paintInterface(QPainter *p, + const QStyleOptionGraphicsItem *option, const QRect &contentsRect) +{ + Q_UNUSED(option) + p->setRenderHint(QPainter::SmoothPixmapTransform); + p->setRenderHint(QPainter::Antialiasing); + + // Now we draw the applet, starting with our svg + m_svg.resize((int)contentsRect.width(), (int)contentsRect.height()); + m_svg.paint(p, (int)contentsRect.left(), (int)contentsRect.top()); + + // We place the icon and text + p->drawPixmap(7, 0, m_icon.pixmap((int)contentsRect.width(),(int)contentsRect.width()-14)); + p->save(); + p->setPen(Qt::white); + if (true) { + qDebug() << "drawing" << config().readEntry("onlinequote") << "price" << m_price; + p->drawText(contentsRect, + Qt::AlignVCenter | Qt::AlignHCenter, + config().readEntry("onlinequote")); + p->drawText(contentsRect, + Qt::AlignBottom | Qt::AlignHCenter, + config().readEntry("symbol") + " " + QString::number(m_price,8,4)); + + } else { + p->drawText(contentsRect, + Qt::AlignBottom | Qt::AlignHCenter, + "Hello Plasmoid!"); + } + p->restore(); +} + +// This is the command that links your applet to the .desktop file +K_EXPORT_PLASMA_APPLET(onlinequote, PlasmaOnlineQuote) diff --git a/qml/CMakeLists.txt b/qml/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/qml/CMakeLists.txt @@ -0,0 +1,34 @@ +if(BUILD_QT4) + set(LIBS ${QT_USE_LIBSPREFIX}Declarative) + set(QML_INSTALL_DIR ${LIB_INSTALL_DIR}/qt4/plugins/imports) +else() + set(LIBS ${QT_USE_LIBSPREFIX}Qml) + set(QML_INSTALL_DIR ${LIB_INSTALL_DIR}/qt5/qml) + set_package_properties(Qt5Qml PROPERTIES URL "git://gitorious.org/qt/qtdeclarative.git" + DESCRIPTION "QML support for Alkimia" + TYPE OPTIONAL + PURPOSE "Allows to use Alkimiain QML code" + ) + if(NOT Qt5Qml_FOUND) + message(STATUS "Qt5Qml not found, qml imports will not be built.") + return() + endif() +endif() + +set(IMPORTS_DIR ${CMAKE_BINARY_DIR}/bin/org/kde/alkimia) +if(WIN32) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${IMPORTS_DIR}) +else() + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${IMPORTS_DIR}) +endif() + +configure_file(qmldir ${IMPORTS_DIR}/qmldir) +add_library(qmlalkimia SHARED qmlalkimiaplugin.cpp) +target_link_libraries(qmlalkimia ${LIBS} alkimia) + +install(TARGETS qmlalkimia + RUNTIME DESTINATION ${QML_INSTALL_DIR}/org/kde/alkimia + LIBRARY DESTINATION ${QML_INSTALL_DIR}/org/kde/alkimia) +install(FILES qmldir DESTINATION ${QML_INSTALL_DIR}/org/kde/alkimia) + +# run qml file with diff --git a/src/alkcompany.h b/qml/qmlalkimiaplugin.h copy from src/alkcompany.h copy to qml/qmlalkimiaplugin.h --- a/src/alkcompany.h +++ b/qml/qmlalkimiaplugin.h @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * * * * This file is part of libalkimia. * * * @@ -17,65 +17,24 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H - -#include "alk_export.h" - -#include -#include -#include -#include +#include +#if QT_VERSION >= 0x050000 +#include +#else +#include +class QQmlExtensionPlugin : public QDeclarativeExtensionPlugin +{ +}; +#undef Q_PLUGIN_METADATA +#define Q_PLUGIN_METADATA(s) +#define Q_DECL_OVERRIDE +#endif -class ALK_EXPORT AlkCompany : public QObject +class QmlAlkimiaPlugin : public QQmlExtensionPlugin { Q_OBJECT -public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); - - /** - * Financial symbol - */ - const QString &symbol() const; - - /** - * Name of the equity - */ - const QString &name() const; - - /** - * Type of the equity - */ - const QString &type() const; + Q_PLUGIN_METADATA(IID "org.kde.alkimia") - /** - * Exchange market of the equity - */ - const QString &exchange() const; - - /** - * Internal id - */ - const QString &recordId() const; - - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); - -private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private *const d; +public: + void registerTypes(const char *uri) Q_DECL_OVERRIDE; }; - -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); - -Q_DECLARE_METATYPE(AlkCompany) - -#endif diff --git a/qml/qmlalkimiaplugin.cpp b/qml/qmlalkimiaplugin.cpp new file mode 100644 --- /dev/null +++ b/qml/qmlalkimiaplugin.cpp @@ -0,0 +1,32 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "qmlalkimiaplugin.h" + +#include "alkonlinequote.h" + +void QmlAlkimiaPlugin::registerTypes(const char *uri) +{ + Q_ASSERT(uri == QLatin1String("org.kde.alkimia")); + qmlRegisterType(uri, 1, 0, "AlkOnlineQuote"); +} + +#if QT_VERSION < 0x050000 +Q_EXPORT_PLUGIN2(qmlalkimiaplugin, QmlAlkimiaPlugin); +#endif diff --git a/qml/qmldir b/qml/qmldir new file mode 100644 --- /dev/null +++ b/qml/qmldir @@ -0,0 +1,2 @@ +module org.kde.alkimia +plugin qmlalkimia diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,28 +4,127 @@ include(CMakePackageConfigHelpers) include(ECMSetupVersion) +include_directories( + ${CMAKE_CURRENT_BINARY_DIR} +) + +########### target alkimia-internal ########### + +set(alkimia_INTERNAL_SRCS +) + +set(alkimia_INTERNAL_HEADERS +) + +set(alkimia_INTERNAL_UI +) + +ki18n_wrap_ui(alkimia_INTERNAL_SRCS ${alkimia_INTERNAL_UI} ) +add_library(alkimia-internal STATIC ${alkimia_INTERNAL_SRCS} ${alkimia_INTERNAL_HEADERS}) +if(NOT BUILD_QT4) + set (ALKIMIA_INTERNAL_LIBS + PRIVATE + KF5::CoreAddons + KF5::KDELibs4Support + KF5::NewStuff + ) +endif() +target_link_libraries(alkimia-internal PUBLIC ${QT_USE_LIBSPREFIX}Core ${ALKIMIA_INTERNAL_LIBS}) +kde_target_enable_exceptions(alkimia-internal PUBLIC) + +########### target alkimia ########### + set(ALKIMIA_LIB_VERSION ${alkimia_VERSION}) set(ALKIMIA_LIB_SOVERSION "${alkimia_VERSION_MAJOR}") set(alkimia_LIB_SRCS - alkvalue.cpp - alkquoteitem.cpp - alkcompany.cpp - ) + alkcompany.cpp + alkdateformat.cpp + alkexception.cpp + alkfinancequoteprocess.cpp + alkmoney.cpp + alkonlinequote.cpp + alkonlinequoteprocess.cpp + alkonlinequotesource.cpp + alkonlinequotesprofile.cpp + alkonlinequotesprofilemanager.cpp + alkonlinequoteswidget.cpp + alkquoteitem.cpp + alkquotereceiver.cpp + alkvalue.cpp +) + +set(alkimia_LIB_HEADERS + alkcompany.h + alkdateformat.h + alkexception.h + alkfinancequoteprocess.h + alkmoney.h + alkonlinequote.h + alkonlinequoteprocess.h + alkonlinequotesource.h + alkonlinequotesprofile.h + alkonlinequotesprofilemanager.h + alkonlinequoteswidget.h + alkquoteitem.h + alkquotereceiver.h +) + +set(alkimia_UI + alkonlinequoteswidget.ui +) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/alkvalue.h.in + ${CMAKE_CURRENT_BINARY_DIR}/alkimia/alkvalue.h + IMMEDIATE +) -set(alkimia_HEADERS - ${CMAKE_CURRENT_BINARY_DIR}/alkvalue.h - alkquoteitem.h - alkcompany.h - ${CMAKE_CURRENT_BINARY_DIR}/alk_export.h - ) +foreach(header ${alkimia_LIB_HEADERS}) + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/${header} + ${CMAKE_CURRENT_BINARY_DIR}/alkimia/${header} + COPYONLY + ) +endforeach() -add_library(alkimia SHARED ${alkimia_LIB_SRCS}) +add_definitions(-DKNSRC_DIR="${CMAKE_CURRENT_SOURCE_DIR}") + +ki18n_wrap_ui(alkimia_LIB_SRCS ${alkimia_UI} ) +add_library(alkimia SHARED ${alkimia_LIB_SRCS} ${alkimia_INTERNAL_SRCS} ${alkimia_LIB_HEADERS}) kde_target_enable_exceptions(alkimia PUBLIC) +if(BUILD_QT4) + set(ALKIMIA_LIBS + PRIVATE + ${KDE_LIBRARIES} + ${KDE4_KDEUI_LIBS} + ${KDE4_KNEWSTUFF3_LIBS}) +else() + set(ALKIMIA_LIBS + PRIVATE + ${QT_USE_LIBSPREFIX}WebKitWidgets + KF5::KDELibs4Support + KF5::NewStuff + ) +endif() +target_link_libraries(alkimia + PRIVATE + alkimia-internal + ${QT_USE_LIBSPREFIX}Core + ${ALKIMIA_LIBS} + ${QT_USE_LIBSPREFIX}WebKit + ${QT_USE_LIBSPREFIX}DBus + ${MP_LIBRARIES} +) -target_link_libraries(alkimia PUBLIC ${QT_USE_LIBSPREFIX}Core ${QT_USE_LIBSPREFIX}DBus ${MP_LIBRARIES}) -generate_export_header(alkimia BASE_NAME alk) +install( + DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/alkimia + DESTINATION ${INCLUDE_INSTALL_DIR}/alkimia/${ALKIMIA_INCLUDE_SUFFIX} + COMPONENT Devel +) + +generate_export_header(alkimia BASE_NAME alk EXPORT_FILE_NAME alkimia/alk_export.h) if(WIN32) set_target_properties(alkimia PROPERTIES SUFFIX "${ALKIMIA_LIB_SOVERSION}${CMAKE_SHARED_LIBRARY_SUFFIX}") @@ -35,10 +134,25 @@ set_target_properties(alkimia PROPERTIES OUTPUT_NAME alkimia${ALKIMIA_LIB_SUFFIX}) set(INCLUDE_INSTALL_DIR include/alkimia/${ALKIMIA_INCLUDE_SUFFIX}) +install(TARGETS alkimia + EXPORT alkimiaTargets + ${INSTALL_TARGETS_DEFAULT_ARGS} +) + +install(FILES + alkimia-quotes.knsrc + kmymoney-quotes.knsrc + skrooge-quotes.knsrc + DESTINATION ${CONFIG_INSTALL_DIR} +) + +install(FILES financequote.pl + DESTINATION ${DATA_INSTALL_DIR}/alkimia${ALKIMIA_PATH_SUFFIX}/misc +) + if (NOT WIN32) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libalkimia.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libalkimia${ALKIMIA_PATH_SUFFIX}.pc IMMEDIATE @ONLY) endif(NOT WIN32) -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/alkvalue.h.in ${CMAKE_CURRENT_BINARY_DIR}/alkvalue.h IMMEDIATE) ########### create package configuration file ########### @@ -59,11 +173,6 @@ ########### install files ############### -install(TARGETS alkimia - EXPORT alkimiaTargets - ${INSTALL_TARGETS_DEFAULT_ARGS} - ) - export(TARGETS alkimia FILE "${CMAKE_CURRENT_BINARY_DIR}/LibAlkimia${ALKIMIA_PATH_SUFFIX}Targets.cmake" NAMESPACE Alkimia:: @@ -75,10 +184,6 @@ DESTINATION ${CMAKECONFIG_INSTALL_DIR} ) -install(FILES ${alkimia_HEADERS} - DESTINATION ${INCLUDE_INSTALL_DIR}/alkimia - COMPONENT Devel) - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/LibAlkimia${ALKIMIA_PATH_SUFFIX}Config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/LibAlkimia${ALKIMIA_PATH_SUFFIX}ConfigVersion.cmake" diff --git a/src/LibAlkimiaConfig.cmake.in b/src/LibAlkimiaConfig.cmake.in --- a/src/LibAlkimiaConfig.cmake.in +++ b/src/LibAlkimiaConfig.cmake.in @@ -4,7 +4,7 @@ include(CMakeFindDependencyMacro) -if("@BUILD_QT4@" STREQUAL "1") +if("@BUILD_QT4@" STREQUAL "ON" OR "@BUILD_QT4@" STREQUAL "1") find_package(Qt4 COMPONENTS QtCore QtDBus) else() find_dependency(Qt5Core) diff --git a/src/alkcompany.h b/src/alkcompany.h --- a/src/alkcompany.h +++ b/src/alkcompany.h @@ -20,7 +20,7 @@ #ifndef ALKCOMPANY_H #define ALKCOMPANY_H -#include "alk_export.h" +#include #include #include diff --git a/src/alkdateformat.h b/src/alkdateformat.h new file mode 100644 --- /dev/null +++ b/src/alkdateformat.h @@ -0,0 +1,58 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKDATEFORMAT_H +#define ALKDATEFORMAT_H + +#include "alkexception.h" + +#include +#include +#include +#include + +/** + * + * Universal date converter + * + * In 'strict' mode, this is designed to be compatable with the QIF profile date + * converter. However, that converter deals with the concept of an apostrophe + * format in a way I don't understand. So for the moment, they are 99% + * compatable, waiting on that issue. (acejones) + */ +class ALK_NO_EXPORT AlkDateFormat +{ +public: + explicit AlkDateFormat(const QString &_format) : m_format(_format) + { + } + + const QString convertDate(const QDate &_in) const; + const QDate convertString(const QString &_in, bool _strict = true, + unsigned _centurymidpoint = QDate::currentDate().year()) const; + const QString &format() const + { + return m_format; + } + +private: + QString m_format; +}; + +#endif // ALKDATEFORMAT_H diff --git a/src/alkdateformat.cpp b/src/alkdateformat.cpp new file mode 100644 --- /dev/null +++ b/src/alkdateformat.cpp @@ -0,0 +1,314 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkdateformat.h" + +#if QT_VERSION < 0x050000 +#include +#include + +const QDate AlkDateFormat::convertString(const QString &_in, bool _strict, + unsigned _centurymidpoint) const +{ + // + // Break date format string into component parts + // + + QRegExp formatrex("%([mdy]+)(\\W+)%([mdy]+)(\\W+)%([mdy]+)", Qt::CaseInsensitive); + if (formatrex.indexIn(m_format) == -1) { + throw ALKEXCEPTION("Invalid format string"); + } + + QStringList formatParts; + formatParts += formatrex.cap(1); + formatParts += formatrex.cap(3); + formatParts += formatrex.cap(5); + + QStringList formatDelimiters; + formatDelimiters += formatrex.cap(2); + formatDelimiters += formatrex.cap(4); + + // + // Break input string up into component parts, + // using the delimiters found in the format string + // + + QRegExp inputrex; + inputrex.setCaseSensitivity(Qt::CaseInsensitive); + + // strict mode means we must enforce the delimiters as specified in the + // format. non-strict allows any delimiters + if (_strict) { + inputrex.setPattern(QString("(\\w+)%1(\\w+)%2(\\w+)").arg(formatDelimiters[0], + formatDelimiters[1])); + } else { + inputrex.setPattern("(\\w+)\\W+(\\w+)\\W+(\\w+)"); + } + + if (inputrex.indexIn(_in) == -1) { + throw ALKEXCEPTION("Invalid input string"); + } + + QStringList scannedParts; + scannedParts += inputrex.cap(1).toLower(); + scannedParts += inputrex.cap(2).toLower(); + scannedParts += inputrex.cap(3).toLower(); + + // + // Convert the scanned parts into actual date components + // + unsigned day = 0, month = 0, year = 0; + bool ok; + QRegExp digitrex("(\\d+)"); + QStringList::const_iterator it_scanned = scannedParts.constBegin(); + QStringList::const_iterator it_format = formatParts.constBegin(); + while (it_scanned != scannedParts.constEnd()) { + // decide upon the first character of the part + switch ((*it_format).at(0).cell()) { + case 'd': + // remove any extraneous non-digits (e.g. read "3rd" as 3) + ok = false; + if (digitrex.indexIn(*it_scanned) != -1) { + day = digitrex.cap(1).toUInt(&ok); + } + if (!ok || day > 31) { + throw ALKEXCEPTION(QString("Invalid day entry: %1").arg(*it_scanned)); + } + break; + case 'm': + month = (*it_scanned).toUInt(&ok); + if (!ok) { + // maybe it's a textual date + unsigned i = 1; + while (i <= 12) { + if (KGlobal::locale()->calendar()->monthName(i, 2000).toLower() == *it_scanned + || KGlobal::locale()->calendar()->monthName(i, 2000, + KCalendarSystem::ShortName). + toLower() == *it_scanned) { + month = i; + } + ++i; + } + } + + if (month < 1 || month > 12) { + throw ALKEXCEPTION(QString("Invalid month entry: %1").arg(*it_scanned)); + } + + break; + case 'y': + if (_strict && (*it_scanned).length() != (*it_format).length()) { + throw ALKEXCEPTION(QString( + "Length of year (%1) does not match expected length (%2).") + .arg(*it_scanned, *it_format)); + } + + year = (*it_scanned).toUInt(&ok); + + if (!ok) { + throw ALKEXCEPTION(QString("Invalid year entry: %1").arg(*it_scanned)); + } + + // + // 2-digit year case + // + // this algorithm will pick a year within +/- 50 years of the + // centurymidpoint parameter. i.e. if the midpoint is 2000, + // then 0-49 will become 2000-2049, and 50-99 will become 1950-1999 + if (year < 100) { + unsigned centuryend = _centurymidpoint + 50; + unsigned centurybegin = _centurymidpoint - 50; + + if (year < centuryend % 100) { + year += 100; + } + year += centurybegin - centurybegin % 100; + } + + if (year < 1900) { + throw ALKEXCEPTION(QString("Invalid year (%1)").arg(year)); + } + + break; + default: + throw ALKEXCEPTION("Invalid format character"); + } + + ++it_scanned; + ++it_format; + } + QDate result(year, month, day); + if (!result.isValid()) { + throw ALKEXCEPTION(QString("Invalid date (yr%1 mo%2 dy%3)").arg(year).arg(month).arg(day)); + } + + return result; +} + +#else +#include +#include + +const QDate AlkDateFormat::convertString(const QString& _in, bool _strict, unsigned _centurymidpoint) const +{ + // + // Break date format string into component parts + // + + QRegularExpression formatrex("%([mdy]+)(\\W+)%([mdy]+)(\\W+)%([mdy]+)", QRegularExpression::CaseInsensitiveOption); + QRegularExpressionMatch match; + if (m_format.indexOf(formatrex, 0, &match) == -1) { + throw ALKEXCEPTION("Invalid format string"); + } + + QStringList formatParts; + formatParts += match.captured(1); + formatParts += match.captured(3); + formatParts += match.captured(5); + + QStringList formatDelimiters; + formatDelimiters += match.captured(2); + formatDelimiters += match.captured(4); + match = QRegularExpressionMatch(); + + // + // Break input string up into component parts, + // using the delimiters found in the format string + // + + QRegularExpression inputrex; + inputrex.setPatternOptions(QRegularExpression::CaseInsensitiveOption); + + // strict mode means we must enforce the delimiters as specified in the + // format. non-strict allows any delimiters + if (_strict) + inputrex.setPattern(QString("(\\w+)%1(\\w+)%2(\\w+)").arg(formatDelimiters[0], formatDelimiters[1])); + else + inputrex.setPattern("(\\w+)\\W+(\\w+)\\W+(\\w+)"); + + if (_in.indexOf(inputrex, 0, &match) == -1) { + throw ALKEXCEPTION("Invalid input string"); + } + + QStringList scannedParts; + scannedParts += match.captured(1).toLower(); + scannedParts += match.captured(2).toLower(); + scannedParts += match.captured(3).toLower(); + match = QRegularExpressionMatch(); + + // + // Convert the scanned parts into actual date components + // + unsigned day = 0, month = 0, year = 0; + bool ok; + QRegularExpression digitrex("(\\d+)"); + QStringList::const_iterator it_scanned = scannedParts.constBegin(); + QStringList::const_iterator it_format = formatParts.constBegin(); + while (it_scanned != scannedParts.constEnd()) { + // decide upon the first character of the part + switch ((*it_format).at(0).cell()) { + case 'd': + // remove any extraneous non-digits (e.g. read "3rd" as 3) + ok = false; + if ((*it_scanned).indexOf(digitrex, 0, &match) != -1) + day = match.captured(1).toUInt(&ok); + if (!ok || day > 31) + throw ALKEXCEPTION(QString("Invalid day entry: %1").arg(*it_scanned)); + break; + case 'm': + month = (*it_scanned).toUInt(&ok); + if (!ok) { + month = 0; + // maybe it's a textual date + unsigned i = 1; + // search the name in the current selected locale + QLocale locale; + while (i <= 12) { + if (locale.standaloneMonthName(i).toLower() == *it_scanned + || locale.standaloneMonthName(i, QLocale::ShortFormat).toLower() == *it_scanned) { + month = i; + break; + } + ++i; + } + // in case we did not find the month in the current locale, + // we look for it in the C locale + if(month == 0) { + QLocale localeC(QLocale::C); + if( !(locale == localeC)) { + i = 1; + while (i <= 12) { + if (localeC.standaloneMonthName(i).toLower() == *it_scanned + || localeC.standaloneMonthName(i, QLocale::ShortFormat).toLower() == *it_scanned) { + month = i; + break; + } + ++i; + } + } + } + } + + if (month < 1 || month > 12) + throw ALKEXCEPTION(QString("Invalid month entry: %1").arg(*it_scanned)); + + break; + case 'y': + if (_strict && (*it_scanned).length() != (*it_format).length()) + throw ALKEXCEPTION(QString("Length of year (%1) does not match expected length (%2).") + .arg(*it_scanned, *it_format)); + + year = (*it_scanned).toUInt(&ok); + + if (!ok) + throw ALKEXCEPTION(QString("Invalid year entry: %1").arg(*it_scanned)); + + // + // 2-digit year case + // + // this algorithm will pick a year within +/- 50 years of the + // centurymidpoint parameter. i.e. if the midpoint is 2000, + // then 0-49 will become 2000-2049, and 50-99 will become 1950-1999 + if (year < 100) { + unsigned centuryend = _centurymidpoint + 50; + unsigned centurybegin = _centurymidpoint - 50; + + if (year < centuryend % 100) + year += 100; + year += centurybegin - centurybegin % 100; + } + + if (year < 1900) + throw ALKEXCEPTION(QString("Invalid year (%1)").arg(year)); + + break; + default: + throw ALKEXCEPTION("Invalid format character"); + } + + ++it_scanned; + ++it_format; + } + QDate result(year, month, day); + if (! result.isValid()) + throw ALKEXCEPTION(QString("Invalid date (yr%1 mo%2 dy%3)").arg(year).arg(month).arg(day)); + + return result; +} +#endif diff --git a/src/alkexception.h b/src/alkexception.h new file mode 100644 --- /dev/null +++ b/src/alkexception.h @@ -0,0 +1,117 @@ +/*************************************************************************** + * Copyright 2000-2002 by Michael Edwardes mte@users.sourceforge.net * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKEXCEPTION_H +#define ALKEXCEPTION_H + +#include + +#include + +/** + * @file + * @author Thomas Baumgart + */ + +/** + * This class describes an exception that is thrown by the engine + * in case of a failure. + */ +class ALK_EXPORT AlkException +{ +public: + + /** + * @def ALKEXCEPTION(text) + * This is the preferred constructor to create a new exception + * object. It automatically inserts the filename and the source + * code line into the object upon creation. + * + * It is equivilant to AlkException(text, __FILE__, __LINE__) + */ +#define ALKEXCEPTION(what) AlkException(what, __FILE__, __LINE__) + + /** + * The constructor to create a new ALKEXCEPTION object. + * + * @param msg reference to QString containing the message + * @param file reference to QString containing the name of the sourcefile where + * the exception was thrown + * @param line unsigned long containing the line number of the line where + * the exception was thrown in the file. + * + * An easier way to use this constructor is to use the macro + * ALKEXCEPTION(text) instead. It automatically assigns the file + * and line parameter to the correct values. + */ + AlkException(const QString &msg, const QString &file, const unsigned long line); + + ~AlkException(); + + /** + * This method is used to return the message that was passed + * during the creation of the exception object. + * + * @return reference to QString containing the message + */ + const QString &what() const + { + return m_msg; + } + + /** + * This method is used to return the filename that was passed + * during the creation of the exception object. + * + * @return reference to QString containing the filename + */ + const QString &file() const + { + return m_file; + } + + /** + * This method is used to return the linenumber that was passed + * during the creation of the exception object. + * + * @return long integer containing the line number + */ + unsigned long line() const + { + return m_line; + } + +private: + /** + * This member variable holds the message + */ + QString m_msg; + + /** + * This member variable holds the filename + */ + QString m_file; + + /** + * This member variable holds the line number + */ + unsigned long m_line; +}; + +#endif diff --git a/src/alkexception.cpp b/src/alkexception.cpp new file mode 100644 --- /dev/null +++ b/src/alkexception.cpp @@ -0,0 +1,32 @@ +/*************************************************************************** + * Copyright 2000-2002 by Michael Edwardes mte@users.sourceforge.net * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkexception.h" + +AlkException::AlkException(const QString &msg, const QString &file, const unsigned long line) +{ + // qDebug("ALKEXCEPTION(%s,%s,%ul)", qPrintable(msg), qPrintable(file), line); + m_msg = msg; + m_file = file; + m_line = line; +} + +AlkException::~AlkException() +{ +} diff --git a/src/alkfinancequoteprocess.h b/src/alkfinancequoteprocess.h new file mode 100644 --- /dev/null +++ b/src/alkfinancequoteprocess.h @@ -0,0 +1,56 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * Copyright 2004 Thomas Baumgart * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKFINANCEQUOTEPROCESS_H +#define ALKFINANCEQUOTEPROCESS_H + +#include + +#include + +/** +Helper class to run the Finance::Quote process. This is used only for the purpose of obtaining +a list of valid sources. The actual price quotes are obtained thru AlkFinanceQouteProcess. +The class also contains functions to convert between the rather cryptic source names used +by the Finance::Quote package, and more user-friendly names. + +@author Thomas Baumgart & Ace Jones , Tony B + */ +class ALK_EXPORT AlkFinanceQuoteProcess : public KProcess +{ + Q_OBJECT +public: + AlkFinanceQuoteProcess(); + void launch(const QString &scriptPath); + bool isFinished() const; + const QStringList getSourceList() const; + const QString crypticName(const QString &niceName) const; + const QString niceName(const QString &crypticName) const; + +public slots: + void slotReceivedDataFromFilter(); + void slotProcessExited(); + +private: + class Private; + Private *d; +}; + +#endif // ALKFINANCEQUOTEPROCESS_H diff --git a/src/alkfinancequoteprocess.cpp b/src/alkfinancequoteprocess.cpp new file mode 100644 --- /dev/null +++ b/src/alkfinancequoteprocess.cpp @@ -0,0 +1,167 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * Copyright 2004 Thomas Baumgart * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkfinancequoteprocess.h" + +#include +#include + +class AlkFinanceQuoteProcess::Private +{ +public: + typedef QMap fqNameMap; + bool m_isDone; + QString m_string; + fqNameMap m_fqNames; + + Private() : m_isDone(false) + { + } +}; + +AlkFinanceQuoteProcess::AlkFinanceQuoteProcess() +{ + d->m_fqNames["aex"] = "AEX"; + d->m_fqNames["aex_futures"] = "AEX Futures"; + d->m_fqNames["aex_options"] = "AEX Options"; + d->m_fqNames["amfiindia"] = "AMFI India"; + d->m_fqNames["asegr"] = "ASE"; + d->m_fqNames["asia"] = "Asia (Yahoo, ...)"; + d->m_fqNames["asx"] = "ASX"; + d->m_fqNames["australia"] = "Australia (ASX, Yahoo, ...)"; + d->m_fqNames["bmonesbittburns"] = "BMO NesbittBurns"; + d->m_fqNames["brasil"] = "Brasil (Yahoo, ...)"; + d->m_fqNames["canada"] = "Canada (Yahoo, ...)"; + d->m_fqNames["canadamutual"] = "Canada Mutual (Fund Library, ...)"; + d->m_fqNames["deka"] = "Deka Investments"; + d->m_fqNames["dutch"] = "Dutch (AEX, ...)"; + d->m_fqNames["dwsfunds"] = "DWS"; + d->m_fqNames["europe"] = "Europe (Yahoo, ...)"; + d->m_fqNames["fidelity"] = "Fidelity (Fidelity, ...)"; + d->m_fqNames["fidelity_direct"] = "Fidelity Direct"; + d->m_fqNames["financecanada"] = "Finance Canada"; + d->m_fqNames["ftportfolios"] = "First Trust (First Trust, ...)"; + d->m_fqNames["ftportfolios_direct"] = "First Trust Portfolios"; + d->m_fqNames["fundlibrary"] = "Fund Library"; + d->m_fqNames["greece"] = "Greece (ASE, ...)"; + d->m_fqNames["indiamutual"] = "India Mutual (AMFI, ...)"; + d->m_fqNames["maninv"] = "Man Investments"; + d->m_fqNames["fool"] = "Motley Fool"; + d->m_fqNames["nasdaq"] = "Nasdaq (Yahoo, ...)"; + d->m_fqNames["nz"] = "New Zealand (Yahoo, ...)"; + d->m_fqNames["nyse"] = "NYSE (Yahoo, ...)"; + d->m_fqNames["nzx"] = "NZX"; + d->m_fqNames["platinum"] = "Platinum Asset Management"; + d->m_fqNames["seb_funds"] = "SEB"; + d->m_fqNames["sharenet"] = "Sharenet"; + d->m_fqNames["za"] = "South Africa (Sharenet, ...)"; + d->m_fqNames["troweprice_direct"] = "T. Rowe Price"; + d->m_fqNames["troweprice"] = "T. Rowe Price"; + d->m_fqNames["tdefunds"] = "TD Efunds"; + d->m_fqNames["tdwaterhouse"] = "TD Waterhouse Canada"; + d->m_fqNames["tiaacref"] = "TIAA-CREF"; + d->m_fqNames["trustnet"] = "Trustnet"; + d->m_fqNames["uk_unit_trusts"] = "U.K. Unit Trusts"; + d->m_fqNames["unionfunds"] = "Union Investments"; + d->m_fqNames["tsp"] = "US Govt. Thrift Savings Plan"; + d->m_fqNames["usfedbonds"] = "US Treasury Bonds"; + d->m_fqNames["usa"] = "USA (Yahoo, Fool ...)"; + d->m_fqNames["vanguard"] = "Vanguard"; + d->m_fqNames["vwd"] = "VWD"; + d->m_fqNames["yahoo"] = "Yahoo"; + d->m_fqNames["yahoo_asia"] = "Yahoo Asia"; + d->m_fqNames["yahoo_australia"] = "Yahoo Australia"; + d->m_fqNames["yahoo_brasil"] = "Yahoo Brasil"; + d->m_fqNames["yahoo_europe"] = "Yahoo Europe"; + d->m_fqNames["yahoo_nz"] = "Yahoo New Zealand"; + d->m_fqNames["zifunds"] = "Zuerich Investments"; + connect(this, SIGNAL(readyReadStandardOutput()), this, SLOT(slotReceivedDataFromFilter())); + connect(this, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(slotProcessExited())); + connect(this, SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotProcessExited())); +} + +void AlkFinanceQuoteProcess::slotReceivedDataFromFilter() +{ + QByteArray data(readAllStandardOutput()); + +// kDebug(2) << "WebPriceQuoteProcess::slotReceivedDataFromFilter(): " << QString(data); + d->m_string += QString(data); +} + +void AlkFinanceQuoteProcess::slotProcessExited() +{ +// kDebug(2) << "WebPriceQuoteProcess::slotProcessExited()"; + d->m_isDone = true; +} + +void AlkFinanceQuoteProcess::launch(const QString &scriptPath) +{ + clearProgram(); + + *this << "perl" << scriptPath << "-l"; + setOutputChannelMode(KProcess::OnlyStdoutChannel); + start(); + if (!waitForStarted()) { + qWarning("Unable to start FQ script"); + } +} + +bool AlkFinanceQuoteProcess::isFinished() const +{ + return d->m_isDone; +} + +const QStringList AlkFinanceQuoteProcess::getSourceList() const +{ + QStringList raw = d->m_string.split(0x0A, QString::SkipEmptyParts); + QStringList sources; + QStringList::iterator it; + for (it = raw.begin(); it != raw.end(); ++it) { + if (d->m_fqNames[*it].isEmpty()) { + sources.append(*it); + } else { + sources.append(d->m_fqNames[*it]); + } + } + sources.sort(); + return sources; +} + +const QString AlkFinanceQuoteProcess::crypticName(const QString &niceName) const +{ + QString ret(niceName); + Private::fqNameMap::const_iterator it; + for (it = d->m_fqNames.begin(); it != d->m_fqNames.end(); ++it) { + if (niceName == it.value()) { + ret = it.key(); + break; + } + } + return ret; +} + +const QString AlkFinanceQuoteProcess::niceName(const QString &crypticName) const +{ + QString ret(d->m_fqNames[crypticName]); + if (ret.isEmpty()) { + ret = crypticName; + } + return ret; +} diff --git a/src/alkimia-quotes-local.knsrc b/src/alkimia-quotes-local.knsrc new file mode 100644 --- /dev/null +++ b/src/alkimia-quotes-local.knsrc @@ -0,0 +1,5 @@ +[KNewStuff3] +ProvidersUrl=http://kmymoney.wh.sag.de/ocs/providers.xml +Categories=Skrooge quote source +TargetDir=skrooge/quotes +Uncompress=archive diff --git a/src/alkimia-quotes.knsrc b/src/alkimia-quotes.knsrc new file mode 100644 --- /dev/null +++ b/src/alkimia-quotes.knsrc @@ -0,0 +1,5 @@ +[KNewStuff3] +ProvidersUrl=https://autoconfig.kde.org/ocs/providers.xml +Categories=Skrooge quote source +TargetDir=alkimia/quotes +Uncompress=archive diff --git a/src/alkmoney.h b/src/alkmoney.h new file mode 100644 --- /dev/null +++ b/src/alkmoney.h @@ -0,0 +1,36 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKMONEY_H +#define ALKMONEY_H + +#include + +class ALK_NO_EXPORT AlkMoney +{ +public: + AlkMoney(double value = 0.0) : m_value(value) + { + } + +protected: + double m_value; +}; + +#endif // ALKMONEY_H diff --git a/src/alkmoney.cpp b/src/alkmoney.cpp new file mode 100644 --- /dev/null +++ b/src/alkmoney.cpp @@ -0,0 +1,20 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkmoney.h" diff --git a/src/alkonlinequote.h b/src/alkonlinequote.h new file mode 100644 --- /dev/null +++ b/src/alkonlinequote.h @@ -0,0 +1,132 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKONLINEQUOTE_H +#define ALKONLINEQUOTE_H + +#include + +#include +#include +#include + +class AlkOnlineQuotesProfile; +class QWebView; + +/** +Retrieves a price quote from a web-based quote source + +@author Ace Jones +*/ +class ALK_EXPORT AlkOnlineQuote : public QObject +{ + Q_OBJECT +public: + explicit AlkOnlineQuote(AlkOnlineQuotesProfile *profile = 0, QObject * = 0); + ~AlkOnlineQuote(); + + /** + * Hold errors reported from price quote fetching and parsing + * + * The implementation provides a type safe way to use + * bit operations like '|=' for combining values and '&' + * for checking value presence. + */ + class Errors + { + public: + enum Type { + None, + Data, + Date, + DateFormat, + Price, + Script, + Source, + Symbol, + Success, + URL, + }; + + Errors(); + Errors(Type type); + Errors(const Errors &e); + Errors &operator |=(Type t); + bool operator &(Type t) const; + + protected: + QList m_type; + }; + + AlkOnlineQuotesProfile *profile(); + void setProfile(AlkOnlineQuotesProfile *profile); + + /** + * Set webkit view for fetching web urls using javascript + * + * @param view webkit view to set + */ + void setWebView(QWebView *view); + + /** + * Set accepted language the online quote should be returned for + * + * @param language accepted language to set + */ + void setAcceptLanguage(const QString &language); + + /** + * This launches a web-based quote update for the given @p _symbol. + * When the quote is received back from the web source, it will be + * emitted on the 'quote' signal. + * + * @param _symbol the trading symbol of the stock to fetch a price for + * @param _id an arbitrary identifier, which will be emitted in the quote + * signal when a price is sent back. + * @param _source the source of the quote (must be a valid value returned + * by quoteSources(). Send QString() to use the default + * source. + * @return bool Whether the quote fetch process was launched successfully + * In case of failures it returns false and @ref errors() + * could be used to get error details. + */ +public slots: + bool launch(const QString &_symbol, const QString &_id, const QString &_source = QString()); + + /** + * If @ref launch(), @ref launchNative() or @ref launchFinanceQuote() returns false, + * this method can be used to get details about the errors that occurred. + * + * @return bit map of errors, see class @ref Errors for details + */ + const Errors &errors(); + +signals: + void quote(QString id, QString symbol, QDate date, double price); + void failed(QString id, QString symbol); + void status(QString s); + void error(QString s); + +private: + class Private; + Private *d; +}; + +#endif // ALKONLINEQUOTE_H diff --git a/src/alkonlinequote.cpp b/src/alkonlinequote.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequote.cpp @@ -0,0 +1,587 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequote.h" + +#include "alkdateformat.h" +#include "alkexception.h" +#include "alkfinancequoteprocess.h" +#include "alkonlinequoteprocess.h" +#include "alkonlinequotesprofile.h" +#include "alkonlinequotesource.h" + +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +AlkOnlineQuote::Errors::Errors() +{ +} + +AlkOnlineQuote::Errors::Errors(Type type) +{ + m_type.append(type); +} + +AlkOnlineQuote::Errors::Errors(const Errors &e) +{ + m_type = e.m_type; +} + +AlkOnlineQuote::Errors &AlkOnlineQuote::Errors::operator |=(Type t) +{ + if (!m_type.contains(t)) { + m_type.append(t); + } + return *this; +} + +bool AlkOnlineQuote::Errors::operator &(Type t) const +{ + return m_type.contains(t); +} + + +class AlkOnlineQuote::Private : public QObject +{ + Q_OBJECT +public: + AlkOnlineQuote *m_p; + AlkOnlineQuoteProcess m_filter; + QString m_quoteData; + QString m_symbol; + QString m_id; + QDate m_date; + double m_price; + AlkOnlineQuoteSource m_source; + AlkOnlineQuote::Errors m_errors; + KUrl m_url; + QEventLoop *m_eventLoop; + QWebView *m_webView; + QString m_acceptLanguage; + AlkOnlineQuotesProfile *m_profile; + + static int dbgArea() + { + static int s_area = KDebug::registerArea("Alkimia (AlkOnlineQuote)"); + return s_area; + } + + Private(AlkOnlineQuote *parent) + : m_p(parent) + , m_eventLoop(nullptr) + , m_webView(nullptr) + { + connect(&m_filter, SIGNAL(processExited(QString)), this, SLOT(slotParseQuote(QString))); + } + + bool initLaunch(const QString &_symbol, const QString &_id, const QString &_source); + bool launchWebKitCssSelector(const QString &_symbol, const QString &_id, + const QString &_source); + bool launchWebKitHtmlParser(const QString &_symbol, const QString &_id, const QString &_source); + bool launchNative(const QString &_symbol, const QString &_id, const QString &_source); + bool launchFinanceQuote(const QString &_symbol, const QString &_id, const QString &_source); + void enter_loop(); + bool parsePrice(const QString &pricestr); + bool parseDate(const QString &datestr); + +public slots: + void slotLoadStarted(); + void slotLoadFinishedHtmlParser(bool ok); + void slotLoadFinishedCssSelector(bool ok); + bool slotParseQuote(const QString &_quotedata); +}; + +bool AlkOnlineQuote::Private::initLaunch(const QString &_symbol, const QString &_id, const QString &_source) +{ + m_symbol = _symbol; + m_id = _id; + m_errors = Errors::None; + + emit m_p->status(QString("(Debug) symbol=%1 id=%2...").arg(_symbol, _id)); + + // Get sources from the config file + QString source = _source; + if (source.isEmpty()) { + source = "KMyMoney Currency"; + } + + if (!m_profile->quoteSources().contains(source)) { + emit m_p->error(i18n("Source %1 does not exist.", source)); + m_errors |= Errors::Source; + return false; + } + + //m_profile->createSource(source); + m_source = AlkOnlineQuoteSource(source, m_profile); + + KUrl url; + + // if the source has room for TWO symbols.. + if (m_source.url().contains("%2")) { + // this is a two-symbol quote. split the symbol into two. valid symbol + // characters are: 0-9, A-Z and the dot. anything else is a separator + QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive); + // if we've truly found 2 symbols delimited this way... + if (splitrx.indexIn(m_symbol) != -1) { + url = KUrl(m_source.url().arg(splitrx.cap(1), splitrx.cap(2))); + } else { + kDebug(Private::dbgArea()) << "WebPriceQuote::launch() did not find 2 symbols"; + } + } else { + // a regular one-symbol quote + url = KUrl(m_source.url().arg(m_symbol)); + } + + m_url = url; + + return true; +} + +void AlkOnlineQuote::Private::slotLoadFinishedHtmlParser(bool ok) +{ + if (!ok) { + emit m_p->error(i18n("Unable to fetch url for %1").arg(m_symbol)); + m_errors |= Errors::URL; + emit m_p->failed(m_id, m_symbol); + } else { + // parse symbol + QWebFrame *frame = m_webView->page()->mainFrame(); + slotParseQuote(frame->toHtml()); + } + if (m_eventLoop) + m_eventLoop->exit(); +} + +void AlkOnlineQuote::Private::slotLoadFinishedCssSelector(bool ok) +{ + if (!ok) { + emit m_p->error(i18n("Unable to fetch url for %1").arg(m_symbol)); + m_errors |= Errors::URL; + emit m_p->failed(m_id, m_symbol); + } else { + // parse symbol + QWebFrame *frame = m_webView->page()->mainFrame(); + QWebElement element = frame->findFirstElement(m_source.sym()); + QString symbol = element.toPlainText(); + if (!symbol.isEmpty()) { + emit m_p->status(i18n("Symbol found: '%1'", symbol)); + } else { + m_errors |= Errors::Symbol; + emit m_p->error(i18n("Unable to parse symbol for %1", m_symbol)); + } + + // parse price + element = frame->findFirstElement(m_source.price()); + QString price = element.toPlainText(); + bool gotprice = parsePrice(price); + + // parse date + element = frame->findFirstElement(m_source.date()); + QString date = element.toPlainText(); + bool gotdate = parseDate(date); + + if (gotprice && gotdate) { + emit m_p->quote(m_id, m_symbol, m_date, m_price); + } else { + emit m_p->failed(m_id, m_symbol); + } + } + if (m_eventLoop) + m_eventLoop->exit(); +} + +void AlkOnlineQuote::Private::slotLoadStarted() +{ + emit m_p->status(i18n("Fetching URL %1...", m_url.prettyUrl())); +} + +bool AlkOnlineQuote::Private::launchWebKitCssSelector(const QString &_symbol, const QString &_id, + const QString &_source) +{ + if (!initLaunch(_symbol, _id, _source)) { + return false; + } + connect(m_webView, SIGNAL(loadStarted(bool)), this, SLOT(slotLoadStarted(bool))); + connect(m_webView, SIGNAL(loadFinished(bool)), this, + SLOT(slotLoadFinishedCssSelector(bool))); + m_webView->setUrl(m_url); + m_eventLoop = new QEventLoop; + m_eventLoop->exec(); + delete m_eventLoop; + disconnect(m_webView, SIGNAL(loadStarted(bool)), this, SLOT(slotLoadStarted(bool))); + disconnect(m_webView, SIGNAL(loadFinished(bool)), this, + SLOT(slotLoadFinishedCssSelector(bool))); + + return !(m_errors & Errors::URL || m_errors & Errors::Price + || m_errors & Errors::Date || m_errors & Errors::Data); +} + +bool AlkOnlineQuote::Private::launchWebKitHtmlParser(const QString &_symbol, const QString &_id, + const QString &_source) +{ + if (!initLaunch(_symbol, _id, _source)) { + return false; + } + connect(m_webView, SIGNAL(loadStarted()), this, SLOT(slotLoadStarted())); + connect(m_webView, SIGNAL(loadFinished(bool)), this, SLOT(slotLoadFinishedHtmlParser(bool))); + QNetworkRequest request; + request.setUrl(m_url); + if (!m_acceptLanguage.isEmpty()) + request.setRawHeader("Accept-Language", m_acceptLanguage.toLocal8Bit()); + m_webView->load(request); + m_eventLoop = new QEventLoop; + m_eventLoop->exec(); + delete m_eventLoop; + disconnect(m_webView, SIGNAL(loadStarted(bool)), this, SLOT(slotLoadStarted(bool))); + disconnect(m_webView, SIGNAL(loadFinished(bool)), this, SLOT(slotLoadFinishedHtmlParser( + bool))); + + return !(m_errors & Errors::URL || m_errors & Errors::Price + || m_errors & Errors::Date || m_errors & Errors::Data); +} + +bool AlkOnlineQuote::Private::launchNative(const QString &_symbol, const QString &_id, + const QString &_source) +{ + bool result = true; + if (!initLaunch(_symbol, _id, _source)) { + return false; + } + + KUrl url = m_url; + if (url.isLocalFile()) { + emit m_p->status(i18nc("The process x is executing", "Executing %1...", url.toLocalFile())); + + m_filter.clearProgram(); + m_filter << url.toLocalFile().split(' ', QString::SkipEmptyParts); + m_filter.setSymbol(m_symbol); + + m_filter.setOutputChannelMode(KProcess::MergedChannels); + m_filter.start(); + + if (m_filter.waitForStarted()) { + result = true; + } else { + emit m_p->error(i18n("Unable to launch: %1", url.toLocalFile())); + m_errors |= Errors::Script; + result = slotParseQuote(QString()); + } + } else { + slotLoadStarted(); + + QString tmpFile; + if (KIO::NetAccess::download(url, tmpFile, 0)) { + // kDebug(Private::dbgArea()) << "Downloaded " << tmpFile; + kDebug(Private::dbgArea()) << "Downloaded" << tmpFile << "from" << url; + QFile f(tmpFile); + if (f.open(QIODevice::ReadOnly)) { + // Find out the page encoding and convert it to unicode + QByteArray page = f.readAll(); + KEncodingProber prober(KEncodingProber::Universal); + prober.feed(page); + QTextCodec *codec = QTextCodec::codecForName(prober.encoding()); + if (!codec) { + codec = QTextCodec::codecForLocale(); + } + QString quote = codec->toUnicode(page); + f.close(); + emit m_p->status(i18n("URL found: %1...", url.prettyUrl())); + if (m_webView) + m_webView->setContent(quote.toLocal8Bit()); + result = slotParseQuote(quote); + } else { + emit m_p->error(i18n("Failed to open downloaded file")); + m_errors |= Errors::URL; + result = slotParseQuote(QString()); + } + KIO::NetAccess::removeTempFile(tmpFile); + } else { + emit m_p->error(KIO::NetAccess::lastErrorString()); + m_errors |= Errors::URL; + result = slotParseQuote(QString()); + } + } + return result; +} + +bool AlkOnlineQuote::Private::launchFinanceQuote(const QString &_symbol, const QString &_id, + const QString &_sourcename) +{ + bool result = true; + m_symbol = _symbol; + m_id = _id; + m_errors = Errors::None; +#if 0 + QString FQSource = _sourcename.section(' ', 1); + m_source = AlkOnlineQuoteSource(_sourcename, m_financeQuoteScriptPath, + "\"([^,\"]*)\",.*", // symbol regexp + "[^,]*,[^,]*,\"([^\"]*)\"", // price regexp + "[^,]*,([^,]*),.*", // date regexp + "%y-%m-%d"); // date format + + //emit status(QString("(Debug) symbol=%1 id=%2...").arg(_symbol,_id)); + + m_filter.clearProgram(); + m_filter << "perl" << m_financeQuoteScriptPath << FQSource << KShell::quoteArg(_symbol); + m_filter.setSymbol(m_symbol); + emit m_p->status(i18nc("Executing 'script' 'online source' 'investment symbol' ", + "Executing %1 %2 %3...", m_financeQuoteScriptPath, FQSource, _symbol)); + + m_filter.setOutputChannelMode(KProcess::MergedChannels); + m_filter.start(); + + // This seems to work best if we just block until done. + if (m_filter.waitForFinished()) { + } else { + emit m_p->error(i18n("Unable to launch: %1", m_financeQuoteScriptPath)); + m_errors |= Errors::Script; + result = slotParseQuote(QString()); + } +#else +#warning to be implemented +#endif + + return result; +} + +bool AlkOnlineQuote::Private::parsePrice(const QString &_pricestr) +{ + bool result = true; + // Deal with european quotes that come back as X.XXX,XX or XX,XXX + // + // We will make the assumption that ALL prices have a decimal separator. + // So "1,000" always means 1.0, not 1000.0. + // + // Remove all non-digits from the price string except the last one, and + // set the last one to a period. + QString pricestr(_pricestr); + if (!pricestr.isEmpty()) { + int pos = pricestr.lastIndexOf(QRegExp("\\D")); + if (pos > 0) { + pricestr[pos] = '.'; + pos = pricestr.lastIndexOf(QRegExp("\\D"), pos - 1); + } + while (pos > 0) { + pricestr.remove(pos, 1); + pos = pricestr.lastIndexOf(QRegExp("\\D"), pos); + } + + m_price = pricestr.toDouble(); + kDebug(Private::dbgArea()) << "Price" << pricestr; + emit m_p->status(i18n("Price found: '%1' (%2)", pricestr, m_price)); + } else { + m_errors |= Errors::Price; + emit m_p->error(i18n("Unable to parse price for '%1'", m_symbol)); + result = false; + } + return result; +} + +bool AlkOnlineQuote::Private::parseDate(const QString &datestr) +{ + if (!datestr.isEmpty()) { + emit m_p->status(i18n("Date found: '%1'", datestr)); + + if (m_source.dateformat().contains("%")) { + AlkDateFormat dateparse(m_source.dateformat()); + try { + m_date = dateparse.convertString(datestr, false /*strict*/); + kDebug(Private::dbgArea()) << "Date" << datestr; + emit m_p->status(i18n("Date format found: '%1' -> '%2'", datestr, m_date.toString())); + } catch (const AlkException &e) { + m_errors |= Errors::DateFormat; + emit m_p->error(i18n("Unable to parse date '%1' using format '%2': %3").arg(datestr, + dateparse.format(), + e.what())); + m_date = QDate::currentDate(); + emit m_p->status(i18n("Using current date for '%1'").arg(m_symbol)); + } + } else { + QDate date = QDate::fromString(datestr, m_source.dateformat()); + if (!date.isValid()) { + m_errors |= Errors::DateFormat; + emit m_p->error(i18n("Unable to parse date '%1' using format '%2'").arg(datestr, + m_source.dateformat())); + m_date = QDate::currentDate(); + emit m_p->status(i18n("Using current date for '%1'").arg(m_symbol)); + } else { + m_date = date; + } + } + } else { + m_errors |= Errors::Date; + emit m_p->error(i18n("Unable to parse date for '%1'").arg(m_symbol)); + m_date = QDate::currentDate(); + emit m_p->status(i18n("Using current date for '%1'").arg(m_symbol)); + } + return true; +} + +/** + * Parse quote data according to currently selected web price quote source + * + * @param _quotedata quote data to parse + * @return true parsing successful + * @return false parsing unsuccessful + */ +bool AlkOnlineQuote::Private::slotParseQuote(const QString &_quotedata) +{ + QString quotedata = _quotedata; + m_quoteData = quotedata; + bool gotprice = false; + bool gotdate = false; + bool result = true; + + kDebug(Private::dbgArea()) << "quotedata" << _quotedata; + + if (!quotedata.isEmpty()) { + if (!m_source.skipStripping()) { + // + // First, remove extranous non-data elements + // + + // HTML tags + quotedata.remove(QRegExp("<[^>]*>")); + + // &...;'s + quotedata.replace(QRegExp("&\\w+;"), " "); + + // Extra white space + quotedata = quotedata.simplified(); + kDebug(Private::dbgArea()) << "stripped text" << quotedata; + } + + QRegExp symbolRegExp(m_source.sym()); + QRegExp dateRegExp(m_source.date()); + QRegExp priceRegExp(m_source.price()); + + if (symbolRegExp.indexIn(quotedata) > -1) { + kDebug(Private::dbgArea()) << "Symbol" << symbolRegExp.cap(1); + emit m_p->status(i18n("Symbol found: '%1'", symbolRegExp.cap(1))); + } else { + m_errors |= Errors::Symbol; + emit m_p->error(i18n("Unable to parse symbol for %1", m_symbol)); + } + + if (priceRegExp.indexIn(quotedata) > -1) { + gotprice = true; + QString pricestr = priceRegExp.cap(1); + parsePrice(pricestr); + } else { + parsePrice(QString()); + } + + if (dateRegExp.indexIn(quotedata) > -1) { + gotdate = true; + QString datestr = dateRegExp.cap(1); + parseDate(datestr); + } else { + parseDate(QString()); + } + + if (gotprice && gotdate) { + emit m_p->quote(m_id, m_symbol, m_date, m_price); + } else { + emit m_p->failed(m_id, m_symbol); + result = false; + } + } else { + m_errors |= Errors::Data; + emit m_p->error(i18n("Unable to update price for %1 (empty quote data)", m_symbol)); + emit m_p->failed(m_id, m_symbol); + result = false; + } + return result; +} + +AlkOnlineQuote::AlkOnlineQuote(AlkOnlineQuotesProfile *profile, QObject *_parent) + : QObject(_parent) + , d(new Private(this)) +{ + if (profile) + d->m_profile = profile; + else + d->m_profile = new AlkOnlineQuotesProfile; +} + +AlkOnlineQuote::~AlkOnlineQuote() +{ + delete d; +} + +AlkOnlineQuotesProfile *AlkOnlineQuote::profile() +{ + return d->m_profile; +} + +void AlkOnlineQuote::setProfile(AlkOnlineQuotesProfile *profile) +{ + d->m_profile = profile; +} + +void AlkOnlineQuote::setWebView(QWebView *view) +{ + d->m_webView = view; +} + +void AlkOnlineQuote::setAcceptLanguage(const QString &language) +{ + d->m_acceptLanguage = language; +} + +bool AlkOnlineQuote::launch(const QString &_symbol, const QString &_id, const QString &_source) +{ + if (_source.contains("Finance::Quote")) { + return d->launchFinanceQuote(_symbol, _id, _source); + } else if (_source.endsWith(".css")) { + return d->launchWebKitCssSelector(_symbol, _id, _source); + } else if (_source.endsWith(".webkit")) { + return d->launchWebKitHtmlParser(_symbol, _id, _source); + } else { + return d->launchNative(_symbol, _id, _source); + } +} + +const AlkOnlineQuote::Errors &AlkOnlineQuote::errors() +{ + return d->m_errors; +} + +#include "alkonlinequote.moc" diff --git a/src/alkonlinequoteprocess.h b/src/alkonlinequoteprocess.h new file mode 100644 --- /dev/null +++ b/src/alkonlinequoteprocess.h @@ -0,0 +1,57 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * Copyright 2004 Thomas Baumgart * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKONLINEQUOTEPROCESS_H +#define ALKONLINEQUOTEPROCESS_H + +#include + +#include + +/** +Helper class to attend the process which is running the script, in the case +of a local script being used to fetch the quote. + +@author Thomas Baumgart & Ace Jones +*/ +class ALK_NO_EXPORT AlkOnlineQuoteProcess : public KProcess +{ + Q_OBJECT +public: + AlkOnlineQuoteProcess(); + inline void setSymbol(const QString &_symbol) + { + m_symbol = _symbol; + m_string.truncate(0); + } + +public slots: + void slotReceivedDataFromFilter(); + void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); + +signals: + void processExited(const QString &); + +private: + QString m_symbol; + QString m_string; +}; + +#endif // ALKONLINEQUOTEPROCESS_H diff --git a/src/alkonlinequoteprocess.cpp b/src/alkonlinequoteprocess.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequoteprocess.cpp @@ -0,0 +1,44 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequoteprocess.h" + +// +// Helper class to babysit the KProcess used for running the local script in that case +// + +AlkOnlineQuoteProcess::AlkOnlineQuoteProcess() +{ + connect(this, SIGNAL(readyReadStandardOutput()), this, SLOT(slotReceivedDataFromFilter())); + connect(this, SIGNAL(finished(int,QProcess::ExitStatus)), this, + SLOT(slotProcessExited(int,QProcess::ExitStatus))); +} + +void AlkOnlineQuoteProcess::slotReceivedDataFromFilter() +{ +// kDebug(2) << "WebPriceQuoteProcess::slotReceivedDataFromFilter(): " << QString(data); + m_string += QString(readAllStandardOutput()); +} + +void AlkOnlineQuoteProcess::slotProcessExited(int /*exitCode*/, QProcess::ExitStatus /*exitStatus*/) +{ +// kDebug(2) << "WebPriceQuoteProcess::slotProcessExited()"; + emit processExited(m_string); + m_string.truncate(0); +} diff --git a/src/alkonlinequotesource.h b/src/alkonlinequotesource.h new file mode 100644 --- /dev/null +++ b/src/alkonlinequotesource.h @@ -0,0 +1,78 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKONLINEQUOTESOURCE_H +#define ALKONLINEQUOTESOURCE_H + +#include + +#include + +/** + * @author Thomas Baumgart & Ace Jones + * + * This is a helper class to store information about an online source + * for stock prices or currency exchange rates. + */ +class ALK_EXPORT AlkOnlineQuoteSource +{ +public: + AlkOnlineQuoteSource(); + AlkOnlineQuoteSource(const AlkOnlineQuoteSource &other); + AlkOnlineQuoteSource &operator=(const AlkOnlineQuoteSource &other); + AlkOnlineQuoteSource(const QString &name, AlkOnlineQuotesProfile *profile); + AlkOnlineQuoteSource(const QString &name, const QString &url, const QString &sym, + const QString &price, const QString &date, const QString &dateformat, + bool skipStripping = false); + ~AlkOnlineQuoteSource(); + bool isValid(); + + bool read(); + bool write(); + void rename(const QString &name); + void remove(); + + QString name() const; + QString url() const; + QString sym() const; + QString price() const; + QString date() const; + QString dateformat() const; + bool skipStripping() const; + bool isGHNS(); + + void setName(const QString &name); + void setUrl(const QString &url); + void setSym(const QString &symbol); + void setPrice(const QString &price); + void setDate(const QString &date); + void setDateformat(const QString &dateformat); + void setSkipStripping(bool state); + void setGHNS(bool state); + + QString ghnsWriteFileName(); + void setProfile(AlkOnlineQuotesProfile *profile); + AlkOnlineQuotesProfile *profile(); + +protected: + class Private; + Private *d; +}; + +#endif // ALKONLINEQUOTESOURCE_H diff --git a/src/alkonlinequotesource.cpp b/src/alkonlinequotesource.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequotesource.cpp @@ -0,0 +1,359 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequotesource.h" + +#include "alkonlinequotesprofile.h" + +#include +#include + +#include +#include + +class AlkOnlineQuoteSource::Private +{ +public: + Private() + : m_skipStripping(false) + , m_profile(nullptr) + , m_isGHNSSource(false) + , m_storageChanged(false) + { + } + + Private(const Private *other) + : m_name(other->m_name) + , m_url(other->m_url) + , m_sym(other->m_sym) + , m_price(other->m_price) + , m_date(other->m_date) + , m_dateformat(other->m_dateformat) + , m_skipStripping(other->m_skipStripping) + , m_profile(other->m_profile) + , m_isGHNSSource(other->m_isGHNSSource) + { + } + + bool read() + { + KConfig *kconfig = m_profile->kConfig(); + const QString &group = QString("Online-Quote-Source-%1").arg(m_name); + if (!kconfig->hasGroup(group)) { + return false; + } + KConfigGroup grp = kconfig->group(group); + m_sym = grp.readEntry("SymbolRegex"); + m_date = grp.readEntry("DateRegex"); + m_dateformat = grp.readEntry("DateFormatRegex", "%m %d %y"); + m_price = grp.readEntry("PriceRegex"); + m_url = grp.readEntry("URL"); + m_skipStripping = grp.readEntry("SkipStripping", false); + m_isGHNSSource = false; + return true; + } + + bool write() + { + KConfig *kconfig = m_profile->kConfig(); + KConfigGroup grp = kconfig->group(QString("Online-Quote-Source-%1").arg(m_name)); + grp.writeEntry("URL", m_url); + grp.writeEntry("PriceRegex", m_price); + grp.writeEntry("DateRegex", m_date); + grp.writeEntry("DateFormatRegex", m_dateformat); + grp.writeEntry("SymbolRegex", m_sym); + if (m_skipStripping) { + grp.writeEntry("SkipStripping", m_skipStripping); + } else { + grp.deleteEntry("SkipStripping"); + } + kconfig->sync(); + return true; + } + + bool remove() + { + KConfig *kconfig = m_profile->kConfig(); + kconfig->deleteGroup(QString("Online-Quote-Source-%1").arg(m_name)); + kconfig->sync(); + return true; + } + + QString ghnsReadFilePath() + { + QString fileName = m_profile->hotNewStuffReadFilePath(m_name); + if (!fileName.endsWith(".txt")) + fileName.append(".txt"); + return fileName; + } + + QString ghnsWriteFilePath() + { + QString fileName = m_profile->hotNewStuffWriteFilePath(m_name); + if (!fileName.endsWith(".txt")) + fileName.append(".txt"); + return fileName; + } + + // This is currently in skrooge format + bool readFromGHNSFile() + { + QFileInfo f(ghnsReadFilePath()); + if (!f.exists()) + f.setFile(ghnsWriteFilePath()); + KConfig config(f.absoluteFilePath()); + KConfigGroup group(&config, ""); + if (!(group.hasKey("mode") && group.readEntry("mode") == "HTML" + && group.hasKey("url") && group.hasKey("date") + && group.hasKey("dateformat") && group.hasKey("price"))) { + return false; + } + m_skipStripping = true; + m_url = group.readEntry("url"); + m_price = group.readEntry("price"); + m_date = group.readEntry("date"); + m_dateformat = group.readEntry("dateformat"); + m_isGHNSSource = true; + return true; + } + + // This is currently in skrooge format + bool writeToGHNSFile() + { + KConfig config(ghnsWriteFilePath()); + KConfigGroup group(&config, ""); + group.writeEntry("url", m_url); + group.writeEntry("price", m_price); + group.writeEntry("date", m_date); + group.writeEntry("dateformat", m_dateformat); + group.writeEntry("mode", "HTML"); + return true; + } + + bool removeGHNSFile() + { + qDebug() << "delete" << ghnsWriteFilePath(); + return true; + } + + QString m_name; + QString m_url; + QString m_sym; + QString m_price; + QString m_date; + QString m_dateformat; + bool m_skipStripping; + AlkOnlineQuotesProfile *m_profile; + bool m_isGHNSSource; + bool m_storageChanged; +}; + +AlkOnlineQuoteSource::AlkOnlineQuoteSource() + : d(new Private) +{ +} + +AlkOnlineQuoteSource::AlkOnlineQuoteSource(const AlkOnlineQuoteSource &other) + : d(new Private(other.d)) +{ +} + +AlkOnlineQuoteSource &AlkOnlineQuoteSource::operator=(const AlkOnlineQuoteSource &other) +{ + delete d; + d = new Private(other.d); + return *this; +} + +AlkOnlineQuoteSource::AlkOnlineQuoteSource(const QString &name, const QString &url, + const QString &sym, const QString &price, + const QString &date, const QString &dateformat, + bool skipStripping) + : d(new Private) +{ + d->m_name = name; + d->m_url = url; + d->m_sym = sym; + d->m_price = price; + d->m_date = date; + d->m_dateformat = dateformat; + d->m_skipStripping = skipStripping; + d->m_isGHNSSource = false; +} + +AlkOnlineQuoteSource::AlkOnlineQuoteSource(const QString &name, AlkOnlineQuotesProfile *profile) + : d(new Private) +{ + d->m_profile = profile; + d->m_name = name; + read(); +} + +AlkOnlineQuoteSource::~AlkOnlineQuoteSource() +{ + delete d; +} + +bool AlkOnlineQuoteSource::isValid() +{ + return !d->m_name.isEmpty(); +} + +QString AlkOnlineQuoteSource::name() const +{ + return d->m_name; +} + +QString AlkOnlineQuoteSource::url() const +{ + return d->m_url; +} + +QString AlkOnlineQuoteSource::sym() const +{ + return d->m_sym; +} + +QString AlkOnlineQuoteSource::price() const +{ + return d->m_price; +} + +QString AlkOnlineQuoteSource::date() const +{ + return d->m_date; +} + +QString AlkOnlineQuoteSource::dateformat() const +{ + return d->m_dateformat; +} + +bool AlkOnlineQuoteSource::skipStripping() const +{ + return d->m_skipStripping; +} + +void AlkOnlineQuoteSource::setName(const QString &name) +{ + d->m_name = name; +} + +void AlkOnlineQuoteSource::setUrl(const QString &url) +{ + d->m_url = url; +} + +void AlkOnlineQuoteSource::setSym(const QString &symbol) +{ + d->m_sym = symbol; +} + +void AlkOnlineQuoteSource::setPrice(const QString &price) +{ + d->m_price = price; +} + +void AlkOnlineQuoteSource::setDate(const QString &date) +{ + d->m_date = date; +} + +void AlkOnlineQuoteSource::setDateformat(const QString &dateformat) +{ + d->m_dateformat = dateformat; +} + +void AlkOnlineQuoteSource::setSkipStripping(bool state) +{ + d->m_skipStripping = state; +} + +void AlkOnlineQuoteSource::setGHNS(bool state) +{ + d->m_storageChanged = d->m_isGHNSSource != state; + d->m_isGHNSSource = state; +} + +bool AlkOnlineQuoteSource::isGHNS() +{ + return d->m_isGHNSSource; +} + +QString AlkOnlineQuoteSource::ghnsWriteFileName() +{ + return d->ghnsWriteFilePath(); +} + +void AlkOnlineQuoteSource::setProfile(AlkOnlineQuotesProfile *profile) +{ + d->m_profile = profile; + qDebug() << "using profile" << profile->name(); +} + +AlkOnlineQuotesProfile *AlkOnlineQuoteSource::profile() +{ + return d->m_profile; +} + +bool AlkOnlineQuoteSource::read() +{ + bool result = false; + if (d->m_profile->hasGHNSSupport()) { + result = d->readFromGHNSFile(); + if (result) + return true; + } + return d->read(); +} + +bool AlkOnlineQuoteSource::write() +{ + bool result = false; + // check if type has been changedd->isGHNS + if (d->m_profile->hasGHNSSupport() && d->m_isGHNSSource) { + result = d->writeToGHNSFile(); + if (d->m_storageChanged) + d->remove(); + return result; + } else { + result = d->write(); + if (d->m_profile->hasGHNSSupport() && d->m_storageChanged) { + d->removeGHNSFile(); + } + } + d->m_storageChanged = false; + return result; +} + +void AlkOnlineQuoteSource::rename(const QString &name) +{ + remove(); + d->m_name = name; + write(); +} + +void AlkOnlineQuoteSource::remove() +{ + if (d->m_profile->hasGHNSSupport() && d->m_isGHNSSource) { + d->removeGHNSFile(); + } else { + d->remove(); + } +} diff --git a/src/alkcompany.h b/src/alkonlinequotesprofile.h copy from src/alkcompany.h copy to src/alkonlinequotesprofile.h --- a/src/alkcompany.h +++ b/src/alkonlinequotesprofile.h @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2018 Ralf Habacker * * * * This file is part of libalkimia. * * * @@ -17,65 +17,55 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H +#ifndef ALKONLINEQUOTESPROFILE_H +#define ALKONLINEQUOTESPROFILE_H -#include "alk_export.h" +#include -#include -#include -#include #include +#include -class ALK_EXPORT AlkCompany : public QObject -{ - Q_OBJECT -public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); +class KConfig; - /** - * Financial symbol - */ - const QString &symbol() const; +class AlkOnlineQuoteSource; +class AlkOnlineQuotesProfileManager; - /** - * Name of the equity - */ - const QString &name() const; +class ALK_EXPORT AlkOnlineQuotesProfile +{ +public: + typedef QMap Map; + enum class Type { + Undefined, GHNS, KMyMoney, Skrooge, Script + }; + AlkOnlineQuotesProfile(const QString &name = "alkimia", Type type = Type::KMyMoney, + const QString &ghnsConfigFile = QString()); + ~AlkOnlineQuotesProfile(); - /** - * Type of the equity - */ - const QString &type() const; + QString name() const; + QString hotNewStuffConfigFile() const; + QString hotNewStuffRelPath() const; + QString hotNewStuffReadFilePath(const QString &fileName) const; + QString hotNewStuffWriteFilePath(const QString &fileName) const; + QString kConfigFile() const; + void setManager(AlkOnlineQuotesProfileManager *manager); + AlkOnlineQuotesProfileManager *manager(); + KConfig *kConfig() const; + Type type(); + bool hasGHNSSupport(); /** - * Exchange market of the equity + * return available default sources of this profile */ - const QString &exchange() const; + const Map defaultQuoteSources(); /** - * Internal id + * return available sources of this profile */ - const QString &recordId() const; - - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); + const QStringList quoteSources(); private: - /// \internal d-pointer class. class Private; - /// \internal d-pointer instance. - Private *const d; + Private *d; }; -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); - -Q_DECLARE_METATYPE(AlkCompany) - -#endif +#endif // ALKONLINEQUOTESPROFILE_H diff --git a/src/alkonlinequotesprofile.cpp b/src/alkonlinequotesprofile.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequotesprofile.cpp @@ -0,0 +1,313 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequotesprofile.h" +#include "alkonlinequotesprofilemanager.h" + +#include "alkonlinequotesource.h" +#include "alkfinancequoteprocess.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +class AlkOnlineQuotesProfile::Private : public QObject +{ + Q_OBJECT +public: + AlkOnlineQuotesProfile *m_p; + QString m_name; + QString m_GHNSFile; + QString m_GHNSFilePath; + QString m_kconfigFile; + AlkOnlineQuotesProfileManager *m_profileManager; + KNS3::DownloadManager *m_manager; + KConfig *m_config; + Type m_type; + static QString m_financeQuoteScriptPath; + static QStringList m_financeQuoteSources; + + Private(AlkOnlineQuotesProfile *p) + : m_p(p) + , m_profileManager(0) + , m_manager(0) + , m_config(0) + , m_type(Type::Undefined) + { + + if (m_financeQuoteScriptPath.isEmpty()) { + m_financeQuoteScriptPath = KGlobal::dirs()->findResource("appdata", + QString("misc/financequote.pl")); + } + } + + ~Private() + { + delete m_manager; + delete m_config; + } + + void checkUpdates() + { + m_manager = new KNS3::DownloadManager(m_p->hotNewStuffConfigFile(), this); + // to know when checking for updates is done + connect(m_manager, SIGNAL(searchResult(KNS3::Entry::List)), this, + SLOT(slotUpdatesFound(KNS3::Entry::List))); + // to know about finished installations + connect(m_manager, SIGNAL(entryStatusChanged(KNS3::Entry)), this, + SLOT(entryStatusChanged(KNS3::Entry))); + // start checking for updates + m_manager->checkForUpdates(); + } + +public Q_SLOTS: + void slotUpdatesFound(const KNS3::Entry::List &updates) + { + foreach (const KNS3::Entry &entry, updates) { + qDebug() << entry.name(); + } + } + + // to know about finished installations + void entryStatusChanged(const KNS3::Entry &entry) + { + qDebug() << entry.summary(); + } + + const QStringList quoteSourcesNative() + { + //KSharedConfigPtr kconfig = KGlobal::config(); + KConfig config(m_kconfigFile); + KConfig *kconfig = &config; + QStringList groups = kconfig->groupList(); + + QStringList::Iterator it; + QRegExp onlineQuoteSource(QString("^Online-Quote-Source-(.*)$")); + + // get rid of all 'non online quote source' entries + for (it = groups.begin(); it != groups.end(); it = groups.erase(it)) { + if (onlineQuoteSource.indexIn(*it) >= 0) { + // Insert the name part + it = groups.insert(it, onlineQuoteSource.cap(1)); + ++it; + } + } + + // Set up each of the default sources. These are done piecemeal so that + // when we add a new source, it's automatically picked up. And any changes + // are also picked up. + QMap defaults = defaultQuoteSources(); + QMap::iterator it_source = defaults.begin(); + while (it_source != defaults.end()) { + if (!groups.contains((*it_source).name())) { + groups += (*it_source).name(); + (*it_source).write(); + kconfig->sync(); + } + ++it_source; + } + + return groups; + } + + const QStringList quoteSourcesFinanceQuote() + { + if (m_financeQuoteSources.empty()) { // run the process one time only + // since this is a static function it can be called without constructing an object + // so we need to make sure that m_financeQuoteScriptPath is properly initialized + if (m_financeQuoteScriptPath.isEmpty()) { + m_financeQuoteScriptPath = KGlobal::dirs()->findResource("appdata", + QString("financequote.pl")); + } + AlkFinanceQuoteProcess getList; + getList.launch(m_financeQuoteScriptPath); + while (!getList.isFinished()) { + qApp->processEvents(); + } + m_financeQuoteSources = getList.getSourceList(); + } + return m_financeQuoteSources; + } + + const QStringList quoteSourcesSkrooge() + { + return quoteSourcesGHNS(); + } + + const QStringList quoteSourcesGHNS() + { + QStringList sources; + QString relPath = m_GHNSFilePath; + + foreach (const QString &file, + KStandardDirs().findAllResources("data", relPath + QString::fromLatin1("/*.txt"))) { + QFileInfo f(file); + QString file2 = f.completeBaseName(); + if (!sources.contains(file2)) { + sources.push_back(file2); + } + } + + return sources; + } + + const AlkOnlineQuotesProfile::Map defaultQuoteSources() + { + QMap result; + + // Use fx-rate.net as the standard currency exchange rate source until + // we have the capability to use more than one source. Use a neutral + // name for the source. + + if (m_p->name() == "alkimia") { + result["Alkimia Currency"] + = AlkOnlineQuoteSource("Alkimia Currency", + "https://fx-rate.net/%1/%2", + QString(), // symbolregexp + "1[ a-zA-Z]+=
*(\\d+\\.\\d+)", + "updated\\s\\d+:\\d+:\\d+\\(\\w+\\)\\s+(\\d{1,2}/\\d{2}/\\d{4})", + "%d/%m/%y", + true // skip HTML stripping + ); + } + return result; + } +}; + +// define static members +QString AlkOnlineQuotesProfile::Private::m_financeQuoteScriptPath; +QStringList AlkOnlineQuotesProfile::Private::m_financeQuoteSources; + + +AlkOnlineQuotesProfile::AlkOnlineQuotesProfile(const QString &name, Type type, + const QString &ghnsConfigFile) + : d(new Private(this)) +{ + d->m_name = name; + d->m_GHNSFile = ghnsConfigFile; + d->m_type = type; + d->m_kconfigFile = name + "rc"; + d->m_config = new KConfig(d->m_kconfigFile); + if (!d->m_GHNSFile.isEmpty()) { + KConfig ghnsFile(hotNewStuffConfigFile()); + KConfigGroup group = ghnsFile.group("KNewStuff3"); + d->m_GHNSFilePath = group.readEntry("TargetDir"); + d->checkUpdates(); + } +} + +AlkOnlineQuotesProfile::~AlkOnlineQuotesProfile() +{ + delete d; +} + +QString AlkOnlineQuotesProfile::name() const +{ + return d->m_name; +} + +QString AlkOnlineQuotesProfile::hotNewStuffConfigFile() const +{ + QString configFile = KStandardDirs::locate("config", d->m_GHNSFile); + if (configFile.isEmpty()) { + configFile = QString("%1/%2").arg(KNSRC_DIR, d->m_GHNSFile); + } + + return configFile; +} + +QString AlkOnlineQuotesProfile::hotNewStuffReadFilePath(const QString &fileName) const +{ + return KStandardDirs::locate("data", d->m_GHNSFilePath + "/" + fileName); +} + +QString AlkOnlineQuotesProfile::hotNewStuffWriteFilePath(const QString &fileName) const +{ + return KStandardDirs::locateLocal("data", d->m_GHNSFilePath + "/" + fileName); +} + +QString AlkOnlineQuotesProfile::hotNewStuffRelPath() const +{ + return d->m_GHNSFilePath; +} + +QString AlkOnlineQuotesProfile::kConfigFile() const +{ + return d->m_kconfigFile; +} + +KConfig *AlkOnlineQuotesProfile::kConfig() const +{ + return d->m_config; +} + +AlkOnlineQuotesProfile::Type AlkOnlineQuotesProfile::type() +{ + return d->m_type; +} + +bool AlkOnlineQuotesProfile::hasGHNSSupport() +{ + return !d->m_GHNSFile.isEmpty(); +} + +const AlkOnlineQuotesProfile::Map AlkOnlineQuotesProfile::defaultQuoteSources() +{ + return d->defaultQuoteSources(); +} + +const QStringList AlkOnlineQuotesProfile::quoteSources() +{ + QStringList result; + switch(d->m_type) { + case AlkOnlineQuotesProfile::Type::KMyMoney: + result << d->quoteSourcesNative(); + break; + case AlkOnlineQuotesProfile::Type::Script: + result << d->quoteSourcesFinanceQuote(); + break; + case AlkOnlineQuotesProfile::Type::Skrooge: + result << d->quoteSourcesSkrooge(); + break; + default: + break; + } + if (hasGHNSSupport()) + result << d->quoteSourcesGHNS(); + return result; +} + +void AlkOnlineQuotesProfile::setManager(AlkOnlineQuotesProfileManager *manager) +{ + d->m_profileManager = manager; +} + +AlkOnlineQuotesProfileManager *AlkOnlineQuotesProfile::manager() +{ + return d->m_profileManager; +} + +#include "alkonlinequotesprofile.moc" diff --git a/src/alkcompany.h b/src/alkonlinequotesprofilemanager.h copy from src/alkcompany.h copy to src/alkonlinequotesprofilemanager.h --- a/src/alkcompany.h +++ b/src/alkonlinequotesprofilemanager.h @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2018 Ralf Habacker * * * * This file is part of libalkimia. * * * @@ -17,65 +17,31 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H +#ifndef ALKONLINEQUOTESPROFILEMANAGER_H +#define ALKONLINEQUOTESPROFILEMANAGER_H -#include "alk_export.h" +#include -#include -#include -#include -#include +#include +#include -class ALK_EXPORT AlkCompany : public QObject +typedef QList AlkOnlineQuotesProfileList; + +class ALK_EXPORT AlkOnlineQuotesProfileManager { - Q_OBJECT public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); - - /** - * Financial symbol - */ - const QString &symbol() const; - - /** - * Name of the equity - */ - const QString &name() const; - - /** - * Type of the equity - */ - const QString &type() const; + AlkOnlineQuotesProfileManager(); + ~AlkOnlineQuotesProfileManager(); - /** - * Exchange market of the equity - */ - const QString &exchange() const; - - /** - * Internal id - */ - const QString &recordId() const; - - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); + void addProfile(AlkOnlineQuotesProfile *profile); + AlkOnlineQuotesProfileList profiles(); + AlkOnlineQuotesProfile *profile(const QString &name); + QStringList profileNames(); + static AlkOnlineQuotesProfileManager &instance(); private: - /// \internal d-pointer class. class Private; - /// \internal d-pointer instance. - Private *const d; + Private *d; }; -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); - -Q_DECLARE_METATYPE(AlkCompany) - -#endif +#endif // ALKONLINEQUOTESPROFILEMANAGER_H diff --git a/src/alkonlinequotesprofilemanager.cpp b/src/alkonlinequotesprofilemanager.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequotesprofilemanager.cpp @@ -0,0 +1,75 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia 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) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequotesprofilemanager.h" +#include "alkonlinequotesprofile.h" + +class AlkOnlineQuotesProfileManager::Private +{ +public: + AlkOnlineQuotesProfileList m_profiles; +}; + +AlkOnlineQuotesProfileManager::AlkOnlineQuotesProfileManager() + : d(new Private) +{ +} + +AlkOnlineQuotesProfileManager::~AlkOnlineQuotesProfileManager() +{ + delete d; +} + +void AlkOnlineQuotesProfileManager::addProfile(AlkOnlineQuotesProfile *profile) +{ + if (!d->m_profiles.contains(profile)) { + d->m_profiles.append(profile); + profile->setManager(this); + } +} + +AlkOnlineQuotesProfileList AlkOnlineQuotesProfileManager::profiles() +{ + return d->m_profiles; +} + +AlkOnlineQuotesProfile *AlkOnlineQuotesProfileManager::profile(const QString &name) +{ + foreach (AlkOnlineQuotesProfile *profile, profiles()) { + if (name == profile->name()) { + return profile; + } + } + return nullptr; +} + +QStringList AlkOnlineQuotesProfileManager::profileNames() +{ + QStringList profiles; + foreach(AlkOnlineQuotesProfile *profile, AlkOnlineQuotesProfileManager::instance().profiles()) { + profiles.append(profile->name()); + } + return profiles; +} + +AlkOnlineQuotesProfileManager &AlkOnlineQuotesProfileManager::instance() +{ + static AlkOnlineQuotesProfileManager manager; + return manager; +} diff --git a/src/alkonlinequoteswidget.h b/src/alkonlinequoteswidget.h new file mode 100644 --- /dev/null +++ b/src/alkonlinequoteswidget.h @@ -0,0 +1,51 @@ +/*************************************************************************** + * Copyright 2004 Thomas Baumgart tbaumgart@kde.org * + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKONLINEQUOTESWIDGET_H +#define ALKONLINEQUOTESWIDGET_H + +#include + +#include + +class QWebView; +class QListWidgetItem; + +class ALK_EXPORT AlkOnlineQuotesWidget : public QWidget +{ + Q_OBJECT +public: + AlkOnlineQuotesWidget(bool showProfiles = false, bool showUpload = false, QWidget *parent = 0); + virtual ~AlkOnlineQuotesWidget(); + + void writeConfig(); + void readConfig(); + void resetConfig(); + + void setView(QWebView *view); + QString acceptLanguage() const; + void setAcceptLanguage(const QString &text); + +private: + class Private; + Private *d; +}; + +#endif diff --git a/src/alkonlinequoteswidget.cpp b/src/alkonlinequoteswidget.cpp new file mode 100644 --- /dev/null +++ b/src/alkonlinequoteswidget.cpp @@ -0,0 +1,566 @@ +/*************************************************************************** + * Copyright 2004 Thomas Baumgart tbaumgart@kde.org * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkonlinequoteswidget.h" + +#include "alkonlinequote.h" +#include "alkonlinequotesprofile.h" +#include "alkonlinequotesprofilemanager.h" +#include "alkonlinequotesource.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +class AlkOnlineQuotesWidget::Private : public QWidget, public Ui::AlkOnlineQuotesWidget +{ + Q_OBJECT +public: + QWebView *m_webView; + QString m_acceptLanguage; + QList m_resetList; + AlkOnlineQuoteSource m_currentItem; + bool m_quoteInEditing; + AlkOnlineQuotesProfile *m_profile; + bool m_showProfiles; + bool m_showUpload; + + Private(bool showProfiles, bool showUpload, QWidget *parent); +public slots: + void slotNewProfile(); + void slotDeleteProfile(); + void slotSelectProfile(); + void slotLoadProfile(); + + void slotDeleteEntry(); + void slotUpdateEntry(); + void slotLoadWidgets(); + void slotEntryChanged(); + void slotNewEntry(); + void slotCheckEntry(); + void slotLogStatus(const QString &s); + void slotLogError(const QString &s); + void slotLogFailed(const QString &id, const QString &symbol); + void slotLogQuote(const QString &id, const QString &symbol, const QDate &date, double price); + void slotEntryRenamed(QListWidgetItem *item); + void slotStartRename(QListWidgetItem *item); + void slotInstallEntries(); + void slotUploadEntry(); + +public: + void loadProfiles(); + void loadQuotesList(const bool updateResetList = false); + void clearIcons(); + void setupIcons(const AlkOnlineQuote::Errors &errors); + QString singleSymbol() const; + QStringList doubleSymbol() const; + QString expandedUrl() const; +}; + +AlkOnlineQuotesWidget::Private::Private(bool showProfiles, bool showUpload, QWidget *parent) + : m_webView(nullptr) + , m_quoteInEditing(false) + , m_profile(nullptr) + , m_showProfiles(showProfiles) + , m_showUpload(showUpload) +{ + setupUi(parent); + + if (!showProfiles) + profilesGroupBox->setVisible(false); + if (!showUpload) + m_uploadButton->setVisible(false); + + loadProfiles(); + + // TODO move to ui file + KGuiItem updateButtenItem(i18nc("Accepts the entered data and stores it", "&Accept"), + KIcon("dialog-ok"), + i18n("Accepts the entered data and stores it"), + i18n("Use this to accept the modified data.")); + m_updateButton->setGuiItem(updateButtenItem); + + KGuiItem deleteButtenItem(i18n("&Delete"), + KIcon("edit-delete"), + i18n("Delete the selected source entry"), + i18n("Use this to delete the selected online source entry")); + m_deleteButton->setGuiItem(deleteButtenItem); + + KGuiItem checkButtonItem(i18nc("Check the selected source entry", "&Check Source"), + KIcon("document-edit-verify"), + i18n("Check the selected source entry"), + i18n("Use this to check the selected online source entry")); + m_checkButton->setGuiItem(checkButtonItem); + + KGuiItem showButtonItem(i18nc("Show the selected source entry in a web browser", "&Show page"), + KIcon("applications-internet"), + i18n("Show the selected source entry in a web browser"), + i18n("Use this to show the selected online source entry")); + m_showButton->setGuiItem(showButtonItem); + + KGuiItem newButtenItem(i18nc("Create a new source entry for online quotes", "&New..."), + KIcon("document-new"), + i18n("Create a new source entry for online quotes"), + i18n("Use this to create a new entry for online quotes")); + m_newButton->setGuiItem(newButtenItem); + + connect(m_newProfile, SIGNAL(clicked()), this, SLOT(slotNewProfile())); + connect(m_deleteProfile, SIGNAL(clicked()), this, SLOT(slotDeleteProfile())); + connect(m_profileList, SIGNAL(itemSelectionChanged()), this, SLOT(slotLoadProfile())); + + connect(m_updateButton, SIGNAL(clicked()), this, SLOT(slotUpdateEntry())); + connect(m_newButton, SIGNAL(clicked()), this, SLOT(slotNewEntry())); + connect(m_checkButton, SIGNAL(clicked()), this, SLOT(slotCheckEntry())); + connect(m_deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteEntry())); + connect(m_installButton, SIGNAL(clicked()), this, SLOT(slotInstallEntries())); + connect(m_uploadButton, SIGNAL(clicked()), this, SLOT(slotUploadEntry())); + + connect(m_quoteSourceList, SIGNAL(itemSelectionChanged()), this, SLOT(slotLoadWidgets())); + connect(m_quoteSourceList, SIGNAL(itemChanged(QListWidgetItem *)), this, + SLOT(slotEntryRenamed(QListWidgetItem *))); + connect(m_quoteSourceList, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, + SLOT(slotStartRename(QListWidgetItem *))); + + connect(m_editURL, SIGNAL(textChanged(QString)), this, SLOT(slotEntryChanged())); + connect(m_editSymbol, SIGNAL(textChanged(QString)), this, SLOT(slotEntryChanged())); + connect(m_editDate, SIGNAL(textChanged(QString)), this, SLOT(slotEntryChanged())); + connect(m_editDateFormat, SIGNAL(textChanged(QString)), this, SLOT(slotEntryChanged())); + connect(m_editPrice, SIGNAL(textChanged(QString)), this, SLOT(slotEntryChanged())); + connect(m_skipStripping, SIGNAL(toggled(bool)), this, SLOT(slotEntryChanged())); + connect(m_ghnsSource, SIGNAL(toggled(bool)), this, SLOT(slotEntryChanged())); + + m_checkSymbol->setText("ORCL"); + m_checkSymbol2->setText("BTC GBP"); + m_updateButton->setEnabled(false); + m_showButton->setVisible(false); + slotLoadProfile(); +} + +void AlkOnlineQuotesWidget::Private::loadProfiles() +{ + AlkOnlineQuotesProfileList list = AlkOnlineQuotesProfileManager::instance().profiles(); + foreach (AlkOnlineQuotesProfile *profile, list) { + QListWidgetItem *item = new QListWidgetItem(dynamic_cast(m_profileList)); + item->setText(profile->name()); + item->setFlags(item->flags() | Qt::ItemIsEditable); + } + m_profileList->setCurrentRow(0); + m_profile = AlkOnlineQuotesProfileManager::instance().profiles().first(); + loadQuotesList(); +} + +void AlkOnlineQuotesWidget::Private::loadQuotesList(const bool updateResetList) +{ + //disconnect the slot while items are being loaded and reconnect at the end + disconnect(m_quoteSourceList, SIGNAL(itemChanged(QListWidgetItem *)), this, + SLOT(slotEntryRenamed(QListWidgetItem *))); + m_quoteInEditing = false; + QStringList groups = m_profile->quoteSources(); + + if (updateResetList) { + m_resetList.clear(); + } + m_quoteSourceList->clear(); + QStringList::Iterator it; + for (it = groups.begin(); it != groups.end(); ++it) { + AlkOnlineQuoteSource source(*it, m_profile); + if (!source.isValid()) { + continue; + } + + QListWidgetItem *item = new QListWidgetItem(*it); + item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled); + m_quoteSourceList->addItem(item); + if (updateResetList) { + m_resetList += source; + } + } + m_quoteSourceList->sortItems(); + + QListWidgetItem *first = m_quoteSourceList->item(0); + if (first) { + m_quoteSourceList->setCurrentItem(first); + } + slotLoadWidgets(); + + m_newButton->setEnabled((m_quoteSourceList->findItems(i18n("New Quote Source"), + Qt::MatchExactly)).count() == 0); + connect(m_quoteSourceList, SIGNAL(itemChanged(QListWidgetItem *)), this, + SLOT(slotEntryRenamed(QListWidgetItem *))); +} + +void AlkOnlineQuotesWidget::Private::slotNewProfile() +{ + QListWidgetItem *item = new QListWidgetItem(dynamic_cast(m_profileList)); + item->setText(QLatin1String("new profile")); + item->setFlags(item->flags() | Qt::ItemIsEditable); +} + +void AlkOnlineQuotesWidget::Private::slotDeleteProfile() +{ + delete m_profileList->currentItem(); +} + +void AlkOnlineQuotesWidget::Private::slotSelectProfile() +{ + slotLoadProfile(); +} + +void AlkOnlineQuotesWidget::Private::slotLoadProfile() +{ + AlkOnlineQuotesProfileList list = AlkOnlineQuotesProfileManager::instance().profiles(); + if (!m_showProfiles) { + AlkOnlineQuotesProfileList list = AlkOnlineQuotesProfileManager::instance().profiles(); + m_profile = list.first(); + loadQuotesList(); + return; + } + + foreach (AlkOnlineQuotesProfile *profile, list) { + if (m_profileList->currentItem()->text() == profile->name()) { + m_profile = profile; + loadQuotesList(); + m_installButton->setVisible(profile->type() == AlkOnlineQuotesProfile::Type::GHNS); + } + } +} + +void AlkOnlineQuotesWidget::Private::slotLoadWidgets() +{ + m_quoteInEditing = false; + QListWidgetItem *item = m_quoteSourceList->currentItem(); + + m_editURL->setEnabled(true); + m_editSymbol->setEnabled(true); + m_editPrice->setEnabled(true); + m_editDate->setEnabled(true); + m_editDateFormat->setEnabled(true); + m_skipStripping->setEnabled(true); + m_ghnsSource->setEnabled(true); + m_editURL->setText(QString()); + m_editSymbol->setText(QString()); + m_editPrice->setText(QString()); + m_editDate->setText(QString()); + m_editDateFormat->setText(QString()); + + if (item) { + m_currentItem = AlkOnlineQuoteSource(item->text(), m_profile); + m_editURL->setText(m_currentItem.url()); + m_editSymbol->setText(m_currentItem.sym()); + m_editPrice->setText(m_currentItem.price()); + m_editDate->setText(m_currentItem.date()); + m_editDateFormat->setText(m_currentItem.dateformat()); + m_skipStripping->setChecked(m_currentItem.skipStripping()); + m_ghnsSource->setChecked(m_currentItem.isGHNS()); + } else { + m_editURL->setEnabled(false); + m_editSymbol->setEnabled(false); + m_editPrice->setEnabled(false); + m_editDate->setEnabled(false); + m_editDateFormat->setEnabled(false); + m_skipStripping->setEnabled(false); + m_ghnsSource->setEnabled(false); + } + + m_updateButton->setEnabled(false); +} + +void AlkOnlineQuotesWidget::Private::slotEntryChanged() +{ + clearIcons(); + bool modified = m_editURL->text() != m_currentItem.url() + || m_editSymbol->text() != m_currentItem.sym() + || m_editDate->text() != m_currentItem.date() + || m_editDateFormat->text() != m_currentItem.dateformat() + || m_editPrice->text() != m_currentItem.price() + || m_skipStripping->isChecked() != m_currentItem.skipStripping() + || m_ghnsSource->isChecked() != m_currentItem.isGHNS(); + + m_updateButton->setEnabled(modified); + m_checkButton->setEnabled(!modified); + m_checkSymbol->setEnabled(!m_currentItem.url().contains("%2")); + m_checkSymbol2->setEnabled(m_currentItem.url().contains("%2")); +} + +void AlkOnlineQuotesWidget::Private::slotDeleteEntry() +{ + QList items = m_quoteSourceList->findItems( + m_currentItem.name(), Qt::MatchExactly); + if (items.size() == 0) { + return; + } + QListWidgetItem *item = items.at(0); + if (!item) { + return; + } + + int ret = KMessageBox::warningContinueCancel(this, + i18n("Are you sure to delete this online quote ?"), + i18n("Delete online quote"), + KStandardGuiItem::cont(), + KStandardGuiItem::cancel(), + QString("DeletingOnlineQuote")); + if (ret == KMessageBox::Cancel) { + return; + } + + // keep this order to avoid deleting the wrong current item + m_currentItem.remove(); + delete item; + slotEntryChanged(); +} + +void AlkOnlineQuotesWidget::Private::slotUpdateEntry() +{ + m_currentItem.setUrl(m_editURL->text()); + m_currentItem.setSym(m_editSymbol->text()); + m_currentItem.setDate(m_editDate->text()); + m_currentItem.setDateformat(m_editDateFormat->text()); + m_currentItem.setPrice(m_editPrice->text()); + m_currentItem.setSkipStripping(m_skipStripping->isChecked()); + m_currentItem.setGHNS(m_ghnsSource->isChecked()); + m_currentItem.write(); + m_checkButton->setEnabled(true); + slotEntryChanged(); +} + +void AlkOnlineQuotesWidget::Private::slotNewEntry() +{ + AlkOnlineQuoteSource newSource(i18n("New Quote Source"), m_profile); + newSource.write(); + loadQuotesList(); + QListWidgetItem *item + = m_quoteSourceList->findItems(i18n("New Quote Source"), Qt::MatchExactly).at(0); + if (item) { + m_quoteSourceList->setCurrentItem(item); + slotLoadWidgets(); + } +} + +void AlkOnlineQuotesWidget::Private::clearIcons() +{ + QPixmap emptyIcon; + m_urlCheckLabel->setPixmap(emptyIcon); + m_dateCheckLabel->setPixmap(emptyIcon); + m_priceCheckLabel->setPixmap(emptyIcon); + m_symbolCheckLabel->setPixmap(emptyIcon); + m_dateFormatCheckLabel->setPixmap(emptyIcon); +} + +void AlkOnlineQuotesWidget::Private::setupIcons(const AlkOnlineQuote::Errors &errors) +{ + QPixmap okIcon(BarIcon("dialog-ok-apply")); + QPixmap failIcon(BarIcon("dialog-cancel")); + + if (errors & AlkOnlineQuote::Errors::URL) { + m_urlCheckLabel->setPixmap(failIcon); + } else { + m_urlCheckLabel->setPixmap(okIcon); + m_symbolCheckLabel->setPixmap(errors & AlkOnlineQuote::Errors::Symbol ? failIcon : okIcon); + m_priceCheckLabel->setPixmap(errors & AlkOnlineQuote::Errors::Price ? failIcon : okIcon); + if (errors & AlkOnlineQuote::Errors::Date) { + m_dateCheckLabel->setPixmap(failIcon); + } else { + m_dateCheckLabel->setPixmap(okIcon); + m_dateFormatCheckLabel->setPixmap( + errors & AlkOnlineQuote::Errors::DateFormat ? failIcon : okIcon); + } + } +} + +void AlkOnlineQuotesWidget::Private::slotCheckEntry() +{ + AlkOnlineQuote quote(m_profile); + m_logWindow->setVisible(true); + m_logWindow->clear(); + clearIcons(); + quote.setWebView(m_webView); + quote.setAcceptLanguage(m_acceptLanguage); + + connect("e, SIGNAL(status(QString)), this, SLOT(slotLogStatus(QString))); + connect("e, SIGNAL(error(QString)), this, SLOT(slotLogError(QString))); + connect("e, SIGNAL(failed(QString,QString)), this, SLOT(slotLogFailed(QString,QString))); + connect("e, SIGNAL(quote(QString,QString,QDate,double)), this, + SLOT(slotLogQuote(QString,QString,QDate,double))); + if (m_currentItem.url().contains("%2")) { + quote.launch(m_checkSymbol2->text(), m_checkSymbol2->text(), m_currentItem.name()); + } else { + quote.launch(m_checkSymbol->text(), m_checkSymbol->text(), m_currentItem.name()); + } + setupIcons(quote.errors()); +} + +void AlkOnlineQuotesWidget::Private::slotLogStatus(const QString &s) +{ + m_logWindow->append(s); +} + +void AlkOnlineQuotesWidget::Private::slotLogError(const QString &s) +{ + slotLogStatus(QString("") + s + QString("")); +} + +void AlkOnlineQuotesWidget::Private::slotLogFailed(const QString &id, const QString &symbol) +{ + slotLogStatus(QString("%1 %2").arg(id, symbol)); +} + +void AlkOnlineQuotesWidget::Private::slotLogQuote(const QString &id, const QString &symbol, + const QDate &date, double price) +{ + slotLogStatus(QString("%1 %2 %3 %4").arg(id, symbol, + date.toString()).arg( + price)); +} + +void AlkOnlineQuotesWidget::Private::slotStartRename(QListWidgetItem *item) +{ + m_quoteInEditing = true; + m_quoteSourceList->editItem(item); +} + +void AlkOnlineQuotesWidget::Private::slotEntryRenamed(QListWidgetItem *item) +{ + //if there is no current item selected, exit + if (m_quoteInEditing == false || !m_quoteSourceList->currentItem() + || item != m_quoteSourceList->currentItem()) { + return; + } + + m_quoteInEditing = false; + QString text = item->text(); + int nameCount = 0; + for (int i = 0; i < m_quoteSourceList->count(); ++i) { + if (m_quoteSourceList->item(i)->text() == text) { + ++nameCount; + } + } + + // Make sure we get a non-empty and unique name + if (text.length() > 0 && nameCount == 1) { + m_currentItem.rename(text); + } else { + item->setText(m_currentItem.name()); + } + m_quoteSourceList->sortItems(); + m_newButton->setEnabled(m_quoteSourceList->findItems(i18n( + "New Quote Source"), + Qt::MatchExactly).count() == 0); +} + +void AlkOnlineQuotesWidget::Private::slotInstallEntries() +{ + QString configFile = m_profile->hotNewStuffConfigFile(); + + QPointer dialog = new KNS3::DownloadDialog(configFile, this); + dialog->exec(); + delete dialog; + loadQuotesList(); +} + +void AlkOnlineQuotesWidget::Private::slotUploadEntry() +{ + QString configFile = m_profile->hotNewStuffConfigFile(); + + QUrl url = QUrl::fromLocalFile(m_currentItem.ghnsWriteFileName()); + qDebug() << "uploading file" << url; + QPointer dialog = new KNS3::UploadDialog(configFile, this); + dialog->setUploadName(m_currentItem.name()); + dialog->setUploadFile(url); + dialog->exec(); + delete dialog; +} + +QString AlkOnlineQuotesWidget::Private::expandedUrl() const +{ + if (m_currentItem.url().contains("%2")) { + return m_currentItem.url().arg(m_checkSymbol2->text()); + } else { + return m_currentItem.url().arg(m_checkSymbol->text()); + } +} + +AlkOnlineQuotesWidget::AlkOnlineQuotesWidget(bool showProfiles, bool showUpload, QWidget *parent) + : QWidget(parent) + , d(new Private(showProfiles, showUpload, this)) +{ +} + +AlkOnlineQuotesWidget::~AlkOnlineQuotesWidget() +{ + delete d; +} + +void AlkOnlineQuotesWidget::readConfig() +{ +} + +void AlkOnlineQuotesWidget::writeConfig() +{ +} + +void AlkOnlineQuotesWidget::resetConfig() +{ + QStringList::ConstIterator it; + QStringList groups = d->m_profile->quoteSources(); + + // delete all currently defined entries + for (it = groups.constBegin(); it != groups.constEnd(); ++it) { + AlkOnlineQuoteSource(*it, d->m_profile).remove(); + } + + // and write back the one's from the reset list + QList::iterator itr; + for (itr = d->m_resetList.begin(); itr != d->m_resetList.end(); ++itr) { + (*itr).write(); + } + + d->loadQuotesList(); +} + +void AlkOnlineQuotesWidget::setView(QWebView *view) +{ + d->m_webView = view; +} + +QString AlkOnlineQuotesWidget::acceptLanguage() const +{ + return d->m_acceptLanguage; +} + +void AlkOnlineQuotesWidget::setAcceptLanguage(const QString &text) +{ + d->m_acceptLanguage = text; +} + +#include "alkonlinequoteswidget.moc" diff --git a/src/alkonlinequoteswidget.ui b/src/alkonlinequoteswidget.ui new file mode 100644 --- /dev/null +++ b/src/alkonlinequoteswidget.ui @@ -0,0 +1,484 @@ + + + AlkOnlineQuotesWidget + + + + 0 + 0 + 523 + 815 + + + + + 0 + 0 + + + + Online Quotes + + + + + + + + + + <html><head/><body><p>Select, add or delete an application profile, where where to load profiles from and save into eg. kmymoney or skrooge.</p></body></html> + + + Application Profiles + + + Qt::AlignCenter + + + + + + + + + + + + + false + + + New + + + + + + + false + + + Delete + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + <html><head/><body><p>online price quotes</p></body></html> + + + Online Quotes + + + Qt::AlignCenter + + + + + + + 0 + 0 + + + + + 16777215 + 120 + + + + + + + + + + New + + + + + + + Delete + + + + + + + Install + + + + + + + Upload + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + <html><head/><body><p><span style=" font-style:italic;">Enter regular expressions which can be used to parse the data returned from the URL entered above. The symbol, price, and date must be found in the quote data to be usable. You may also try the KMyMoney forum at </span><a href="https://forum.kde.org/viewforum.php?f=69"><span style=" text-decoration: underline; color:#2980b9;">https://forum.kde.org/viewforum.php?f=69</span></a> or the <span style=" font-style:italic;">user's mailinglist at </span><a href="mailto:kmymoney@kde.org"><span style=" font-style:italic; text-decoration: underline; color:#2980b9;">kmymoney@kde.org</span></a><span style=" font-style:italic;"> to find what settings work for other users in your country.</span></p></body></html> + + + Details + + + Qt::AlignCenter + + + + + + + + + + Regular Expression to extract the date from the downloaded data + + + + + + + Date Format + + + false + + + + + + + + + + + + + + Regular Expression to extract the symbol from the downloaded data + + + + + + + Date + + + false + + + + + + + <p>For easier processing of the data returned by the online source, KMyMoney usually strips unused parts before it is parsed with the regular expressions. If matching of the fields relies on those items, then use this option to turn stripping off.</p> + +<p>The following items are usually removed by stripping: + +<ul> +<li>HTML tags such as <b>&lt;tag&gt;</b></li> +<li>& encoded characters such as <b>&amp;nbsp;</b></li> +<li>duplicate whitespace</li> +</ul> +</p> + + + Skip HTML stripping + + + + + + + + + + + + + + + + + + + + + URL + + + false + + + + + + + Regular Expression to extract the price from the downloaded data + + + + + + + Options + + + + + + + + + + GHNS Source + + + + + + + + + + + + + + + + + + + + + Price + + + false + + + + + + + Symbol + + + false + + + + + + + Regular Expression to extract the date from the downloaded data + + + + + + + URL to be used to download the quote + + + Enter the URL from which stock quotes will be fetched. <b>%1</b> will be replaced with the symbol for the security being quoted. For currency conversions, <b>%2</b> will be replaced with the currency to be quoted and <b>%1</b> with the currency the quote is based on. + + + + + + + + + 0 + + + + + Accept + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + Debugging + + + Qt::AlignCenter + + + + + + + + + + + + One Symbol + + + + + + + + + + + + + + Two Symbols + + + + + + + + + + + + + + + + + + + + + Check Source + + + + + + + Show Page + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + + KListWidget + QListWidget +
klistwidget.h
+
+ + KPushButton + QPushButton +
kpushbutton.h
+
+ + KTextEdit + QTextEdit +
ktextedit.h
+
+ + KLineEdit + QLineEdit +
klineedit.h
+
+
+ + +
diff --git a/src/alkquoteitem.h b/src/alkquoteitem.h --- a/src/alkquoteitem.h +++ b/src/alkquoteitem.h @@ -20,8 +20,7 @@ #ifndef ALKQUOTEITEM_H #define ALKQUOTEITEM_H -#include "alk_export.h" -#include "alkvalue.h" +#include #include #include diff --git a/src/alkquotereceiver.h b/src/alkquotereceiver.h new file mode 100644 --- /dev/null +++ b/src/alkquotereceiver.h @@ -0,0 +1,62 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 ALKQUOTERECEIVER_H +#define ALKQUOTERECEIVER_H + +#include "alkmoney.h" + +#include +#include +#include + +class AlkOnlineQuote; + +namespace convertertest { +/** +Simple class to handle signals/slots for unit tests + +@author Ace Jones +*/ +class ALK_NO_EXPORT AlkQuoteReceiver : public QObject +{ + Q_OBJECT +public: + explicit AlkQuoteReceiver(AlkOnlineQuote *q, QObject *parent = 0); + ~AlkQuoteReceiver(); + void setVerbose(bool verbose) + { + m_verbose = verbose; + } + +public Q_SLOTS: + void slotGetQuote(const QString &, const QString &, const QDate &, const double &); + void slotStatus(const QString &); + void slotError(const QString &); +public: + QStringList m_statuses; + QStringList m_errors; + AlkMoney m_price; + QDate m_date; +protected: + bool m_verbose; +}; +} // end namespace convertertest + +#endif // ALKQUOTERECEIVER_H diff --git a/src/alkquotereceiver.cpp b/src/alkquotereceiver.cpp new file mode 100644 --- /dev/null +++ b/src/alkquotereceiver.cpp @@ -0,0 +1,67 @@ +/*************************************************************************** + * Copyright 2004 Ace Jones * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "alkquotereceiver.h" +#include "alkonlinequote.h" + +#include + +convertertest::AlkQuoteReceiver::AlkQuoteReceiver(AlkOnlineQuote *q, QObject *parent) + : QObject(parent) +{ + connect(q, SIGNAL(quote(QString,QString,QDate,double)), + this, SLOT(slotGetQuote(QString,QString,QDate,double))); + connect(q, SIGNAL(status(QString)), + this, SLOT(slotStatus(QString))); + connect(q, SIGNAL(error(QString)), + this, SLOT(slotError(QString))); +} + +convertertest::AlkQuoteReceiver::~AlkQuoteReceiver() +{ +} + +void convertertest::AlkQuoteReceiver::slotGetQuote(const QString &a, const QString &b, + const QDate &d, const double &m) +{ + if (m_verbose) { + qDebug() << "test::AlkQuoteReceiver::slotGetQuote( , " << a << " , " << b << " , " << d + << " , " << m << " )"; + } + m_price = AlkMoney(m); + m_date = d; +} + +void convertertest::AlkQuoteReceiver::slotStatus(const QString &msg) +{ + if (m_verbose) { + qDebug() << "test::AlkQuoteReceiver::slotStatus( " << msg << " )"; + } + + m_statuses += msg; +} + +void convertertest::AlkQuoteReceiver::slotError(const QString &msg) +{ + if (m_verbose) { + qDebug() << "test::AlkQuoteReceiver::slotError( " << msg << " )"; + } + + m_errors += msg; +} diff --git a/src/alkvalue.h.in b/src/alkvalue.h.in --- a/src/alkvalue.h.in +++ b/src/alkvalue.h.in @@ -21,15 +21,15 @@ #ifndef ALKVALUE_H #define ALKVALUE_H +#include + // Workaround: include before gmpxx.h to fix build with gcc-4.9 /** @todo When gmp version is higer than 5.1.3, remove cstddef include */ #include #include <@MP_HEADER@> // krazy:exclude=camelcase #include #include -#include "alk_export.h" - /** * This class represents a financial value within Alkimia. * It can be used to represent balances, shares, amounts etc. @@ -215,6 +215,8 @@ /// @return QString representation in form '[-]num/denom'. QString toString() const; + double toDouble() const; + /** * This method transforms the AlkValue into its canonicalized * form by reducing it to the smallest denominator. Example: diff --git a/src/alkvalue.cpp b/src/alkvalue.cpp --- a/src/alkvalue.cpp +++ b/src/alkvalue.cpp @@ -18,7 +18,7 @@ * along with this program. If not, see * ***************************************************************************/ -#include "alkvalue.h" +#include "alkimia/alkvalue.h" #include #include @@ -251,6 +251,11 @@ return mpqToString(d->m_val); } +double AlkValue::toDouble() const +{ + return d->m_val.get_d(); +} + AlkValue AlkValue::convertDenominator(int _denom, const RoundingMethod how) const { AlkValue in(*this); diff --git a/src/financequote.pl b/src/financequote.pl new file mode 100644 --- /dev/null +++ b/src/financequote.pl @@ -0,0 +1,121 @@ +#!/usr/bin/perl +###################################################################### +### financequote.pl - KMyMoney interface to Finance::Quote +### +### derived from GnuCash finance-quote-helper script which is +### Copyright 2001 Rob Browning +### +### This program is free software; you can redistribute it and/or +### modify it under the terms of the 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, contact: +### +### Free Software Foundation Voice: +1-617-542-5942 +### 59 Temple Place - Suite 330 Fax: +1-617-542-2652 +### Boston, MA 02111-1307, USA gnu@gnu.org +###################################################################### + +#use diagnostics; # while testing +use strict; +use Data::Dumper; + +my $prgnam = "kmymoneyfq.pl"; +my $version = "1.00"; +# perl modules required by this routine and Finance::Quote +my @modules = qw(Date::Manip Finance::Quote LWP XML::Parser XML::Writer); + +# main - check command line arguments + +my $testonly; +my $listonly; +# analyze the arguments +foreach my $arg (@ARGV) { + my $listopt = "-l"; # I had a much slicker way of doing this but it stopped working... + my $testopt = "-t"; + $testonly = 1 if $arg =~ $testopt; + $listonly = 1 if $arg =~ $listopt; +} + +# test call; check that all required modules are present +if ($testonly) { + my @absent_modules; # to build list of missing modules + + foreach my $module (@modules) { + if (!eval "require $module") { + push (@absent_modules, $module); + } + } + if (@absent_modules) { + foreach my $module (@absent_modules) { + print STDERR " ".$module."\n"; + } + exit 254; # missing modules exit code for kmymoney + } + exit 0; +} + +# load the required modules +foreach my $module (@modules) { + eval "require $module"; + $module->import(); +} + +# create a finance quote object and set required parameters +my $q = Finance::Quote->new(); +$q->set_currency(); # disable any currency conversion +$q->timeout(60); # timeout 60 seconds +$q->failover(0); # disable failover + +# process call for exchange list only +if ($listonly) { + my @sources = $q->sources(); + foreach my $source (@sources) { + print "$source\n"; + } + exit 0; +} + +my $source = $ARGV[0]; +my $symbol = $ARGV[1]; + +#print "\tfinding price for <$symbol> from <$source>\n"; +my %qhash = $q->fetch($source, $symbol); # get price data from F::Q +#my %qhash = ("RHATsuccess" => 1, "RHATdate" => "4/4/2004", "RHATcurrency" => "USD", + #"RHATbid" => "25.55", "RHATask" => "26.04"); +#print Dumper(%qhash); +my $errcode; +$errcode = 0; + +if (!%qhash) { $errcode = 1;} # no data from fq (?bad exchange?) + elsif ($qhash {$symbol, "success"} != 1) {$errcode = 2;} # got data but quote failed (?bad symbol?) + elsif (!$qhash{$symbol, "last"} and !$qhash{$symbol, "price"} ) {$errcode = 3;} # can't find a price (?hmmm?) +if ($errcode != 0) { + print "Error " => "$errcode"; +} else { + # extract the date and convert from m/d/yyyy to yyyy-mm-dd + my ($usdate, $month, $day, $year, $yyyymmdd); + $usdate = $qhash{$symbol, "date"}; + ($month,$day,$year) = ($usdate =~ /([0-9]+)\/([0-9]+)\/([0-9]+)/); + # i'm sure I can do the folowing with a regex but I'm just too idle... + $month = "0$month" if ($month < 9); + $day = "0$day" if ($day < 9); + $yyyymmdd = "$year-$month-$day"; + # and the price + # (tried having bid and ask here, but could be undef for some stocks (IBM) + # and looked pretty unrealistic for others (e.g. RHAT on 15/5/04 was 12.09-38.32!)) + my $price = $qhash {$symbol, "last"}; + # if no price was found, try to extract it from the price symbol + # see http://bugs.kde.org/show_bug.cgi?id=234268 for details + $price = $qhash {$symbol, "price"} if (!$price); + + print "\"$symbol\",\"$yyyymmdd\",\"$price\""; +} + diff --git a/src/kmymoney-quotes.knsrc b/src/kmymoney-quotes.knsrc new file mode 100644 --- /dev/null +++ b/src/kmymoney-quotes.knsrc @@ -0,0 +1,5 @@ +[KNewStuff3] +ProvidersUrl=https://autoconfig.kde.org/ocs/providers.xml +Categories=Skrooge quote source +TargetDir=kmymoney/quotes +Uncompress=archive diff --git a/src/skrooge-quotes.knsrc b/src/skrooge-quotes.knsrc new file mode 100644 --- /dev/null +++ b/src/skrooge-quotes.knsrc @@ -0,0 +1,5 @@ +[KNewStuff3] +ProvidersUrl=https://autoconfig.kde.org/ocs/providers.xml +Categories=Skrooge quote source +TargetDir=skrooge/quotes +Uncompress=archive diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,28 @@ +add_definitions(-DCMAKE_CURRENT_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}") +set(TEST_LIB + alkimia + alkimia-internal + ${QT_USE_LIBSPREFIX}Core + ${QT_USE_LIBSPREFIX}WebKit +) + +if(BUILD_QT4) + list(APPEND TEST_LIB + ${QT_USE_LIBSPREFIX}Declarative + ${KDE_LIBRARIES} + ) + set(RESOURCES qmlalkonlinequotetest.qrc) + message("FIXME: qmlalkonlinequotetest need to be implemented") +else() + list(APPEND TEST_LIB + ${QT_USE_LIBSPREFIX}Qml + ${QT_USE_LIBSPREFIX}WebKitWidgets + ) + find_package(Qt5QuickCompiler) + qtquick_compiler_add_resources(RESOURCES qmlalkonlinequotetest.qrc) +endif() +add_executable(qmlalkonlinequotetest + qmlalkonlinequotetest.cpp + ${RESOURCES} +) +target_link_libraries(qmlalkonlinequotetest ${TEST_LIB}) diff --git a/tests/qmlalkonlinequotetest-qt4.qml b/tests/qmlalkonlinequotetest-qt4.qml new file mode 100644 --- /dev/null +++ b/tests/qmlalkonlinequotetest-qt4.qml @@ -0,0 +1,103 @@ +import QtQuick 1.0 +import org.kde.alkimia 1.0 + +Item { + width: 500 + height: 300 + + AlkOnlineQuote { + id: quote + onError: { + console.log(s) + errorLabel.text = s + } + onStatus: { + console.log(s) + statusLabel.text = s + } + onQuote: { + statusLabel.text = "" + dateLabel.text = "Date: " + date + priceLabel.text = "Price: " + price + } + } + + Text { + id: symbolLabel + y: 50 + x: 0 + text: "Enter Symbol:" + } + TextInput { + y: 50 + x: 100 + id: symbol + text: "CAD EUR" + //placeholderText: qsTr("Symbol") + } + + Text { + id: quoteLabel + y: 80 + x: 0 + text: "Enter Quote:" + } + TextInput { + y: 80 + x: 100 + id: source + text: "Alkimia Currency" + //placeholderText: qsTr("Source") + } + + Rectangle { + width: 200 + height: 30 + y: 122 + x: 100 + color: "lightgray" + MouseArea { + id: mouseArea; + anchors.fill: parent; + + onClicked: { + dateLabel.text = "" + priceLabel.text = "" + errorLabel.text = "" + statusLabel.text = "" + quote.launch(symbol.text, "", source.text) + } + } + } + + Text { + id: fetchLabel + y: 128 + x: 170 + text: "Fetch" + } + + Text { + id: statusLabel + y: 150 + x: 100 + } + + Text { + id: priceLabel + y: 180 + x: 100 + } + + Text { + id: dateLabel + y: 210 + x: 100 + } + + Text { + id: errorLabel + y: 240 + x: 100 + } +} diff --git a/src/alkcompany.h b/tests/qmlalkonlinequotetest.cpp copy from src/alkcompany.h copy to tests/qmlalkonlinequotetest.cpp --- a/src/alkcompany.h +++ b/tests/qmlalkonlinequotetest.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright 2011 Alvaro Soliverez asoliverez@kde.org * + * Copyright 2018 Ralf Habacker ralf.habacker@freenet.de * * * * This file is part of libalkimia. * * * @@ -17,65 +17,46 @@ * along with this program. If not, see * ***************************************************************************/ -#ifndef ALKCOMPANY_H -#define ALKCOMPANY_H +#include "alkonlinequote.h" -#include "alk_export.h" - -#include -#include -#include -#include - -class ALK_EXPORT AlkCompany : public QObject +#if QT_VERSION >= 0x050000 +#include +#include +#else +#include +class QGuiApplication : public QApplication { - Q_OBJECT public: - AlkCompany(QObject *parent = 0); - AlkCompany(const AlkCompany &company, QObject *parent = 0); - ~AlkCompany(); - - /** - * Financial symbol - */ - const QString &symbol() const; - - /** - * Name of the equity - */ - const QString &name() const; - - /** - * Type of the equity - */ - const QString &type() const; - - /** - * Exchange market of the equity - */ - const QString &exchange() const; - - /** - * Internal id - */ - const QString &recordId() const; + QGuiApplication(int &argc, char **argv) : QApplication(argc, argv) {} +}; - void setSymbol(const QString &symbol); - void setName(const QString &name); - void setType(const QString &type); - void setExchange(const QString &exchange); - void setRecordId(const QString &recordId); +#include +#include +#include -private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private *const d; +class QQmlApplicationEngine : public QDeclarativeEngine +{ +public: + void load(const QUrl &url) + { + QString s = url.toString(); + s.replace(".qml", "-qt4.qml"); + s.replace("qrc:", CMAKE_CURRENT_SOURCE_DIR); + QUrl a = QUrl::fromLocalFile(s); + view.setSource(a); + view.show(); + } + QDeclarativeView view; }; +#endif -ALK_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AlkCompany &company); -ALK_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AlkCompany &company); +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); -Q_DECLARE_METATYPE(AlkCompany) + QQmlApplicationEngine engine; + //engine.addImportPath(CMAKE_BINARY_DIR "/bin"); + engine.load(QUrl("qrc:/qmlalkonlinequotetest.qml")); -#endif + return app.exec(); +} diff --git a/tests/qmlalkonlinequotetest.qml b/tests/qmlalkonlinequotetest.qml new file mode 100644 --- /dev/null +++ b/tests/qmlalkonlinequotetest.qml @@ -0,0 +1,97 @@ +import QtQuick 2.6 +import QtQuick.Controls 2.0 +import org.kde.alkimia 1.0 + +ApplicationWindow { + id: root + width: 500 + height: 300 + visible: true + + AlkOnlineQuote { + id: quote + onError: { + console.log(s) + errorLabel.text = s + } + onStatus: { + console.log(s) + statusLabel.text = s + } + onQuote: { + statusLabel.text = "" + dateLabel.text = "Date: " + date + priceLabel.text = "Price: " + price + } + } + + Label { + id: symbolLabel + y: 56 + x: 0 + text: "Enter symbol:" + } + + TextField { + y: 50 + x: 100 + id: symbol + text: "CAD EUR" + placeholderText: qsTr("Symbol") + } + + Label { + id: quoteLabel + y: 86 + x: 0 + text: "Enter quote:" + } + + TextField { + y: 80 + x: 100 + id: source + text: "Alkimia Currency" + placeholderText: qsTr("Source") + } + + Button { + width: 200 + height: 30 + y: 122 + x: 100 + text: "Fetch" + + onClicked: { + dateLabel.text = "" + priceLabel.text = "" + errorLabel.text = "" + statusLabel.text = "" + quote.launch(symbol.text, "", source.text) + } + } + + Label { + id: statusLabel + y: 150 + x: 100 + } + + Label { + id: priceLabel + y: 180 + x: 100 + } + + Label { + id: dateLabel + y: 210 + x: 100 + } + + Label { + id: errorLabel + y: 240 + x: 100 + } +} diff --git a/tests/qmlalkonlinequotetest.qrc b/tests/qmlalkonlinequotetest.qrc new file mode 100644 --- /dev/null +++ b/tests/qmlalkonlinequotetest.qrc @@ -0,0 +1,5 @@ + + + qmlalkonlinequotetest.qml + + diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/tools/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(onlinequoteseditor) diff --git a/tools/onlinequoteseditor/CMakeLists.txt b/tools/onlinequoteseditor/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/tools/onlinequoteseditor/CMakeLists.txt @@ -0,0 +1,35 @@ +include_directories( + ${CMAKE_SOURCE_DIR}/src + ${CMAKE_BINARY_DIR}/src +) + +set(SOURCES + main.cpp + mainwindow.cpp +) + +set(HEADERS + mainwindow.h +) + +set(UI + mainwindow.ui +) + +ki18n_wrap_ui(SOURCES ${UI} ) + +#kde4_add_app_icon(SOURCES "${KDE4_INSTALL_DIR}/share/icons/oxygen/*/actions/application-exit.png") + +ecm_add_executable(onlinequoteseditor ${SOURCES} ${HEADERS}) +if(BUILD_QT4) + set(LIBS ${KDE4_KDECORE_LIBS} ${KDE4_KDEUI_LIBS}) +else() + set(LIBS Qt5::Widgets Qt5::WebKitWidgets KF5::KDELibs4Support) +endif() + +target_link_libraries(onlinequoteseditor + alkimia + ${LIBS} +) + +install(TARGETS onlinequoteseditor ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) diff --git a/tools/onlinequoteseditor/main.cpp b/tools/onlinequoteseditor/main.cpp new file mode 100644 --- /dev/null +++ b/tools/onlinequoteseditor/main.cpp @@ -0,0 +1,55 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "mainwindow.h" + +#if QT_VERSION >= 0x050000 +#define KABOUTDATA_H +#include +#define KAboutData K4AboutData +#else +#include +#endif + +#include +#include + +int main(int argc, char **argv) +{ + KAboutData about("onlinequoteseditor", 0, + ki18n("onlinequoteseditor"), + "1.0", + ki18n("Editor for online price quotes used by finance applications"), + KAboutData::License_GPL, + ki18n("(C) 2018 Ralf Habacker")); + KCmdLineArgs::init(argc, argv, &about); + + KApplication app(true); + KCmdLineOptions options; + KCmdLineArgs::addCmdLineOptions(options); // Add my own options. + + KComponentData a(&about); + + // Get application specific arguments + KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); + + MainWindow w; + w.show(); + return app.exec(); +} diff --git a/tools/onlinequoteseditor/mainwindow.h b/tools/onlinequoteseditor/mainwindow.h new file mode 100644 --- /dev/null +++ b/tools/onlinequoteseditor/mainwindow.h @@ -0,0 +1,50 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class QUrl; + +namespace Ui { +class MainWindow; +} + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + explicit MainWindow(QWidget *parent = 0); + ~MainWindow(); + +protected slots: + void slotUrlChanged(const QUrl &url); + void slotEditingFinished(); + void slotLanguageChanged(const QString &); + +private: + class Private; + Private *d; + Ui::MainWindow *ui; +}; + +#endif // MAINWINDOW_H diff --git a/tools/onlinequoteseditor/mainwindow.cpp b/tools/onlinequoteseditor/mainwindow.cpp new file mode 100644 --- /dev/null +++ b/tools/onlinequoteseditor/mainwindow.cpp @@ -0,0 +1,138 @@ +/*************************************************************************** + * Copyright 2018 Ralf Habacker * + * * + * This file is part of libalkimia. * + * * + * libalkimia is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2.1 of * + * the License or (at your option) version 3 or any later version. * + * * + * libalkimia is distributed in the hope that 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 "mainwindow.h" +#include "ui_mainwindow.h" + +#include "alkonlinequotesprofile.h" +#include "alkonlinequotesprofilemanager.h" +#include "alkonlinequoteswidget.h" + +#include +#include +#include +#include +#include + +class MainWindow::Private +{ +public: + Private() + : view(nullptr) + , urlLine(nullptr) + , quotesWidget(nullptr) + { + } + + ~Private() + { + delete view; + delete quotesWidget; + } + QWebView *view; + QLineEdit *urlLine; + AlkOnlineQuotesWidget *quotesWidget; +}; + +void MainWindow::slotUrlChanged(const QUrl &url) +{ + d->urlLine->setText(url.toString()); +} + +void MainWindow::slotEditingFinished() +{ + QUrl url(d->urlLine->text()); + QNetworkRequest request; + request.setUrl(url); + if (!d->quotesWidget->acceptLanguage().isEmpty()) + request.setRawHeader("Accept-Language", d->quotesWidget->acceptLanguage().toLocal8Bit()); + d->view->load(request); +} + +void MainWindow::slotLanguageChanged(const QString &text) +{ + d->quotesWidget->setAcceptLanguage(text); + if (!d->urlLine->text().isEmpty()) + slotEditingFinished(); +} + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , d(new Private) + , ui(new Ui::MainWindow) +{ + AlkOnlineQuotesProfileManager &manager = AlkOnlineQuotesProfileManager::instance(); + + manager.addProfile(new AlkOnlineQuotesProfile("alkimia", AlkOnlineQuotesProfile::Type::KMyMoney, "alkimia-quotes.knsrc")); + //manager.addProfile(new AlkOnlineQuotesProfile("local", AlkOnlineQuotesProfile::Type::GHNS, "alkimia-quotes-local.knsrc")); + manager.addProfile(new AlkOnlineQuotesProfile("skrooge", AlkOnlineQuotesProfile::Type::GHNS, "skrooge-quotes.knsrc")); + manager.addProfile(new AlkOnlineQuotesProfile("kmymoney", AlkOnlineQuotesProfile::Type::KMyMoney, "kmymoney-quotes.knsrc")); + ui->setupUi(this); + + QDockWidget *dockWidget = new QDockWidget(tr("Browser"), this); + d->view = new QWebView; + connect(d->view, SIGNAL(urlChanged(QUrl)), this, SLOT(slotUrlChanged(QUrl))); + + d->urlLine = new QLineEdit; + connect(d->urlLine, SIGNAL(editingFinished()), this, SLOT(slotEditingFinished())); + + d->quotesWidget = new AlkOnlineQuotesWidget(true, true); + d->quotesWidget->setView(d->view); + setCentralWidget(d->quotesWidget); + + // setup language box + QComboBox *box = new QComboBox; + QList allLocales = QLocale::matchingLocales( + QLocale::AnyLanguage, + QLocale::AnyScript, + QLocale::AnyCountry); + + QStringList languages; + foreach(const QLocale &locale, allLocales) { + languages.append(locale.uiLanguages()); + } + languages.sort(); + box->addItems(languages); + d->quotesWidget->setAcceptLanguage(box->currentText()); + connect(box, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotLanguageChanged(QString))); + + // setup layouts + QHBoxLayout *hLayout = new QHBoxLayout; + hLayout->addWidget(d->urlLine); + hLayout->addWidget(box); + + QVBoxLayout *layout = new QVBoxLayout; + layout->addLayout(hLayout); + layout->addWidget(d->view); + QWidget *group = new QWidget; + group->setLayout(layout); + dockWidget->setWidget(group); + addDockWidget(Qt::RightDockWidgetArea, dockWidget); + + // setup inspector + d->view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); + QWebInspector *inspector = new QWebInspector; + inspector->setPage(d->view->page()); +} + +MainWindow::~MainWindow() +{ + delete d; + delete ui; +} diff --git a/tools/onlinequoteseditor/mainwindow.ui b/tools/onlinequoteseditor/mainwindow.ui new file mode 100644 --- /dev/null +++ b/tools/onlinequoteseditor/mainwindow.ui @@ -0,0 +1,42 @@ + + + MainWindow + + + + 0 + 0 + 400 + 300 + + + + OnlineQuotesEditor + + + + + + + + 0 + 0 + 400 + 27 + + + + + + TopToolBarArea + + + false + + + + + + + +