(m_dockWidget->widget());
if (p != nullptr) {
p->refresh();
}
}
if (m_currentDocument != nullptr) {
// Automatic bookmarks creation
if (m_currentDocument->getMainDatabase() != nullptr) {
QString doc_id = m_currentDocument->getUniqueIdentifier();
if (m_docUniqueIdentifier != doc_id) {
m_docUniqueIdentifier = doc_id;
bool exist = false;
SKGError err = m_currentDocument->existObjects(QStringLiteral("node"), QLatin1String(""), exist);
if (!err && !exist) {
importStandardBookmarks();
// The file is considered has not modified
m_currentDocument->setFileNotModified();
}
// Automatic open of autostart bookmark
if (!err && !(QApplication::keyboardModifiers() &Qt::ShiftModifier)) {
goHome();
}
}
}
}
}
QString SKGBookmarkPlugin::title() const
{
return i18nc("Noun, a bookmark as in a webbrowser bookmark", "Bookmarks");
}
QString SKGBookmarkPlugin::icon() const
{
return QStringLiteral("bookmarks");
}
QStringList SKGBookmarkPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tips", "... some bookmarks can be opened automatically when the application is launched.
"));
output.push_back(i18nc("Description of a tips", "... bookmarks can be reorganized by drag & drop.
"));
output.push_back(i18nc("Description of a tips", "... a double click on a folder of bookmarks will open all the bookmarks it contains.
"));
output.push_back(i18nc("Description of a tips", "... you can import standard bookmarks.
"));
return output;
}
int SKGBookmarkPlugin::getOrder() const
{
return 3;
}
QDockWidget* SKGBookmarkPlugin::getDockWidget()
{
return m_dockWidget;
}
void SKGBookmarkPlugin::importStandardBookmarks()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
SKGBEGINTRANSACTION(*m_currentDocument, i18nc("Noun, name of the user action", "Import standard bookmarks"), err);
QStringList bks;
bks << i18nc("Noun, bookmark name", "Dashboard") % "|N|dashboard-show|\"Dashboard plugin\";\"Dashboard\";\"
<parameters menuOther="Y" menuCurrent="Y" menuFavorite="N" menuAssets="Y" menuInvestment="Y" menuCreditCard="Y"/>
\"\"/> "
"
<parameters menuTransfert="Y"/>
\"\"/> "
"
<parameters menuFavorite="N"/>
\"\"/>
<parameters menuShares="Y" menuSharesOwnedOnly="N" menuIndexes="Y"/>
\"\"/> \""
<< i18nc("Noun, bookmark name", "Report > Income vs Expenditure on 12 last months") % "|N|view-statistics|\"Skrooge report plugin\";\"Rapport\";\""
"
<parameters graphMode="1" graphicViewState="<!DOCTYPE SKGML>
<parameters isToolBarVisible="Y" antialiasing="Y"/>
" splitterState="000000ff00000000000000020000025b0000032901000000060100000001" bottomToolBarVisible="Y" filter="" legendVisible="N" allPositive="Y" linearRegressionVisible="Y" sortColumn="0" limitVisible="Y" web="<!DOCTYPE SKGML>"
"
<parameters zoomFactor="0"/>
" sortOrder="0"/>
\"\" mode=\"\"0\"\" period=\"\"3\"\" incomes=\"\"Y\"\" interval=\"\"2\"\" lines=\"\"t_TYPEEXPENSENLS\"\" lines2=\"\"#NOTHING#\"\" nbLevelLines=\"\"0\"\" nbLevelColumns=\"\"0\"\" forecast=\"\"0\"\" columns=\"\"d_DATEMONTH\"\" nb_intervals=\"\"12\"\" forecastValue=\"\"20\"\" transfers=\"\"N\"\" currentPage=\"\"0\"\"/>\""
<< i18nc("Noun, bookmark name", "Report > Pie categories in 12 last months") % "|N|view-statistics|\"Skrooge report plugin\";\"Rapport\";\"
<parameters graphMode="2" graphicViewState="<!DOCTYPE SKGML>"
"
<parameters isToolBarVisible="Y" antialiasing="Y"/>
" splitterState="000000ff00000000000000020000025b0000032901000000060100000001" bottomToolBarVisible="Y" filter="" legendVisible="N" allPositive="Y" linearRegressionVisible="Y" sortColumn="-1" limitVisible="Y" web="<!DOCTYPE SKGML>"
"
<parameters zoomFactor="0"/>
" sortOrder="0"/>
\"\" mode=\"\"0\"\" period=\"\"3\"\" incomes=\"\"Y\"\" interval=\"\"2\"\" lines=\"\"t_REALCATEGORY\"\" lines2=\"\"#NOTHING#\"\" nbLevelLines=\"\"0\"\" nbLevelColumns=\"\"0\"\" forecast=\"\"0\"\" columns=\"\"d_DATEMONTH\"\" nb_intervals=\"\"12\"\" forecastValue=\"\"20\"\" transfers=\"\"N\"\" currentPage=\"\"0\"\"/>\""
<< i18nc("Noun, bookmark name", "Report > History") % "|N|view-statistics|\"Skrooge report plugin\";\"Rapport\";\""
"
<parameters graphMode="1" graphicViewState="<!DOCTYPE SKGML>
<parameters isToolBarVisible="Y" antialiasing="Y"/>
" splitterState="000000ff0000000000000002000002b50000032601000000060100000001" bottomToolBarVisible="Y" filter="" legendVisible="N" allPositive="N" linearRegressionVisible="Y" sortColumn="-1" limitVisible="Y" web="<!DOCTYPE SKGML>"
"
<parameters zoomFactor="0"/>
" sortOrder="0"/>
\"\" mode=\"\"1\"\" period=\"\"0\"\" incomes=\"\"Y\"\" interval=\"\"2\"\" lines=\"\"#NOTHING#\"\" lines2=\"\"#NOTHING#\"\" nbLevelLines=\"\"0\"\" nbLevelColumns=\"\"0\"\" forecast=\"\"0\"\" columns=\"\"d_DATEMONTH\"\" nb_intervals=\"\"1\"\" forecastValue=\"\"20\"\" transfers=\"\"Y\"\" currentPage=\"\"0\"\"/>\"";
for (const auto& bk : qAsConst(bks)) {
QStringList line = SKGServices::splitCSVLine(bk, '|', false);
if (line.count() == 4) {
SKGNodeObject node;
err = SKGNodeObject::createPathNode(m_currentDocument, line.at(0), node);
IFOKDO(err, node.setAutoStart(line.at(1) == QStringLiteral("Y")))
IFOKDO(err, node.setIcon(line.at(2)))
IFOKDO(err, node.setData(line.at(3)))
IFOKDO(err, node.save())
}
}
// status
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Standard bookmarks imported.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Import standard bookmarks failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPlugin::goHome()
{
if (SKGMainPanel::getMainPanel() != nullptr) {
SKGMainPanel::getMainPanel()->closeAllPages(false); // Home do not close pinned pages
}
SKGObjectBase::SKGListSKGObjectBase oNodeList;
if (m_currentDocument != nullptr) {
m_currentDocument->getObjects(QStringLiteral("v_node"), QStringLiteral("t_autostart='Y' ORDER BY f_sortorder, t_name"), oNodeList);
}
int nbAutoStartedBookmarks = oNodeList.count();
for (int i = 0; i < nbAutoStartedBookmarks; ++i) {
SKGNodeObject autostarted_bookmark(oNodeList.at(i));
autostarted_bookmark.load();
SKGTRACEIN(10, "autostarting bookmark : " % autostarted_bookmark.getName());
SKGBookmarkPluginDockWidget::openBookmark(autostarted_bookmark, i > 0, true);
}
}
void SKGBookmarkPlugin::onOpenBookmark()
{
auto* callerAction = qobject_cast(this->sender());
if (callerAction != nullptr) {
SKGNodeObject node(m_currentDocument, callerAction->data().toInt());
SKGBookmarkPluginDockWidget::openBookmark(node, (QGuiApplication::mouseButtons() & Qt::MidButton) != 0u || (QApplication::keyboardModifiers() & Qt::ControlModifier) != 0u);
}
}
void SKGBookmarkPlugin::onAddBookmark()
{
SKGTRACEINFUNC(1);
SKGError err;
// Get current page
SKGNodeObject node;
{
// Get current selection
SKGNodeObject parentNode;
auto* callerAction = qobject_cast(this->sender());
if (callerAction != nullptr) {
parentNode = SKGNodeObject(m_currentDocument, callerAction->data().toInt());
}
// Create bookmark
err = SKGBookmarkPluginDockWidget::createNodeFromPage(SKGMainPanel::getMainPanel()->currentPage(), parentNode, node);
}
// status bar
IFOK(err) {
err = SKGError(0, i18nc("Successful message after an user action", "Bookmark created"));
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPlugin::onShowBookmarkMenu()
{
auto* callerMenu = qobject_cast(this->sender());
if ((callerMenu != nullptr) && (m_currentDocument != nullptr)) {
// Remove previous menu
callerMenu->clear();
// Build query
QString wc = QStringLiteral("rd_node_id=0 OR rd_node_id IS NULL OR rd_node_id=''");
int idParent = callerMenu->property("id").toInt();
if (idParent != 0) {
wc = "rd_node_id=" % SKGServices::intToString(idParent);
}
// Build new menu
SKGObjectBase::SKGListSKGObjectBase listNode;
m_currentDocument->getObjects(QStringLiteral("v_node"), wc % " ORDER BY f_sortorder, t_name", listNode);
int nb = listNode.count();
for (int i = 0; i < nb; ++i) {
SKGNodeObject node(listNode.at(i));
if (node.isFolder()) {
// This is a folder
auto menu = new QMenu(callerMenu);
if (menu != nullptr) {
callerMenu->addMenu(menu);
menu->setTitle(node.getName());
menu->setIcon(node.getIcon());
menu->setProperty("id", node.getID());
connect(menu, &QMenu::aboutToShow, this, &SKGBookmarkPlugin::onShowBookmarkMenu);
}
} else {
// This is a bookmark
auto act = new QAction(callerMenu);
if (act != nullptr) {
callerMenu->addAction(act);
act->setText(node.getName());
act->setIcon(node.getIcon());
act->setData(node.getID());
connect(act, &QAction::triggered, this, &SKGBookmarkPlugin::onOpenBookmark);
}
}
}
// Add separator
auto sep = new QAction(this);
sep->setSeparator(true);
callerMenu->addAction(sep);
// This common actions
{
// Open all
auto act = new QAction(callerMenu);
if (act != nullptr) {
callerMenu->addAction(act);
act->setText(i18nc("Action", "Open all"));
act->setIcon(SKGServices::fromTheme(QStringLiteral("quickopen")));
act->setData(idParent);
connect(act, &QAction::triggered, this, &SKGBookmarkPlugin::onOpenBookmark);
}
if (SKGMainPanel::getMainPanel()->currentPageIndex() >= 0) {
// Bookmark current here
auto act2 = new QAction(callerMenu);
if (act2 != nullptr) {
callerMenu->addAction(act2);
act2->setText(i18nc("Action", "Bookmark current page here"));
act2->setIcon(SKGServices::fromTheme(QStringLiteral("list-add")));
act2->setData(idParent);
connect(act2, &QAction::triggered, this, &SKGBookmarkPlugin::onAddBookmark);
}
}
}
}
}
#include
diff --git a/plugins/generic/skg_bookmark/skgbookmarkplugindockwidget.cpp b/plugins/generic/skg_bookmark/skgbookmarkplugindockwidget.cpp
index c857eeaaf..71a6ede0a 100644
--- a/plugins/generic/skg_bookmark/skgbookmarkplugindockwidget.cpp
+++ b/plugins/generic/skg_bookmark/skgbookmarkplugindockwidget.cpp
@@ -1,608 +1,608 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for bookmarks management.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgbookmarkplugindockwidget.h"
#include
#include
#include
#include
#include "skgbookmark_settings.h"
#include "skgdocument.h"
#include "skginterfaceplugin.h"
#include "skgmainpanel.h"
#include "skgnodeobject.h"
#include "skgobjectmodelbase.h"
#include "skgsortfilterproxymodel.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
bool SKGBookmarkPluginDockWidget::m_middleClick = false;
SKGBookmarkPluginDockWidget::SKGBookmarkPluginDockWidget(QWidget* iParent, SKGDocument* iDocument)
: SKGWidget(iParent, iDocument), m_mainMenu(nullptr), m_actDelete(nullptr), m_actRename(nullptr), m_actChangeIcon(nullptr), m_actAddBookmark(nullptr), m_actAddBookmarks(nullptr),
m_actAddBookmarkGroup(nullptr), m_actSetAutostart(nullptr), m_actUnsetAutostart(nullptr), m_modelview(nullptr)
{
SKGTRACEINFUNC(1);
if (iDocument == nullptr) {
return;
}
ui.setupUi(this);
QPalette newPalette = QApplication::palette();
newPalette.setColor(QPalette::Base, Qt::transparent);
ui.kBookmarksList->setPalette(newPalette);
ui.kBookmarksList->setRootIsDecorated(false);
ui.kBookmarksList->setAnimated(false); // Not compatible with double click
ui.kBookmarksList->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui.kTools->setIcon(SKGServices::fromTheme(QStringLiteral("configure")));
ui.kBookmarksList->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui.kBookmarksList, &SKGTreeView::customContextMenuRequested, this, &SKGBookmarkPluginDockWidget::showMenu);
// Add model
m_modelview = new SKGObjectModelBase(getDocument(), QStringLiteral("v_node"), QStringLiteral("1=1 ORDER BY f_sortorder, t_name"), this, QStringLiteral("rd_node_id"));
auto modelproxy = new SKGSortFilterProxyModel(this);
modelproxy->setSourceModel(m_modelview);
ui.kBookmarksList->setModel(modelproxy);
connect(ui.kFilterEdit, &QLineEdit::textChanged, this, [ = ](const QString & itext) {
modelproxy->setFilterKeyColumn(-1);
modelproxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
modelproxy->setFilterFixedString(itext);
});
connect(ui.kBookmarksList, &SKGTreeView::selectionChangedDelayed, this, &SKGBookmarkPluginDockWidget::refresh);
connect(ui.kBookmarksList, &SKGTreeView::pressed, this, &SKGBookmarkPluginDockWidget::onBeforeOpenBookmark);
connect(ui.kBookmarksList, &SKGTreeView::pressed, this, &SKGBookmarkPluginDockWidget::onOpenBookmark);
connect(ui.kBookmarksList, &SKGTreeView::doubleClicked, this, &SKGBookmarkPluginDockWidget::onOpenBookmarkFolder);
connect(SKGMainPanel::getMainPanel(), &SKGMainPanel::currentPageChanged, this, &SKGBookmarkPluginDockWidget::onPageChanged);
connect(m_modelview, &SKGObjectModelBase::beforeReset, ui.kBookmarksList, &SKGTreeView::saveSelection);
connect(m_modelview, &SKGObjectModelBase::afterReset, ui.kBookmarksList, &SKGTreeView::resetSelection);
ui.kBookmarksList->setTextResizable(false);
// Refresh action states
refresh();
}
SKGBookmarkPluginDockWidget::~SKGBookmarkPluginDockWidget()
{
SKGTRACEINFUNC(1);
m_mainMenu = nullptr;
m_actDelete = nullptr;
m_actRename = nullptr;
m_actChangeIcon = nullptr;
m_actAddBookmark = nullptr;
m_actAddBookmarks = nullptr;
m_actAddBookmarkGroup = nullptr;
m_actSetAutostart = nullptr;
m_actUnsetAutostart = nullptr;
m_modelview = nullptr;
}
QWidget* SKGBookmarkPluginDockWidget::mainWidget()
{
return ui.kBookmarksList;
}
void SKGBookmarkPluginDockWidget::initMenu()
{
if (m_mainMenu == nullptr) {
// Build contextual menu
m_mainMenu = new QMenu(ui.kBookmarksList);
QAction* actExpandAll = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("format-indent-more")), i18nc("Noun, user action", "Expand all"));
connect(actExpandAll, &QAction::triggered, ui.kBookmarksList, &SKGTreeView::expandAll);
QAction* actCollapseAll = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("format-indent-less")), i18nc("Noun, user action", "Collapse all"));
connect(actCollapseAll, &QAction::triggered, ui.kBookmarksList, &SKGTreeView::collapseAll);
ui.kBookmarksList->insertAction(nullptr, actCollapseAll);
m_mainMenu->addSeparator();
m_actAddBookmark = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("list-add")), i18nc("Verb", "Bookmark current page"));
connect(m_actAddBookmark, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onAddBookmark);
m_actAddBookmarks = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("list-add")), i18nc("Verb", "Bookmark all pages"));
connect(m_actAddBookmarks, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onAddBookmarks);
m_actAddBookmarkGroup = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("folder-new")), i18nc("Verb", "Add bookmark group"));
connect(m_actAddBookmarkGroup, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onAddBookmarkGroup);
m_mainMenu->addSeparator();
m_actDelete = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("edit-delete")), i18nc("Verb, delete an item", "Delete"));
connect(m_actDelete, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onRemoveBookmark);
m_mainMenu->addSeparator();
m_actSetAutostart = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("media-playback-start")), i18nc("Verb, automatically load when the application is started", "Autostart"));
connect(m_actSetAutostart, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onSetAutostart);
m_actUnsetAutostart = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("media-playback-stop")), i18nc("Verb", "Remove Autostart"));
connect(m_actUnsetAutostart, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onUnsetAutostart);
m_actRename = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("edit-rename")), i18nc("Verb, change the name of an item", "Rename"));
m_actRename->setShortcut(Qt::Key_F2);
connect(m_actRename, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onRenameBookmark);
m_actChangeIcon = m_mainMenu->addAction(SKGServices::fromTheme(QStringLiteral("edit-image-face-add")), i18nc("Verb, change the icon of an item", "Change icon..."));
connect(m_actChangeIcon, &QAction::triggered, this, &SKGBookmarkPluginDockWidget::onChangeIconBookmark);
m_mainMenu->addSeparator();
m_mainMenu->addAction(SKGMainPanel::getMainPanel()->getGlobalAction(QStringLiteral("tab_overwritebookmark")));
ui.kTools->setMenu(m_mainMenu);
}
}
void SKGBookmarkPluginDockWidget::showMenu(const QPoint iPos)
{
initMenu();
m_mainMenu->popup(ui.kBookmarksList->mapToGlobal(iPos));
}
void SKGBookmarkPluginDockWidget::onSetAutostart()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
setAutostart(QStringLiteral("Y"));
}
void SKGBookmarkPluginDockWidget::onUnsetAutostart()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
setAutostart(QStringLiteral("N"));
}
void SKGBookmarkPluginDockWidget::setAutostart(const QString& value)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGObjectBase::SKGListSKGObjectBase selectedBookmarks = getSelectedObjects();
SKGError err;
// foreach selected bookmark, set the t_autostart attribute to 'y' or 'n'
{
int nb = selectedBookmarks.count();
SKGBEGINPROGRESSTRANSACTION(*getDocument(), value == QStringLiteral("Y") ? i18nc("Noun, name of the user action", "Autostart bookmarks") : i18nc("Noun, name of the user action", "Do not Autostart bookmarks"), err, nb);
for (int i = 0 ; !err && i < nb ; ++i) {
SKGNodeObject bookmark(selectedBookmarks.at(i));
err = bookmark.setAttribute(QStringLiteral("t_autostart"), value);
IFOKDO(err, bookmark.save())
// Send message
IFOKDO(err, bookmark.getDocument()->sendMessage(i18nc("An information message", "The Autostart status of bookmark '%1' has been changed", bookmark.getDisplayName()), SKGDocument::Hidden));
IFOKDO(err, getDocument()->stepForward(i + 1))
}
}
// status bar
IFOKDO(err, SKGError(0, value == QStringLiteral("Y") ? i18nc("Successful message after an user action", "Autostart bookmarks") : i18nc("Successful message after an user action", "Do not Autostart bookmarks")))
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPluginDockWidget::openBookmark(const SKGNodeObject& iNode, bool iFirstInNewPage, bool iPin)
{
SKGTRACEINFUNC(1);
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
QVector nodes;
nodes.reserve(20);
nodes.push_back(iNode);
int setForcusOn = 0;
int nbTab = SKGMainPanel::getMainPanel()->countPages();
if (nbTab != 0) {
setForcusOn = nbTab - 1;
SKGTabPage* cPage = SKGMainPanel::getMainPanel()->currentPage();
if (m_middleClick || ((cPage != nullptr) && cPage->isPin())) {
setForcusOn = nbTab;
} else {
setForcusOn = SKGMainPanel::getMainPanel()->currentPageIndex();
}
}
int tabNumberForNextOpen = (m_middleClick || iFirstInNewPage ? -1 : SKGMainPanel::getMainPanel()->currentPageIndex());
for (int i = 0; i < nodes.count(); ++i) { // WARNING: This list is modified dynamically
SKGNodeObject selectedNode = nodes.at(i);
QStringList data = SKGServices::splitCSVLine(selectedNode.getData());
if (data.count() > 2) {
// This bookmark has information ==> we open it
SKGTabPage* page = SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName(data[0]), tabNumberForNextOpen, data[2], selectedNode.getName(), SKGServices::intToString(selectedNode.getID()), i == nodes.count() - 1);
if (page != nullptr) {
if (skgbookmark_settings::pinhomebookmarks()) {
page->setPin(iPin);
}
SKGTabWidget* tab = SKGMainPanel::getMainPanel()->getTabWidget();
if (tab != nullptr) {
tab->setTabIcon(tab->indexOf(page), selectedNode.getIcon());
}
selectedNode.opened = true;
tabNumberForNextOpen = -1;
}
} else {
// This bookmark is a folder ==> we open children by recursion
SKGObjectBase::SKGListSKGObjectBase children;
selectedNode.getNodes(children);
for (const auto& item : qAsConst(children)) {
nodes.push_back(SKGNodeObject(item));
}
}
}
QApplication::restoreOverrideCursor();
// Set focus on first page
SKGMainPanel::getMainPanel()->setCurrentPage(setForcusOn);
}
void SKGBookmarkPluginDockWidget::onBeforeOpenBookmark()
{
m_middleClick = (QApplication::keyboardModifiers() & Qt::ControlModifier) != 0u || (QApplication::mouseButtons() & Qt::MidButton) != 0u;
}
void SKGBookmarkPluginDockWidget::onOpenBookmark(const QModelIndex& index)
{
SKGTRACEINFUNC(1);
if (!(QApplication::mouseButtons() & Qt::RightButton)) {
auto* proxyModel = qobject_cast(ui.kBookmarksList->model());
auto* model = qobject_cast(proxyModel->sourceModel());
if (model != nullptr) {
SKGNodeObject node(model->getObject(proxyModel->mapToSource(index)));
if (!node.isFolder()) {
openBookmark(node);
}
}
}
}
void SKGBookmarkPluginDockWidget::onOpenBookmarkFolder(const QModelIndex& index)
{
SKGTRACEINFUNC(1);
if (!(QApplication::mouseButtons() & Qt::RightButton)) {
auto* proxyModel = qobject_cast(ui.kBookmarksList->model());
auto* model = qobject_cast(proxyModel->sourceModel());
if (model != nullptr) {
SKGNodeObject node(model->getObject(proxyModel->mapToSource(index)));
if (node.isFolder()) {
openBookmark(node);
}
}
}
}
void SKGBookmarkPluginDockWidget::onAddBookmarkGroup()
{
SKGTRACEINFUNC(1);
SKGError err;
SKGNodeObject node;
{
// Get current selection name
QString name;
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
if (!bookmarks.isEmpty()) {
SKGNodeObject parentNode(bookmarks.at(0));
if (!parentNode.isFolder()) {
// This is not a folder, we have to take the parent
SKGNodeObject parentNodeTmp;
parentNode.getParentNode(parentNodeTmp);
parentNode = parentNodeTmp;
}
name = parentNode.getFullName();
}
// Add current name
if (!name.isEmpty()) {
name += OBJECTSEPARATOR;
}
name += i18nc("Default name for bookmark", "New bookmark");
// Create bookmark folder
SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Bookmark folder creation '%1'", name), err);
IFOKDO(err, SKGNodeObject::createPathNode(getDocument(), name, node, true))
// Send message
IFOKDO(err, node.getDocument()->sendMessage(i18nc("An information message", "The bookmark folder '%1' has been added", node.getDisplayName()), SKGDocument::Hidden));
}
// status bar
IFOK(err) {
ui.kBookmarksList->selectObject(node.getUniqueID());
err = SKGError(0, i18nc("Successful message after an user action", "Bookmark group created"));
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPluginDockWidget::onAddBookmarks()
{
SKGTRACEINFUNC(1);
SKGError err;
SKGNodeObject rootNode;
{
// Get current selection name
QString name;
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
if (!bookmarks.isEmpty()) {
SKGNodeObject parentNode(bookmarks.at(0));
if (!parentNode.isFolder()) {
// This is not a folder, we have to take the parent
SKGNodeObject parentNodeTmp;
parentNode.getParentNode(parentNodeTmp);
parentNode = parentNodeTmp;
}
name = parentNode.getFullName();
}
// Add current name
if (!name.isEmpty()) {
name += OBJECTSEPARATOR;
}
name += i18nc("Default name for bookmark", "New bookmark");
// Create bookmark folder
SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Bookmarks creation"), err);
err = SKGNodeObject::createPathNode(getDocument(), name, rootNode, true);
int nb = SKGMainPanel::getMainPanel()->countPages();
for (int i = 0; !err && i < nb; ++i) {
SKGNodeObject node;
err = createNodeFromPage(SKGMainPanel::getMainPanel()->page(i), rootNode, node);
// Send message
IFOKDO(err, node.getDocument()->sendMessage(i18nc("An information message", "The bookmark '%1' has been added", node.getDisplayName()), SKGDocument::Hidden));
}
}
// status bar
IFOK(err) {
ui.kBookmarksList->selectObject(rootNode.getUniqueID());
err = SKGError(0, i18nc("Successful message after an user action", "Bookmarks created"));
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPluginDockWidget::onAddBookmark()
{
SKGTRACEINFUNC(1);
SKGError err;
// Get current page
SKGNodeObject node;
{
// Get current selection
SKGNodeObject parentNode(getDocument(), 0);
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
if (!bookmarks.isEmpty()) {
parentNode = bookmarks.at(0);
}
// Create bookmark
err = createNodeFromPage(SKGMainPanel::getMainPanel()->currentPage(), parentNode, node);
}
// status bar
IFOK(err) {
ui.kBookmarksList->selectObject(node.getUniqueID());
err = SKGError(0, i18nc("Successful message after an user action", "Bookmark created"));
}
SKGMainPanel::displayErrorMessage(err);
}
SKGError SKGBookmarkPluginDockWidget::createNodeFromPage(SKGTabPage* iPage, const SKGNodeObject& iParentNode, SKGNodeObject& oCreatedNode)
{
SKGTRACEINFUNC(1);
SKGError err;
// Get current page
oCreatedNode = SKGNodeObject();
if (iPage != nullptr) {
// Get current selection name
QString name;
SKGNodeObject parentNode = iParentNode;
if (!parentNode.isFolder()) {
// This is not a folder, we have to take the parent
SKGNodeObject parentNodeTmp;
parentNode.getParentNode(parentNodeTmp);
parentNode = parentNodeTmp;
}
name = parentNode.getFullName();
// Add current name
if (!name.isEmpty()) {
name += OBJECTSEPARATOR;
}
QString defaultName = iPage->objectName();
QString defaultIcon;
SKGInterfacePlugin* plugin = SKGMainPanel::getMainPanel()->getPluginByName(defaultName);
if (plugin != nullptr) {
defaultName = plugin->title();
defaultIcon = plugin->icon();
}
name += defaultName;
// Create bookmark
SKGBEGINTRANSACTION(*iParentNode.getDocument(), i18nc("Noun, name of the user action", "Bookmark creation '%1'", name), err);
err = SKGNodeObject::createPathNode(iParentNode.getDocument(), name, oCreatedNode, true);
IFOK(err) {
QString value = SKGServices::stringToCsv(iPage->objectName()) % ';' %
SKGServices::stringToCsv(defaultName) % ';' %
SKGServices::stringToCsv(iPage->getState());
err = oCreatedNode.setData(value);
IFOKDO(err, oCreatedNode.setIcon(defaultIcon))
IFOKDO(err, oCreatedNode.save())
// Send message
IFOKDO(err, oCreatedNode.getDocument()->sendMessage(i18nc("An information message", "The bookmark '%1' has been added", oCreatedNode.getDisplayName()), SKGDocument::Hidden));
}
}
return err;
}
void SKGBookmarkPluginDockWidget::onRenameBookmark()
{
SKGTRACEINFUNC(1);
QItemSelectionModel* selModel = ui.kBookmarksList->selectionModel();
auto* proxyModel = qobject_cast< QSortFilterProxyModel* >(ui.kBookmarksList->model());
if ((proxyModel != nullptr) && (selModel != nullptr)) {
auto* model = qobject_cast(proxyModel->sourceModel());
if (model != nullptr) {
QModelIndexList indexes = selModel->selectedRows();
if (indexes.count() == 1) {
ui.kBookmarksList->edit(indexes.at(0));
}
}
}
}
void SKGBookmarkPluginDockWidget::onChangeIconBookmark()
{
SKGTRACEINFUNC(1);
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
if (bookmarks.count() == 1) {
SKGNodeObject node(bookmarks.at(0));
KIconDialog diag(this);
diag.setup(KIconLoader::NoGroup);
QString icon = diag.openDialog();
if (!icon.isEmpty()) {
SKGError err;
{
SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Bookmark icon change"), err);
err = node.setIcon(icon);
IFOKDO(err, node.save())
// Send message
IFOKDO(err, node.getDocument()->sendMessage(i18nc("An information message", "The icon of the bookmark '%1' has been changed", node.getDisplayName()), SKGDocument::Hidden));
}
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Bookmark icon changed")))
SKGMainPanel::displayErrorMessage(err);
}
}
}
void SKGBookmarkPluginDockWidget::onRemoveBookmark()
{
SKGTRACEINFUNC(1);
SKGError err;
{
SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Bookmark delete"), err);
// Get current selection
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
int nb = bookmarks.count();
for (int i = 0; i < nb && !err; ++i) {
SKGNodeObject node(bookmarks.at(i));
err = node.remove();
}
}
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Bookmark deleted")))
SKGMainPanel::displayErrorMessage(err);
}
void SKGBookmarkPluginDockWidget::onBookmarkEditorChanged()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Enable bookmark buttons
int nbSelectedObjects = getNbSelectedObjects();
bool testAdd = getDocument()->getMainDatabase() != nullptr && nbSelectedObjects <= 1;
if (m_actAddBookmarkGroup != nullptr) {
m_actAddBookmarkGroup->setEnabled(testAdd);
}
if (m_actAddBookmark != nullptr) {
m_actAddBookmark->setEnabled(testAdd && SKGMainPanel::getMainPanel()->currentPageIndex() >= 0);
}
if (m_actAddBookmarks != nullptr) {
m_actAddBookmarks->setEnabled(testAdd && SKGMainPanel::getMainPanel()->currentPageIndex() >= 0);
}
if (m_actDelete != nullptr) {
m_actDelete->setEnabled(nbSelectedObjects > 0);
}
if (m_actRename != nullptr) {
m_actRename->setEnabled(nbSelectedObjects == 1);
}
if (m_actChangeIcon != nullptr) {
m_actChangeIcon->setEnabled(nbSelectedObjects == 1);
}
}
void SKGBookmarkPluginDockWidget::refresh()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Bookmarks
SKGObjectBase::SKGListSKGObjectBase bookmarks = getSelectedObjects();
int nbSelectedObjects = bookmarks.count();
if (nbSelectedObjects == 1) {
SKGNodeObject node(bookmarks.at(0));
if (m_actSetAutostart != nullptr) {
m_actSetAutostart->setEnabled(node.getAttribute(QStringLiteral("t_autostart")) != QStringLiteral("Y"));
}
if (m_actUnsetAutostart != nullptr) {
m_actUnsetAutostart->setEnabled(node.getAttribute(QStringLiteral("t_autostart")) == QStringLiteral("Y"));
}
} else {
if (m_actSetAutostart != nullptr) {
m_actSetAutostart->setEnabled(nbSelectedObjects > 1);
}
if (m_actUnsetAutostart != nullptr) {
m_actUnsetAutostart->setEnabled(nbSelectedObjects > 1);
}
}
onBookmarkEditorChanged();
}
void SKGBookmarkPluginDockWidget::onPageChanged()
{
// Set current selection of dock
QString id;
SKGTabPage* cPage = SKGMainPanel::getMainPanel()->currentPage();
if (cPage != nullptr) {
id = cPage->getBookmarkID();
}
ui.kBookmarksList->selectObject(id % "-node");
}
void SKGBookmarkPluginDockWidget::resizeEvent(QResizeEvent* iEvent)
{
if (iEvent != nullptr) {
QSize newSize = iEvent->size();
// Compute icon size
int s = qMax(qMin(newSize.width() / 5, 64), 16);
ui.kBookmarksList->setIconSize(QSize(s, s));
}
QWidget::resizeEvent(iEvent);
}
diff --git a/plugins/generic/skg_dashboard/skgdashboardplugin.cpp b/plugins/generic/skg_dashboard/skgdashboardplugin.cpp
index 1d9396547..0bc23e147 100644
--- a/plugins/generic/skg_dashboard/skgdashboardplugin.cpp
+++ b/plugins/generic/skg_dashboard/skgdashboardplugin.cpp
@@ -1,118 +1,118 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A dashboard
*
* @author Stephane MANKOWSKI
*/
#include "skgdashboardplugin.h"
#include
#include
#include
#include
#include "skgdashboard_settings.h"
#include "skgdashboardpluginwidget.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGDashboardPluginFactory, registerPlugin();)
SKGDashboardPlugin::SKGDashboardPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& iArg) : SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
Q_UNUSED(iArg);
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGDashboardPlugin::~SKGDashboardPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
}
bool SKGDashboardPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_dashboard"), title());
setXMLFile(QStringLiteral("skg_dashboard.rc"));
// Create yours actions here
return true;
}
SKGTabPage* SKGDashboardPlugin::getWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
return new SKGDashboardPluginWidget(SKGMainPanel::getMainPanel(), m_currentDocument);
}
QWidget* SKGDashboardPlugin::getPreferenceWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
auto w = new QWidget();
ui.setupUi(w);
return w;
}
KConfigSkeleton* SKGDashboardPlugin::getPreferenceSkeleton()
{
return skgdashboard_settings::self();
}
QString SKGDashboardPlugin::title() const
{
return i18nc("Noun, a summary of your financial situation", "Dashboard");
}
QString SKGDashboardPlugin::icon() const
{
return QStringLiteral("dashboard-show");
}
QString SKGDashboardPlugin::toolTip() const
{
return i18nc("Noun, a summary of your financial situation", "Dashboard");
}
int SKGDashboardPlugin::getOrder() const
{
return 8;
}
QStringList SKGDashboardPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tips", "... the dashboard is there to give you a summary of your situation.
"));
output.push_back(i18nc("Description of a tips", "... the dashboard can be reorganized by drag and drop.
"));
output.push_back(i18nc("Description of a tips", "... some widgets of the dashboard have parameters.
"));
return output;
}
bool SKGDashboardPlugin::isInPagesChooser() const
{
return true;
}
#include
diff --git a/plugins/generic/skg_dashboard/skgdashboardpluginwidget.cpp b/plugins/generic/skg_dashboard/skgdashboardpluginwidget.cpp
index 28ba74765..9c2e6f59b 100644
--- a/plugins/generic/skg_dashboard/skgdashboardpluginwidget.cpp
+++ b/plugins/generic/skg_dashboard/skgdashboardpluginwidget.cpp
@@ -1,466 +1,466 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A dashboard.
*
* @author Stephane MANKOWSKI
*/
#include "skgdashboardpluginwidget.h"
#include
#include
#include
#include
#include
#include
#include
#include "skgboardwidget.h"
#include "skgdocument.h"
#include "skgflowlayout.h"
#include "skginterfaceplugin.h"
#include "skgmainpanel.h"
#include "skgservices.h"
#include "skgtraces.h"
#include "skgzoomselector.h"
SKGDashboardPluginWidget::SKGDashboardPluginWidget(QWidget* iParent, SKGDocument* iDocument)
: SKGTabPage(iParent, iDocument), m_flowLayout(nullptr), m_menu(nullptr), m_addMenu(nullptr)
{
SKGTRACEINFUNC(1);
if (iDocument == nullptr) {
return;
}
ui.setupUi(this);
// Create a context menu for adding widgets
setContextMenuPolicy(Qt::CustomContextMenu);
m_menu = new QMenu(this);
connect(this, &SKGDashboardPluginWidget::customContextMenuRequested, this, &SKGDashboardPluginWidget::showHeaderMenu);
m_addMenu = m_menu->addMenu(SKGServices::fromTheme(QStringLiteral("list-add")), i18nc("Verb", "Add"));
// Drag and drop
m_clickedPoint = QPoint(-1, -1);
ui.kTitle->setPixmap(SKGServices::fromTheme(KAboutData::applicationData().programIconName()).pixmap(22, 22), KTitleWidget::ImageLeft);
ui.kTitle->setComment("" % i18nc("Message", "Welcome to %1", KAboutData::applicationData().displayName()) % "");
// Build menu
if (m_addMenu != nullptr) {
m_addMenu->clear();
int index = 0;
while (index >= 0) {
SKGInterfacePlugin* plugin = SKGMainPanel::getMainPanel()->getPluginByIndex(index);
if (plugin != nullptr) {
int nbdbw = plugin->getNbDashboardWidgets();
for (int j = 0; j < nbdbw; ++j) {
// Create menu
QAction* act = m_addMenu->addAction(plugin->getDashboardWidgetTitle(j));
if (act != nullptr) {
act->setIcon(SKGServices::fromTheme(plugin->icon()));
act->setData(QString(plugin->objectName() % '-' % SKGServices::intToString(j)));
connect(act, &QAction::triggered, this, &SKGDashboardPluginWidget::onAddWidget);
}
}
} else {
index = -2;
}
++index;
}
}
// Build layout
m_flowLayout = new SKGFlowLayout(ui.kContent, 0, 0, 0);
// Plug buttons with menus
if ((m_addMenu != nullptr) && (ui.kAddWidget != nullptr)) {
ui.kAddWidget->setIcon(m_addMenu->icon());
ui.kAddWidget->setMenu(m_addMenu);
ui.kAddWidget->setPopupMode(QToolButton::InstantPopup);
}
}
SKGDashboardPluginWidget::~SKGDashboardPluginWidget()
{
SKGTRACEINFUNC(1);
m_menu = nullptr;
m_addMenu = nullptr;
m_flowLayout = nullptr;
}
QString SKGDashboardPluginWidget::getState()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
QDomElement root = doc.createElement(QStringLiteral("parameters"));
doc.appendChild(root);
root.setAttribute(QStringLiteral("zoomPosition"), SKGServices::intToString(zoomPosition()));
int nb = m_items.count();
for (int i = 0; i < nb; ++i) {
QDomElement element = doc.createElement("ITEM-" % SKGServices::intToString(i + 1));
root.appendChild(element);
QStringList param = SKGServices::splitCSVLine(m_items.at(i), '-');
SKGBoardWidget* item = m_itemsPointers.at(i);
if (item != nullptr) {
element.setAttribute(QStringLiteral("name"), param.at(0));
element.setAttribute(QStringLiteral("index"), param.at(1));
element.setAttribute(QStringLiteral("state"), item->getState());
element.setAttribute(QStringLiteral("zoom"), SKGServices::intToString(item->getZoomRatio() * 5 - 15));
}
}
return doc.toString();
}
void SKGDashboardPluginWidget::setState(const QString& iState)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
doc.setContent(iState);
QDomElement root = doc.documentElement();
// Initialisation
int nb = (m_flowLayout != nullptr ? m_flowLayout->count() : 0);
for (int i = 0; i < nb; ++i) {
SKGBoardWidget* item = m_itemsPointers.at(0);
if (item != nullptr) {
m_flowLayout->removeWidget(item);
item->hide();
m_items.removeAt(0);
m_itemsPointers.removeAt(0);
item->deleteLater();
}
}
QString zoomPositionS = root.attribute(QStringLiteral("zoomPosition"));
if (zoomPositionS.isEmpty()) {
zoomPositionS = '0';
}
setZoomPosition(SKGServices::stringToInt(zoomPositionS));
int index = 1;
while (index > 0) {
QDomElement element = root.firstChildElement("ITEM-" % SKGServices::intToString(index));
if (!element.isNull()) {
SKGInterfacePlugin* plugin = SKGMainPanel::getMainPanel()->getPluginByName(element.attribute(QStringLiteral("name")));
QString indexString = element.attribute(QStringLiteral("index"));
if (indexString.isEmpty()) {
indexString = '0';
}
QString zoom = element.attribute(QStringLiteral("zoom"));
if (zoom.isEmpty()) {
zoom = '0';
}
if (plugin != nullptr) {
addItem(plugin, SKGServices::stringToInt(indexString), SKGServices::stringToInt(zoom), element.attribute(QStringLiteral("state")));
}
} else {
index = -1;
}
++index;
}
// In case of reset
if (m_items.isEmpty() && root.attribute(QStringLiteral("zoomPosition")).isEmpty()) {
int index2 = 0;
while (index2 >= 0) {
SKGInterfacePlugin* plugin = SKGMainPanel::getMainPanel()->getPluginByIndex(index2);
if (plugin != nullptr) {
int nb2 = plugin->getNbDashboardWidgets();
for (int j = 0; j < nb2; ++j) {
addItem(plugin, j);
}
} else {
index2 = -2;
}
++index2;
}
}
}
QString SKGDashboardPluginWidget::getDefaultStateAttribute()
{
return QStringLiteral("SKGDASHBOARD_DEFAULT_PARAMETERS");
}
void SKGDashboardPluginWidget::refresh()
{
SKGTRACEINFUNC(1);
}
QWidget* SKGDashboardPluginWidget::zoomableWidget()
{
return SKGTabPage::zoomableWidget();
}
QList< QWidget* > SKGDashboardPluginWidget::printableWidgets()
{
QList< QWidget* > output;
output.reserve(m_itemsPointers.count());
for (auto w : qAsConst(m_itemsPointers)) {
output.push_back(w);
}
return output;
}
bool SKGDashboardPluginWidget::eventFilter(QObject* iObject, QEvent* iEvent)
{
if ((iEvent != nullptr) && iEvent->type() == QEvent::HoverLeave) {
// Leave widget
m_timer.stop();
return true;
}
if ((iEvent != nullptr) && (iObject != nullptr) &&
(iEvent->type() == QEvent::MouseButtonPress ||
iEvent->type() == QEvent::MouseButtonRelease ||
iEvent->type() == QEvent::MouseMove ||
iEvent->type() == QEvent::DragEnter ||
iEvent->type() == QEvent::DragMove ||
iEvent->type() == QEvent::Drop ||
iEvent->type() == QEvent::HoverMove)) {
// Search SKGBoardWidget corresponding to this widget
SKGBoardWidget* toMove = nullptr;
int toMoveIndex = -1;
int nb = m_itemsPointers.count();
for (int i = 0; toMove == nullptr && i < nb; ++i) {
SKGBoardWidget* w = m_itemsPointers.at(i);
if ((w != nullptr) && w->getDragWidget() == iObject) {
toMove = w;
toMoveIndex = i;
}
}
if (iEvent->type() == QEvent::MouseButtonPress) {
// Drag
auto* mevent = dynamic_cast(iEvent);
if (mevent && mevent->button() == Qt::LeftButton) {
m_clickedPoint = mevent->pos();
m_timer.stop();
}
} else if (iEvent->type() == QEvent::MouseButtonRelease) {
// Drag
auto* mevent = dynamic_cast(iEvent);
if (mevent && mevent->button() == Qt::LeftButton) {
m_clickedPoint = QPoint(-1, -1);
}
} else if (iEvent->type() == QEvent::MouseMove) {
// Drag
if (m_clickedPoint != QPoint(-1, -1) && toMoveIndex != -1) {
auto* mevent = dynamic_cast(iEvent);
if (mevent) {
int distance = (mevent->pos() - m_clickedPoint).manhattanLength();
if (distance >= QApplication::startDragDistance()) {
auto mimeData = new QMimeData;
mimeData->setData(QStringLiteral("application/x-skgdashboardpluginwidget"), SKGServices::intToString(toMoveIndex).toLatin1());
auto drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec(); // krazy:exclude=crashy
return true;
}
}
}
} else if (iEvent->type() == QEvent::DragEnter) {
// Drop move
auto* devent = dynamic_cast(iEvent);
if (devent && devent->mimeData()->hasFormat(QStringLiteral("application/x-skgdashboardpluginwidget"))) {
devent->accept();
return true;
}
} else if (iEvent->type() == QEvent::DragMove) {
// Drop move
auto* devent = dynamic_cast(iEvent);
if (devent && devent->mimeData()->hasFormat(QStringLiteral("application/x-skgdashboardpluginwidget"))) {
int oldPos = SKGServices::stringToInt(devent->mimeData()->data(QStringLiteral("application/x-skgdashboardpluginwidget")));
if (oldPos != toMoveIndex) {
devent->accept();
} else {
devent->ignore();
}
return true;
}
} else if (iEvent->type() == QEvent::Drop) {
// Drop
auto* devent = dynamic_cast(iEvent);
if (devent && devent->mimeData()->hasFormat(QStringLiteral("application/x-skgdashboardpluginwidget"))) {
int oldPos = SKGServices::stringToInt(devent->mimeData()->data(QStringLiteral("application/x-skgdashboardpluginwidget")));
if (oldPos + 1 == toMoveIndex) {
++toMoveIndex;
}
// Move item
if (toMoveIndex > oldPos) {
--toMoveIndex;
}
moveItem(oldPos, toMoveIndex);
return true;
}
}
}
return SKGTabPage::eventFilter(iObject, iEvent);
}
void SKGDashboardPluginWidget::showHeaderMenu(const QPoint iPos)
{
// Display menu
if (m_menu != nullptr) {
m_menu->popup(mapToGlobal(iPos));
}
}
void SKGDashboardPluginWidget::onAddWidget()
{
auto* send = qobject_cast(this->sender());
if (send != nullptr) {
QString id = send->data().toString();
QStringList param = SKGServices::splitCSVLine(id, '-');
SKGInterfacePlugin* db = SKGMainPanel::getMainPanel()->getPluginByName(param.at(0));
if (db != nullptr) {
addItem(db, SKGServices::stringToInt(param.at(1)));
}
}
}
void SKGDashboardPluginWidget::onMoveWidget(int iMove)
{
// Get current position
QWidget* send = qobject_cast(this->sender());
if (send != nullptr) {
int currentPos = m_itemsPointers.indexOf(parentBoardWidget(send));
int newPos = currentPos + iMove;
if (newPos < 0) {
newPos = 0;
} else if (newPos > m_items.count() - 1) {
newPos = m_items.count() - 1;
}
moveItem(currentPos, newPos);
}
}
void SKGDashboardPluginWidget::moveItem(int iFrom, int iTo)
{
// Compute new position
if (iTo != iFrom) {
// Move item
m_items.move(iFrom, iTo);
m_itemsPointers.move(iFrom, iTo);
// Build list of items in the right order
QList listWidgets;
int nb = m_itemsPointers.count();
listWidgets.reserve(nb);
for (int i = 0; i < nb; ++i) {
SKGBoardWidget* wgt2 = m_itemsPointers.at(i);
m_flowLayout->removeWidget(wgt2);
listWidgets.push_back(wgt2);
}
// Add items
nb = listWidgets.count();
for (int i = 0; i < nb; ++i) {
SKGBoardWidget* dbw = listWidgets.at(i);
dbw->setParent(ui.kContent);
m_flowLayout->addWidget(dbw);
}
}
}
SKGBoardWidget* SKGDashboardPluginWidget::parentBoardWidget(QWidget* iWidget)
{
auto* output = qobject_cast< SKGBoardWidget* >(iWidget);
if ((output == nullptr) && (iWidget != nullptr)) {
QWidget* iParent = iWidget->parentWidget();
if (iParent != nullptr) {
output = SKGDashboardPluginWidget::parentBoardWidget(iParent);
}
}
return output;
}
void SKGDashboardPluginWidget::onRemoveWidget()
{
int p = -1;
QWidget* send = qobject_cast(this->sender());
if (send != nullptr) {
p = m_itemsPointers.indexOf(parentBoardWidget(send));
}
if (p >= 0) {
// Get item
SKGBoardWidget* wgt = m_itemsPointers.at(p);
// Delete widget
m_flowLayout->removeWidget(wgt);
wgt->hide();
wgt->deleteLater();
// Remove item
m_items.removeAt(p);
m_itemsPointers.removeAt(p);
}
}
void SKGDashboardPluginWidget::addItem(SKGInterfacePlugin* iDashboard, int iIndex, int iZoom, const QString& iState)
{
if ((iDashboard != nullptr) && (m_flowLayout != nullptr)) {
SKGBoardWidget* dbw = iDashboard->getDashboardWidget(iIndex);
if (dbw != nullptr) {
// Add widget
dbw->setParent(ui.kContent);
dbw->setState(iState);
m_flowLayout->addWidget(dbw);
// Install filter
QWidget* drag = dbw->getDragWidget();
if (drag != nullptr) {
drag->installEventFilter(this);
drag->setAcceptDrops(true);
drag->setAttribute(Qt::WA_Hover);
}
// Connect widget
connect(dbw, &SKGBoardWidget::requestRemove, this, &SKGDashboardPluginWidget::onRemoveWidget, Qt::QueuedConnection);
connect(dbw, &SKGBoardWidget::requestMove, this, &SKGDashboardPluginWidget::onMoveWidget, Qt::QueuedConnection);
// Set size
dbw->setZoomRatio((iZoom + 15.0) / 5.0);
QString id = iDashboard->objectName() % '-' % SKGServices::intToString(iIndex);
m_items.push_back(id);
m_itemsPointers.push_back(dbw);
}
}
}
diff --git a/plugins/generic/skg_debug/skgdebugplugin.cpp b/plugins/generic/skg_debug/skgdebugplugin.cpp
index 9d3ec6ea6..cf555d99f 100644
--- a/plugins/generic/skg_debug/skgdebugplugin.cpp
+++ b/plugins/generic/skg_debug/skgdebugplugin.cpp
@@ -1,129 +1,129 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for debug.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgdebugplugin.h"
#include
#include
#include
#include "skgdebugpluginwidget.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGDebugPluginFactory, registerPlugin();)
SKGDebugPlugin::SKGDebugPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) : SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGDebugPlugin::~SKGDebugPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
}
bool SKGDebugPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
if (m_currentDocument == nullptr) {
return false;
}
setComponentName(QStringLiteral("skg_debug"), title());
setXMLFile(QStringLiteral("skg_debug.rc"));
// Menu
auto restartProfiling = new QAction(SKGServices::fromTheme(QStringLiteral("fork")), i18nc("Restart the profiling, a method used for analysing performances", "Restart profiling"), this);
connect(restartProfiling, &QAction::triggered, this, &SKGDebugPlugin::onRestartProfiling);
actionCollection()->setDefaultShortcut(restartProfiling, Qt::CTRL + Qt::Key_Pause);
registerGlobalAction(QStringLiteral("debug_restart_profiling"), restartProfiling);
QStringList overlayopen;
overlayopen.push_back(QStringLiteral("quickopen"));
auto openProfiling = new QAction(SKGServices::fromTheme(QStringLiteral("fork"), overlayopen), i18nc("Open the profiling, a method used for analysing performances", "Open profiling"), this);
connect(openProfiling, &QAction::triggered, this, &SKGDebugPlugin::onOpenProfiling);
actionCollection()->setDefaultShortcut(openProfiling, Qt::ALT + Qt::Key_Pause);
registerGlobalAction(QStringLiteral("debug_open_profiling"), openProfiling);
return true;
}
SKGTabPage* SKGDebugPlugin::getWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
return new SKGDebugPluginWidget(SKGMainPanel::getMainPanel(), m_currentDocument);
}
QString SKGDebugPlugin::title() const
{
return i18nc("Noun, a plugin allowing to access the SQLite database, useful to debug", "Debug");
}
QString SKGDebugPlugin::icon() const
{
return QStringLiteral("tools-report-bug");
}
QString SKGDebugPlugin::toolTip() const
{
return i18nc("A tool tip, explaining that the plugin is useful for debugging purposes", "Useful for debug");
}
bool SKGDebugPlugin::isInPagesChooser() const
{
return true;
}
bool SKGDebugPlugin::isEnabled() const
{
return (SKGTraces::SKGLevelTrace > 0 || SKGTraces::SKGPerfo);
}
void SKGDebugPlugin::onRestartProfiling()
{
SKGTraces::cleanProfilingStatistics();
}
void SKGDebugPlugin::onOpenProfiling()
{
// Call debug plugin
QString dumpString;
QStringList dump = SKGTraces::getProfilingStatistics();
int nbl = dump.count();
for (int i = 0; i < nbl; ++i) {
dumpString += dump.at(i);
dumpString += '\n';
}
if (SKGMainPanel::getMainPanel() != nullptr) {
SKGMainPanel::getMainPanel()->openPage("skg://debug_plugin/?sqlResult=" % SKGServices::encodeForUrl(dumpString));
}
}
#include
diff --git a/plugins/generic/skg_debug/skgdebugpluginwidget.cpp b/plugins/generic/skg_debug/skgdebugpluginwidget.cpp
index b043f272f..28c6f8348 100644
--- a/plugins/generic/skg_debug/skgdebugpluginwidget.cpp
+++ b/plugins/generic/skg_debug/skgdebugpluginwidget.cpp
@@ -1,224 +1,224 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for debug.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgdebugpluginwidget.h"
#include
#include
#include
#include "skgdocument.h"
#include "skgmainpanel.h"
#include "skgservices.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
SKGDebugPluginWidget::SKGDebugPluginWidget(QWidget* iParent, SKGDocument* iDocument)
: SKGTabPage(iParent, iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (iDocument == nullptr) {
return;
}
ui.setupUi(this);
// Set icons
ui.kSQLPushButton->setIcon(SKGServices::fromTheme(QStringLiteral("system-run")));
ui.kSQLTransactionPushButton->setIcon(SKGServices::fromTheme(QStringLiteral("system-run")));
ui.kRefreshViewsAndIndexes->setIcon(SKGServices::fromTheme(QStringLiteral("view-refresh")));
// Fill combo box
ui.kExplainCmb->addItem(SKGServices::fromTheme(QStringLiteral("system-run")), i18nc("Execute an SQL query", "Execute"));
ui.kExplainCmb->addItem(SKGServices::fromTheme(QStringLiteral("help-hint")), i18nc("Explain an SQL query", "Explain"));
ui.kExplainCmb->addItem(SKGServices::fromTheme(QStringLiteral("games-hint")), i18nc("Explain the SQL query plan", "Explain query plan"));
ui.kExplainCmb->addItem(SKGServices::fromTheme(QStringLiteral("media-playback-start")), i18nc("Execute script", "Execute script [%1]", "javascript"));
ui.kInput->setVisible(false);
// Set level trace
ui.kTraceLevel->setValue(SKGTraces::SKGLevelTrace);
// Set profiling mode
ui.kEnableProfilingChk->setCheckState(SKGTraces::SKGPerfo ? Qt::Checked : Qt::Unchecked);
// Init debug page
QStringList tables;
ui.kSQLInput->addItem(QStringLiteral("SELECT * FROM sqlite_master;"));
iDocument->getDistinctValues(QStringLiteral("sqlite_master"), QStringLiteral("name"), QStringLiteral("type in ('table', 'view')"), tables);
int nb = tables.count();
for (int i = 0; i < nb; ++i) {
ui.kSQLInput->addItem("SELECT * FROM " % tables.at(i) % ';');
}
ui.kSQLInput->addItem(QStringLiteral("ANALYZE;"));
ui.kSQLInput->addItem(QStringLiteral("PRAGMA integrity_check;"));
for (int i = 0; i < nb; ++i) {
ui.kSQLInput->addItem("PRAGMA table_info(" % tables.at(i) % ");");
ui.kSQLInput->addItem("PRAGMA index_list(" % tables.at(i) % ");");
}
iDocument->getDistinctValues(QStringLiteral("sqlite_master"), QStringLiteral("name"), QStringLiteral("type='index'"), tables);
nb = tables.count();
for (int i = 0; i < nb; ++i) {
ui.kSQLInput->addItem("PRAGMA index_info(" % tables.at(i) % ");");
}
connect(ui.kTraceLevel, &QSlider::valueChanged, this, &SKGDebugPluginWidget::onTraceLevelModified);
connect(ui.kEnableProfilingChk, &QCheckBox::stateChanged, this, &SKGDebugPluginWidget::onProfilingModeChanged);
connect(ui.kExplainCmb, static_cast(&SKGComboBox::currentIndexChanged), this, &SKGDebugPluginWidget::onModeChanged);
connect(ui.kSQLPushButton, &QPushButton::clicked, this, &SKGDebugPluginWidget::onExecuteSqlOrder);
connect(ui.kSQLTransactionPushButton, &QPushButton::clicked, this, &SKGDebugPluginWidget::onExecuteSqlOrderInTransaction);
connect(ui.kRefreshViewsAndIndexes, &QPushButton::clicked, this, &SKGDebugPluginWidget::onRefreshViewsAndIndexes);
}
SKGDebugPluginWidget::~SKGDebugPluginWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
QString SKGDebugPluginWidget::getState()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
QDomElement root = doc.createElement(QStringLiteral("parameters"));
doc.appendChild(root);
root.setAttribute(QStringLiteral("explain"), ui.kExplainCmb->currentIndex());
root.setAttribute(QStringLiteral("enableProfiling"), ui.kEnableProfilingChk->checkState() == Qt::Checked ? QStringLiteral("Y") : QStringLiteral("N"));
root.setAttribute(QStringLiteral("levelTraces"), ui.kTraceLevel->value());
root.setAttribute(QStringLiteral("sqlOrder"), ui.kSQLInput->currentText());
return doc.toString();
}
void SKGDebugPluginWidget::setState(const QString& iState)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
doc.setContent(iState);
QDomElement root = doc.documentElement();
QString explain = root.attribute(QStringLiteral("explain"));
QString enableProfiling = root.attribute(QStringLiteral("enableProfiling"));
QString levelTraces = root.attribute(QStringLiteral("levelTraces"));
QString sqlOrder = root.attribute(QStringLiteral("sqlOrder"));
QString sqlResult = root.attribute(QStringLiteral("sqlResult"));
if (!explain.isEmpty()) {
ui.kExplainCmb->setCurrentIndex(SKGServices::stringToInt(explain == QStringLiteral("Y") ? QStringLiteral("1") : explain));
}
if (!enableProfiling.isEmpty()) {
ui.kEnableProfilingChk->setCheckState(enableProfiling == QStringLiteral("Y") ? Qt::Checked : Qt::Unchecked);
}
if (!levelTraces.isEmpty()) {
ui.kTraceLevel->setValue(SKGServices::stringToInt(levelTraces));
}
ui.kSQLInput->setText(sqlOrder);
ui.kSQLResult->setPlainText(sqlResult);
}
void SKGDebugPluginWidget::onExecuteSqlOrderInTransaction()
{
onExecuteSqlOrder(true);
}
void SKGDebugPluginWidget::onExecuteSqlOrder(bool iInTransaction)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
int exp = ui.kExplainCmb->currentIndex();
if (exp > 2) {
// Script execution
ui.kSQLResult->clear();
QJSEngine myEngine;
// skgresult.setText(skgdocument.getUniqueIdentifier())
// skgerror=skgdocument.sendMessage(QStringLiteral("Hello"))
// skgerror=skgdocument.sendMessage(QStringLiteral("Hello"))
// skgmainpanel.closeAllOtherPages(skgmainpanel.currentPage())
auto t = myEngine.globalObject();
t.setProperty(QStringLiteral("skgresult"), myEngine.newQObject(ui.kSQLResult));
t.setProperty(QStringLiteral("skgdocument"), myEngine.newQObject(getDocument()));
t.setProperty(QStringLiteral("skgerror"), myEngine.newQObject(&err));
t.setProperty(QStringLiteral("skgmainpanel"), myEngine.newQObject(SKGMainPanel::getMainPanel()));
// Finally execute the scripting code.
myEngine.evaluate(ui.kInput->toPlainText());
} else {
// SQL execution
QString text = ui.kSQLInput->currentText();
if (exp == 1) {
text = "EXPLAIN " % text;
} else if (exp == 2) {
text = "EXPLAIN QUERY PLAN " % text;
}
QString oResult;
double time = SKGServices::getMicroTime();
if (iInTransaction) {
SKGBEGINTRANSACTION(*getDocument(), i18nc("Display an SQL command from the debug plugin", "SQL command from debug plugin"), err);
IFOKDO(err, getDocument()->dumpSelectSqliteOrder(text, oResult));
} else {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = getDocument()->dumpSelectSqliteOrder(text, oResult);
QApplication::restoreOverrideCursor();
}
time = SKGServices::getMicroTime() - time;
oResult += i18nc("Display the execution time needed by an SQL query", "\nExecution time: %1 ms", SKGServices::doubleToString(time));
IFOK(err) {
ui.kSQLResult->setPlainText(oResult);
} else {
ui.kSQLResult->setPlainText(err.getFullMessageWithHistorical());
}
}
}
void SKGDebugPluginWidget::onTraceLevelModified()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGTraces::SKGLevelTrace = ui.kTraceLevel->value();
}
void SKGDebugPluginWidget::onModeChanged()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
int exp = ui.kExplainCmb->currentIndex();
ui.kInput->setVisible(exp > 2);
ui.kSQLInput->setVisible(exp < 3);
}
void SKGDebugPluginWidget::onProfilingModeChanged()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGTraces::SKGPerfo = (ui.kEnableProfilingChk->checkState() == Qt::Checked);
}
void SKGDebugPluginWidget::onRefreshViewsAndIndexes()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
SKGError err;
err = getDocument()->refreshViewsIndexesAndTriggers();
IFKO(err) {
ui.kSQLResult->setPlainText(err.getFullMessageWithHistorical());
}
QApplication::restoreOverrideCursor();
}
diff --git a/plugins/generic/skg_delete/skgdeleteplugin.cpp b/plugins/generic/skg_delete/skgdeleteplugin.cpp
index 6ab991531..f3dfa20d3 100644
--- a/plugins/generic/skg_delete/skgdeleteplugin.cpp
+++ b/plugins/generic/skg_delete/skgdeleteplugin.cpp
@@ -1,138 +1,138 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for delete operation.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgdeleteplugin.h"
#include
#include
#include
#include
#include
#include
#include
#include "skgerror.h"
#include "skgmainpanel.h"
#include "skgobjectbase.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGDeletePluginFactory, registerPlugin();)
SKGDeletePlugin::SKGDeletePlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGDeletePlugin::~SKGDeletePlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
}
bool SKGDeletePlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_delete"), title());
setXMLFile(QStringLiteral("skg_delete.rc"));
// Menu
QStringList tmp;
m_currentDocument->getDistinctValues(QStringLiteral("sqlite_master"), QStringLiteral("name"), QStringLiteral("type='table' AND name!='parameters'"), tmp);
auto actDelete = new QAction(SKGServices::fromTheme(QStringLiteral("edit-delete")), i18nc("Verb, delete an item", "Delete"), this);
connect(actDelete, &QAction::triggered, this, &SKGDeletePlugin::onDelete);
actionCollection()->setDefaultShortcut(actDelete, Qt::Key_Delete);
registerGlobalAction(QStringLiteral("edit_delete"), actDelete, tmp, 1, -1, 200, true);
return true;
}
QString SKGDeletePlugin::title() const
{
return i18nc("Verb, delete an item", "Delete");
}
int SKGDeletePlugin::getOrder() const
{
return 5;
}
void SKGDeletePlugin::onDelete()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((SKGMainPanel::getMainPanel() != nullptr) && (m_currentDocument != nullptr)) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
if (nb > 0) {
if (selection[0].getRealTable() == QStringLiteral("doctransaction")) {
err = m_currentDocument->beginTransaction(QStringLiteral("#INTERNAL#"));
IFOKDO(err, m_currentDocument->executeSqliteOrder(QStringLiteral("CREATE TRIGGER fkdc_doctransaction_doctransaction_i_parent_id "
"BEFORE DELETE ON doctransaction "
"FOR EACH ROW BEGIN "
" DELETE FROM doctransaction WHERE OLD.t_name!='#INTERNAL#' AND doctransaction.id = OLD.i_parent; "
"END")));
for (int i = 0; !err && i < nb; ++i) {
err = selection.at(i).remove();
}
m_currentDocument->executeSqliteOrder(QStringLiteral("DROP TRIGGER IF EXISTS fkdc_doctransaction_doctransaction_i_parent_id"));
SKGENDTRANSACTION(m_currentDocument, err);
} else {
SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Verb, delete an item", "Delete"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
err = selection.at(i).remove();
if (err && err.getReturnCode() == ERR_FORCEABLE) {
QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
int rc = KMessageBox::questionYesNo(SKGMainPanel::getMainPanel(),
err.getFullMessage() % '\n' % i18nc("Question", "Do you want to force the deletion ?"),
i18nc("Question", "Do you want to force the deletion ?"),
KStandardGuiItem::yes(), KStandardGuiItem::no(),
QStringLiteral("forcedelete"));
QApplication::restoreOverrideCursor();
if (rc == KMessageBox::Yes) {
err = selection.at(i).remove(true, true);
}
}
IFOKDO(err, m_currentDocument->stepForward(i + 1))
}
}
}
//
KMessageBox::enableMessage(QStringLiteral("forcedelete"));
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Objects deleted.")))
}
// Display error
SKGMainPanel::displayErrorMessage(err, true);
}
#include
diff --git a/plugins/generic/skg_file/skgfileplugin.cpp b/plugins/generic/skg_file/skgfileplugin.cpp
index 9090169ee..48deef164 100644
--- a/plugins/generic/skg_file/skgfileplugin.cpp
+++ b/plugins/generic/skg_file/skgfileplugin.cpp
@@ -1,625 +1,625 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for file operation.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgfileplugin.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "skgerror.h"
#include "skgfile_settings.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGFilePluginFactory, registerPlugin();)
SKGFilePlugin::SKGFilePlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent),
m_saveAction(nullptr), m_recentFiles(nullptr), m_currentDocument(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Set save on close mode
if (SKGMainPanel::getMainPanel() != nullptr) {
SKGMainPanel::getMainPanel()->setSaveOnClose(skgfile_settings::saveonclose());
}
}
SKGFilePlugin::~SKGFilePlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (m_recentFiles != nullptr) {
m_recentFiles->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "RecentFiles"));
}
m_currentDocument = nullptr;
m_recentFiles = nullptr;
m_saveAction = nullptr;
}
bool SKGFilePlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
if (m_currentDocument == nullptr) {
return false;
}
setComponentName(QStringLiteral("skg_file"), title());
setXMLFile(QStringLiteral("skg_file.rc"));
// Menu
registerGlobalAction(QStringLiteral("file_new"), KStandardAction::openNew(this, SLOT(onNew()), actionCollection()));
registerGlobalAction(QStringLiteral("file_open"), KStandardAction::open(this, SLOT(onOpen()), actionCollection()));
m_saveAction = KStandardAction::save(this, SLOT(onSave()), actionCollection());
registerGlobalAction(QStringLiteral("file_save"), m_saveAction);
registerGlobalAction(QStringLiteral("file_save_as"), KStandardAction::saveAs(this, SLOT(onSaveAs()), actionCollection()));
auto actChangePassword = new QAction(SKGServices::fromTheme(QStringLiteral("document-encrypt")), i18nc("Action allowing the user to change his document password", "Change password..."), this);
connect(actChangePassword, &QAction::triggered, this, &SKGFilePlugin::onChangePassword);
actionCollection()->setDefaultShortcut(actChangePassword, Qt::CTRL + Qt::Key_K);
registerGlobalAction(QStringLiteral("file_change_password"), actChangePassword);
// Recent file
m_recentFiles = KStandardAction::openRecent(this, SLOT(onOpen(QUrl)), actionCollection());
if (m_recentFiles != nullptr) {
m_recentFiles->loadEntries(KConfigGroup(KSharedConfig::openConfig(), "RecentFiles"));
}
// Get last argument
connect(this, &SKGFilePlugin::loadFile, this, &SKGFilePlugin::onOpen, Qt::QueuedConnection);
return true;
}
QStringList SKGFilePlugin::processArguments(const QStringList& iArgument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QStringList output = iArgument;
if (m_currentDocument->getCurrentFileName().isEmpty()) {
int nbArg = iArgument.count();
int openMode = 1; // 0=no open, 1=open last opened if settings set, 2=new document
if (nbArg != 0) {
openMode = 2;
QString filename = iArgument.at(nbArg - 1);
QString extension = QFileInfo(filename).suffix().toUpper();
auto inputFile = QFileInfo(filename);
if (!inputFile.isAbsolute()) {
filename = QFileInfo(QDir::currentPath(), filename).absoluteFilePath();
}
QString extensionDocument = m_currentDocument->getFileExtension().toUpper();
if (extension == extensionDocument) {
if (QFile(filename).exists()) {
if (SKGMainPanel::getMainPanel() != nullptr) {
QSplashScreen* splashScreen = SKGMainPanel::getMainPanel()->splashScreen();
if (splashScreen != nullptr) {
splashScreen->showMessage(i18nc("Splash screen message", "Opening file %1...", filename), Qt::AlignLeft, QColor(221, 130, 8)); // krazy:exclude=qmethods
}
}
Q_EMIT loadFile(QUrl::fromLocalFile(filename));
output.pop_back();
openMode = 0;
} else {
m_currentDocument->sendMessage(i18nc("Error Message", "File %1 not found! Impossible to open it.", filename), SKGDocument::Error);
}
}
}
if (openMode != 0) {
// Read Setting
bool openlastfile = skgfile_settings::openlastfile();
if (openMode == 1 && openlastfile) {
QString lastOpenedFile = skgfile_settings::lastfilepath();
if (!lastOpenedFile.isEmpty() && QFile(lastOpenedFile).exists()) {
if (SKGMainPanel::getMainPanel() != nullptr) {
QSplashScreen* splashScreen = SKGMainPanel::getMainPanel()->splashScreen();
if (splashScreen != nullptr) {
splashScreen->showMessage(i18nc("Splash screen message", "Opening file %1...", lastOpenedFile), Qt::AlignLeft, QColor(221, 130, 8)); // krazy:exclude=qmethods
}
}
Q_EMIT loadFile(QUrl::fromLocalFile(lastOpenedFile));
} else {
openMode = 2;
}
} else {
openMode = 2;
}
if (openMode == 2 && m_currentDocument->getMainDatabase() == nullptr) {
onNew();
}
}
// To be sure that the document has the right parameters
savePreferences();
}
return output;
}
QWidget* SKGFilePlugin::getPreferenceWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
auto w = new QWidget();
ui.setupUi(w);
connect(ui.kcfg_backup_enabled, &QCheckBox::toggled, ui.kcfg_prefix, &SKGComboBox::setEnabled);
connect(ui.kcfg_backup_enabled, &QCheckBox::toggled, ui.kcfg_suffix, &SKGComboBox::setEnabled);
connect(ui.kcfg_storeInKdeWallet, &QCheckBox::toggled, ui.kcfg_selectedWallet, &SKGComboBox::setEnabled);
ui.kcfg_prefix->addItem(QLatin1String(""));
ui.kcfg_prefix->addItem(QStringLiteral("."));
ui.kcfg_suffix->addItem(QStringLiteral(".old"));
ui.kcfg_suffix->addItem(QStringLiteral(".back"));
ui.kcfg_suffix->addItem(QStringLiteral("..back"));
ui.kcfg_suffix->addItem(QStringLiteral("..old"));
ui.kcfg_suffix->addItem(QStringLiteral("~"));
ui.kcfg_selectedWallet->addItems(KWallet::Wallet::walletList());
return w;
}
KConfigSkeleton* SKGFilePlugin::getPreferenceSkeleton()
{
return skgfile_settings::self();
}
SKGError SKGFilePlugin::savePreferences() const
{
SKGError err;
if (m_currentDocument != nullptr) {
// Read Setting
QString prefix;
QString suffix;
if (skgfile_settings::backup_enabled()) {
prefix = skgfile_settings::prefix();
suffix = skgfile_settings::suffix();
}
// Save setting in document
m_currentDocument->setBackupParameters(prefix, suffix);
// Set save on close mode
if (SKGMainPanel::getMainPanel()) {
SKGMainPanel::getMainPanel()->setSaveOnClose(skgfile_settings::saveonclose());
}
}
return err;
}
void SKGFilePlugin::refresh()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Refresh action status
if (m_currentDocument != nullptr) {
if (m_saveAction != nullptr) {
m_saveAction->setEnabled(m_currentDocument->isFileModified());
}
}
}
QString SKGFilePlugin::title() const
{
return i18nc("Noun, a file as in a text file", "File");
}
QString SKGFilePlugin::icon() const
{
return QStringLiteral("document-save");
}
QString SKGFilePlugin::toolTip() const
{
return i18nc("File Management, as in Save File, Save As...", "File management");
}
QStringList SKGFilePlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tip", "... the last opened file can be open automatically when the application is launched.
"));
output.push_back(i18nc("Description of a tip", "... you can secure your document with a password.
"));
return output;
}
int SKGFilePlugin::getOrder() const
{
// Must be one of the first
return 1;
}
void SKGFilePlugin::onNew()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((SKGMainPanel::getMainPanel() != nullptr) && (m_currentDocument != nullptr) && SKGMainPanel::getMainPanel()->queryFileClose()) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
SKGMainPanel::getMainPanel()->closeAllPages(true);
err = m_currentDocument->initialize();
IFOKDO(err, m_currentDocument->setLanguage(QLocale::languageToString(QLocale().language())))
QApplication::restoreOverrideCursor();
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after creating a document", "Document successfully created.")))
else {
err.addError(ERR_FAIL, i18nc("Error message: Could not create a document", "Document creation failed."));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGFilePlugin::onSave()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
if (m_currentDocument->getCurrentFileName().isEmpty()) {
onSaveAs();
} else {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = m_currentDocument->save();
QApplication::restoreOverrideCursor();
// Refresh
SKGMainPanel::getMainPanel()->refresh();
// status bar
IFOKDO(err, SKGError(0, i18nc("Successfully saved a file", "File successfully saved.")))
else {
err.addError(ERR_FAIL, i18nc("Error message: Could not save a file", "Cannot save file"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
}
void SKGFilePlugin::onSaveAs()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QString fileName = SKGMainPanel::getSaveFileName("kfiledialog:///" % m_currentDocument->objectName(),
"*." % m_currentDocument->getFileExtension() % '|' % i18nc("Associated with the file extension : for example, .csv --> CSV document", "%1 document", KAboutData::applicationData().displayName()),
SKGMainPanel::getMainPanel());
if (fileName.isEmpty()) {
return;
}
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = m_currentDocument->saveAs(fileName, true);
QApplication::restoreOverrideCursor();
// Refresh
SKGMainPanel::getMainPanel()->refresh();
// status bar
IFOK(err) {
err = SKGError(0, i18nc("Successfully saved a file", "File '%1' saved.", fileName));
// Add in recentFiles
if (m_recentFiles != nullptr) {
m_recentFiles->addUrl(QUrl::fromLocalFile(fileName));
m_recentFiles->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "RecentFiles"));
}
// Set as last open file in kcfg
KSharedConfigPtr config = KSharedConfig::openConfig();
KConfigGroup pref = config->group("File");
pref.writePathEntry("lastfilepath", fileName);
} else {
err.addError(ERR_FAIL, i18nc("Error message: Could not save a file", "Failed to save '%1'.", fileName));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGFilePlugin::onReOpen()
{
auto* act = qobject_cast< QAction* >(sender());
if (act != nullptr) {
QString filename = act->data().toString();
QFile(SKGDocument::getTemporaryFile(filename)).remove();
onOpen(QUrl::fromLocalFile(filename));
}
}
void SKGFilePlugin::onOpen(const QUrl& iUrl)
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((SKGMainPanel::getMainPanel() != nullptr) && (m_currentDocument != nullptr) && SKGMainPanel::getMainPanel()->queryFileClose()) {
bool useKWallet = skgfile_settings::storeInKdeWallet();
QString pwd;
QString programName = KAboutData::applicationData().displayName();
QString fileName = iUrl.toLocalFile();
if (fileName.isEmpty()) {
auto* act = qobject_cast< QAction* >(sender());
if (act != nullptr) {
fileName = act->property("filename").toString();
}
}
if (fileName.isEmpty()) {
fileName = QFileDialog::getOpenFileUrl(SKGMainPanel::getMainPanel(), i18nc("Panel title", "Open file"),
QUrl(),
i18nc("File format for open dialog panel", "%1 document", programName) % "(*." % m_currentDocument->getFileExtension() % ")").toLocalFile();
}
if (!fileName.isEmpty()) {
// Check if temporary file exists
bool restoreTmpFile = false;
QString tmpFile = SKGDocument::getTemporaryFile(fileName);
if (QFile(tmpFile).exists()) {
KMessageWidget* msg = SKGMainPanel::getMainPanel()->displayMessage(i18nc("Warning message", "Your document has been restored from its temporary file. You can decide to reopen the original document."), SKGDocument::Warning);
auto reopen = new QAction(i18nc("Noun", "Reopen"), msg);
reopen->setIcon(SKGServices::fromTheme(QStringLiteral("quickopen")));
reopen->setData(fileName);
msg->addAction(reopen);
connect(reopen, &QAction::triggered, this, &SKGFilePlugin::onReOpen);
connect(reopen, &QAction::triggered, msg, &KMessageWidget::deleteLater, Qt::QueuedConnection);
restoreTmpFile = true;
}
// Open
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
SKGMainPanel::getMainPanel()->closeAllPages(true);
err = m_currentDocument->load(fileName, QLatin1String(""), restoreTmpFile);
QApplication::restoreOverrideCursor();
if (err && err.getReturnCode() == ERR_ENCRYPTION) {
m_currentDocument->close();
// Open failed
// Password must be asked
QString additionalMessage;
do {
// Reset error
err = SKGError(0, QLatin1String(""));
pwd = QLatin1String("");
// Get password
if (useKWallet) {
SKGTRACEL(10) << "Use KWallet" << endl;
// Use KWallet
QString walletName = skgfile_settings::selectedWallet();
if (!KWallet::Wallet::walletList().contains(walletName)) {
walletName = KWallet::Wallet::walletList().value(SKGServices::stringToInt(skgfile_settings::selectedWallet()));
if (walletName.isEmpty()) {
walletName = QStringLiteral("kdewallet");
}
}
KWallet::Wallet* w = KWallet::Wallet::openWallet(walletName, SKGMainPanel::getMainPanel()->winId());
if (w != nullptr) {
// Change folder
if (!w->hasFolder(programName)) {
w->createFolder(programName);
}
w->setFolder(programName);
// Read password
w->readPassword(fileName, pwd);
if (pwd.isEmpty()) {
SKGTRACEL(10) << "Password not found in KWallet for " << fileName << endl;
useKWallet = false;
}
delete w;
w = nullptr;
}
}
if (!useKWallet) {
SKGTRACEL(10) << "Ask password" << endl;
// Use password dialog
QPointer dlg = new KPasswordDialog(SKGMainPanel::getMainPanel());
dlg->setPrompt(additionalMessage % i18nc("Question", "This file seems to be protected.\nPlease enter the password."));
if (dlg->exec() == QDialog::Accepted) {
pwd = dlg->password();
}
delete dlg;
}
// Load file
if (!pwd.isEmpty()) {
QSplashScreen* splashScreen = SKGMainPanel::getMainPanel()->splashScreen();
if (splashScreen != nullptr) {
splashScreen->hide();
}
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = m_currentDocument->load(fileName, pwd, restoreTmpFile);
IFKO(err) {
if (err.getReturnCode() == ERR_ENCRYPTION) {
additionalMessage = i18nc("The user did not provide the correct password", "Wrong password.\n");
useKWallet = false;
} else {
// Load error
QApplication::restoreOverrideCursor();
break;
}
}
QApplication::restoreOverrideCursor();
if (splashScreen != nullptr) {
splashScreen->show();
}
}
} while (err);
}
IFOKDO(err, m_currentDocument->setLanguage(QLocale::languageToString(QLocale().language())))
// status bar
IFOK(err) {
err = SKGError(0, i18nc("Successfully opened a file", "File '%1' opened.", fileName));
// Add in recentFiles
if (m_recentFiles != nullptr) {
m_recentFiles->addUrl(QUrl::fromLocalFile(fileName));
m_recentFiles->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "RecentFiles"));
}
// Set as last open file in kcfg
KSharedConfigPtr config = KSharedConfig::openConfig();
KConfigGroup pref = config->group("File");
pref.writePathEntry("lastfilepath", fileName);
// Store password if KDE wallet if needed
if (skgfile_settings::storeInKdeWallet() && !useKWallet) {
// Use KWallet
QString walletName = skgfile_settings::selectedWallet();
if (!KWallet::Wallet::walletList().contains(walletName)) {
walletName = KWallet::Wallet::walletList().value(SKGServices::stringToInt(skgfile_settings::selectedWallet()));
if (walletName.isEmpty()) {
walletName = QStringLiteral("kdewallet");
}
}
KWallet::Wallet* w = KWallet::Wallet::openWallet(walletName, SKGMainPanel::getMainPanel()->winId());
if (w != nullptr) {
// Change folder
w->setFolder(programName);
// Write password
w->writePassword(fileName, pwd);
delete w;
w = nullptr;
}
}
} else {
this->onNew();
if (err.getReturnCode() != ERR_CORRUPTION) {
err.addError(ERR_FAIL, i18nc("Error message: Could not open a file", "Failed to open '%1'.", fileName));
}
}
// Display error
QAction* recovery = nullptr;
#ifdef Q_OS_UNIX
if (err.getReturnCode() == ERR_CORRUPTION) {
recovery = new QAction(i18nc("Noun", "Try a recovery"), this);
recovery->setIcon(SKGServices::fromTheme(QStringLiteral("games-solve")));
recovery->setData(SKGServices::stringsToCsv(QStringList() << fileName << pwd));
connect(recovery, &QAction::triggered, this, &SKGFilePlugin::onRecover);
}
#endif
SKGMainPanel::displayErrorMessage(err, recovery);
}
}
}
void SKGFilePlugin::onRecover()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
auto* act = qobject_cast< QAction* >(sender());
if ((act != nullptr) && (m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QStringList params = SKGServices::splitCSVLine(act->data().toString());
QString recoveredFileName;
err = m_currentDocument->recover(params.at(0), params.at(1), recoveredFileName);
IFOK(err) {
// Display recovery message
KMessageWidget* msg = SKGMainPanel::getMainPanel()->displayMessage(i18nc("Positive message", "Your document has been recovered here: %1\nTake care the recovery could be not perfect", recoveredFileName), SKGDocument::Positive);
auto reopen = new QAction(i18nc("Noun", "Open the recovered file"), msg);
reopen->setIcon(SKGServices::fromTheme(QStringLiteral("quickopen")));
reopen->setData(recoveredFileName);
msg->addAction(reopen);
connect(reopen, &QAction::triggered, this, &SKGFilePlugin::onReOpen);
connect(reopen, &QAction::triggered, msg, &KMessageWidget::deleteLater, Qt::QueuedConnection);
} else {
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
}
void SKGFilePlugin::onChangePassword()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QPointer dlg = new KNewPasswordDialog(SKGMainPanel::getMainPanel());
dlg->setPrompt(i18n("Take care, if you lose your password then it will be impossible to open your document. Warning, this action can not be undone excepted by changing the password again."));
if (dlg->exec() == 0) {
err = SKGError(0, i18nc("Successfully changed the document password", "Changing password was canceled."));
} else {
QString newPassword = dlg->password();
IFOKDO(err, m_currentDocument->changePassword(newPassword));
// status
IFOKDO(err, SKGError(0, i18nc("Successfully changed the document password", "Password changed.")))
else {
err.addError(ERR_FAIL, i18nc("Error message: Could not change the document password", "Failed to change password."));
}
}
delete dlg;
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
SKGAdviceList SKGFilePlugin::advice(const QStringList& iIgnoredAdvice)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGAdviceList output;
// Backup
if (!iIgnoredAdvice.contains(QStringLiteral("skgfileplugin_notvalidated"))) {
SKGAdvice ad;
ad.setUUID(QStringLiteral("skgfileplugin_notvalidated"));
ad.setPriority(2);
ad.setShortMessage(i18nc("Advice to the user that he should backup his document", "Backup your document"));
ad.setLongMessage(i18nc("Explain the user that he should backup his document", "Do not forget to backup your document on another device."));
output.push_back(ad);
}
return output;
}
#include
diff --git a/plugins/generic/skg_highlight/skghighlightplugin.cpp b/plugins/generic/skg_highlight/skghighlightplugin.cpp
index 72670e5d5..a99811fd4 100644
--- a/plugins/generic/skg_highlight/skghighlightplugin.cpp
+++ b/plugins/generic/skg_highlight/skghighlightplugin.cpp
@@ -1,162 +1,162 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to highlight objects
*
* @author Stephane MANKOWSKI
*/
#include "skghighlightplugin.h"
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGHighlightPluginFactory, registerPlugin();)
SKGHighlightPlugin::SKGHighlightPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGHighlightPlugin::~SKGHighlightPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
}
bool SKGHighlightPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_highlight"), title());
setXMLFile(QStringLiteral("skg_highlight.rc"));
// ------------
auto actSwitchHighLight = new QAction(SKGServices::fromTheme(QStringLiteral("bookmarks")), i18nc("Verb", "Switch highlight"), this);
connect(actSwitchHighLight, &QAction::triggered, this, &SKGHighlightPlugin::onSwitchHighLight);
actionCollection()->setDefaultShortcut(actSwitchHighLight, Qt::CTRL + Qt::Key_H);
registerGlobalAction(QStringLiteral("edit_switch_highlight"), actSwitchHighLight, QStringList() << QStringLiteral("query:type='table' AND sql LIKE '%t_bookmarked%'"), 1, -1, 301);
// ------------
auto actSwitchClose = new QAction(SKGServices::fromTheme(QStringLiteral("dialog-close")), i18nc("Verb", "Switch close"), this);
connect(actSwitchClose, &QAction::triggered, this, &SKGHighlightPlugin::onSwitchClose);
registerGlobalAction(QStringLiteral("edit_switch_close"), actSwitchClose, QStringList() << QStringLiteral("query:type='table' AND sql LIKE '%t_close%'"), 1, -1, 301);
// Create yours actions here
return true;
}
QString SKGHighlightPlugin::title() const
{
return toolTip();
}
QString SKGHighlightPlugin::icon() const
{
return QStringLiteral("bookmarks");
}
QString SKGHighlightPlugin::toolTip() const
{
return i18nc("The tool tip", "Highlight");
}
int SKGHighlightPlugin::getOrder() const
{
return 6;
}
void SKGHighlightPlugin::onSwitchClose()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
// Get Selection
if ((SKGMainPanel::getMainPanel() != nullptr) && (m_currentDocument != nullptr)) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
{
SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Noun, name of the user action", "Close"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
SKGObjectBase obj(selection.at(i));
IFOKDO(err, obj.setAttribute(QStringLiteral("t_close"), obj.getAttribute(QStringLiteral("t_close")) == QStringLiteral("Y") ? QStringLiteral("N") : QStringLiteral("Y")))
IFOKDO(err, obj.save())
// Send message
IFOKDO(err, m_currentDocument->sendMessage(i18nc("An information to the user", "The close status of '%1' has been changed", obj.getDisplayName()), SKGDocument::Hidden));
IFOKDO(err, m_currentDocument->stepForward(i + 1))
}
}
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Closed.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Closure failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGHighlightPlugin::onSwitchHighLight()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
// Get Selection
if ((SKGMainPanel::getMainPanel() != nullptr) && (m_currentDocument != nullptr)) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
{
SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Noun, name of the user action", "Highlight"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
SKGObjectBase obj(selection.at(i));
IFOKDO(err, obj.setAttribute(QStringLiteral("t_bookmarked"), obj.getAttribute(QStringLiteral("t_bookmarked")) == QStringLiteral("Y") ? QStringLiteral("N") : QStringLiteral("Y")))
IFOKDO(err, obj.save())
// Send message
IFOKDO(err, m_currentDocument->sendMessage(i18nc("An information to the user", "The highlight status of '%1' has been changed", obj.getDisplayName()), SKGDocument::Hidden));
IFOKDO(err, m_currentDocument->stepForward(i + 1))
}
}
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Highlighted.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Highlight failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
#include
diff --git a/plugins/generic/skg_monthly/skgmonthlyplugin.cpp b/plugins/generic/skg_monthly/skgmonthlyplugin.cpp
index 3a15695ed..88ea3b9b4 100644
--- a/plugins/generic/skg_monthly/skgmonthlyplugin.cpp
+++ b/plugins/generic/skg_monthly/skgmonthlyplugin.cpp
@@ -1,188 +1,188 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin for monthly report
*
* @author Stephane MANKOWSKI
*/
#include "skgmonthlyplugin.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgmonthlypluginwidget.h"
#include "skgreport.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGMonthlyPluginFactory, registerPlugin();)
SKGMonthlyPlugin::SKGMonthlyPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent),
m_currentBankDocument(nullptr), m_mainPage(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGMonthlyPlugin::~SKGMonthlyPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentBankDocument = nullptr;
}
bool SKGMonthlyPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentBankDocument = iDocument;
setComponentName(QStringLiteral("skg_monthly"), title());
setXMLFile(QStringLiteral("skg_monthly.rc"));
// Make needed paths
QString writablePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
QString path = writablePath % QLatin1Char('/') + KAboutData::applicationData().componentName() % QStringLiteral("/html/default");
if (!QDir(writablePath).mkpath(KAboutData::applicationData().componentName() % QStringLiteral("/html/default"))) {
SKGTRACE << "WARNING: Impossible to create html/default in " << writablePath << endl;
}
// Copy "default" directory in locale
const auto dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html/default", QStandardPaths::LocateDirectory);
for (const auto& dir : dirs) {
QDirIterator it(dir, QStringList() << QStringLiteral("*.html"));
while (it.hasNext()) {
QString file = it.next();
QString target = path % QLatin1Char('/') % QFileInfo(file).fileName();
QFile(target).remove();
if (file != target && !QFile(file).copy(target)) {
SKGTRACE << "WARNING: Impossible to copie " << file << " in " << target << endl;
}
}
}
// Create yours actions here
return true;
}
QStringList SKGMonthlyPlugin::processArguments(const QStringList& iArgument)
{
// Initialise the main page
if (m_mainPage == nullptr) {
#ifdef SKG_WEBENGINE
{
SKGTRACEIN(10, "SKGMonthlyPlugin::setupActions-Init SKGWebView");
m_mainPage = new SKGWebView(SKGMainPanel::getMainPanel(), 0, false);
SKGMainPanel::getMainPanel()->setMainWidget(m_mainPage);
refreshMainPage();
connect(m_currentBankDocument, &SKGDocument::transactionSuccessfullyEnded, this, &SKGMonthlyPlugin::refreshMainPage);
qApp->processEvents(QEventLoop::AllEvents, 500);
}
#else
m_mainPage = new QWebView();
m_mainPage->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
connect(m_mainPage, &QWebView::linkClicked, this, [ = ](const QUrl & val) {
SKGMainPanel::getMainPanel()->openPage(val);
});
SKGMainPanel::getMainPanel()->setMainWidget(m_mainPage);
refreshMainPage();
connect(m_currentBankDocument, &SKGDocument::transactionSuccessfullyEnded, this, &SKGMonthlyPlugin::refreshMainPage);
#endif
}
return iArgument;
}
void SKGMonthlyPlugin::refreshMainPage()
{
QString html;
QString templateFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html/main.txt");
if (templateFile.isEmpty()) {
html = i18nc("Error message", "File %1/html/main.txt not found", KAboutData::applicationData().componentName());
} else {
if ((m_currentBankDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
SKGReport* rep = m_currentBankDocument->getReport();
// Enrich with tips of the day
rep->setTipsOfDay(SKGMainPanel::getMainPanel()->getTipsOfDay());
SKGError err = SKGReport::getReportFromTemplate(rep, templateFile, html);
IFKO(err) html += err.getFullMessageWithHistorical();
delete rep;
}
}
#ifdef SKG_WEBENGINE
m_mainPage->setHtml(html, QUrl("file://"));
#else
m_mainPage->setHtml(html);
#endif
}
SKGTabPage* SKGMonthlyPlugin::getWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
return new SKGMonthlyPluginWidget(SKGMainPanel::getMainPanel(), m_currentBankDocument);
}
QString SKGMonthlyPlugin::title() const
{
return toolTip();
}
QString SKGMonthlyPlugin::icon() const
{
return QStringLiteral("view-calendar-journal");
}
QString SKGMonthlyPlugin::toolTip() const
{
return i18nc("A tool tip", "Monthly report");
}
int SKGMonthlyPlugin::getOrder() const
{
return 50;
}
QStringList SKGMonthlyPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tips", "... you can generate a monthly report.
"));
output.push_back(i18nc("Description of a tips", "... you can download more monthly report templates.
"));
output.push_back(i18nc("Description of a tips", "... you can create and share your own monthly report template.
"));
return output;
}
bool SKGMonthlyPlugin::isInPagesChooser() const
{
return true;
}
#include
diff --git a/plugins/generic/skg_monthly/skgmonthlypluginwidget.cpp b/plugins/generic/skg_monthly/skgmonthlypluginwidget.cpp
index a6fcbc33c..5d86e1595 100644
--- a/plugins/generic/skg_monthly/skgmonthlypluginwidget.cpp
+++ b/plugins/generic/skg_monthly/skgmonthlypluginwidget.cpp
@@ -1,393 +1,393 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin for monthly report.
*
* @author Stephane MANKOWSKI
*/
#include "skgmonthlypluginwidget.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef SKG_WEBENGINE
#include
#else
#include
#endif
#include
#include
#include
#include "skgmainpanel.h"
#include "skgreport.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
SKGMonthlyPluginWidget::SKGMonthlyPluginWidget(QWidget* iParent, SKGDocument* iDocument)
: SKGTabPage(iParent, iDocument), m_upload(nullptr)
{
SKGTRACEINFUNC(1);
if (iDocument == nullptr) {
return;
}
ui.setupUi(this);
ui.kMonth->setMode(SKGSimplePeriodEdit::PREVIOUS_PERIODS | SKGSimplePeriodEdit::PREVIOUS_MONTHS);
ui.kDeleteTemplate->hide();
ui.kRefresh->setIcon(SKGServices::fromTheme(QStringLiteral("view-refresh")));
ui.kGetNewHotStuff->setIcon(SKGServices::fromTheme(QStringLiteral("get-hot-new-stuff")));
ui.kDeleteTemplate->setIcon(SKGServices::fromTheme(QStringLiteral("edit-delete")));
auto newValidator = new QRegExpValidator(QRegExp(QStringLiteral("^[\\w\\s]+$")), this);
ui.kTemplate->setValidator(newValidator);
connect(getDocument(), &SKGDocument::tableModified, this, &SKGMonthlyPluginWidget::dataModified, Qt::QueuedConnection);
connect(ui.kMonth, static_cast(&SKGComboBox::currentTextChanged), this, &SKGMonthlyPluginWidget::onPeriodChanged, Qt::QueuedConnection);
QStringList overlays;
overlays.push_back(QStringLiteral("list-add"));
m_upload = new QAction(SKGServices::fromTheme(QStringLiteral("get-hot-new-stuff"), overlays), i18n("Upload"), this);
connect(m_upload, &QAction::triggered, this, &SKGMonthlyPluginWidget::onPutNewHotStuff);
auto menu = new QMenu(this);
menu->addAction(m_upload);
ui.kGetNewHotStuff->setMenu(menu);
connect(ui.kDeleteTemplate, &QToolButton::clicked, this, &SKGMonthlyPluginWidget::onDeleteTemplate);
connect(ui.kTemplate, static_cast(&SKGComboBox::returnPressed), this, &SKGMonthlyPluginWidget::onAddTemplate);
connect(ui.kTemplate, &SKGComboBox::editTextChanged, this, &SKGMonthlyPluginWidget::onTemplateChanged);
connect(ui.kGetNewHotStuff, &QToolButton::clicked, this, &SKGMonthlyPluginWidget::onGetNewHotStuff);
connect(ui.kRefresh, &QToolButton::clicked, this, &SKGMonthlyPluginWidget::onPeriodChanged);
// Refresh
fillTemplateList();
dataModified(QLatin1String(""), 0);
}
SKGMonthlyPluginWidget::~SKGMonthlyPluginWidget()
{
SKGTRACEINFUNC(1);
}
QString SKGMonthlyPluginWidget::getState()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
QDomElement root = doc.createElement(QStringLiteral("parameters"));
doc.appendChild(root);
// Get state
root.setAttribute(QStringLiteral("month"), ui.kMonth->text());
root.setAttribute(QStringLiteral("template"), ui.kTemplate->text());
root.setAttribute(QStringLiteral("web"), ui.kWebView->getState());
return doc.toString();
}
void SKGMonthlyPluginWidget::setState(const QString& iState)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QDomDocument doc(QStringLiteral("SKGML"));
doc.setContent(iState);
QDomElement root = doc.documentElement();
// Set state
QString webS = root.attribute(QStringLiteral("web"));
if (!webS.isEmpty()) {
ui.kWebView->setState(webS);
}
QString templat = root.attribute(QStringLiteral("template"));
if (!templat.isEmpty()) {
bool p = ui.kTemplate->blockSignals(true);
ui.kTemplate->setText(templat);
ui.kTemplate->blockSignals(p);
onTemplateChanged();
}
QString month = root.attribute(QStringLiteral("month"));
if (!month.isEmpty()) {
ui.kMonth->setText(month);
}
onPeriodChanged();
}
QString SKGMonthlyPluginWidget::getDefaultStateAttribute()
{
return QStringLiteral("SKGMONTHLY_DEFAULT_PARAMETERS");
}
QWidget* SKGMonthlyPluginWidget::mainWidget()
{
return ui.kWebView;
}
void SKGMonthlyPluginWidget::fillTemplateList()
{
disconnect(ui.kTemplate, static_cast(&SKGComboBox::currentTextChanged), this, &SKGMonthlyPluginWidget::onPeriodChanged);
// Get previous selected item
QString current = ui.kTemplate->text();
// Fill
ui.kTemplate->clear();
const auto dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html", QStandardPaths::LocateDirectory);
for (const auto& dir : dirs) {
QDirIterator it(dir, QStringList() << QStringLiteral("*.txt"));
while (it.hasNext()) {
QString file = it.next();
QFileInfo f(file);
QString file2 = f.completeBaseName();
if (!ui.kTemplate->contains(file2) && file2 != QStringLiteral("main")) {
ui.kTemplate->addItem(file2, file);
}
}
}
// Set previous selected itemData
if (!current.isEmpty() && ui.kTemplate->contains(current)) {
ui.kTemplate->setCurrentItem(current);
}
connect(ui.kTemplate, static_cast(&SKGComboBox::currentTextChanged), this, &SKGMonthlyPluginWidget::onPeriodChanged, Qt::QueuedConnection);
}
void SKGMonthlyPluginWidget::onAddTemplate()
{
QString templat = ui.kTemplate->text().trimmed();
QString templateDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + KAboutData::applicationData().componentName();
QString templatFileName = templateDir % "/html/" % templat % ".txt";
QStringList templates;
const auto dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html", QStandardPaths::LocateDirectory);
for (const auto& dir : dirs) {
QDirIterator it(dir, QStringList() << QStringLiteral("*.txt"));
while (it.hasNext()) {
templates.append(it.next());
}
}
if (!templat.isEmpty() && (!templates.contains(templatFileName) || QFileInfo(templatFileName).isWritable())) {
SKGError err;
if (!templates.contains(templatFileName)) {
// Create the new template
QString source = QStandardPaths::locate(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html/tutorial.txt");
QDir(templateDir).mkpath(QStringLiteral("html"));
if (SKGServices::upload(QUrl::fromLocalFile(source), QUrl::fromLocalFile(templatFileName))) {
err.setReturnCode(ERR_FAIL).setMessage(i18nc("An error message", "Impossible to copy file from '%1' to '%2'", source, templatFileName));
} else {
fillTemplateList();
}
}
// Open the created or already existing file
QDesktopServices::openUrl(QUrl::fromLocalFile(templatFileName));
onTemplateChanged();
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGMonthlyPluginWidget::onDeleteTemplate()
{
QString templat = ui.kTemplate->text().trimmed();
QString templatFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + KAboutData::applicationData().componentName() % "/html/" % templat % ".txt";
if (!templat.isEmpty()) {
// This is a new source
SKGError err;
// Delete the file
QFile file(templatFileName);
if (!file.remove()) {
err.setReturnCode(ERR_INVALIDARG).setMessage(i18nc("Error message", "Deletion of '%1' failed", templatFileName));
}
IFOK(err) ui.kTemplate->removeItem(ui.kTemplate->findText(templat));
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGMonthlyPluginWidget::onTemplateChanged()
{
QString templat = ui.kTemplate->text().trimmed();
QString templatFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + KAboutData::applicationData().componentName() % "/html/" % templat % ".txt";
bool local = !templat.isEmpty() && QFileInfo(templatFileName).isWritable();
ui.kDeleteTemplate->setVisible(local);
m_upload->setEnabled(local);
}
void SKGMonthlyPluginWidget::dataModified(const QString& iTableName, int iIdTransaction)
{
SKGTRACEINFUNC(1);
Q_UNUSED(iIdTransaction);
QSqlDatabase* db = getDocument()->getMainDatabase();
setEnabled(db != nullptr);
// TODO(Stephane MANKOWSKI): v_operation_display must be generic
if (db != nullptr && (iTableName == QStringLiteral("v_operation_display") || iTableName.isEmpty())) {
// Fill combo
QDate date = QDate::currentDate();
QStringList list;
// TODO(Stephane MANKOWSKI): v_operation_display must be generic
getDocument()->getDistinctValues(QStringLiteral("v_operation_display"), QStringLiteral("MIN(d_DATEMONTH)"), QStringLiteral("d_date<=CURRENT_DATE"), list);
if (!list.isEmpty()) {
if (!list[0].isEmpty()) {
date = SKGServices::periodToDate(list[0]);
}
}
ui.kMonth->setFirstDate(date);
ui.kRefresh->setEnabled(!list.isEmpty());
}
}
QString SKGMonthlyPluginWidget::getPeriod()
{
return ui.kMonth->period();
}
void SKGMonthlyPluginWidget::onPeriodChanged()
{
SKGTRACEINFUNC(1);
QString month = getPeriod();
if (!month.isEmpty()) {
// Display report
QString htmlReport = getDocument()->getParameter("SKG_MONTHLY_REPORT_" % month);
if (htmlReport.isEmpty() || sender() == ui.kRefresh || sender() == ui.kTemplate) {
SKGError err;
SKGBEGINLIGHTTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Compute monthly report for '%1'", month), err);
htmlReport = getReport();
err = getDocument()->setParameter("SKG_MONTHLY_REPORT_" % month, htmlReport);
}
// Display html report
#ifdef SKG_WEBENGINE
ui.kWebView->page()->setHtml(htmlReport, QUrl("file://"));
#else
ui.kWebView->setHtml(htmlReport);
ui.kWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
#endif
}
}
void SKGMonthlyPluginWidget::onGetNewHotStuff()
{
QPointer dialog = new KNS3::DownloadDialog(KAboutData::applicationData().componentName() % "_monthly.knsrc", this);
dialog->exec();
fillTemplateList();
}
void SKGMonthlyPluginWidget::onPutNewHotStuff()
{
QString templat = ui.kTemplate->text().trimmed();
// Create zip file
QString templatFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + KAboutData::applicationData().componentName() % "/html/" % templat % ".txt";
QString templatHFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + KAboutData::applicationData().componentName() % "/html/" % templat % ".html";
QString zipFileName = QDir::tempPath() % "/" % templat % ".zip";
KZip zip(zipFileName);
if (zip.open(QIODevice::WriteOnly)) {
zip.addLocalFile(templatFileName, templat % ".txt");
if (QFile(templatHFileName).exists()) {
zip.addLocalFile(templatHFileName, templat % ".html");
}
zip.close();
// Create screen shots
QString preview1 = QDir::tempPath() % "/" % templat % "_preview1.png";
QString preview2 = QDir::tempPath() % "/" % templat % "_preview2.png";
QString preview3 = QDir::tempPath() % "/" % templat % "_preview3.png";
#ifdef SKG_WEBENGINE
// TODO(SMI): QWebEngine
#else
bool previous = ui.kWebView->blockSignals(true);
QWebFrame* frame = ui.kWebView->page()->mainFrame();
frame->setScrollBarValue(Qt::Vertical, frame->scrollBarMaximum(Qt::Vertical));
ui.kWebView->exportInFile(preview2);
frame->setScrollBarValue(Qt::Vertical, frame->scrollBarMaximum(Qt::Vertical) / 2);
ui.kWebView->exportInFile(preview3);
frame->setScrollBarValue(Qt::Vertical, 0);
ui.kWebView->exportInFile(preview1);
ui.kWebView->blockSignals(previous);
#endif
// Open dialog
QPointer dialog = new KNS3::UploadDialog(KAboutData::applicationData().componentName() % "_monthly.knsrc", this);
dialog->setUploadFile(QUrl::fromLocalFile(zipFileName));
dialog->setUploadName(templat);
dialog->setPreviewImageFile(0, QUrl::fromLocalFile(preview1));
dialog->setPreviewImageFile(1, QUrl::fromLocalFile(preview2));
dialog->setPreviewImageFile(2, QUrl::fromLocalFile(preview3));
dialog->setDescription(i18nc("Default description for a monthly report template", "My favorite template"));
dialog->setVersion(QStringLiteral("0.1"));
dialog->setChangelog(QStringLiteral("V0.1 - Initial version"));
dialog->exec();
// Delete temporary files
QFile(zipFileName).remove();
QFile(preview1).remove();
QFile(preview2).remove();
QFile(preview3).remove();
}
}
QString SKGMonthlyPluginWidget::getReport()
{
QString html;
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
// Get period
if (!getPeriod().isEmpty()) {
SKGReport* rep = getDocument()->getReport();
if (rep != nullptr) {
rep->setPeriod(getPeriod());
// Enrich with tips of the day
rep->setTipsOfDay(SKGMainPanel::getMainPanel()->getTipsOfDay());
err = SKGReport::getReportFromTemplate(rep, ui.kTemplate->itemData(ui.kTemplate->currentIndex()).toString(), html);
delete rep;
}
}
QApplication::restoreOverrideCursor();
// status bar
IFKO(err) html += err.getFullMessageWithHistorical();
return html;
}
diff --git a/plugins/generic/skg_print/skgprintplugin.cpp b/plugins/generic/skg_print/skgprintplugin.cpp
index 56644c03a..54fe0aa7e 100644
--- a/plugins/generic/skg_print/skgprintplugin.cpp
+++ b/plugins/generic/skg_print/skgprintplugin.cpp
@@ -1,300 +1,300 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to print pages
*
* @author Stephane MANKOWSKI
*/
#include "skgprintplugin.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgprint_settings.h"
#include "skgtraces.h"
#include "skgtreeview.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGPrintPluginFactory, registerPlugin();)
SKGPrintPlugin::SKGPrintPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
Q_UNUSED(iWidget);
m_printer.setResolution(QPrinter::HighResolution);
}
SKGPrintPlugin::~SKGPrintPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
}
bool SKGPrintPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_print"), title());
setXMLFile(QStringLiteral("skg_print.rc"));
registerGlobalAction(QStringLiteral("file_print"), KStandardAction::print(this, SLOT(onPrint()), actionCollection()), QStringList(), -1);
registerGlobalAction(QStringLiteral("file_print_preview"), KStandardAction::printPreview(this, SLOT(onPrintPreview()), actionCollection()), QStringList(), -1);
auto actPrintHtmlAction = new QAction(SKGServices::fromTheme(QStringLiteral("preview")), i18nc("Verb, print in an html file", "Print into a html file"), this);
connect(actPrintHtmlAction, &QAction::triggered, this, &SKGPrintPlugin::onPrintHtml);
registerGlobalAction(QStringLiteral("file_print_html"), actPrintHtmlAction, QStringList(), -1);
return true;
}
KConfigSkeleton* SKGPrintPlugin::getPreferenceSkeleton()
{
return skgprint_settings::self();
}
QString SKGPrintPlugin::title() const
{
return i18nc("Verb, action to use a printer", "print");
}
int SKGPrintPlugin::getOrder() const
{
return 2;
}
QStringList SKGPrintPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tips", "... you can print all opened pages.
"));
return output;
}
void SKGPrintPlugin::onPrint()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if (SKGMainPanel::getMainPanel() != nullptr) {
QPointer dialog = new QPrintDialog(&m_printer, SKGMainPanel::getMainPanel());
dialog->setOption(QAbstractPrintDialog::PrintCurrentPage, true);
dialog->setMinMax(1, SKGMainPanel::getMainPanel()->getTabWidget()->count());
if (dialog->exec() == QDialog::Accepted) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
print(&m_printer);
QApplication::restoreOverrideCursor();
}
}
}
void SKGPrintPlugin::onPrintPreview()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
// TODO(SMI): QWebEngine does not work
QPointer dialog = new QPrintPreviewDialog(SKGMainPanel::getMainPanel());
connect(dialog.data(), &QPrintPreviewDialog::paintRequested, this, &SKGPrintPlugin::print);
dialog->exec();
}
void SKGPrintPlugin::onPrintHtml()
{
QString html;
getHtml(&m_printer, html);
QString fileName = QDir::tempPath() % "/skrooge.html";
QSaveFile file(fileName);
if (file.open(QIODevice::WriteOnly)) {
QTextStream out(&file);
out << html;
// Close file
file.commit();
}
QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
}
SKGError SKGPrintPlugin::getHtml(QPrinter* iPrinter, QString& oHtml) const
{
SKGError err;
- _SKGTRACEINFUNCRC(10, err);
+ _SKGTRACEINFUNCRC(10, err)
if ((SKGMainPanel::getMainPanel() != nullptr) && (iPrinter != nullptr)) {
QString html;
// Get printer options
int docCopies;
int pageCopies;
if (iPrinter->collateCopies()) {
docCopies = 1;
pageCopies = iPrinter->actualNumCopies();
} else {
docCopies = iPrinter->actualNumCopies();
pageCopies = 1;
}
int fromPage = qMin(iPrinter->fromPage(), iPrinter->toPage());
int toPage = qMax(iPrinter->fromPage(), iPrinter->toPage());
// Compute the number of pages
SKGTabWidget* tabs = SKGMainPanel::getMainPanel()->getTabWidget();
int nbpages = tabs->count();
if (fromPage == 0 && toPage == 0) {
fromPage = 1;
toPage = nbpages;
}
if (iPrinter->printRange() == QPrinter::CurrentPage) {
fromPage = SKGMainPanel::getMainPanel()->currentPageIndex() + 1;
toPage = fromPage;
}
SKGTRACEL(10) << "Nb copy document=" << docCopies << endl;
SKGTRACEL(10) << "Nb copy page=" << docCopies << endl;
SKGTRACEL(10) << "From=" << fromPage << endl;
SKGTRACEL(10) << "To=" << toPage << endl;
// Copy document
for (int c = 1; !err && c <= docCopies; ++c) {
for (int i = 1; !err && i <= nbpages; ++i) {
// Compute page
int pageToTreat = (iPrinter->pageOrder() == QPrinter::LastPageFirst ? nbpages + 1 - i : i);
// Do we have to print it
if (pageToTreat >= fromPage && pageToTreat <= toPage) {
// Yes, get the widget
// Copy pages
for (int p = 1; !err && p <= pageCopies; ++p) {
auto* page = qobject_cast(tabs->widget(pageToTreat - 1));
if (page != nullptr) {
// Add page break if needed
if (!html.isEmpty()) {
html = html % "";
}
// Add widgets
QList widgets = page->printableWidgets();
int nbw = widgets.count();
for (int j = 0; !err && j < nbw; ++j) {
QWidget* w = widgets.at(j);
if (w != nullptr) {
// Add widget
/*SKGTreeView* tw = qobject_cast< SKGTreeView* >(w);
if (tw) {
QTextBrowser* tb = tw->getTextBrowser();
if (tb) {
html = html % tb->toHtml();
delete tb;
}
} else {*/
#ifdef SKG_WEBENGINE
auto q = qobject_cast< QWebEngineView* >(w);
#else
auto q = qobject_cast< QWebView* >(w);
#endif
if (q != nullptr) {
#ifdef SKG_WEBENGINE
q->page()->toHtml([&](const QString & result) {
html = html % result;
});
qApp->processEvents(QEventLoop::AllEvents, 5000);
#else
html = html % q->page()->currentFrame()->toHtml();
#endif
} else {
// Save palette
QPalette previousPalette = w->palette();
// Draw in a picture with white background
QPalette palette;
palette.setColor(QPalette::Background, Qt::white);
w->setPalette(palette);
QImage image = w->grab().toImage();
// Restore palette
w->setPalette(previousPalette);
QByteArray byteArray;
QBuffer buffer(&byteArray);
image.save(&buffer, "PNG");
QString imgBase64 = QString::fromLatin1(byteArray.toBase64().data());
html = html % "";
}
// }
}
}
}
}
}
}
}
oHtml = "" + html + "";
}
return err;
}
void SKGPrintPlugin::print(QPrinter* iPrinter)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if ((SKGMainPanel::getMainPanel() != nullptr) && (iPrinter != nullptr)) {
QString html;
SKGError err = getHtml(iPrinter, html);
// Print
m_toPrint.setFixedSize(QSize(iPrinter->width(), iPrinter->height()));
#ifdef SKG_WEBENGINE
// TODO(SMI): QWebEngine - doesn't work - bad quality printing
disconnect(&m_toPrint);
connect(&m_toPrint, &QWebEngineView::loadFinished, &m_toPrint, [ = ]() {
m_toPrint.page()->print(iPrinter, [](bool) {});
});
m_toPrint.setHtml(html, QUrl("file://"));
#else
m_toPrint.setHtml(html);
m_toPrint.print(iPrinter);
#endif
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Print successfully done.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Print failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
#include
diff --git a/plugins/generic/skg_properties/skgpropertiesplugin.cpp b/plugins/generic/skg_properties/skgpropertiesplugin.cpp
index 47eaff1e1..b9d6b3c0a 100644
--- a/plugins/generic/skg_properties/skgpropertiesplugin.cpp
+++ b/plugins/generic/skg_properties/skgpropertiesplugin.cpp
@@ -1,355 +1,355 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to manage properties on objects
*
* @author Stephane MANKOWSKI
*/
#include "skgpropertiesplugin.h"
#include
#include
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgpropertiesplugindockwidget.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGPropertiesPluginFactory, registerPlugin();)
SKGPropertiesPlugin::SKGPropertiesPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent),
m_currentDocument(nullptr), m_dockWidget(nullptr), m_dockContent(nullptr), m_addPropertyMenu(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Get list of bills
m_billsProcess.setStandardOutputFile(QDir::tempPath() % "/skg_bills.csv");
m_billsProcess.start(QStringLiteral("boobill bills -q -f csv -v"));
connect(&m_billsProcess, QOverload::of(&QProcess::finished), this, &SKGPropertiesPlugin::onBillsRetreived);
connect(&m_billsProcess, static_cast(&QProcess::error), this, &SKGPropertiesPlugin::onBillsRetreived);
}
SKGPropertiesPlugin::~SKGPropertiesPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
m_dockWidget = nullptr;
m_dockContent = nullptr;
m_addPropertyMenu = nullptr;
if (m_billsProcess.state() == QProcess::Running) {
m_billsProcess.kill();
}
}
void SKGPropertiesPlugin::onBillsRetreived()
{
QFile file(QDir::tempPath() % "/skg_bills.csv");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
stream.readLine(); // To avoid header id;date;format;label;idparent;price;currency;deadline;startdate;finishdate
while (!stream.atEnd()) {
// Read line
QString line = stream.readLine().trimmed();
m_bills.push_back(line);
}
// close file
file.close();
}
file.remove();
}
bool SKGPropertiesPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_properties"), title());
setXMLFile(QStringLiteral("skg_properties.rc"));
m_dockContent = new SKGPropertiesPluginDockWidget(SKGMainPanel::getMainPanel(), m_currentDocument);
if (m_dockContent != nullptr) {
connect(m_dockContent, &SKGPropertiesPluginDockWidget::selectionChanged, SKGMainPanel::getMainPanel(), &SKGMainPanel::refresh);
m_dockWidget = new QDockWidget(SKGMainPanel::getMainPanel());
if (m_dockWidget != nullptr) {
m_dockWidget->setObjectName(QStringLiteral("skg_properties_docwidget"));
m_dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
m_dockWidget->setWindowTitle(title());
m_dockWidget->setWidget(m_dockContent);
// add action to control hide / display of Bookmarks
QAction* toggle = m_dockWidget->toggleViewAction();
QAction* panelAction = actionCollection()->addAction(QStringLiteral("view_properties"));
registerGlobalAction(QStringLiteral("view_properties"), panelAction);
panelAction->setCheckable(true);
panelAction->setChecked(toggle->isChecked());
panelAction->setText(toggle->text());
actionCollection()->setDefaultShortcut(panelAction, Qt::SHIFT + Qt::Key_F12);
connect(panelAction, &QAction::triggered, toggle, &QAction::trigger);
connect(toggle, &QAction::toggled, panelAction, &QAction::setChecked);
}
}
// Menu
auto actAddProperty = new KToolBarPopupAction(SKGServices::fromTheme(icon()), i18nc("Allows user to add a user defined property on an object", "Add property"), this);
m_addPropertyMenu = actAddProperty->menu();
connect(m_addPropertyMenu, &QMenu::aboutToShow, this, &SKGPropertiesPlugin::onShowAddPropertyMenu);
actAddProperty->setStickyMenu(false);
actAddProperty->setDelayed(false);
registerGlobalAction(QStringLiteral("add_property"), actAddProperty, QStringList() << QStringLiteral("query:type='table' AND name NOT LIKE 'doctransaction%'"), 1, -1, 450);
return true;
}
void SKGPropertiesPlugin::onAddProperty()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
// Scope for the transaction
auto* act = qobject_cast(sender());
if ((act != nullptr) && (m_currentDocument != nullptr)) {
// Get parameters
QStringList list = act->data().toStringList();
const QString& name = list.at(0);
const QString& value = list.at(1);
// Create properties
IFOK(err) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Create a user defined property", "Property creation"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
err = selection.at(i).setProperty(name, value);
IFOKDO(err, m_currentDocument->stepForward(i + 1))
}
}
}
// status bar
IFOK(err) {
err = SKGError(0, i18nc("The user defined property was successfully created", "Property created"));
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGPropertiesPlugin::onDownloadAndAddBills()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
// Scope for the transaction
auto* act = qobject_cast(sender());
if ((act != nullptr) && (m_currentDocument != nullptr)) {
// Get parameters
QStringList list = act->data().toStringList();
const QString& id = list.at(0);
QString fileName = QDir::tempPath() % '/' % list.at(3) % '.' % list.at(2);
// Create properties
IFOK(err) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Create a user defined property", "Property creation"), err, 2 * nb);
for (int i = 0; !err && i < nb; ++i) {
// Download the files
QFile::remove(fileName);
QString cmd = "boobill download " % id % " \"" % fileName % '"';
QProcess p;
p.start(cmd);
if (!p.waitForFinished(60000) || p.exitCode() != 0) {
err.setReturnCode(ERR_FAIL).setMessage(i18nc("Error message", "The following command line failed with code %2:\n'%1'", cmd, p.exitCode()));
} else {
IFOKDO(err, m_currentDocument->stepForward(2 * i))
IFOKDO(err, selection.at(i).setProperty(i18nc("Noun", "Bill"), id, fileName))
QStringList importedBills = SKGServices::splitCSVLine(m_currentDocument->getParameter(QStringLiteral("SKG_IMPORTED_BILLS")));
importedBills.push_back(id);
IFOKDO(err, m_currentDocument->setParameter(QStringLiteral("SKG_IMPORTED_BILLS"), SKGServices::stringsToCsv(importedBills)))
IFOKDO(err, m_currentDocument->stepForward(2 * i + 1))
QFile::remove(fileName);
}
}
}
}
// status bar
IFOK(err) {
err = SKGError(0, i18nc("The user defined property was successfully created", "Property created"));
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGPropertiesPlugin::onShowAddPropertyMenu()
{
if ((m_addPropertyMenu != nullptr) && (m_currentDocument != nullptr)) {
m_addPropertyMenu->clear();
// Get selection
SKGObjectBase::SKGListSKGObjectBase sels = SKGMainPanel::getMainPanel()->getSelectedObjects();
if (!sels.isEmpty()) {
// Get the table of the selection
QString table = sels.at(0).getRealTable();
// Get list of more used properties for this table
SKGStringListList listTmp;
m_currentDocument->executeSelectSqliteOrder(
"SELECT t_name, t_value FROM (SELECT t_name, t_value, COUNT(1) AS nb FROM parameters WHERE (t_uuid_parent like '%-" % table % "' OR t_uuid_parent like '%-sub" % table % "') AND t_name NOT LIKE 'SKG_%' AND b_blob IS NULL GROUP BY t_name, t_value) ORDER BY nb DESC LIMIT 7",
listTmp);
// Create actions
int nb = listTmp.count();
QIcon iconp = SKGServices::fromTheme(icon());
if (nb > 1) {
for (int i = 1; i < nb; ++i) {
// Should the string below be translated ??? It contains no word...
QAction* act = m_addPropertyMenu->addAction(iconp, i18nc("Add a property (attribute=value)", "Add %1=%2", listTmp.at(i).at(0), listTmp.at(i).at(1)));
if (act != nullptr) {
act->setData(listTmp.at(i));
connect(act, &QAction::triggered, this, &SKGPropertiesPlugin::onAddProperty);
}
}
} else {
QAction* act = m_addPropertyMenu->addAction(iconp, i18nc("Help", "No property found. You must create a property from the dock first."));
act->setEnabled(false);
}
// Check if the sub process is still running
if (m_billsProcess.state() == QProcess::Running) {
// Create separator
{
QAction* act = m_addPropertyMenu->addAction(QLatin1String(""));
act->setSeparator(true);
}
// Add download on going
QAction* act = m_addPropertyMenu->addAction(i18nc("Message", "Download list of available bills on going..."));
if (act != nullptr) {
act->setEnabled(false);
}
} else {
// Check if some bills can be downloaded
int nb2 = m_bills.count();
if (nb2 != 0) {
// Create separator
{
QAction* act = m_addPropertyMenu->addAction(QLatin1String(""));
act->setSeparator(true);
}
// Create action
QStringList importedBills = SKGServices::splitCSVLine(m_currentDocument->getParameter(QStringLiteral("SKG_IMPORTED_BILLS")));
QMenu* menuMore = nullptr;
QIcon icond = SKGServices::fromTheme(icon(), QStringList() << QStringLiteral("download"));
QSet backendDone;
for (int j = 1; j < nb2; ++j) {
// id;date;format;label;idparent;price;currency;deadline;startdate;finishdate
QStringList fields = SKGServices::splitCSVLine(m_bills.at(j));
if (fields.count() > 3 && !importedBills.contains(fields.at(0))) {
QStringList ids = SKGServices::splitCSVLine(fields.at(0), '@');
if (ids.count() == 2) {
const QString& backend = ids.at(1);
// Selection of the menu where the item must be added
QMenu* menu;
if (!backendDone.contains(backend)) {
// This item must be added in root menu
menu = m_addPropertyMenu;
backendDone.insert(backend);
} else {
// This item must be added in "More..." menu
if (menuMore == nullptr) {
menuMore = new QMenu(i18nc("Noun", "More..."), m_addPropertyMenu);
}
menu = menuMore;
}
// Should the string below be translated ??? It contains no word...
QAction* act = menu->addAction(icond, i18nc("Add a property (attribute=value)", "Download and add %1 (%2)", fields[3] % '.' % fields[2], fields[0]));
if (act != nullptr) {
act->setToolTip(fields[0]);
act->setData(fields);
connect(act, &QAction::triggered, this, &SKGPropertiesPlugin::onDownloadAndAddBills);
}
}
}
}
// Add "More..." menu
if (menuMore != nullptr) {
m_addPropertyMenu->addMenu(menuMore);
}
}
}
}
}
}
void SKGPropertiesPlugin::refresh()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (m_dockContent != nullptr) {
m_dockContent->refresh();
}
}
QDockWidget* SKGPropertiesPlugin::getDockWidget()
{
return m_dockWidget;
}
QString SKGPropertiesPlugin::title() const
{
return i18nc("Noun, an item's properties", "Properties");
}
QString SKGPropertiesPlugin::icon() const
{
return QStringLiteral("tag");
}
int SKGPropertiesPlugin::getOrder() const
{
return 6;
}
QStringList SKGPropertiesPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tip", "... you can manage properties on all objects.
"));
output.push_back(i18nc("Description of a tip", "... you can add files or Internet links as property.
"));
output.push_back(i18nc("Description of a tip", "... you can automatically download and add bills as properties by using %1.
", "weboob"));
return output;
}
#include
diff --git a/plugins/generic/skg_properties/skgpropertiesplugindockwidget.cpp b/plugins/generic/skg_properties/skgpropertiesplugindockwidget.cpp
index 7fcee04a3..f5e9e1baa 100644
--- a/plugins/generic/skg_properties/skgpropertiesplugindockwidget.cpp
+++ b/plugins/generic/skg_properties/skgpropertiesplugindockwidget.cpp
@@ -1,386 +1,386 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to manage properties on objects.
*
* @author Stephane MANKOWSKI
*/
#include "skgpropertiesplugindockwidget.h"
#include
#include
#include
#include
#include
#include "skgdocument.h"
#include "skgmainpanel.h"
#include "skgnamedobject.h"
#include "skgobjectmodelbase.h"
#include "skgpropertyobject.h"
#include "skgservices.h"
#include "skgsortfilterproxymodel.h"
#include "skgtraces.h"
#include "skgtransactionmng.h"
SKGPropertiesPluginDockWidget::SKGPropertiesPluginDockWidget(QWidget* iParent, SKGDocument* iDocument)
: SKGWidget(iParent, iDocument)
{
SKGTRACEINFUNC(1);
if (iDocument == nullptr) {
return;
}
ui.setupUi(this);
ui.kPicture->hide();
ui.kAdd->setMaximumWidth(ui.kAdd->height());
ui.kRemove->setMaximumWidth(ui.kRemove->height());
ui.kSelectFile->setMaximumWidth(ui.kSelectFile->height());
ui.kAdd->setIcon(SKGServices::fromTheme(QStringLiteral("list-add")));
ui.kRename->setIcon(SKGServices::fromTheme(QStringLiteral("dialog-ok")));
ui.kRemove->setIcon(SKGServices::fromTheme(QStringLiteral("list-remove")));
ui.kSelectFile->setIcon(SKGServices::fromTheme(QStringLiteral("document-open")));
ui.kOpenBtn->setIcon(SKGServices::fromTheme(QStringLiteral("quickopen")));
ui.kAttribute->lineEdit()->setPlaceholderText(i18n("Name"));
ui.kValue->lineEdit()->setPlaceholderText(i18n("Value"));
ui.kForCmb->addItem(i18n("Selection"));
ui.kForCmb->addItem(i18n("All"));
// Add model
auto modelview = new SKGObjectModelBase(getDocument(), QStringLiteral("parameters"), QStringLiteral("1=1 ORDER BY t_uuid_parent, t_name"), this, QLatin1String(""), false);
auto modelproxy = new SKGSortFilterProxyModel(this);
modelproxy->setSourceModel(modelview);
ui.kView->setModel(modelproxy);
connect(ui.kFilterEdit, &QLineEdit::textChanged, this, [ = ](const QString & itext) {
modelproxy->setFilterKeyColumn(-1);
modelproxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
modelproxy->setFilterFixedString(itext);
});
auto actOpenPropertyFileAction = new QAction(QStringLiteral("internal action to open property file"), this);
connect(actOpenPropertyFileAction, &QAction::triggered, this, &SKGPropertiesPluginDockWidget::onOpenPropertyFileByUrl);
SKGMainPanel::getMainPanel()->registerGlobalAction(QStringLiteral("open_property_file"), actOpenPropertyFileAction);
ui.kView->setDefaultSaveParameters(getDocument(), QStringLiteral("SKG_DEFAULT_PROPERTIES"));
connect(modelview, &SKGObjectModelBase::beforeReset, ui.kView, &SKGTreeView::saveSelection);
connect(modelview, &SKGObjectModelBase::afterReset, ui.kView, &SKGTreeView::resetSelection);
connect(ui.kView, &SKGTableView::selectionChangedDelayed, this, &SKGPropertiesPluginDockWidget::onSelectionChanged);
connect(ui.kForCmb, static_cast(&SKGComboBox::currentTextChanged), this, &SKGPropertiesPluginDockWidget::refresh);
connect(ui.kAdd, &QPushButton::clicked, this, &SKGPropertiesPluginDockWidget::onAddProperty);
connect(ui.kRemove, &QPushButton::clicked, this, &SKGPropertiesPluginDockWidget::onRemoveProperty);
connect(ui.kSelectFile, &QPushButton::clicked, this, &SKGPropertiesPluginDockWidget::onSelectFile);
connect(ui.kOpenBtn, &QPushButton::clicked, this, &SKGPropertiesPluginDockWidget::onOpenFile);
connect(ui.kView, &SKGTableView::clickEmptyArea, this, &SKGPropertiesPluginDockWidget::cleanEditor);
connect(ui.kRename, &QPushButton::clicked, this, &SKGPropertiesPluginDockWidget::onRenameProperty);
ui.kView->setTextResizable(false);
}
SKGPropertiesPluginDockWidget::~SKGPropertiesPluginDockWidget()
{
SKGTRACEINFUNC(1);
}
void SKGPropertiesPluginDockWidget::refresh()
{
SKGTRACEINFUNC(1);
// Change filter
auto* proxyModel = qobject_cast(ui.kView->model());
auto* model = qobject_cast(proxyModel->sourceModel());
if (model != nullptr) {
QString filter;
if (ui.kForCmb->currentIndex() == 1) {
filter = QStringLiteral("t_uuid_parent!='document' AND t_name NOT LIKE 'SKG_%'");
ui.kAdd->setEnabled(false);
ui.kSelectFile->setEnabled(false);
ui.kRemove->setEnabled(false);
ui.kAttribute->setEnabled(false);
ui.kValue->setEnabled(false);
} else if (ui.kForCmb->currentIndex() == 0) {
filter = QStringLiteral("t_uuid_parent IN (");
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
if (nb != 0) {
ui.kAdd->setEnabled(true);
ui.kSelectFile->setEnabled(true);
ui.kRemove->setEnabled(false);
ui.kAttribute->setEnabled(true);
ui.kValue->setEnabled(true);
QString tableName;
for (int i = 0; i < nb; ++i) {
if (i > 0) {
filter += ',';
} else {
tableName = selection.at(i).getRealTable();
}
filter += '\'' % selection.at(i).getUniqueID() % '\'';
}
// Fill combo box
QString t = tableName;
if (t.startsWith(QLatin1String("sub"))) {
t = t.right(t.length() - 3);
}
SKGMainPanel::fillWithDistinctValue(QList() << ui.kAttribute, getDocument(), QStringLiteral("parameters"), QStringLiteral("t_name"), "(t_uuid_parent like '%-" % t % "' OR t_uuid_parent like '%-sub" % t % "') AND t_name NOT LIKE 'SKG_%'");
SKGMainPanel::fillWithDistinctValue(QList() << ui.kValue, getDocument(), QStringLiteral("parameters"), QStringLiteral("t_value"), "(t_uuid_parent like '%-" % t % "' OR t_uuid_parent like '%-sub" % t % "') AND t_name NOT LIKE 'SKG_%'");
} else {
filter += QStringLiteral("'XXX'"); // Always false
ui.kAdd->setEnabled(false);
ui.kSelectFile->setEnabled(false);
ui.kRemove->setEnabled(false);
ui.kAttribute->setEnabled(false);
ui.kValue->setEnabled(false);
}
filter += QStringLiteral(") AND t_name NOT LIKE 'SKG_%'");
}
filter += QStringLiteral(" ORDER BY t_uuid_parent, t_name");
ui.kView->saveSelection();
model->setFilter(filter);
model->refresh();
ui.kView->resetSelection();
}
ui.kView->setState(QLatin1String(""));
if (ui.kView->isAutoResized()) {
ui.kView->resizeColumnsToContentsDelayed();
}
onSelectionChanged();
}
void SKGPropertiesPluginDockWidget::onSelectionChanged()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
int nbSelected = getNbSelectedObjects();
ui.kPicture->hide();
ui.kOpenBtn->hide();
ui.kRemove->setEnabled(nbSelected > 0);
if (nbSelected > 0) {
SKGObjectBase::SKGListSKGObjectBase objs = getSelectedObjects();
SKGPropertyObject obj(objs.at(0));
ui.kAttribute->setText(obj.getAttribute(QStringLiteral("t_name")));
ui.kValue->setText(obj.getAttribute(QStringLiteral("t_value")));
if (nbSelected == 1) {
QUrl u = obj.getUrl(true);
ui.kOpenBtn->show();
if (u.scheme() == QStringLiteral("file")) {
ui.kPicture->show();
ui.kPicture->showPreview(u);
}
}
}
if (ui.kView->isAutoResized()) {
ui.kView->resizeColumnsToContentsDelayed();
}
}
void SKGPropertiesPluginDockWidget::openPropertyFile(const SKGPropertyObject& iProp)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
QUrl url = iProp.getUrl(true);
if (!url.scheme().isEmpty() && !QDesktopServices::openUrl(url)) {
QString fileNameToSave = SKGMainPanel::getSaveFileName(QStringLiteral("kfiledialog:///IMPEXP"), QLatin1String(""), SKGMainPanel::getMainPanel());
if (!fileNameToSave.isEmpty()) {
QFile(url.toLocalFile()).copy(fileNameToSave);
}
}
QApplication::restoreOverrideCursor();
}
void SKGPropertiesPluginDockWidget::onOpenPropertyFileByUrl()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
auto* act = qobject_cast(sender());
if (act != nullptr) {
SKGPropertyObject obj(getDocument(), SKGServices::stringToInt(act->property("id").toString()));
openPropertyFile(obj);
}
}
void SKGPropertiesPluginDockWidget::onOpenFile()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
int nbSelected = getNbSelectedObjects();
if (nbSelected == 1) {
SKGObjectBase::SKGListSKGObjectBase objs = getSelectedObjects();
SKGPropertyObject obj(objs.at(0));
openPropertyFile(obj);
}
if (ui.kView->isAutoResized()) {
ui.kView->resizeColumnsToContentsDelayed();
}
}
void SKGPropertiesPluginDockWidget::onAddProperty()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
QStringList listUUID;
// Scope for the transaction
{
// Get parameters
QString name = ui.kAttribute->text();
QString value = ui.kValue->text();
QVariant blob;
QFile file(value);
if (file.exists()) {
int mode = KMessageBox::questionYesNoCancel(this, i18nc("Question", "Do you want copy or link the file?"),
QString(),
KGuiItem(i18nc("Question", "Copy"), QStringLiteral("edit-copy")),
KGuiItem(i18nc("Question", "Link"), QStringLiteral("edit-link")));
if (mode == KMessageBox::Cancel) {
return;
}
if (mode == KMessageBox::Yes) {
// Value is a file name ==> blob
if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
err = SKGError(ERR_INVALIDARG, i18nc("Error message: could not open the requested file", "Open file '%1' failed", value));
} else {
QByteArray blob_bytes = file.readAll();
if (blob_bytes.isEmpty()) {
err = SKGError(ERR_INVALIDARG, i18nc("Error message: could not open the requested file", "Open file '%1' failed", value));
} else {
blob = blob_bytes;
value = QFileInfo(value).fileName();
}
// close file
file.close();
}
}
}
// Create properties
IFOK(err) {
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Create a user defined property", "Property creation"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
SKGPropertyObject prop;
err = selection.at(i).setProperty(name, value, blob, &prop);
IFOK(err) {
listUUID.push_back(prop.getUniqueID());
err = getDocument()->stepForward(i + 1);
}
}
}
}
// status bar
IFOK(err) {
err = SKGError(0, i18nc("The user defined property was successfully created", "Property created"));
ui.kView->selectObjects(listUUID, true);
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGPropertiesPluginDockWidget::onRenameProperty()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGError err;
QStringList listUUID;
// Scope for the transaction
{
// Rename properties
IFOK(err) {
SKGObjectBase::SKGListSKGObjectBase selection = ui.kView->getSelectedObjects();
int nb = selection.count();
SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Create a user defined property", "Rename property"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
const SKGObjectBase& prop(selection.at(i));
IFOKDO(err, getDocument()->executeSqliteOrder("UPDATE parameters SET t_name='" % SKGServices::stringToSqlString(ui.kAttribute->text()) % "' WHERE id=" % SKGServices::intToString(prop.getID())))
IFOK(err) {
listUUID.push_back(prop.getUniqueID());
err = getDocument()->stepForward(i + 1);
}
}
}
}
// status bar
IFOK(err) {
err = SKGError(0, i18nc("The user property was successfully renamed", "Property renamed"));
ui.kView->selectObjects(listUUID, true);
}
SKGMainPanel::displayErrorMessage(err);
}
void SKGPropertiesPluginDockWidget::onSelectFile()
{
QString fileName = QFileDialog::getOpenFileName(this, i18nc("Open panel caption", "Select a file"));
ui.kValue->setText(fileName);
}
void SKGPropertiesPluginDockWidget::onRemoveProperty()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
{
SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();
int nb = selection.count();
SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Verb, delete an item", "Delete"), err, nb);
for (int i = 0; !err && i < nb; ++i) {
err = selection.at(i).remove();
IFOKDO(err, getDocument()->stepForward(i + 1))
}
}
// status bar
IFOKDO(err, SKGError(0, i18nc("The user defined property was successfully deleted", "Properties deleted.")))
else {
err.addError(ERR_FAIL, i18nc("Error message: Could not delete an item", "Delete failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
void SKGPropertiesPluginDockWidget::cleanEditor()
{
if (getNbSelectedObjects() == 0) {
ui.kAttribute->setText(QLatin1String(""));
ui.kValue->setText(QLatin1String(""));
}
}
QWidget* SKGPropertiesPluginDockWidget::mainWidget()
{
return ui.kView;
}
diff --git a/plugins/generic/skg_selectall/skgselectallplugin.cpp b/plugins/generic/skg_selectall/skgselectallplugin.cpp
index cdd090c2d..df36e3a79 100644
--- a/plugins/generic/skg_selectall/skgselectallplugin.cpp
+++ b/plugins/generic/skg_selectall/skgselectallplugin.cpp
@@ -1,158 +1,158 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to select all
*
* @author Stephane MANKOWSKI
*/
#include "skgselectallplugin.h"
#include
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgtreeview.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGSelectAllPluginFactory, registerPlugin();)
SKGSelectAllPlugin::SKGSelectAllPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent), m_currentDocument(nullptr), m_selectionMessage(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
connect(SKGMainPanel::getMainPanel(), &SKGMainPanel::selectionChanged, this, &SKGSelectAllPlugin::onSelectionChanged);
}
SKGSelectAllPlugin::~SKGSelectAllPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
m_selectionMessage = nullptr;
}
bool SKGSelectAllPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_selectall"), title());
setXMLFile(QStringLiteral("skg_selectall.rc"));
// Menu
registerGlobalAction(QStringLiteral("edit_select_all"), actionCollection()->addAction(KStandardAction::SelectAll, QStringLiteral("edit_select_all"), this, SLOT(onSelectAll())), QStringList(), 0);
return true;
}
QString SKGSelectAllPlugin::title() const
{
return i18nc("Select all objects in a list", "Select all");
}
QString SKGSelectAllPlugin::icon() const
{
return QStringLiteral("edit-select-all");
}
QString SKGSelectAllPlugin::toolTip() const
{
return i18nc("Select all objects in a list", "Select all");
}
int SKGSelectAllPlugin::getOrder() const
{
return 6;
}
QStringList SKGSelectAllPlugin::tips() const
{
QStringList output;
return output;
}
void SKGSelectAllPlugin::onSelectionChanged()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (SKGMainPanel::getMainPanel() != nullptr) {
if (m_selectionMessage == nullptr) {
// Add statusbar
m_selectionMessage = new QLabel(SKGMainPanel::getMainPanel());
SKGMainPanel::getMainPanel()->statusBar()->insertPermanentWidget(1, m_selectionMessage);
}
SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
int nb = selection.count();
if (nb != 0) {
double sum = 0.0;
double max = -std::numeric_limits::max();
double min = std::numeric_limits::max();
int count = 0;
for (int i = 0; i < nb; ++i) {
const SKGObjectBase& obj(selection.at(i));
QString val = obj.getAttribute(QStringLiteral("f_REALCURRENTAMOUNT"));
if (val.isEmpty()) {
val = obj.getAttribute(QStringLiteral("f_CURRENTAMOUNT"));
}
if (!val.isEmpty()) {
double vald = SKGServices::stringToDouble(val);
sum += vald;
max = qMax(max, vald);
min = qMin(min, vald);
count++;
}
}
if (count > 1) {
m_selectionMessage->setText(i18n("Selection: %1 lines for %2 (min: %3, average: %4, max: %5)",
nb,
m_currentDocument->formatPrimaryMoney(sum),
m_currentDocument->formatPrimaryMoney(min),
m_currentDocument->formatPrimaryMoney(sum / count),
m_currentDocument->formatPrimaryMoney(max)));
} else if (count > 0) {
m_selectionMessage->setText(i18n("Selection: %1 line for %2", nb, m_currentDocument->formatPrimaryMoney(sum)));
} else {
m_selectionMessage->setText(i18np("Selection: %1 line", "Selection: %1 lines", nb));
}
} else {
m_selectionMessage->clear();
}
}
}
void SKGSelectAllPlugin::onSelectAll()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (SKGMainPanel::getMainPanel() != nullptr) {
SKGTabPage* page = SKGMainPanel::getMainPanel()->currentPage();
if (page != nullptr) {
auto* view = qobject_cast(page->mainWidget());
if (view != nullptr) {
view->selectAll();
}
}
}
}
#include
diff --git a/plugins/generic/skg_statistic/skgstatisticplugin.cpp b/plugins/generic/skg_statistic/skgstatisticplugin.cpp
index e5c352f24..7d8c6178c 100644
--- a/plugins/generic/skg_statistic/skgstatisticplugin.cpp
+++ b/plugins/generic/skg_statistic/skgstatisticplugin.cpp
@@ -1,264 +1,264 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* A plugin to generate statistic
*
* @author Stephane MANKOWSKI
*/
#include "skgstatisticplugin.h"
#ifdef HAVE_UNAME
# include
#endif
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "skgmainpanel.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGStatisticPluginFactory, registerPlugin();)
SKGStatisticPlugin::SKGStatisticPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent), m_currentDocument(nullptr)
{
Q_UNUSED(iWidget);
m_timeInit = QDateTime::currentDateTime();
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
connect(SKGMainPanel::getMainPanel(), &SKGMainPanel::currentPageChanged, this, &SKGStatisticPlugin::pageChanged);
connect(SKGMainPanel::getMainPanel(), &SKGMainPanel::pageOpened, this, &SKGStatisticPlugin::pageOpened);
}
SKGStatisticPlugin::~SKGStatisticPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Set duration
m_stats[QStringLiteral("avg.exec_time_sec")] = (m_stats.value(QStringLiteral("avg.exec_time_sec")).toDouble() * (m_stats.value(QStringLiteral("nb_launch")).toInt() - 1) + m_timeInit.secsTo(QDateTime::currentDateTime())) / m_stats.value(QStringLiteral("nb_launch")).toInt();
// Write stat file
writeStats();
m_currentDocument = nullptr;
}
bool SKGStatisticPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_statistic"), title());
setXMLFile(QStringLiteral("skg_statistic.rc"));
return true;
}
void SKGStatisticPlugin::refresh()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (m_currentDocument != nullptr) {
if (m_currentDocument->getMainDatabase() != nullptr) {
static bool initialisationDone = false;
if (!initialisationDone) {
// Connect actions
QMap > actions = SKGMainPanel::getMainPanel()->getGlobalActions();
QStringList keys = actions.keys();
for (const auto& k : keys) {
QPointer act = actions[k];
connect(act.data(), &QAction::triggered, this, &SKGStatisticPlugin::triggerAction);
}
initialisationDone = true;
}
QString doc_id = m_currentDocument->getUniqueIdentifier();
if (m_docUniqueIdentifier != doc_id) {
m_docUniqueIdentifier = doc_id;
// Initialize
QString appname = KAboutData::applicationData().componentName();
QDir::home().mkdir("." % appname);
QString docUUID = QString(QCryptographicHash::hash(m_currentDocument->getCurrentFileName().toLatin1(), QCryptographicHash::Md5).toHex());
m_file = QDir::homePath() % "/." % appname % "/" % docUUID % ".stats.txt";
// Read previous stat file
readStats();
// Initial values
if (!m_stats.contains(QStringLiteral("init.date"))) {
m_stats[QStringLiteral("init.date")] = QDate::currentDate();
m_stats[QStringLiteral("init.qt_version")] = qVersion();
m_stats[QStringLiteral("init.app_name")] = appname;
m_stats[QStringLiteral("init.app_version")] = KAboutData::applicationData().version();
}
m_stats[QStringLiteral("nb_launch")] = m_stats.value(QStringLiteral("nb_launch")).toInt() + 1;
// Current values
m_stats[QStringLiteral("current.date")] = QDate::currentDate();
m_stats[QStringLiteral("current.qt_version")] = qVersion();
m_stats[QStringLiteral("current.app_version")] = KAboutData::applicationData().version();
m_stats[QStringLiteral("current.language")] = QLocale::languageToString(QLocale().language());
m_stats[QStringLiteral("current.country")] = QLocale::countryToString(QLocale().country());
// OS
#ifdef Q_OS_WIN32
QString os = QStringLiteral("Windows");
#elif defined(Q_OS_FREEBSD)
QString os = QStringLiteral("FreeBSD");
#elif defined(Q_OS_NETBSD)
QString os = QStringLiteral("NetBSD");
#elif defined(Q_OS_OPENBSD)
QString os = QStringLiteral("OpenBSD");
#elif defined(Q_OS_LINUX)
QString os = QStringLiteral("Linux");
#elif defined(Q_OS_MAC)
QString os = QStringLiteral("Mac OS");
#else
QString os = QStringLiteral("Unknown");
#endif
m_stats[QStringLiteral("current.os")] = os;
QRect scr = QGuiApplication::primaryScreen()->geometry();
m_stats[QStringLiteral("current.screen")] = QString(SKGServices::intToString(scr.width()) % 'x' % SKGServices::intToString(scr.height()));
#ifdef HAVE_UNAME
struct utsname buf {};
if (uname(&buf) != -1) {
m_stats[QStringLiteral("current.os.machine")] = QString::fromLocal8Bit(buf.machine);
m_stats[QStringLiteral("current.os.version")] = QString::fromLocal8Bit(buf.version);
}
#endif
// Nb calls
QMap > actions = SKGMainPanel::getMainPanel()->getGlobalActions();
QStringList keys = actions.keys();
for (const auto& k : qAsConst(keys)) {
QPointer act = actions[k];
if (act != nullptr) {
QString id = "nb_call." % act->objectName();
if (!m_stats.contains(id)) {
m_stats[id] = 0;
}
}
}
m_stats[QStringLiteral("document.uuid")] = docUUID;
// Set tables sizes
QStringList tables;
m_currentDocument->getTablesList(tables);
for (const auto& t : qAsConst(tables)) {
QString r;
m_currentDocument->executeSingleSelectSqliteOrder("SELECT COUNT(1) FROM " % t, r);
m_stats["count." % t] = SKGServices::stringToInt(r);
}
}
}
}
}
void SKGStatisticPlugin::readStats()
{
m_stats.clear();
// Read file
QFile data(m_file);
if (data.open(QFile::ReadOnly)) {
// Parse json
m_stats = QJsonDocument::fromJson(data.readAll()).toVariant().toMap();
data.close();
}
}
void SKGStatisticPlugin::writeStats()
{
// Write it in file
QFile data(m_file);
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
// serialize json
QJsonDocument serializer = QJsonDocument::fromVariant(m_stats);
QByteArray doc = serializer.toJson(QJsonDocument::Indented);
data.write(doc);
data.close();
}
}
void SKGStatisticPlugin::triggerAction()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
auto* act = qobject_cast< QAction* >(sender());
if (act != nullptr) {
QString id = "nb_call." % act->objectName();
SKGTRACEL(10) << "SKGStatisticPlugin::triggerAction " << id << "++" << endl;
m_stats[id] = m_stats[id].toInt() + 1;
}
}
void SKGStatisticPlugin::pageChanged()
{
SKGTabPage::SKGPageHistoryItem currentPage = SKGMainPanel::getMainPanel()->currentPageHistoryItem();
if (!currentPage.plugin.isEmpty()) {
QString id = "nb_activated_" % QString(currentPage.bookmarkID.isEmpty() ? QStringLiteral("page") : QStringLiteral("bookmark")) % "." % currentPage.plugin;
m_stats[id] = m_stats[id].toInt() + 1;
}
}
void SKGStatisticPlugin::pageOpened()
{
SKGTabPage::SKGPageHistoryItem currentPage = SKGMainPanel::getMainPanel()->currentPageHistoryItem();
if (!currentPage.plugin.isEmpty()) {
QString id = "nb_opened_" % QString(currentPage.bookmarkID.isEmpty() ? QStringLiteral("page") : QStringLiteral("bookmark")) % "." % currentPage.plugin;
m_stats[id] = m_stats[id].toInt() + 1;
}
}
QString SKGStatisticPlugin::title() const
{
return i18nc("The title", "Statistic");
}
QString SKGStatisticPlugin::icon() const
{
return QStringLiteral("dialog-information");
}
QString SKGStatisticPlugin::toolTip() const
{
return title();
}
int SKGStatisticPlugin::getOrder() const
{
return 9999;
}
bool SKGStatisticPlugin::isInPagesChooser() const
{
return false;
}
#include
diff --git a/plugins/generic/skg_undoredo/skgundoredoplugin.cpp b/plugins/generic/skg_undoredo/skgundoredoplugin.cpp
index 2faceb37d..bad245cf7 100644
--- a/plugins/generic/skg_undoredo/skgundoredoplugin.cpp
+++ b/plugins/generic/skg_undoredo/skgundoredoplugin.cpp
@@ -1,402 +1,402 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is a plugin for undo and redo operation.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgundoredoplugin.h"
#include
#include
#include
#include
#include
#include
#include "skgerror.h"
#include "skgmainpanel.h"
#include "skgservices.h"
#include "skgtraces.h"
#include "skgundoredo_settings.h"
#include "skgundoredoplugindockwidget.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGUndoRedoPluginFactory, registerPlugin();)
SKGUndoRedoPlugin::SKGUndoRedoPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
SKGInterfacePlugin(iParent),
m_undoSaveAction(nullptr), m_undoAction(nullptr), m_redoAction(nullptr), m_undoMenu(nullptr), m_redoMenu(nullptr), m_currentDocument(nullptr), m_dockWidget(nullptr)
{
Q_UNUSED(iWidget);
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
}
SKGUndoRedoPlugin::~SKGUndoRedoPlugin()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = nullptr;
m_dockWidget = nullptr;
m_undoSaveAction = nullptr;
m_undoAction = nullptr;
m_redoAction = nullptr;
m_undoMenu = nullptr;
m_redoMenu = nullptr;
}
bool SKGUndoRedoPlugin::setupActions(SKGDocument* iDocument)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
m_currentDocument = iDocument;
setComponentName(QStringLiteral("skg_undoredo"), title());
setXMLFile(QStringLiteral("skg_undoredo.rc"));
// Menu
m_undoSaveAction = new QAction(SKGServices::fromTheme(QStringLiteral("document-revert")), i18nc("Verb, action to cancel previous action", "Revert document"), this);
connect(m_undoSaveAction, &QAction::triggered, this, &SKGUndoRedoPlugin::onUndoSave);
actionCollection()->setDefaultShortcut(m_undoSaveAction, Qt::CTRL + Qt::ALT + Qt::Key_Z);
registerGlobalAction(QStringLiteral("edit_undolastsave"), m_undoSaveAction);
m_undoAction = new KToolBarPopupAction(SKGServices::fromTheme(QStringLiteral("edit-undo")), i18nc("Verb, action to cancel previous action", "Undo"), this);
connect(m_undoAction, &KToolBarPopupAction::triggered, this, &SKGUndoRedoPlugin::onUndo);
actionCollection()->setDefaultShortcut(m_undoAction, Qt::CTRL + Qt::Key_Z);
m_undoAction->setPriority(QAction::LowPriority);
m_undoMenu = m_undoAction->menu();
connect(m_undoMenu, &QMenu::aboutToShow, this, &SKGUndoRedoPlugin::onShowUndoMenu);
m_undoAction->setStickyMenu(false);
m_undoAction->setData(1);
registerGlobalAction(QStringLiteral("edit_undo"), m_undoAction);
m_redoAction = new KToolBarPopupAction(SKGServices::fromTheme(QStringLiteral("edit-redo")), i18nc("Verb, action to redo previous cancelled action", "Redo"), this);
connect(m_redoAction, &KToolBarPopupAction::triggered, this, &SKGUndoRedoPlugin::onRedo);
actionCollection()->setDefaultShortcut(m_redoAction, Qt::CTRL + Qt::SHIFT + Qt::Key_Z);
m_redoAction->setPriority(QAction::LowPriority);
m_redoMenu = m_redoAction->menu();
connect(m_redoMenu, &QMenu::aboutToShow, this, &SKGUndoRedoPlugin::onShowRedoMenu);
m_redoAction->setStickyMenu(false);
m_redoAction->setData(1);
registerGlobalAction(QStringLiteral("edit_redo"), m_redoAction);
// Menu
auto act = new QAction(SKGServices::fromTheme(QStringLiteral("edit-clear-history")), i18nc("Verb, action to cancel previous action", "Clear history"), this);
connect(act, &QAction::triggered, this, &SKGUndoRedoPlugin::onClearHistory);
registerGlobalAction(QStringLiteral("edit_clear_history"), act);
// Dock creation
m_dockWidget = new QDockWidget(SKGMainPanel::getMainPanel());
m_dockWidget->setObjectName(QStringLiteral("skg_undoredo_docwidget"));
m_dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
m_dockWidget->setWindowTitle(title());
// add action to control hide / display of history
QAction* toggle = m_dockWidget->toggleViewAction();
QAction* panelAction = actionCollection()->addAction(QStringLiteral("view_transactions"));
registerGlobalAction(QStringLiteral("view_transactions"), panelAction);
panelAction->setCheckable(true);
panelAction->setChecked(toggle->isChecked());
panelAction->setText(toggle->text());
actionCollection()->setDefaultShortcut(panelAction, Qt::SHIFT + Qt::Key_F11);
connect(panelAction, &QAction::triggered, toggle, &QAction::trigger);
connect(toggle, &QAction::toggled, panelAction, &QAction::setChecked);
return true;
}
void SKGUndoRedoPlugin::refresh()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
if (m_dockWidget->widget() == nullptr) {
auto w = new SKGUndoRedoPluginDockWidget(SKGMainPanel::getMainPanel(), m_currentDocument);
connect(w, &SKGUndoRedoPluginDockWidget::selectionChanged, SKGMainPanel::getMainPanel(), &SKGMainPanel::refresh);
m_dockWidget->setWidget(w);
}
if (m_currentDocument != nullptr) {
bool undoPossible = (m_currentDocument->getNbTransaction(SKGDocument::UNDO) > 0);
if (m_undoSaveAction != nullptr) {
m_undoSaveAction->setEnabled(undoPossible);
}
if (m_undoAction != nullptr) {
m_undoAction->setEnabled(undoPossible);
}
if (m_redoAction != nullptr) {
m_redoAction->setEnabled(m_currentDocument->getNbTransaction(SKGDocument::REDO) > 0);
}
// Refresh undo redo
QString name;
m_currentDocument->getTransactionToProcess(SKGDocument::UNDO, &name);
QString message = i18nc("Verb", "Undo operation '%1'.", name);
if (name.isEmpty()) {
message = QLatin1String("");
}
if (m_undoAction != nullptr) {
m_undoAction->setStatusTip(message);
}
m_currentDocument->getTransactionToProcess(SKGDocument::REDO, &name);
message = i18nc("Verb", "Redo operation '%1'.", name);
if (name.isEmpty()) {
message = QLatin1String("");
}
if (m_redoAction != nullptr) {
m_redoAction->setStatusTip(message);
}
}
}
QWidget* SKGUndoRedoPlugin::getPreferenceWidget()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
// Read Setting
if (m_currentDocument != nullptr) {
KSharedConfigPtr config = KSharedConfig::openConfig();
KConfigGroup pref = config->group("skg_undoredo");
pref.writeEntry("maxNumberOfUndo", SKGServices::stringToInt(m_currentDocument->getParameter(QStringLiteral("SKG_UNDO_MAX_DEPTH"))));
pref.writeEntry("cleanHistoryOnSave", (m_currentDocument->getParameter(QStringLiteral("SKG_UNDO_CLEAN_AFTER_SAVE")) == QStringLiteral("Y")));
}
// Create widget
auto w = new QWidget();
ui.setupUi(w);
return w;
}
KConfigSkeleton* SKGUndoRedoPlugin::getPreferenceSkeleton()
{
return skgundoredo_settings::self();
}
SKGError SKGUndoRedoPlugin::savePreferences() const
{
SKGError err;
if (m_currentDocument != nullptr) {
// Read Setting
QString max = SKGServices::intToString(skgundoredo_settings::maxNumberOfUndo());
QString clean = (skgundoredo_settings::cleanHistoryOnSave() ? QStringLiteral("Y") : QStringLiteral("N"));
// Save setting in document
if (max != m_currentDocument->getParameter(QStringLiteral("SKG_UNDO_MAX_DEPTH"))) {
err = m_currentDocument->setParameter(QStringLiteral("SKG_UNDO_MAX_DEPTH"), max);
}
if (clean != m_currentDocument->getParameter(QStringLiteral("SKG_UNDO_CLEAN_AFTER_SAVE"))) {
err = m_currentDocument->setParameter(QStringLiteral("SKG_UNDO_CLEAN_AFTER_SAVE"), clean);
}
}
return err;
}
QString SKGUndoRedoPlugin::title() const
{
return i18nc("Noun", "History");
}
QString SKGUndoRedoPlugin::icon() const
{
return QStringLiteral("edit-undo");
}
QString SKGUndoRedoPlugin::toolTip() const
{
return i18nc("Noun", "History");
}
QStringList SKGUndoRedoPlugin::tips() const
{
QStringList output;
output.push_back(i18nc("Description of a tips", "... you can undo and redo your modifications.
"));
output.push_back(i18nc("Description of a tips", "... you can modify the maximum size of the undo/redo stack in the settings.
"));
return output;
}
int SKGUndoRedoPlugin::getOrder() const
{
return 4;
}
SKGAdviceList SKGUndoRedoPlugin::advice(const QStringList& iIgnoredAdvice)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
SKGAdviceList output;
if (!iIgnoredAdvice.contains(QStringLiteral("skgundoredoplugin_too_big"))) {
// Get nb transaction
int nbObject = m_currentDocument->getNbTransaction();
int priority = qMin(10, nbObject / 50);
if (priority > 0) {
SKGAdvice ad;
ad.setUUID(QStringLiteral("skgundoredoplugin_too_big"));
ad.setPriority(priority);
ad.setShortMessage(i18nc("Advice on making the best (short)", "History is too large"));
ad.setLongMessage(i18nc("Advice on making the best (long)", "You can improve performances by reducing your history size in settings."));
QStringList autoCorrections;
autoCorrections.push_back(QStringLiteral("skg://edit_clear_history"));
autoCorrections.push_back(i18nc("Advice on making the best (action)", "Open settings panel"));
ad.setAutoCorrections(autoCorrections);
output.push_back(ad);
}
}
return output;
}
SKGError SKGUndoRedoPlugin::executeAdviceCorrection(const QString& iAdviceIdentifier, int iSolution)
{
SKGError err;
if ((m_currentDocument != nullptr) && iAdviceIdentifier == QStringLiteral("skgundoredoplugin_too_big")) {
SKGMainPanel::getMainPanel()->optionsPreferences(this->objectName());
return err;
}
return SKGInterfacePlugin::executeAdviceCorrection(iAdviceIdentifier, iSolution);
}
void SKGUndoRedoPlugin::onClearHistory()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = m_currentDocument->removeAllTransactions();
QApplication::restoreOverrideCursor();
// status bar
IFOKDO(err, SKGError(0, i18nc("Message for successful user action", "Clear history successfully done.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Clear history failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGUndoRedoPlugin::onUndoSave()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
err = m_currentDocument->undoRedoTransaction(SKGDocument::UNDOLASTSAVE);
QApplication::restoreOverrideCursor();
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Undo successfully done.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Undo failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGUndoRedoPlugin::onUndo()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
int pos = qobject_cast(sender())->data().toInt();
for (int i = 1 ; !err && i <= pos; ++i) {
err = m_currentDocument->undoRedoTransaction(SKGDocument::UNDO);
}
QApplication::restoreOverrideCursor();
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Undo successfully done.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Undo failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGUndoRedoPlugin::onShowUndoMenu()
{
if ((m_undoMenu != nullptr) && (m_currentDocument != nullptr)) {
m_undoMenu->clear();
SKGStringListList listTmp;
m_currentDocument->executeSelectSqliteOrder(
QStringLiteral("SELECT t_name, t_savestep FROM doctransaction WHERE t_mode='U' ORDER BY d_date DESC LIMIT 7"),
listTmp);
int nb = listTmp.count();
for (int i = 1; i < nb; ++i) {
QAction* act = m_undoMenu->addAction(listTmp.at(i).at(1) == QStringLiteral("Y") ? SKGServices::fromTheme(QStringLiteral("document-revert")) : SKGServices::fromTheme(QStringLiteral("edit-undo")), listTmp.at(i).at(0));
if (act != nullptr) {
act->setData(i);
connect(act, &QAction::triggered, this, &SKGUndoRedoPlugin::onUndo);
}
}
}
}
void SKGUndoRedoPlugin::onRedo()
{
SKGError err;
- SKGTRACEINFUNCRC(10, err);
+ SKGTRACEINFUNCRC(10, err)
if ((m_currentDocument != nullptr) && (SKGMainPanel::getMainPanel() != nullptr)) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
int pos = qobject_cast(sender())->data().toInt();
for (int i = 1 ; !err && i <= pos; ++i) {
err = m_currentDocument->undoRedoTransaction(SKGDocument::REDO);
}
QApplication::restoreOverrideCursor();
// status bar
IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Redo successfully done.")))
else {
err.addError(ERR_FAIL, i18nc("Error message", "Redo failed"));
}
// Display error
SKGMainPanel::displayErrorMessage(err);
}
}
void SKGUndoRedoPlugin::onShowRedoMenu()
{
if ((m_redoMenu != nullptr) && (m_currentDocument != nullptr)) {
m_redoMenu->clear();
SKGStringListList listTmp;
m_currentDocument->executeSelectSqliteOrder(
QStringLiteral("SELECT t_name FROM doctransaction WHERE t_mode='R' ORDER BY d_date ASC LIMIT 7"),
listTmp);
int nb = listTmp.count();
for (int i = 1; i < nb; ++i) {
QAction* act = m_redoMenu->addAction(SKGServices::fromTheme(QStringLiteral("edit-redo")), listTmp.at(i).at(0));
if (act != nullptr) {
act->setData(i);
connect(act, &QAction::triggered, this, &SKGUndoRedoPlugin::onRedo);
}
}
}
}
QDockWidget* SKGUndoRedoPlugin::getDockWidget()
{
return m_dockWidget;
}
#include
diff --git a/plugins/import/skrooge_import_afb120/skgimportpluginafb120.cpp b/plugins/import/skrooge_import_afb120/skgimportpluginafb120.cpp
index 8ba0232bc..72180a6ca 100644
--- a/plugins/import/skrooge_import_afb120/skgimportpluginafb120.cpp
+++ b/plugins/import/skrooge_import_afb120/skgimportpluginafb120.cpp
@@ -1,213 +1,213 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is Skrooge plugin for AFB120 import / export.
* http://jerome.girod.perso.sfr.fr/finance/afb120x.php
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgimportpluginafb120.h"
#include
#include
#include
#include
#include "skgbankincludes.h"
#include "skgimportexportmanager.h"
#include "skgservices.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGImportPluginAFB120Factory, registerPlugin();)
SKGImportPluginAFB120::SKGImportPluginAFB120(QObject* iImporter, const QVariantList& iArg)
: SKGImportPlugin(iImporter)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
Q_UNUSED(iArg);
}
SKGImportPluginAFB120::~SKGImportPluginAFB120()
= default;
bool SKGImportPluginAFB120::isImportPossible()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
return (m_importer == nullptr ? true : m_importer->getFileNameExtension() == QStringLiteral("AFB120") || m_importer->getFileNameExtension() == QStringLiteral("CFO"));
}
double SKGImportPluginAFB120::toAmount(const QString& iAmount, int iNbDecimal)
{
QString amount = iAmount;
QChar lastChar = amount.right(1).at(0);
int codeAscii = lastChar.toLatin1();
int sign = (codeAscii > 79 && codeAscii != 123 ? -1 : 1);
if (codeAscii == 123 || codeAscii == 125) {
amount[amount.count() - 1] = '0';
} else {
bool ok = false;
amount[amount.count() - 1] = QChar(codeAscii + QChar('1').toLatin1() - QString(sign == -1 ? QStringLiteral("0x4A") : QStringLiteral("0x41")).toUInt(&ok, 16));
}
return static_cast(sign) * SKGServices::stringToDouble(amount) / qPow(10, iNbDecimal);
}
SKGError SKGImportPluginAFB120::importFile()
{
if (m_importer == nullptr) {
return SKGError(ERR_ABORT, i18nc("Error message", "Invalid parameters"));
}
SKGError err;
SKGTRACEINFUNCRC(2, err);
// Begin transaction
err = m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import %1 file", "AFB120"), 2);
IFOK(err) {
// Open file
IFOK(err) {
QFile file(m_importer->getLocalFileName());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
err.setReturnCode(ERR_INVALIDARG).setMessage(i18nc("Error message", "Open file '%1' failed", m_importer->getFileName().toDisplayString()));
} else {
// Read lines
QStringList lines;
{
QTextStream stream(&file);
if (!m_importer->getCodec().isEmpty()) {
stream.setCodec(m_importer->getCodec().toLatin1().constData());
}
while (!stream.atEnd()) {
// Read line
QString line = stream.readLine().trimmed();
if (!line.isEmpty()) {
lines.push_back(line);
}
}
}
// close file
file.close();
// Step 1 done
IFOKDO(err, m_importer->getDocument()->stepForward(1))
// Read lines
SKGAccountObject account;
SKGUnitObject unit;
QString bankName = QStringLiteral("AFB120");
QString inititalAmount;
int nb = lines.count();
IFOKDO(err, m_importer->getDocument()->beginTransaction("#INTERNAL#" % i18nc("Import step", "Import operations"), nb))
for (int i = 0; i < nb && !err; ++i) {
// Read line
const QString& line = lines.at(i);
if (!line.isEmpty()) {
if (line.startsWith(QLatin1String("01"))) {
// Previous balance
QString accountNumber = line.mid(22 - 1, 11);
inititalAmount = line.mid(91 - 1, 14);
SKGObjectBase::SKGListSKGObjectBase listAccount;
err = m_importer->getDocument()->getObjects(QStringLiteral("v_account"), "t_number='" % accountNumber % '\'', listAccount);
IFOK(err) {
if (listAccount.count() == 1) {
// Yes ! Only one account found
account = listAccount.at(0);
err = m_importer->getDocument()->sendMessage(i18nc("An information message", "Using account '%1' for import", account.getName()));
} else {
if (listAccount.count() > 1) {
err = m_importer->getDocument()->sendMessage(i18nc("An information message", "More than one possible account found."));
}
SKGBankObject bank(m_importer->getDocument());
IFOKDO(err, bank.setName(bankName))
IFOKDO(err, bank.setNumber(bankName))
if (!err && bank.load().isFailed()) {
err = bank.save();
}
IFOKDO(err, bank.addAccount(account))
IFOKDO(err, account.setName(accountNumber))
IFOKDO(err, account.setNumber(accountNumber))
IFOKDO(err, account.setType(SKGAccountObject::CURRENT))
if (!err && account.load().isFailed()) {
err = account.save();
}
IFOKDO(err, m_importer->getDocument()->sendMessage(i18nc("An information message", "Default account '%1' created for import", accountNumber)))
}
}
} else if (line.startsWith(QLatin1String("04"))) {
// Operation
QString unitCode = line.mid(17 - 1, 3);
QString nbDecimal = line.mid(20 - 1, 1);
// QString codeMode = line.mid(33 - 1, 2);
QString dateJJMMAA = line.mid(35 - 1, 6);
QString comment = line.mid(49 - 1, 31).trimmed();
QString amount = line.mid(91 - 1, 14);
// Initialize balance
if (unit.getID() == 0) {
err = SKGUnitObject::createCurrencyUnit(m_importer->getDocument(), unitCode, unit);
if (account.getNbOperation() > 1) {
IFOKDO(err, m_importer->getDocument()->sendMessage(i18nc("An information message", "The initial balance of '%1' has not been set because some operations are already existing", account.getName()), SKGDocument::Warning))
} else {
// Set initial balance
IFOKDO(err, account.setInitialBalance(toAmount(inititalAmount, SKGServices::stringToInt(nbDecimal)), unit))
IFOKDO(err, account.save())
IFOKDO(err, m_importer->getDocument()->sendMessage(i18nc("An information message", "The initial balance of '%1' has been set with AFB120 file content", account.getName())))
}
}
SKGOperationObject operation;
IFOKDO(err, account.addOperation(operation, true))
IFOKDO(err, operation.setDate(SKGServices::stringToTime(SKGServices::dateToSqlString(dateJJMMAA, QStringLiteral("DDMMYYYY"))).date()))
IFOKDO(err, operation.setUnit(unit))
IFOKDO(err, operation.setAttribute(QStringLiteral("t_imported"), QStringLiteral("T")))
IFOKDO(err, operation.setComment(comment))
QByteArray hash = QCryptographicHash::hash(line.toUtf8(), QCryptographicHash::Md5);
IFOKDO(err, operation.setImportID(QStringLiteral("AFB120-") % hash.toHex()))
IFOKDO(err, operation.save(false))
SKGSubOperationObject subop;
IFOKDO(err, operation.addSubOperation(subop))
IFOKDO(err, subop.setComment(comment))
IFOKDO(err, subop.setQuantity(toAmount(amount, SKGServices::stringToInt(nbDecimal))))
IFOKDO(err, subop.save(false, false))
}
}
IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
}
SKGENDTRANSACTION(m_importer->getDocument(), err);
// Step 2 done
IFOKDO(err, m_importer->getDocument()->stepForward(2))
}
}
}
SKGENDTRANSACTION(m_importer->getDocument(), err);
return err;
}
QString SKGImportPluginAFB120::getMimeTypeFilter() const
{
return "*.afb120 *.cfo|" % i18nc("A file format", "AFB120 file (cfomb)");
}
#include
diff --git a/plugins/import/skrooge_import_backend/skgimportpluginbackend.cpp b/plugins/import/skrooge_import_backend/skgimportpluginbackend.cpp
index 5d990af2b..ad644da0c 100644
--- a/plugins/import/skrooge_import_backend/skgimportpluginbackend.cpp
+++ b/plugins/import/skrooge_import_backend/skgimportpluginbackend.cpp
@@ -1,417 +1,417 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is Skrooge plugin for BACKEND import / export.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgimportpluginbackend.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "skgbankincludes.h"
#include "skgimportexportmanager.h"
#include "skgservices.h"
#include "skgtraces.h"
/**
* This plugin factory.
*/
K_PLUGIN_FACTORY(SKGImportPluginBackendFactory, registerPlugin();)
SKGImportPluginBackend::SKGImportPluginBackend(QObject* iImporter, const QVariantList& iArg)
: SKGImportPlugin(iImporter)
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
Q_UNUSED(iArg);
m_listBackends = KServiceTypeTrader::self()->query(QStringLiteral("Skrooge/Import/Backend"));
}
SKGImportPluginBackend::~SKGImportPluginBackend()
= default;
QExplicitlySharedDataPointer SKGImportPluginBackend::getService() const
{
for (const auto& service : m_listBackends) {
if (service->property(QStringLiteral("X-Krunner-ID"), QVariant::String).toString().toUpper() == m_importer->getFileNameExtension()) {
return service;
}
}
return QExplicitlySharedDataPointer(nullptr);
}
QString SKGImportPluginBackend::getParameter(const QString& iAttribute)
{
auto service = getService();
QString output = service->property(iAttribute, QVariant::String).toString();
QMap parameters = this->getImportParameters();
for (int i = 1; i <= 10; ++i) {
QString param = "parameter" + SKGServices::intToString(i);
if (output.contains(QStringLiteral("%") % param)) {
output = output.replace(QStringLiteral("%") % param, parameters.value(param));
}
}
return output;
}
bool SKGImportPluginBackend::isImportPossible()
{
- SKGTRACEINFUNC(10);
+ SKGTRACEINFUNC(10)
return (m_importer == nullptr ? true : getService().data() != nullptr);
}
struct download {
download(int iNbToDownload, QString iDate, QString iCmd, QString iPwd, QString iPath)
: m_nbToDownload(iNbToDownload), m_date(std::move(iDate)), m_cmd(std::move(iCmd)), m_pwd(std::move(iPwd)), m_path(std::move(iPath))
{
}
using result_type = QString;
QString operator()(const QString& iAccountId)
{
QString file = m_path % "/" % iAccountId % ".csv";
// Build cmd
QString cmd = m_cmd;
cmd = cmd.replace(QStringLiteral("%2"), SKGServices::intToString(m_nbToDownload)).replace(QStringLiteral("%1"), iAccountId).replace(QStringLiteral("%3"), m_pwd).replace(QStringLiteral("%4"), m_date);
// Execute
QProcess p;
cmd = SKGServices::getFullPathCommandLine(cmd);
SKGTRACEL(10) << "Execute: " << cmd << endl;
p.setStandardOutputFile(file);
int retry = 0;
do {
p.start(QStringLiteral("/bin/bash"), QStringList() << QStringLiteral("-c") << cmd);
if (p.waitForFinished(1000 * 60 * 2)) {
if (p.exitCode() == 0) {
return iAccountId;
}
SKGTRACE << i18nc("A warning message", "WARNING: The command %1 failed with code %2 (Retry %3)", cmd, p.exitCode(), retry + 1) << endl;
} else {
SKGTRACE << i18nc("A warning message", "WARNING: The command %1 failed due to a time out (Retry %2)", cmd, retry + 1) << endl;
p.terminate();
p.kill();
}
++retry;
} while (retry < 6);
QString errorMsg = i18nc("Error message", "The following command line failed with code %2:\n'%1'", cmd, p.exitCode());
SKGTRACE << errorMsg << endl;
return QStringLiteral("ERROR:") + errorMsg;
}
int m_nbToDownload;
QString m_date;
QString m_cmd;
QString m_pwd;
QString m_path;
};
SKGError SKGImportPluginBackend::importFile()
{
if (m_importer == nullptr) {
return SKGError(ERR_ABORT, i18nc("Error message", "Invalid parameters"));
}
SKGError err;
SKGTRACEINFUNCRC(2, err);
SKGBEGINPROGRESSTRANSACTION(*m_importer->getDocument(), i18nc("Noun, name of the user action", "Import with %1", "Backend"), err, 3);
QString bankendName = m_importer->getFileNameExtension().toLower();
// Get parameters
QMap parameters = this->getImportParameters();
QString pwd = parameters[QStringLiteral("password")];
// Get list of accounts
QStringList backendAccounts;
QMap backendAccountsBalance;
QMap backendAccountsName;
QString csvfile = m_tempDir.path() % "/skrooge_backend.csv";
QString cmd = getParameter(QStringLiteral("X-SKROOGE-getaccounts")).replace(QStringLiteral("%3"), pwd);
QProcess p;
cmd = SKGServices::getFullPathCommandLine(cmd);
SKGTRACEL(10) << "Execute: " << cmd << endl;
p.setStandardOutputFile(csvfile);
p.start(QStringLiteral("/bin/bash"), QStringList() << QStringLiteral("-c") << cmd);
if (!p.waitForFinished(1000 * 60 * 2) || p.exitCode() != 0) {
err.setReturnCode(ERR_FAIL).setMessage(i18nc("Error message", "The following command line failed with code %2:\n'%1'", cmd, p.exitCode()));
} else {
QFile file(csvfile);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
err.setReturnCode(ERR_INVALIDARG).setMessage(i18nc("Error message", "Open file '%1' failed", csvfile));
} else {
QRegExp reggetaccounts(getParameter(QStringLiteral("X-SKROOGE-getaccountid")));
QRegExp reggetaccountbalance(getParameter(QStringLiteral("X-SKROOGE-getaccountbalance")));
QRegExp reggetaccountname(getParameter(QStringLiteral("X-SKROOGE-getaccountname")));
QTextStream stream(&file);
stream.readLine(); // To avoid header
QStringList backendAccountsUniqueId;
while (!stream.atEnd()) {
// Read line
QString line = stream.readLine().trimmed();
SKGTRACEL(10) << "Read line: " << line << endl;
// Get account id
int pos = reggetaccounts.indexIn(line);
if (pos > -1) {
QString accountid = reggetaccounts.cap(1);
QString uniqueid = SKGServices::splitCSVLine(accountid, QLatin1Char('@')).at(0);
if (!backendAccounts.contains(accountid) && !backendAccountsUniqueId.contains(uniqueid)) {
backendAccounts.push_back(accountid);
backendAccountsUniqueId.push_back(uniqueid);
// Get account balance
pos = reggetaccountbalance.indexIn(line);
if (pos > -1) {
backendAccountsBalance[accountid] = reggetaccountbalance.cap(1);
} else {
backendAccountsBalance[accountid] = '0';
}
// Get account name
pos = reggetaccountname.indexIn(line);
if (pos > -1) {
backendAccountsName[accountid] = reggetaccountname.cap(1);
} else {
backendAccountsName[accountid] = QLatin1String("");
}
}
} else {
// This is an error
err.setReturnCode(ERR_FAIL).setMessage(line).addError(ERR_FAIL, i18nc("Error message", "Impossible to find the account id with the regular expression '%1' in line '%2'", getParameter(QStringLiteral("X-SKROOGE-getaccountid")), line));
break;
}
}
// close file
file.close();
file.remove();
}
}
// Download operations
IFOKDO(err, m_importer->getDocument()->stepForward(1, i18nc("Progress message", "Download operations")))
IFOK(err) {
if (backendAccounts.isEmpty()) {
err.setReturnCode(ERR_FAIL).setMessage(i18nc("Error message", "Your backend '%1' seems to be not well configure because no account has been found.", bankendName));
} else {
// Compute the begin date for download
QDate lastDownload = SKGServices::stringToTime(m_importer->getDocument()->getParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_DATE")).date();
QString lastList = m_importer->getDocument()->getParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_LIST");
QString currentList = backendAccounts.join(QStringLiteral(";"));
int nbToDownload = 0;
QString fromDate;
if (currentList != lastList || !lastDownload.isValid()) {
nbToDownload = 99999;
fromDate = QStringLiteral("2000-01-01");
} else {
nbToDownload = qMax(lastDownload.daysTo(QDate::currentDate()) * 10, qint64(20));
fromDate = SKGServices::dateToSqlString(lastDownload.addDays(-4));
}
// Download
QStringList listDownloadedId;
QString bulk = getParameter(QStringLiteral("X-SKROOGE-getbulk"));
QString cmddownload;
if (!bulk.isEmpty()) {
// mode bulk
SKGTRACEL(10) << "Mode getbulk" << endl;
QProcess pbulk;
QString cmd = bulk.replace(QStringLiteral("%1"), m_tempDir.path());
cmd = SKGServices::getFullPathCommandLine(cmd);
cmddownload = cmd;
SKGTRACEL(10) << "Execute: " << cmd << endl;
pbulk.start(QStringLiteral("/bin/bash"), QStringList() << QStringLiteral("-c") << cmd);
if (!pbulk.waitForFinished(1000 * 60 * 2) || pbulk.exitCode() != 0) {
err.setReturnCode(ERR_FAIL).setMessage(i18nc("Error message", "The following command line failed with code %2:\n'%1'", cmd, pbulk.exitCode()));
} else {
SKGTRACEL(10) << "Searching csv files " << endl;
QDirIterator it(m_tempDir.path(), QStringList() << QStringLiteral("*.csv"));
while (it.hasNext()) {
auto id = QFileInfo(it.next()).baseName();
listDownloadedId.push_back(id);
SKGTRACEL(10) << "Find id: " << id << endl;
}
}
} else {
// mode getoperations
SKGTRACEL(10) << "Mode getoperations" << endl;
cmddownload = getParameter(QStringLiteral("X-SKROOGE-getoperations"));
QFuture f = QtConcurrent::mapped(backendAccounts, download(nbToDownload, fromDate, cmddownload, pwd, m_tempDir.path()));
f.waitForFinished();
listDownloadedId = f.results();
}
listDownloadedId.removeAll(QLatin1String(""));
// Build list of errors
QStringList errors;
int nb = listDownloadedId.count();
errors.reserve(nb);
for (int i = nb - 1; i >= 0; --i) {
auto item = listDownloadedId.value(i);
if (item.startsWith(QLatin1String("ERROR:"))) {
listDownloadedId.removeAt(i);
errors.push_back(item.right(item.length() - 6));
}
}
// Check
IFOK(err) {
bool checkOK = true;
int nb = listDownloadedId.count();
if (errors.count() != 0) {
// Some accounts have not been downloaded
if (nb == 0) {
err = SKGError(ERR_FAIL, i18nc("Error message", "No accounts downloaded with the following command:\n%1\nCheck your backend installation.", cmddownload));
} else {
// Warning
m_importer->getDocument()->sendMessage(i18nc("Warning message", "Some accounts have not been downloaded. %1", errors.join(QStringLiteral(". "))), SKGDocument::Warning);
}
SKGTRACEL(10) << errors.count() << " accounts not imported => checkOK=false" << endl;
checkOK = false;
}
// import
IFOKDO(err, m_importer->getDocument()->stepForward(2, i18nc("Progress message", "Import")))
if (!err && (nb != 0)) {
// import
SKGBEGINPROGRESSTRANSACTION(*m_importer->getDocument(), "#INTERNAL#" % i18nc("Noun, name of the user action", "Import one account with %1", "Backend"), err, nb);
// Get all messages
SKGDocument::SKGMessageList messages;
IFOKDO(err, m_importer->getDocument()->getMessages(m_importer->getDocument()->getCurrentTransaction(), messages, true))
// Import all files
for (int i = 0; !err && i < nb; ++i) {
// Rename the imported name
QString file = m_tempDir.path() % "/" % listDownloadedId.at(i) % ".csv";
if (!listDownloadedId.at(i).contains(QStringLiteral("-")) && !backendAccountsName[listDownloadedId.at(i)].isEmpty()) {
QString newFileName = m_tempDir.path() % "/" % backendAccountsName[listDownloadedId.at(i)] % '-' % listDownloadedId.at(i) % ".csv";
if (QFile::rename(file, newFileName)) {
file = newFileName;
}
}
// Import
SKGImportExportManager imp1(m_importer->getDocument(), QUrl::fromLocalFile(file));
imp1.setAutomaticValidation(m_importer->automaticValidation());
imp1.setAutomaticApplyRules(m_importer->automaticApplyRules());
// This option is not used with backend import
imp1.setSinceLastImportDate(false);
imp1.setCodec(m_importer->getCodec());
QMap newParameters = imp1.getImportParameters();
newParameters[QStringLiteral("automatic_search_header")] = 'N';
newParameters[QStringLiteral("header_position")] = '1';
newParameters[QStringLiteral("automatic_search_columns")] = 'N';
newParameters[QStringLiteral("columns_positions")] = getParameter(QStringLiteral("X-SKROOGE-csvcolumns"));
newParameters[QStringLiteral("mode_csv_unit")] = 'N';
newParameters[QStringLiteral("mode_csv_rule")] = 'N';
newParameters[QStringLiteral("balance")] = backendAccountsBalance[listDownloadedId.at(i)];
newParameters[QStringLiteral("donotfinalize")] = 'Y';
imp1.setImportParameters(newParameters);
IFOKDO(err, imp1.importFile())
if (!backendAccountsBalance[listDownloadedId.at(i)].isEmpty()) {
SKGAccountObject act;
IFOKDO(err, imp1.getDefaultAccount(act));
m_importer->addAccountToCheck(act, SKGServices::stringToDouble(backendAccountsBalance[listDownloadedId.at(i)]));
}
IFOKDO(err, m_importer->getDocument()->stepForward(i + 1))
}
// Remove all temporary files
for (int i = 0; i < nb; ++i) {
QString file = m_tempDir.path() % "/" % listDownloadedId.at(i) % ".csv";
QFile::remove(file);
}
// Reset message
IFOKDO(err, m_importer->getDocument()->removeMessages(m_importer->getDocument()->getCurrentTransaction()))
int nbm = messages.count();
for (int j = 0; j < nbm; ++j) {
SKGDocument::SKGMessage msg = messages.at(j);
m_importer->getDocument()->sendMessage(msg.Text, msg.Type, msg.Action);
}
// Finalize import
IFOKDO(err, m_importer->finalizeImportation())
// Disable std finalisation
QMap parameters = m_importer->getImportParameters();
parameters[QStringLiteral("donotfinalize")] = 'Y';
m_importer->setImportParameters(parameters);
// Check balances of accounts
auto accountsToCheck = m_importer->getAccountsToCheck();
int nb = accountsToCheck.count();
for (int i = 0; !err && i < nb; ++i) {
// Get the account to check
auto act = accountsToCheck[i].first;
auto targetBalance = accountsToCheck[i].second;
auto soluces = act.getPossibleReconciliations(targetBalance, false);
if (soluces.isEmpty()) {
SKGTRACEL(10) << "Account " << listDownloadedId.at(i) << " not reconciliable => checkOK=false" << endl;
checkOK = false;
}
}
if (checkOK) {
// Last import is memorized only in case of 100% success
IFOKDO(err, m_importer->getDocument()->setParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_DATE", SKGServices::dateToSqlString(QDateTime::currentDateTime())))
IFOKDO(err, m_importer->getDocument()->setParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_LIST", currentList))
} else {
// Remove last import for next import
IFOKDO(err, m_importer->getDocument()->setParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_DATE", QLatin1String("")))
IFOKDO(err, m_importer->getDocument()->setParameter("SKG_LAST_" % bankendName.toUpper() % "_IMPORT_LIST", QLatin1String("")))
}
}
IFOKDO(err, m_importer->getDocument()->stepForward(3))
}
}
}
return err;
}
QString SKGImportPluginBackend::getMimeTypeFilter() const
{
return QLatin1String("");
}
#include
diff --git a/plugins/import/skrooge_import_csv/skgimportplugincsv.cpp b/plugins/import/skrooge_import_csv/skgimportplugincsv.cpp
index f3d9e6f70..ee4766ca3 100644
--- a/plugins/import/skrooge_import_csv/skgimportplugincsv.cpp
+++ b/plugins/import/skrooge_import_csv/skgimportplugincsv.cpp
@@ -1,1044 +1,1044 @@
/***************************************************************************
* Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see *
***************************************************************************/
/** @file
* This file is Skrooge plugin for CSV import / export.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgimportplugincsv.h"
#include
#include