From 991486a0429446df400bf86ba4a0583be57f2992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9gory=20Soutad=C3=A9?= Date: Thu, 25 Aug 2011 17:45:41 +0200 Subject: [PATCH] First pass --- Makefile | 25 +- src/controller/KissCount.cpp | 178 +- src/controller/KissCount.hpp | 95 +- src/main.cpp | 34 +- src/model/Account.hpp | 12 +- src/model/AccountAmount.hpp | 11 +- src/model/Category.hpp | 17 +- src/model/Database.cpp | 1566 ++++++++--------- src/model/Database.hpp | 138 +- src/model/Operation.cpp | 2 +- src/model/Operation.hpp | 19 +- src/model/User.cpp | 65 +- src/model/User.hpp | 31 +- src/model/export/ExportEngine.hpp | 14 +- src/model/export/XMLExportEngine.cpp | 4 +- src/model/import/ImportEngine.hpp | 32 +- src/model/import/XMLImportEngine.cpp | 4 +- src/view/AccountPanel.cpp | 1121 ------------ src/view/AccountPanel.hpp | 93 - src/view/ExportPanel.cpp | 155 -- src/view/ExportPanel.hpp | 63 - src/view/GenerateDialog.cpp | 238 --- src/view/GenerateDialog.hpp | 53 - src/view/ImportPanel.cpp | 458 ----- src/view/ImportPanel.hpp | 67 - src/view/KissPanel.hpp | 29 - src/view/PasswordDialog.cpp | 95 - src/view/PasswordDialog.hpp | 45 - src/view/PreferencesPanel.cpp | 863 --------- src/view/PreferencesPanel.hpp | 73 - src/view/SearchBanner.cpp | 220 --- src/view/SearchBanner.hpp | 61 - src/view/SearchPanel.cpp | 265 --- src/view/SearchPanel.hpp | 64 - src/view/StatsPanel.cpp | 416 ----- src/view/StatsPanel.hpp | 70 - src/view/UsersDialog.cpp | 138 -- src/view/UsersDialog.hpp | 50 - src/view/grid/CalendarEditor.cpp | 111 -- src/view/grid/CalendarEditor.hpp | 61 - src/view/grid/GridAccount.cpp | 1553 ---------------- src/view/grid/GridAccount.hpp | 102 -- src/view/grid/wxGridCellBitmapRenderer.cpp | 43 - src/view/grid/wxGridCellBitmapRenderer.hpp | 40 - src/view/grid/wxGridCellButtonEditor.cpp | 94 - src/view/grid/wxGridCellButtonEditor.hpp | 54 - src/view/grid/wxGridCellButtonRenderer.cpp | 96 - src/view/grid/wxGridCellButtonRenderer.hpp | 39 - src/view/grid/wxGridCellFastBoolEditor.hpp | 24 - src/view/grid/wxGridCellFormulaEditor.cpp | 93 - src/view/grid/wxGridCellFormulaEditor.hpp | 56 - src/view/grid/wxGridCellStarEditor.cpp | 53 - src/view/grid/wxGridCellStarEditor.hpp | 37 - src/view/grid/wxGridCellTabStringRenderer.cpp | 40 - src/view/grid/wxGridCellTabStringRenderer.hpp | 35 - src/view/grid/wxGridCellTreeButtonEditor.cpp | 76 - src/view/grid/wxGridCellTreeButtonEditor.hpp | 50 - .../grid/wxGridCellTreeButtonRenderer.cpp | 85 - .../grid/wxGridCellTreeButtonRenderer.hpp | 41 - src/view/grid/wxMyGrid.cpp | 48 - src/view/grid/wxMyGrid.hpp | 22 - src/view/view.hpp | 12 +- src/view/wxUI.cpp | 322 ++-- src/view/wxUI.hpp | 62 +- 64 files changed, 1257 insertions(+), 8876 deletions(-) delete mode 100644 src/view/AccountPanel.cpp delete mode 100644 src/view/AccountPanel.hpp delete mode 100644 src/view/ExportPanel.cpp delete mode 100644 src/view/ExportPanel.hpp delete mode 100644 src/view/GenerateDialog.cpp delete mode 100644 src/view/GenerateDialog.hpp delete mode 100644 src/view/ImportPanel.cpp delete mode 100644 src/view/ImportPanel.hpp delete mode 100644 src/view/PasswordDialog.cpp delete mode 100644 src/view/PasswordDialog.hpp delete mode 100644 src/view/PreferencesPanel.cpp delete mode 100644 src/view/PreferencesPanel.hpp delete mode 100644 src/view/SearchBanner.cpp delete mode 100644 src/view/SearchBanner.hpp delete mode 100644 src/view/SearchPanel.cpp delete mode 100644 src/view/SearchPanel.hpp delete mode 100644 src/view/StatsPanel.cpp delete mode 100644 src/view/StatsPanel.hpp delete mode 100644 src/view/UsersDialog.cpp delete mode 100644 src/view/UsersDialog.hpp delete mode 100644 src/view/grid/CalendarEditor.cpp delete mode 100644 src/view/grid/CalendarEditor.hpp delete mode 100644 src/view/grid/GridAccount.cpp delete mode 100644 src/view/grid/GridAccount.hpp delete mode 100644 src/view/grid/wxGridCellBitmapRenderer.cpp delete mode 100644 src/view/grid/wxGridCellBitmapRenderer.hpp delete mode 100644 src/view/grid/wxGridCellButtonEditor.cpp delete mode 100644 src/view/grid/wxGridCellButtonEditor.hpp delete mode 100644 src/view/grid/wxGridCellButtonRenderer.cpp delete mode 100644 src/view/grid/wxGridCellButtonRenderer.hpp delete mode 100644 src/view/grid/wxGridCellFastBoolEditor.hpp delete mode 100644 src/view/grid/wxGridCellFormulaEditor.cpp delete mode 100644 src/view/grid/wxGridCellFormulaEditor.hpp delete mode 100644 src/view/grid/wxGridCellStarEditor.cpp delete mode 100644 src/view/grid/wxGridCellStarEditor.hpp delete mode 100644 src/view/grid/wxGridCellTabStringRenderer.cpp delete mode 100644 src/view/grid/wxGridCellTabStringRenderer.hpp delete mode 100644 src/view/grid/wxGridCellTreeButtonEditor.cpp delete mode 100644 src/view/grid/wxGridCellTreeButtonEditor.hpp delete mode 100644 src/view/grid/wxGridCellTreeButtonRenderer.cpp delete mode 100644 src/view/grid/wxGridCellTreeButtonRenderer.hpp delete mode 100644 src/view/grid/wxMyGrid.cpp delete mode 100644 src/view/grid/wxMyGrid.hpp diff --git a/Makefile b/Makefile index 673f18f..4a3fea3 100644 --- a/Makefile +++ b/Makefile @@ -4,26 +4,14 @@ SHARE_DIR=$(DESTDIR)$(ROOT_DIR)"/share/kisscount/" DOC_DIR=$(DESTDIR)$(ROOT_DIR)"/share/doc/kisscount/" BIN_DIR=$(DESTDIR)$(ROOT_DIR)"/bin/" -CXXFLAGS+=`wx-config --cxxflags` -Wall -Isrc -ggdb -CXXFLAGS+=-I./lib/wxsqlite3-1.9.9/include -CXXFLAGS+=-I./lib/freechart/include -CXXFLAGS+=-I/usr/include/libxml2 +CXXFLAGS=`pkg-config --cflags QtCore QtGui QtSql` -Wall -Isrc -ggdb CXXFLAGS+=-Wl,--rpath,"$(LIB_DIR)" CXXFLAGS+=-DRESSOURCES_ROOT="\"$(SHARE_DIR)\"" # For developpers #CXXFLAGS+=-DRESSOURCES_ROOT="\"./ressources/\"" -LDFLAGS+=`wx-config --libs` +LDFLAGS=`pkg-config --libs QtCore QtGui QtSql` LDFLAGS+=-lofx -LDFLAGS+=-lxml2 - -ifdef WIN32 -LDFLAGS+=-L./lib/wxsqlite3-1.9.9/lib/ -lwxcode_msw_wxsqlite3-2.8 -LDFLAGS+=-L./lib/freechart/lib -lwxcode_msw_freechart-2.8 -else -LDFLAGS+=-L./lib/wxsqlite3-1.9.9/lib/ -lwxcode_gtk2u_wxsqlite3-2.8 -LDFLAGS+=-L./lib/freechart/lib -lwxcode_gtk2u_freechart-2.8 -endif CXX=$(HOST)g++ @@ -31,17 +19,16 @@ SOURCES=$(shell find src -name '*.cpp' -type f | tr '\n' ' ') HEADERS=$(shell find src -name '*.h' -type f) OBJS=$(SOURCES:.cpp=.o) -all: check kc +all: kc clean: find src -type f -name '*.[o~]' -exec rm -f \{\} \; rm -f kc -%.o : src/model/%.cpp src/model/import/%.cpp src/model/export/%.cpp src/view/%.cpp src/view/grid/%.cpp src/controller/%.cpp src/%.cpp - $(CXX) $(CXXFLAGS) -c $< +# %.o : src/model/%.cpp src/model/import/%.cpp src/model/export/%.cpp src/view/%.cpp src/view/grid/%.cpp src/controller/%.cpp src/%.cpp -check: - if ! test -d lib ; then echo lib directory not found, please see INSTALL ; return 1 ; fi +%.o : src/model/%.cpp src/model/import/%.cpp src/model/export/%.cpp src/view/%.cpp src/controller/%.cpp src/%.cpp src/%.c + $(CXX) $(CXXFLAGS) -c $< kc: $(OBJS) $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS) diff --git a/src/controller/KissCount.cpp b/src/controller/KissCount.cpp index 86434a8..4b2e561 100644 --- a/src/controller/KissCount.cpp +++ b/src/controller/KissCount.cpp @@ -36,9 +36,9 @@ KissCount::KissCount(const char* bdd_filename) : _user(0) _wxUI->SetLanguage(wxLocale::GetSystemLanguage()); - _wxUI->Show(true); - _wxUI->Centre(); - _wxUI->Disable(); + _wxUI->show(); + // _wxUI->Centre(); + // _wxUI->Disable(); try { @@ -64,17 +64,17 @@ KissCount::~KissCount() if (_user) delete _user; } -std::list KissCount::GetUsers() +std::list KissCount::GetUsers() { return _db->GetUsers(); } -bool KissCount::IsValidUser(const wxString& user, const wxString& password) +bool KissCount::IsValidUser(const std::string& user, const std::string& password) { return _db->IsValidUser(user, password) ; } -void KissCount::LoadUser(const wxString& user) +void KissCount::LoadUser(const std::string& user) { if (_user) delete _user; _user = _db->LoadUser(user) ; @@ -100,12 +100,12 @@ User* KissCount::GetUser() return _user; } -double KissCount::GetAccountAmount(const wxString& id, int month, int year) +double KissCount::GetAccountAmount(int id, int month, int year) { return _db->GetAccountAmount(id, month, year); } -double KissCount::CalcAccountAmount(const wxString& id, int month, int year, bool* had_values) +double KissCount::CalcAccountAmount(int id, int month, int year, bool* had_values) { return _db->CalcAccountAmount(id, month, year, had_values); } @@ -115,7 +115,7 @@ void KissCount::UpdateOperation(Operation& op, bool checkTransfert) // Unlink if (checkTransfert) { - op.transfert = wxT(""); + op.transfert = 0; _user->LinkOrUnlinkOperation(op); } @@ -126,9 +126,9 @@ void KissCount::UpdateOperation(Operation& op, bool checkTransfert) _user->LinkOrUnlinkOperation(op); } -wxString KissCount::AddOperation(Operation& op, bool checkTransfert) +int KissCount::AddOperation(Operation& op, bool checkTransfert) { - wxString ret = _db->AddOperation(_user, op, checkTransfert); + int ret = _db->AddOperation(_user, op, checkTransfert); if (checkTransfert && op.transfert.Length()) _user->LinkOrUnlinkOperation(op); @@ -140,7 +140,7 @@ void KissCount::DeleteOperation(Operation& op) { if (op.transfert.Length()) { - op.transfert = wxT(""); + op.transfert = 0; _user->LinkOrUnlinkOperation(op); } _db->DeleteOperation(_user, op); @@ -159,22 +159,22 @@ void KissCount::DeleteOperations(int month, int year) } } -double KissCount::MetaAmount(const wxString& id) +double KissCount::MetaAmount(int id) { return _db->MetaAmount(id); } -double KissCount::MetaPositiveAmount(const wxString& id) +double KissCount::MetaPositiveAmount(int id) { return _db->MetaPositiveAmount(id); } -void KissCount::SetAccountAmount(const wxString& accountId, int month, int year, double amount) +void KissCount::SetAccountAmount(int accountId, int month, int year, double amount) { _db->SetAccountAmount(accountId, month, year, amount); } -wxString KissCount::AddAccount(Account& ac) +int KissCount::AddAccount(Account& ac) { wxDateTime curDate; @@ -196,7 +196,7 @@ void KissCount::UpdateAccount(Account& ac) std::sort(_user->_accounts.begin(), _user->_accounts.end(), Account()); } -void KissCount::DeleteAccount(Account& ac, const wxString& replacement) +void KissCount::DeleteAccount(Account& ac, int replacement) { std::map >* >::iterator it2; @@ -209,27 +209,27 @@ void KissCount::DeleteAccount(Account& ac, const wxString& replacement) LoadYear(it2->first, true); } -void KissCount::AddSharedAccount(Account& ac, const wxString& granted) +void KissCount::AddSharedAccount(Account& ac, const std::string& granted) { _db->AddSharedAccount(ac, granted); } -void KissCount::RemoveSharedAccount(Account& ac, const wxString& granted) +void KissCount::RemoveSharedAccount(Account& ac, const std::string& granted) { _db->RemoveSharedAccount(ac, granted); } -std::map KissCount::getSharedAccountOwners(const wxString& account) +std::map KissCount::getSharedAccountOwners(int account) { return _db->getSharedAccountOwners(account); } -wxString KissCount::getSharedAccountOwner(const wxString& account) +int KissCount::getSharedAccountOwner(int account) { return _db->getSharedAccountOwner(account); } -wxString KissCount::AddCategory(Category& category) +int KissCount::AddCategory(Category& category) { category.id = _db->AddCategory(_user, category); _user->AddCategory(category); @@ -243,7 +243,7 @@ void KissCount::UpdateCategory(Category& category) _user->UpdateCategory(category); } -void KissCount::DeleteCategory(Category& category, const wxString& replacement) +void KissCount::DeleteCategory(Category& category, int replacement) { std::map >* >::iterator it; @@ -264,7 +264,7 @@ std::map > KissCount::GetAllOperations() void KissCount::GenerateMonth(int monthFrom, int yearFrom, int monthTo, int yearTo) { std::vector::iterator it, it2; - std::map meta; + std::map meta; Operation op; _db->GenerateMonth(_user, monthFrom, yearFrom, monthTo, yearTo); @@ -317,17 +317,17 @@ void KissCount::GenerateMonth(int monthFrom, int yearFrom, int monthTo, int year _wxUI->GenerateMonth(monthTo, yearTo); } -void KissCount::ChangePassword(const wxString& password) +void KissCount::ChangePassword(const std::string& password) { _db->ChangePassword(_user, password); } -bool KissCount::UserExists(const wxString& name) +bool KissCount::UserExists(const std::string& name) { return _db->UserExists(name); } -void KissCount::ChangeName(const wxString& name) +void KissCount::ChangeName(const std::string& name) { _db->ChangeName(_user, name); _user->_name = name; @@ -339,13 +339,13 @@ wxString default_cats[] = { _("Unexpected"), _("Other") }; -void KissCount::NewUser(const wxString& name) +void KissCount::NewUser(const std::string& name) { wxDateTime curDate; Account ac = { - /*.id = */wxT(""), + /*.id = */0, /*.name = */_("Account 1"), - /*.number = */wxT(""), + /*.number = */0, /*.shared = */false, /*.blocked = */false, /*._default = */true, @@ -360,20 +360,20 @@ void KissCount::NewUser(const wxString& name) AddAccount(ac); - cat.parent = wxT("0") ; cat.name = wxT("Fix") ; cat.backcolor = view::OWN_YELLOW ; cat.forecolor = *wxBLACK; cat.fix_cost = true; + cat.parent = 0 ; cat.name = "Fix" ; cat.backcolor = view::OWN_YELLOW ; cat.forecolor = Qt::black; cat.fix_cost = true; AddCategory(cat); - cat.parent = wxT("0") ; cat.name = wxT("Groceries") ; cat.backcolor = view::OWN_GREEN; cat.forecolor = *wxBLACK; cat.fix_cost = false; + cat.parent = 0 ; cat.name = "Groceries" ; cat.backcolor = view::OWN_GREEN; cat.forecolor = Qt::black; cat.fix_cost = false; AddCategory(cat); - cat.parent = wxT("0") ; cat.name = wxT("Hobbies") ; cat.backcolor = view::OWN_GREEN; cat.forecolor = *wxBLACK; cat.fix_cost = false; + cat.parent = 0 ; cat.name = "Hobbies" ; cat.backcolor = view::OWN_GREEN; cat.forecolor = Qt::black; cat.fix_cost = false; AddCategory(cat); - cat.parent = wxT("0") ; cat.name = wxT("Car") ; cat.backcolor = view::OWN_GREEN; cat.forecolor = *wxBLACK; cat.fix_cost = false; + cat.parent = 0 ; cat.name = "Car" ; cat.backcolor = view::OWN_GREEN; cat.forecolor = Qt::black; cat.fix_cost = false; AddCategory(cat); - cat.parent = wxT("0") ; cat.name = wxT("Unexpected") ; cat.backcolor = view::OWN_GREEN; cat.forecolor = *wxBLACK; cat.fix_cost = false; + cat.parent = 0 ; cat.name = "Unexpected" ; cat.backcolor = view::OWN_GREEN; cat.forecolor = Qt::black; cat.fix_cost = false; AddCategory(cat); - cat.parent = wxT("0") ; cat.name = wxT("Other") ; cat.backcolor = view::OWN_GREEN; cat.forecolor = *wxBLACK; cat.fix_cost = false; + cat.parent = 0 ; cat.name = "Other" ; cat.backcolor = view::OWN_GREEN; cat.forecolor = Qt::black; cat.fix_cost = false; AddCategory(cat); - SetOperationOrder(wxT("ASC")); + SetOperationOrder("ASC"); _db->GenerateMonth(_user, -1, -1, (int)curDate.GetMonth(), curDate.GetYear()); } @@ -389,27 +389,27 @@ void KissCount::KillMe() void KissCount::SetLanguage(wxLanguage language) { - _user->_preferences[wxT("language")] = wxString::Format(wxT("%d"), language) ; - _db->UpdatePreference(_user, wxT("language")); + _user->_preferences["language"] = wxString::Format(wxT("%d"), language) ; + _db->UpdatePreference(_user, "language"); } /* ASC (default) or DESC */ -void KissCount::SetOperationOrder(const wxString& order) +void KissCount::SetOperationOrder(const std::string& order) { - _user->_preferences[wxT("operation_order")] = order; - _db->UpdatePreference(_user, wxT("operation_order")); + _user->_preferences["operation_order"] = order; + _db->UpdatePreference(_user, "operation_order"); } -const wxString& KissCount::GetOperationOrder() +const std::string& KissCount::GetOperationOrder() { - return _user->_preferences[wxT("operation_order")] ; + return _user->_preferences["operation_order"] ; } -std::vector* KissCount::Search(wxString* description, wxDateTime* dateFrom, wxDateTime* dateTo, - wxString* amountFrom, wxString* amountTo, - std::vector categories, int types, std::vector accounts) +std::vector* KissCount::Search(std::string* description, wxDateTime* dateFrom, wxDateTime* dateTo, + int* amountFrom, int* amountTo, + std::vector categories, int types, std::vector accounts) { return _db->Search(_user, description, dateFrom, dateTo, amountFrom, amountTo, categories, types, accounts, true); @@ -460,8 +460,8 @@ bool KissCount::SearchPreviousOperation(Operation* res, Operation& op, int month } void KissCount::GetStats(int monthFrom, int yearFrom, int monthTo, int yearTo, - std::map > >* accountAmounts, - std::map* categories) + std::map > >* accountAmounts, + std::map* categories) { wxString monthF = wxString::Format(wxT("%d"), monthFrom); wxString monthT = wxString::Format(wxT("%d"), monthTo); @@ -472,8 +472,8 @@ void KissCount::GetStats(int monthFrom, int yearFrom, int monthTo, int yearTo, } void KissCount::GetMonthStats(int month, int year, int nbDays, - std::map >* operations, - std::map* categories) + std::map >* operations, + std::map* categories) { wxString monthS = wxString::Format(wxT("%d"), month); wxString yearS = wxString::Format(wxT("%d"), year); @@ -482,70 +482,76 @@ void KissCount::GetMonthStats(int month, int year, int nbDays, } -std::map* KissCount::GetNotChecked(int month, int year) +std::map* KissCount::GetNotChecked(int month, int year) { return _db->GetNotChecked(_user, month, year); } -std::map* KissCount::GetVirtualAmount(int month, int year) +std::map* KissCount::GetVirtualAmount(int month, int year) { return _db->GetVirtualAmount(_user, month, year); } -wxFont KissCount::ExtractFont(wxString strFont) +QFont KissCount::ExtractFont(std::string strFont) { - long int pos, pointSize, family, style, weight; + long int pointSize, family, style, weight; + size_t pos; + std::string tmp; wxString faceName; - if (!strFont.Length()) + if (!strFont.size()) { DEFAULT_FONT(f); return f; } - pos = strFont.Find(wxT(";")); + pos = strFont.find(";"); if (pos != -1) { - strFont.SubString(0, pos).ToLong(&pointSize); - strFont = strFont.SubString(pos+1, strFont.Length()); + tmp = substring(strFont, 0, pos); + pointSize = QString(tmp).toInt(); + strFont = strFont.substring(pos+1, strFont.size()); + } + + pos = strFont.find(";"); + + if (pos != -1) + { + tmp = substring(strFont, 0, pos); + family = QString(tmp).toInt(); + strFont = strFont.substring(pos+1, strFont.size()); + } + + pos = strFont.find(";"); + + if (pos != -1) + { + tmp = substring(strFont, 0, pos); + style = QString(tmp).toInt(); + strFont = strFont.substring(pos+1, strFont.size()); } pos = strFont.Find(wxT(";")); if (pos != -1) { - strFont.SubString(0, pos).ToLong(&family); - strFont = strFont.SubString(pos+1, strFont.Length()); - } - - pos = strFont.Find(wxT(";")); - - if (pos != -1) - { - strFont.SubString(0, pos).ToLong(&style); - strFont = strFont.SubString(pos+1, strFont.Length()); - } - - pos = strFont.Find(wxT(";")); - - if (pos != -1) - { - strFont.SubString(0, pos).ToLong(&weight); - strFont = strFont.SubString(pos+1, strFont.Length()); + tmp = substring(strFont, 0, pos); + weight = QString(tmp).toInt(); + strFont = strFont.substring(pos+1, strFont.size()); } faceName = strFont; - return wxFont(pointSize, family, style, weight, false, faceName) ; + return QFont(faceName, pointSize, weight); } -wxString KissCount::CompactFont(const wxFont& font) +std::string KissCount::CompactFont(const QFont& font) { - wxString res = wxString::Format(wxT("%d;%d;%d;%d;"), font.GetPointSize(), font.GetFamily(), font.GetStyle(), font.GetWeight()); - res += font.GetFaceName(); + QString res = QString::sprintf("%d;%d;%d;%d;", font.pointSize(), 0, 0, font.weight()); + res += font.family(); - return res; + return res.toStdString(); } void KissCount::UnRegisterImportEngine(ImportEngine* engine) @@ -580,7 +586,7 @@ wxString KissCount::GetImportEngineExtensions() return res; } -ImportEngine* KissCount::GetImportEngine(wxString path) +ImportEngine* KissCount::GetImportEngine(std::string path) { std::vector::iterator it; std::vector* importEngines = KissCount::GetImportEngines(); @@ -615,13 +621,13 @@ void KissCount::RegisterExportEngine(ExportEngine* engine) wxString KissCount::GetExportEngineExtensions() { - wxString res; + std::string res; std::vector::iterator it; int i; std::vector* exportEngines = KissCount::GetExportEngines(); for(i=0; i<(int)exportEngines->size()-1; i++) - res = res + (*exportEngines)[i]->GetFileExt() + wxT("|") ; + res = res + (*exportEngines)[i]->GetFileExt() + "|" ; if (exportEngines->size()) res = res + (*exportEngines)[i]->GetFileExt(); @@ -629,7 +635,7 @@ wxString KissCount::GetExportEngineExtensions() return res; } -ExportEngine* KissCount::GetExportEngine(wxString path) +ExportEngine* KissCount::GetExportEngine(std::string path) { std::vector::iterator it; std::vector* exportEngines = KissCount::GetExportEngines(); diff --git a/src/controller/KissCount.hpp b/src/controller/KissCount.hpp index 26f0256..2b9b117 100644 --- a/src/controller/KissCount.hpp +++ b/src/controller/KissCount.hpp @@ -22,112 +22,115 @@ #include +#include + #include #include #include -#include - #include #define APP_VERSION "0.3" -#define ESCAPE_CHARS(s) { \ +#define ESCAPE_CHARS(s) s +/*{ \ if (s.Find(wxT("\\\"")) == wxNOT_FOUND) \ s.Replace(wxT("\""), wxT("\\\""), true); \ if (s.Find(wxT("\\\'")) == wxNOT_FOUND) \ s.Replace(wxT("\'"), wxT("\\\'"), true); \ } - -#define UNESCAPE_CHARS(s) { \ +*/ +#define UNESCAPE_CHARS(s) s +/*{ \ s.Replace(wxT("\\\""), wxT("\""), true); \ s.Replace(wxT("\\\'"), wxT("\'"), true); \ } +*/ class wxUI; class Database; class ImportEngine; class ExportEngine; -class KissCount +class KissCount : public QApplication { public: KissCount(const char* bdd_filename); ~KissCount(); - std::list GetUsers(); - bool IsValidUser(const wxString& user, const wxString& password); - void LoadUser(const wxString& user); + std::list GetUsers(); + bool IsValidUser(const std::string& user, const std::string& password); + void LoadUser(const std::string& user); User* GetUser(); - void ChangePassword(const wxString& password); - bool UserExists(const wxString& name); - void ChangeName(const wxString& name); - void NewUser(const wxString& name); + void ChangePassword(const std::string& password); + bool UserExists(const std::string& name); + void ChangeName(const std::string& name); + void NewUser(const std::string& name); void LoadYear(int year, bool force=false); - wxString AddOperation(Operation& op, bool checkTransfert=true); + int AddOperation(Operation& op, bool checkTransfert=true); void UpdateOperation(Operation& op, bool checkTransfert=true); void DeleteOperation(Operation& op); void DeleteOperations(int month, int year); - double MetaAmount(const wxString& id); - double MetaPositiveAmount(const wxString& id); + double MetaAmount(int id); + double MetaPositiveAmount(int id); - double GetAccountAmount(const wxString& id, int month, int year); - void SetAccountAmount(const wxString& accountId, int month, int year, double value); - double CalcAccountAmount(const wxString& id, int month, int year, bool* had_values); + double GetAccountAmount(int id, int month, int year); + void SetAccountAmount(int accountId, int month, int year, double value); + double CalcAccountAmount(int id, int month, int year, bool* had_values); - wxString AddAccount(Account& ac); + int AddAccount(Account& ac); void UpdateAccount(Account& ac); - void DeleteAccount(Account& ac, const wxString& replacement); - void AddSharedAccount(Account& ac, const wxString& granted); - void RemoveSharedAccount(Account& ac, const wxString& granted); - std::map getSharedAccountOwners(const wxString& account); - wxString getSharedAccountOwner(const wxString& account); + void DeleteAccount(Account& ac, int replacement); + void AddSharedAccount(Account& ac, const std::string& granted); + void RemoveSharedAccount(Account& ac, const std::string& granted); + std::map getSharedAccountOwners(int account); + int getSharedAccountOwner(int account); - wxString AddCategory(Category& category); + int AddCategory(Category& category); void UpdateCategory(Category& category); - void DeleteCategory(Category& category, const wxString& replacement); + void DeleteCategory(Category& category, int replacement); std::map > GetAllOperations(); void GenerateMonth(int monthFrom, int yearFrom, int monthTo, int yearTo); void KillMe(); - void SetLanguage(wxLanguage language); - void SetOperationOrder(const wxString& order); - const wxString& GetOperationOrder(); - - std::vector* Search(wxString* description, wxDateTime* dateFrom, wxDateTime* dateTo, - wxString* amountFrom, wxString* amountTo, - std::vector categories, int types, std::vector accounts); + void SetLanguage(std::string language); + void SetOperationOrder(const std::string& order); + const std::string& GetOperationOrder(); + + std::vector* Search(std::string* description, QDate* dateFrom, QDate* dateTo, + int* amountFrom, int* amountTo, + std::vector categories, int types, std::vector accounts); bool SearchPreviousOperation(Operation* res, Operation& op, int month, int year, bool limitToType); void GetStats(int monthFrom, int yearFrom, int monthTo, int yearTo, - std::map > >* accountAmounts, - std::map* categories); + std::map > >* accountAmounts, + std::map* categories); void GetMonthStats(int month, int year, int nbDays, - std::map >* operations, - std::map* categories); + std::map >* operations, + std::map* categories); - std::map* GetNotChecked(int month, int year); - std::map* GetVirtualAmount(int month, int year); + std::map* GetNotChecked(int month, int year); + std::map* GetVirtualAmount(int month, int year); - static wxFont ExtractFont(wxString strFont); - static wxString CompactFont(const wxFont& font); + static QFont ExtractFont(std::string); + static std::string CompactFont(const QFont& font); static void RegisterImportEngine(ImportEngine* engine); static void UnRegisterImportEngine(ImportEngine* engine); - wxString GetImportEngineExtensions(); - ImportEngine* GetImportEngine(wxString path); + std::string GetImportEngineExtensions(); + ImportEngine* GetImportEngine(std::string path); static void RegisterExportEngine(ExportEngine* engine); static void UnRegisterExportEngine(ExportEngine* engine); - wxString GetExportEngineExtensions(); - ExportEngine* GetExportEngine(wxString path); + std::string GetExportEngineExtensions(); + ExportEngine* GetExportEngine(std::string path); void UpdateImportPattern(); diff --git a/src/main.cpp b/src/main.cpp index e45bbac..edffb0a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,28 +17,22 @@ along with KissCount. If not, see . */ -#include #include -class MyApp: public wxApp +int main(int argc, char *argv[]) { - virtual bool OnInit() + try { - try - { - if (argc == 2) - new KissCount(wxString(argv[1]).mb_str()); - else - new KissCount(0); - } - catch (std::string s) - { - std::cerr << "Error " << s << "\n"; - return false; - } - - return true; - } -}; + if (argc == 2) + KissCount(wxString(argv[1]).mb_str()); + else + KissCount(0); -IMPLEMENT_APP(MyApp); + return KissCount.exec(); + } + catch (std::string s) + { + std::cerr << "Error " << s << "\n"; + throw; + } +} diff --git a/src/model/Account.hpp b/src/model/Account.hpp index b8ea99a..f0b4243 100644 --- a/src/model/Account.hpp +++ b/src/model/Account.hpp @@ -20,12 +20,10 @@ #ifndef ACCOUNT_H #define ACCOUNT_H -#include - struct Account { - wxString id; - wxString name; - wxString number; + int id; + std::string name; + std::string number; bool shared; bool blocked; bool _default; @@ -43,10 +41,10 @@ struct Account { if (!ac1._virtual && ac2._virtual) return true; if (ac1._virtual && !ac2._virtual) return false; - return (ac1.name.Cmp(ac2.name) < 0); + return ac1.name < ac2.name; } - bool operator == (const wxString& accountId) + bool operator == (int accountId) { return id == accountId; } diff --git a/src/model/AccountAmount.hpp b/src/model/AccountAmount.hpp index a7dbc64..283e61a 100644 --- a/src/model/AccountAmount.hpp +++ b/src/model/AccountAmount.hpp @@ -21,21 +21,14 @@ #define ACCOUNTAMOUNT_H struct AccountAmount { - wxString account; + int account; int month; int year; bool operator()(const AccountAmount& x, const AccountAmount& y) const { - long x1, y1; - if (x.account != y.account) - { - x.account.ToLong(&x1); - y.account.ToLong(&y1); - - return x1 < y1; - } + return x.account < y.account; return (x.year < y.year || ((x.year == y.year) && x.month < y.month)); } diff --git a/src/model/Category.hpp b/src/model/Category.hpp index f099d7e..20bc8b3 100644 --- a/src/model/Category.hpp +++ b/src/model/Category.hpp @@ -20,19 +20,20 @@ #ifndef CATEGORY_H #define CATEGORY_H -#include +#include +#include struct Category { - wxString id; - wxString parent; - wxString name; - wxColour backcolor; - wxColour forecolor; - wxString font; + int id; + int parent; + std::string name; + QColor backcolor; + QColor forecolor; + std::string font; bool fix_cost; - bool operator == (const wxString& catId) + bool operator == (int catId) { return id == catId; } diff --git a/src/model/Database.cpp b/src/model/Database.cpp index 35d29a9..44985a0 100644 --- a/src/model/Database.cpp +++ b/src/model/Database.cpp @@ -18,28 +18,34 @@ */ #include -#include -#include +#include #include +#include +#include +#include +#include +#include +#include + #include "Database.hpp" -static inline wxString DoubleToString(double d) +static inline QString DoubleToString(double d) { - wxString res; + QString res; - res = wxString::Format(wxT("%.2lf"), d); - res.Replace(wxT(","), wxT(".")); - - return res; + res = res.sprintf("%.2lf", d); + + return res.replace(",", "."); } Database::Database(const char* filename, KissCount* kiss) : _kiss(kiss) { std::ifstream bdd_file; - std::string sPath = std::string(wxGetHomeDir().mb_str()) + std::string(BDD_FILE); - wxString wPath = wxGetHomeDir() + wxT(BDD_FILE); + QString sPath = QDir::home().path() + "/" + BDD_FILE; + + _db = QSqlDatabase::addDatabase("QSQLITE"); if (filename) { @@ -47,21 +53,22 @@ Database::Database(const char* filename, KissCount* kiss) : _kiss(kiss) if (!bdd_file.good()) { - wxMessageBox(_("Unable to open Database"), _("Error"), wxICON_ERROR | wxOK ); + QMessageBox::critical(0, _("Error"), _("Unable to open Database")); throw std::string("Unable to open ") + filename; } - _db.Open(wxString(filename, wxConvUTF8)); - if (!_db.IsOpen()) + _db.setDatabaseName(filename); + + if (!_db.open()) { - wxMessageBox(_("Unable to open Database"), _("Error"), wxICON_ERROR | wxOK ); + QMessageBox::critical(0, _("Error"), _("Unable to open Database")); throw std::string("Unable to open ") + filename; } } else { // If default BDD file, assume this can be the first load - bdd_file.open(sPath.c_str(), std::ifstream::in); + bdd_file.open(sPath.toStdString().c_str(), std::ifstream::in); if (!bdd_file.good()) { @@ -69,11 +76,12 @@ Database::Database(const char* filename, KissCount* kiss) : _kiss(kiss) } else { - _db.Open(wPath); - if (!_db.IsOpen()) + _db.setDatabaseName(sPath); + + if (!_db.open()) { - wxMessageBox(_("Unable to open Database"), _("Error"), wxICON_ERROR | wxOK ); - throw std::string("Unable to open ") + sPath; + QMessageBox::critical(0, _("Error"), _("Unable to open Database")); + throw std::string("Unable to open ") + sPath.toStdString(); } } } @@ -85,266 +93,281 @@ Database::Database(const char* filename, KissCount* kiss) : _kiss(kiss) void Database::CreateDatabase() { - std::ifstream init_script; - std::string line; - wxString wxline; - std::string sPath = std::string(wxGetHomeDir().mb_str()) + std::string(BDD_FILE); - wxString wPath = wxGetHomeDir() + wxT(BDD_FILE); - wxFileName dirname( wxGetHomeDir() +wxT("/.kisscount/"), wxPATH_UNIX); - wxFileName filename (wPath); - wxFile file; - wxString message = _("No database found, would you like to create a new one ?\n\n"); + QFile init_script(INIT_SCRIPT); + QString sPath = QDir::home().path() + BDD_FILE; + QDir dirname( QDir::home().path() + "/.kisscount/"); + QFile file(sPath); + QString message = _("No database found, would you like to create a new one ?\n\n"); message += _("!! Warning !! If there was a bug, the old database will be suppressed !"); - if (dirname.DirExists()) + if (dirname.exists()) { - wxMessageDialog dialog(0, message, wxT("KissCount"), wxYES_NO); - - if (dialog.ShowModal() == wxID_NO) + if (QMessageBox::question(0, "KissCount", message, QMessageBox::Yes|QMessageBox::No) == QMessageBox::No) throw std::string("No database") ; } - init_script.open(INIT_SCRIPT); - - if (!init_script) + if (!init_script.exists() || !init_script.open(QIODevice::ReadOnly | QIODevice::Text)) { - wxMessageBox(_(INIT_SCRIPT " not found, aborting"), _("Error"), wxICON_ERROR | wxOK ); + QMessageBox::critical(0, _("Error"), _(INIT_SCRIPT " not found, aborting")); throw "init.sql not found, aborting"; } - if (!dirname.DirExists() && !dirname.Mkdir()) + if (!dirname.exists() && !dirname.mkdir(dirname.absolutePath())) { - wxMessageBox(_("Unable to Create ") + wxGetHomeDir() +wxT("/.kisscount/"), _("Error"), wxICON_ERROR | wxOK ); - throw std::string("Unable to create ") + std::string(wxGetHomeDir().mb_str()) + std::string("/.kisscount/"); + QMessageBox::critical(0, _("Error"), _("Unable to Create ") + dirname.absolutePath() ); + throw std::string("Unable to create ") + dirname.absolutePath().toStdString(); } - if (!filename.FileExists() && !file.Create(wPath, false, wxS_IRUSR|wxS_IWUSR|wxS_IXUSR)) + if (!file.exists() && !file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - wxMessageBox(_("Unable to Create ") + wPath, _("Error"), wxICON_ERROR | wxOK ); - throw std::string("Unable to create ") + sPath; + QMessageBox::critical(0, _("Error"), _("Unable to Create ") + QString(sPath)); + throw std::string("Unable to create ") + sPath.toStdString(); } - _db.Open(wPath); + file.close(); - if (!_db.IsOpen()) + _db.setDatabaseName(sPath); + + if (!_db.open()) { - wxMessageBox(_("Unable to open Database"), _("Error"), wxICON_ERROR | wxOK ); - throw std::string("Unable to open ") + sPath; + QMessageBox::critical(0, _("Error"), _("Unable to open Database")); + throw std::string("Unable to open ") + sPath.toStdString(); } - do + while (!init_script.atEnd()) { - getline(init_script, line); - wxline = wxString(line.c_str(), wxConvUTF8); - wxline.Trim(false); - if (!wxline.Length() || wxline.StartsWith(wxT("--"))) continue; - if (!_db.CheckSyntax(wxline)) + QByteArray line = file.readLine().trimmed(); + + if (line.isEmpty() || line.startsWith("--")) continue; + + QSqlQuery query (QString(line), _db); + + if (!query.isValid()) { - std::cout << line << " is invalid !\n" ; + std::cout << QString(line).toStdString() << " is invalid !\n" ; continue; } - try + + if (!query.exec()) { - _db.ExecuteUpdate(wxline); - } - catch (...) - { - wxMessageBox(_("Error creating original database"), _("Error"), wxICON_ERROR | wxOK ); - remove(sPath.c_str()); + QMessageBox::critical(0, _("Error"), _("Error creating original database")); + init_script.close(); + file.remove(); throw line; } - } while (init_script); + } init_script.close(); } -wxString Database::HashPassword(const wxString& password) +QString Database::HashPassword(const QString& password) { blk_SHA_CTX sha_ctx; unsigned char sha[20]; - wxString wxSHA; + QString res; blk_SHA1_Init(&sha_ctx); - blk_SHA1_Update(&sha_ctx, password.mb_str(), password.Length()); + blk_SHA1_Update(&sha_ctx, password.toStdString().c_str(), password.size()); blk_SHA1_Final(sha, &sha_ctx); for(int i=0; i<20; i++) - wxSHA += wxString::Format(wxT("%02x"), (int)sha[i]); - - return wxSHA; -} - -std::list Database::GetUsers() -{ - std::list res; - wxString req; - // Check whether value exists in table - wxSQLite3ResultSet set ; - - req = wxT("SELECT name FROM user ORDER BY name"); - EXECUTE_SQL_QUERY(req, set, res); - - while (set.NextRow()) - { - res.push_back(set.GetAsString(0)); - } - set.Finalize(); + res += QString::number((int)sha[i], 16); return res; } -bool Database::IsValidUser(const wxString& user, const wxString& password) +std::list Database::GetUsers() { - bool res; - wxString req; - wxSQLite3ResultSet set; + std::list res; + QSqlQuery query; - req = wxT("SELECT name FROM user WHERE name='") + user + wxT("' AND password='") + HashPassword(password) + wxT("'"); - - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(QString("SELECT name FROM user ORDER BY name"), res); - res = set.NextRow() ; - set.Finalize(); + while (query.next()) + res.push_back(query.value(0).toString().toStdString()); return res; } -User* Database::LoadUser(const wxString& name) +bool Database::IsValidUser(const QString& user, const QString& password) +{ + QSqlQuery query; + + EXECUTE_SQL_QUERY(QString("SELECT name FROM user WHERE name='%1' AND password='%2'").arg(user, HashPassword(password)), false); + + return query.next(); +} + +static inline void fillOperation(Operation* op, const QSqlRecord& set) +{ + op->id = set.value("id").toInt(); + op->parent = set.value("parent").toInt(); + op->account = set.value("account").toInt(); + op->day = set.value("day").toInt(); + op->month = set.value("month").toInt(); + op->year = set.value("year").toInt(); + op->amount = set.value("amount").toDouble(); + op->description = set.value("description").toString().toStdString(); + op->category = set.value("category").toInt(); + op->fix_cost = set.value("fix_cost").toBool(); + op->checked = set.value("checked").toBool(); + op->transfert = set.value("transfert").toInt(); + op->formula = set.value("formula").toString().toStdString(); + op->meta = set.value("meta").toBool(); + op->_virtual = set.value("virtual").toBool(); +} + +static inline void fillAccount(Account* account, const QSqlRecord& set) +{ + account->id = set.value("id").toInt(); + account->name = set.value("name").toString().toStdString(); + account->number = set.value("number").toString().toStdString(); + account->shared = set.value("shared").toBool(); + account->blocked = set.value("blocked").toBool(); + account->_default = set.value("default_account").toBool(); + account->_virtual = set.value("virtual").toBool(); + account->is_owner = true; +} + +static inline void fillCategory(Category* category, const QSqlRecord& set) +{ + category->id = set.value("id").toInt(); + category->parent = set.value("parent").toInt(); + category->name = set.value("name").toString().toStdString(); + category->backcolor = QColor(set.value("backcolor").toString()); + category->forecolor = QColor(set.value("forecolor").toString()); + category->font = set.value("font").toString().toStdString(); + category->fix_cost = set.value("fix_cost").toBool(); +} + +User* Database::LoadUser(const std::string& name) { - wxSQLite3ResultSet set; - wxString req; User* user; Account account; Category category; ImportPattern importPattern; + QString req; + QSqlRecord set; + QSqlQuery query; std::vector::iterator it; - req = wxT("SELECT * FROM user WHERE name='") + name + wxT("'"); + EXECUTE_SQL_QUERY(QString("SELECT * FROM user WHERE name='%1'").arg(name), 0); - EXECUTE_SQL_QUERY(req, set, 0); - - if (!set.NextRow()) + if (!query.next()) return 0; user = new User(this); - user->_id = set.GetAsString(wxT("id")); - user->_name = set.GetAsString(wxT("name")); - user->_password = wxT("") ; // Security reasons set.GetAsString("password"); + set = query.record(); - user->_preferences[wxT("operation_order")] = wxT("ASC") ; + user->_id = set.value("id").toInt(); + user->_name = set.value("name").toString().toStdString(); + user->_password = "" ; // Security reasons set.value("password").toString().toStdString(); - set.Finalize(); + user->_preferences["operation_order"] = "ASC" ; - req = wxT("SELECT * FROM account WHERE user='") + user->_id + wxT("' ORDER BY default_account DESC, virtual, blocked, name ASC"); + query.clear(); - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); + req = QString("SELECT * FROM account WHERE user='%1' ORDER BY default_account DESC, virtual, blocked, name ASC").arg(user->_id); - while (set.NextRow()) + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); + + while (query.next()) { - account.id = set.GetAsString(wxT("id")); - account.name = set.GetAsString(wxT("name")); - account.number = set.GetAsString(wxT("number")); - account.shared = set.GetBool(wxT("shared")); - account.blocked = set.GetBool(wxT("blocked")); - account._default = set.GetBool(wxT("default_account")); - account._virtual = set.GetBool(wxT("virtual")); - account.is_owner = true; + set = query.record(); + fillAccount(&account, set); user->_accounts.push_back(account); } - set.Finalize(); - req = wxT("SELECT * FROM account WHERE id IN (SELECT account FROM shared_account WHERE user='") + user->_id + wxT("') ORDER BY name, blocked, virtual ASC"); + query.clear(); - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); + req = QString("SELECT * FROM account WHERE id IN (SELECT account FROM shared_account WHERE user='%1') ORDER BY name, blocked, virtual ASC").arg(user->_id); - while (set.NextRow()) + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); + + while (query.next()) { - account.id = set.GetAsString(wxT("id")); - account.name = set.GetAsString(wxT("name")); - account.number = set.GetAsString(wxT("number")); - account.shared = set.GetBool(wxT("shared")); - account.blocked = set.GetBool(wxT("blocked")); - account._default = set.GetBool(wxT("default_account")); - account._virtual = set.GetBool(wxT("virtual")); + set = query.record(); + fillAccount(&account, set); account.is_owner = false; user->_accounts.push_back(account); } - set.Finalize(); + + query.clear(); if (!user->_accounts.empty()) { it = user->_accounts.begin(); - req = wxT("SELECT DISTINCT year FROM operation WHERE account IN('") + it->id; + req = "SELECT DISTINCT year FROM operation WHERE account IN('" + QString::number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += wxT("', '") + QString::number(it->id) ; } - req += wxT("')"); - req += wxT(" OR user='") + user->_id + wxT("'"); - req += wxT(" ORDER BY year ASC"); + req += "')"; + req += " OR user='" + QString::number(user->_id) + "'"; + req += " ORDER BY year ASC"; - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); - while (set.NextRow()) + while (query.next()) { - user->_operations[set.GetInt(wxT("year"))] = 0; + set = query.record(); + user->_operations[set.value("year").toInt()] = 0; } - set.Finalize(); } - req = wxT("SELECT * FROM category WHERE user='") + user->_id + wxT("' ORDER BY fix_cost DESC, name ASC"); - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); + req = QString("SELECT * FROM category WHERE user='%1' ORDER BY fix_cost DESC, name ASC").arg(user->_id); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); - while (set.NextRow()) + while (query.next()) { - category.id = set.GetAsString(wxT("id")); - category.parent = set.GetAsString(wxT("parent")); - category.name = set.GetAsString(wxT("name")); - category.backcolor = wxColour(set.GetAsString(wxT("backcolor"))); - category.forecolor = wxColour(set.GetAsString(wxT("forecolor"))); - category.font = set.GetAsString(wxT("font")); - category.fix_cost = set.GetBool(wxT("fix_cost")); + set = query.record(); + fillCategory(&category, set); user->_categories.push_back(category); user->_categoriesFonts.push_back(_kiss->ExtractFont(category.font)); } - set.Finalize(); + query.clear(); - req = wxT("SELECT name, value FROM preference WHERE user='") + user->_id + wxT("' ORDER BY value ASC"); - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); + req = QString("SELECT name, value FROM preference WHERE user='%1' ORDER BY value ASC").arg(user->_id); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); - while (set.NextRow()) - user->_preferences[set.GetAsString(wxT("name"))] = set.GetAsString(wxT("value")); - - set.Finalize(); - - req = wxT("SELECT * FROM import_pattern WHERE user='") + user->_id + wxT("'"); - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, {delete user;}, {delete user;}); - - while (set.NextRow()) + while (query.next()) { - importPattern.pattern = set.GetAsString(wxT("pattern")); - importPattern.account = set.GetAsString(wxT("account")); - importPattern.category = set.GetAsString(wxT("category")); - - user->_importPatterns[set.GetAsString(wxT("description"))] = importPattern; + set = query.record(); + user->_preferences[set.value("name").toString().toStdString()] = set.value("value").toString().toStdString(); } - set.Finalize(); + query.clear(); + + req = QString("SELECT * FROM import_pattern WHERE user='%1'").arg(user->_id); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, {delete user;}, {delete user;}); + + while (query.next()) + { + set = query.record(); + importPattern.pattern = set.value("pattern").toString().toStdString(); + importPattern.account = set.value("account").toInt(); + importPattern.category = set.value("category").toInt(); + + user->_importPatterns[set.value("description").toString().toStdString()] = importPattern; + } + + query.clear(); return user; } void Database::LoadYear(User* user, int year) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; std::vector::iterator it; + QSqlQuery query; if (user->_operations[year] == 0) user->_operations[year] = new std::map >(); @@ -352,129 +375,100 @@ void Database::LoadYear(User* user, int year) if (!user->_accounts.size()) return; it = user->_accounts.begin(); - req = wxT("SELECT * FROM operation WHERE (account IN('") + it->id; + req = "SELECT * FROM operation WHERE (account IN('" + QString::number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += "', '" + QString::number(it->id) ; } - req += wxT("')"); - req += wxT(" OR user='") + user->_id + wxT("')"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), year) + wxT("'"); - req += wxT(" ORDER BY fix_cost DESC, year, month ASC, day "); - req += user->_preferences[wxT("operation_order")]; + req += "')"; + req += " OR user='" + QString::number(user->_id) + "')"; + req += " AND year='" + QString::number(year) + "'"; + req += " ORDER BY fix_cost DESC, year, month ASC, day "; + req += user->_preferences["operation_order"]; - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - while (set.NextRow()) + while (query.next()) { Operation op; - op.id = set.GetAsString(wxT("id")); - op.parent = set.GetAsString(wxT("parent")); - op.account = set.GetAsString(wxT("account")); - op.day = set.GetInt(wxT("day")); - op.month = set.GetInt(wxT("monthpp")); - op.year = set.GetInt(wxT("year")); - op.amount = set.GetDouble(wxT("amount")); - op.description = set.GetAsString(wxT("description")); - op.category = set.GetAsString(wxT("category")); - op.fix_cost = set.GetBool(wxT("fix_cost")); - op.checked = set.GetBool(wxT("checked")); - op.transfert = set.GetAsString(wxT("transfert")); - op.formula = set.GetAsString(wxT("formula")); - op.meta = set.GetBool(wxT("meta")); - op._virtual = set.GetBool(wxT("virtual")); + set = query.record(); + fillOperation(&op, set); (*user->_operations[op.year])[op.month].push_back(op); } user->ResolveGroups(year); - set.Finalize(); + query.clear(); } -double Database::GetAccountAmount(const wxString& id, int month, int year) +double Database::GetAccountAmount(int id, int month, int year) { - wxSQLite3ResultSet set; - wxString req; - double res; + QSqlRecord set; + QString req; + double res = 0.0; + QSqlQuery query; - req = wxT("SELECT amount FROM account_amount WHERE account='") + id ; - req += wxT("' AND month='") + wxString::Format(wxT("%d"), month); - req += wxT("' AND year='") + wxString::Format(wxT("%d"), year); - req += wxT("'"); + req = QString("SELECT amount FROM account_amount WHERE account='%1' AND month='%2' AND year='%3'").arg(id, month, year) ; - EXECUTE_SQL_QUERY(req , set, 0.0); + EXECUTE_SQL_QUERY(req, 0.0); - if (set.NextRow()) - res = set.GetDouble(wxT("amount")); - else + if (query.next()) { - SetAccountAmount(id, month, year, 0.0); - res = 0.0; + set = query.record(); + res = set.value("amount").toDouble(); } + else + SetAccountAmount(id, month, year, 0.0); - set.Finalize(); + query.clear(); return res; } -double Database::CalcAccountAmount(const wxString& id, int month, int year, bool* had_values) +double Database::CalcAccountAmount(int id, int month, int year, bool* had_values) { - wxSQLite3ResultSet set; - wxString req; - double res; + QSqlRecord set; + QString req; + double res = 0.0; + QSqlQuery query; - req = wxT("SELECT SUM(id) AS id, SUM(amount) AS amount FROM operation WHERE account='") + id ; - req += wxT("' AND month='") + wxString::Format(wxT("%d"), month); - req += wxT("' AND year='") + wxString::Format(wxT("%d"), year); - req += wxT("'"); - req += wxT(" AND meta='0'"); + req = QString("SELECT SUM(id) AS id, SUM(amount) AS amount FROM operation WHERE account='%1' AND month='%2' AND year='%3' AND meta='0'").arg(id, month ,year) ; - EXECUTE_SQL_QUERY(req , set, 0.0); + EXECUTE_SQL_QUERY(req, 0.0); - if (set.NextRow()) + if (query.next()) { - res = set.GetDouble(wxT("amount")); + set = query.record(); + res = set.value("amount").toDouble(); if (had_values) - *had_values = set.GetInt(wxT("id")) > 0 ; + *had_values = set.value("id").toInt() > 0 ; } else { - res=0.0; if (had_values) *had_values = false; } - set.Finalize(); + query.clear(); return res; } -bool Database::GetOperation(const wxString& id, Operation* op) +bool Database::GetOperation(int id, Operation* op) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; + QSqlQuery query; - req = wxT("SELECT * FROM operation WHERE id='") + id + wxT("'"); + req = QString("SELECT * FROM operation WHERE id='%1").arg(id); - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(req, false); - if (!set.NextRow()) return false; + if (!query.next()) return false; + + set = query.record(); - op->id = set.GetAsString(wxT("id")); - op->parent = set.GetAsString(wxT("parent")); - op->account = set.GetAsString(wxT("account")); - op->day = set.GetInt(wxT("day")); - op->month = set.GetInt(wxT("monthpp")); - op->year = set.GetInt(wxT("year")); - op->amount = set.GetDouble(wxT("amount")); - op->description = set.GetAsString(wxT("description")); - op->category = set.GetAsString(wxT("category")); - op->fix_cost = set.GetBool(wxT("fix_cost")); - op->checked = set.GetBool(wxT("checked")); - op->transfert = set.GetAsString(wxT("transfert")); - op->formula = set.GetAsString(wxT("formula")); - op->meta = set.GetBool(wxT("meta")); - op->_virtual = set.GetBool(wxT("virtual")); + fillOperation(op, set); return true; } @@ -482,119 +476,93 @@ bool Database::GetOperation(const wxString& id, Operation* op) void Database::LinkOrUnlinkOperation(User* user, Operation& op) { Operation linked; - wxString req; - wxSQLite3ResultSet set; + QString req; + QSqlRecord set; Account account, account2; bool _virtual; + QSqlQuery query; - if (op.transfert.Length()) + if (op.transfert) { // No one or not linked if (!GetOperation(op.transfert, &linked) || op.description != linked.description || op.amount != -linked.amount || op.account == linked.account) { - req = wxT("UPDATE operation SET transfert='' virtual='0' WHERE id='") + op.id + wxT("'") ; + req = QString("UPDATE operation SET transfert='' virtual='0' WHERE id='%1'").arg(op.id); EXECUTE_SQL_UPDATE(req, ); - op.transfert = wxT(""); - op._virtual = 0; + op.transfert = 0; + op._virtual = false; return; } } // Not Linked else { - req = wxT("SELECT id FROM operation WHERE transfert='") + op.id + wxT("'"); + req = QString("SELECT id FROM operation WHERE transfert='%1'").arg(op.id); - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - if (set.NextRow()) + if (query.next()) { - req = wxT("UPDATE operation SET transfert='', virtual='0' WHERE id='") + set.GetAsString(wxT("id")) + wxT("'") ; + set = query.record(); + req = QString("UPDATE operation SET transfert='', virtual='0' WHERE id='%1'").arg(set.value("id").toString().toStdString()); + query.clear(); EXECUTE_SQL_UPDATE(req, ); } + else + query.clear(); - req = wxT("SELECT id, account FROM operation WHERE description=\"") + op.description + wxT("\""); - req += wxT(" AND month='") + wxString::Format(wxT("%d"), op.month) + wxT("'"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), op.year) + wxT("'"); - req += wxT(" AND amount='") + DoubleToString(-op.amount) + wxT("'"); - req += wxT(" AND meta='0'"); - req += wxT(" AND account !='") + op.account + wxT("'"); - req += wxT(" AND (transfert='' OR transfert IS 0)"); + req = QString("SELECT id, account FROM operation WHERE description=\"%1\" AND month='%2' AND year='%3' AND amount='%4' AND meta='0' AND account !='%5' AND transfert=''").arg(op.description, op.month, op.year, DoubleToString(-op.amount), op.account), - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); op._virtual = false; // Don't need to link - if (!set.NextRow()) return ; + if (!query.next()) return ; + + set = query.record(); // Link - linked.id = set.GetAsString(wxT("id")); + linked.id = set.value("id").toInt(); op.transfert = linked.id; account = user->GetAccount(op.account); - account2 = user->GetAccount(set.GetAsString(wxT("account"))); + account2 = user->GetAccount(set.value("account").toInt()); _virtual = account._virtual || account2._virtual; - req = wxT("UPDATE operation SET transfert='") + linked.id + wxT("'"); - if (_virtual) - req += wxT(", virtual='1'"); - else - req += wxT(", virtual='0'"); - req += wxT(" WHERE id='") + op.id + wxT("'") ; + query.clear(); + + req = QString("UPDATE operation SET transfert='%1', virtual='%2' WHERE id='%3'").arg((linked.id) ?: "", _virtual, op.id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("UPDATE operation SET transfert='") + op.id + wxT("'") ; - if (_virtual) - req += wxT(", virtual='1'"); - else - req += wxT(", virtual='0'"); - req += wxT(" WHERE id='") + linked.id + wxT("'") ; + query.clear(); + + req = QString("UPDATE operation SET transfert='%1', virtual='%2' WHERE id='%3'").arg((op.id) ?: "", _virtual, linked.id); EXECUTE_SQL_UPDATE(req, ); op._virtual = _virtual; + + query.clear(); } } void Database::UpdateOperation(User* user, Operation& op, bool checkTransfert) { - wxString req; + QString req; + QSqlQuery query; if (checkTransfert) LinkOrUnlinkOperation(user, op); ESCAPE_CHARS(op.description); - req = wxT("UPDATE operation SET ") ; - req += wxT("parent='") + op.parent + wxT("'"); - req += wxT(", account='") + op.account + wxT("'"); - req += wxT(", year='") + wxString::Format(wxT("%d"), op.year) + wxT("'"); - req += wxT(", month='") + wxString::Format(wxT("%d"), op.month) + wxT("'"); - req += wxT(", day='") + wxString::Format(wxT("%d"), op.day) + wxT("'"); - req += wxT(", amount='") + DoubleToString(op.amount) + wxT("'"); - req += wxT(", description=\"") + op.description + wxT("\""); - req += wxT(", category='") + op.category + wxT("'"); - if (op.fix_cost) - req += wxT(", fix_cost='1'"); - else - req += wxT(", fix_cost='0'"); - if (op.checked) - req += wxT(", checked='1'"); - else - req += wxT(", checked='0'"); - req += wxT(", transfert='") + op.transfert + wxT("'"); - if (op.meta) - req += wxT(", meta='1'"); - else - req += wxT(", meta='0'"); - if (op._virtual) - req += wxT(", virtual='1'"); - else - req += wxT(", virtual='0'"); - req += wxT(", formula='") + op.formula + wxT("'"); - req += wxT(" WHERE id='") + op.id + wxT("'"); + req = "UPDATE operation SET parent='%1', account='%2', year='%3'n month='%4', day='%5', amount='%6', description=\"%7\", category='%8'" ; + req = req.arg((op.parent) ?: "", op.account, op.year, op.month, op.day, DoubleToString(op.amount), op.description, op.category); + req += "fix_cost='%1', checked='%2', transfert='%3', meta='%4', virtual='%5', formula='%6' WHERE id='%7'"; + req = req.arg(op.fix_cost, op.checked, (op.transfert) ?: "", op.meta, op._virtual, op.formula, op.id); EXECUTE_SQL_UPDATE(req, ); @@ -604,53 +572,31 @@ void Database::UpdateOperation(User* user, Operation& op, bool checkTransfert) wxString Database::AddOperation(User* user, Operation& op, bool checkTransfert) { - wxString req, res; - wxSQLite3ResultSet set; + QString req; + QSqlRecord set; + QSqlQuery query; ESCAPE_CHARS(op.description); - req = wxT("INSERT INTO operation ('user', 'parent', 'account', 'year', 'month', 'day', 'amount', 'description', 'category', 'fix_cost', 'formula', 'transfert', 'meta', 'virtual') VALUES ('") ; - req += user->_id + wxT("'"); - req += wxT(", '") + op.parent + wxT("'"); - req += wxT(", '") + op.account + wxT("'"); - req += wxT(", '") + wxString::Format(wxT("%d"), op.year) + wxT("'"); - req += wxT(", '") + wxString::Format(wxT("%d"), op.month) + wxT("'"); - req += wxT(", '") + wxString::Format(wxT("%d"), op.day) + wxT("'"); - req += wxT(", '") + DoubleToString(op.amount) + wxT("'"); - req += wxT(", \"") + op.description + wxT("\""); - req += wxT(", '") + op.category + wxT("'"); - if (op.fix_cost) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - req += wxT(", '") + op.formula + wxT("'"); - req += wxT(", '") + op.transfert + wxT("'"); - if (op.meta) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - if (op._virtual) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - req += wxT(")"); + req = "INSERT INTO operation ('user', 'parent', 'account', 'year', 'month', 'day', 'amount', 'description', 'category', 'fix_cost', 'formula', 'transfert', 'meta', 'virtual') VALUES ('%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8'" ; + req = req.arg(user->_id, (op.parent) ?: "", op.account, op.year, op.month, op.day, DoubleToString(op.amount), op.description); + req += ", '%1', '%2', '%3', '%4', '%5', '%6')"; + req = req.arg(op.category, op.fix_cost, op.formula, (op.transfert) ?: "", op.meta, op._virtual); - EXECUTE_SQL_UPDATE(req, wxT("0")); + EXECUTE_SQL_UPDATE(req, 0); - res = _db.GetLastRowId().ToString(); - - op.id = res; + op.id = query.lastInsertId().toInt(); if (checkTransfert) LinkOrUnlinkOperation(user, op); - return res; + return op.id; } void Database::DeleteOperation(User* user, Operation& op) { - wxString req; - req = wxT("DELETE FROM operation WHERE id='") + op.id + wxT("'"); + QSqlQuery query; + QString req = QString("DELETE FROM operation WHERE id='%1'").arg(op.id); EXECUTE_SQL_UPDATE(req, ); @@ -659,20 +605,20 @@ void Database::DeleteOperation(User* user, Operation& op) void Database::DeleteOperations(User* user, int month, int year) { - wxString req; + QString req; std::vector::iterator it; it = user->_accounts.begin(); - req = wxT("DELETE FROM account_amount WHERE account IN('") + it->id; + req = "DELETE FROM account_amount WHERE account IN('" + QString::Number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += "', '" + QString::Number(it->id) ; } - req += wxT("')"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), year) + wxT("'"); + req += "')"; + req += " AND year='" + QString::Number(year) + "'"; if (month != -1) - req += wxT(" AND month='") + wxString::Format(wxT("%d"), month) + wxT("'"); + req += " AND month='" + QString::Number(month) + "'"; EXECUTE_SQL_UPDATE(req, ); @@ -681,46 +627,34 @@ void Database::DeleteOperations(User* user, int month, int year) it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += "', '" + QString::Number(it->id) ; } - req += wxT("')"); - req += wxT(" OR user='") + user->_id + wxT("')"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), year) + wxT("'"); + req += "')"; + req += " OR user='" + QString::Number(user->_id) + "')"; + req += " AND year='" + QString::Number(year) + "'"; if (month != -1) - req += wxT(" AND month='") + wxString::Format(wxT("%d"), month) + wxT("'"); + req += " AND month='" + QString::Number(month) + "'"; EXECUTE_SQL_UPDATE(req, ); } -bool Database::LoadOperation(User* user, const wxString& id) +bool Database::LoadOperation(User* user, int id) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; bool ret = false; std::vector::iterator it; + QSqlQuery query; - req = wxT("SELECT * FROM operation WHERE id='") + id + wxT("'"); + req = QString("SELECT * FROM operation WHERE id='%1'").arg(id); - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(req, false); - if (set.NextRow()) + if (query.next()) { Operation op; - op.id = set.GetAsString(wxT("id")); - op.parent = set.GetAsString(wxT("parent")); - op.account = set.GetAsString(wxT("account")); - op.day = set.GetInt(wxT("day")); - op.month = set.GetInt(wxT("monthpp")); - op.year = set.GetInt(wxT("year")); - op.amount = set.GetDouble(wxT("amount")); - op.description = set.GetAsString(wxT("description")); - op.category = set.GetAsString(wxT("category")); - op.fix_cost = set.GetBool(wxT("fix_cost")); - op.checked = set.GetBool(wxT("checked")); - op.transfert = set.GetAsString(wxT("transfert")); - op.formula = set.GetAsString(wxT("formula")); - op.meta = set.GetBool(wxT("meta")); - op._virtual = set.GetBool(wxT("virtual")); + set = query.record(); + fillOperation(&op, set); if (user->_operations[op.year]) { @@ -751,167 +685,130 @@ bool Database::LoadOperation(User* user, const wxString& id) } } - set.Finalize(); + query.clear(); return ret; } // We may not have access to all operations if we have a shared account -double Database::MetaAmount(const wxString& id) +double Database::MetaAmount(int id) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; double res = 0.0; + QSqlQuery query; - req = wxT("SELECT SUM(amount) as amount FROM operation WHERE parent='") + id + wxT("'"); + req = QString("SELECT SUM(amount) as amount FROM operation WHERE parent='%1'").arg(id); - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(req, false); - if (set.NextRow()) - res = set.GetDouble(wxT("amount")); - - set.Finalize(); + if (query.next()) + { + set = query.record(); + res = set.value("amount").toDouble(); + } + + query.clear(); return res; } // Idem -double Database::MetaPositiveAmount(const wxString& id) +double Database::MetaPositiveAmount(int id) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; double res = 0.0; + QSqlQuery query; - req = wxT("SELECT SUM(amount) as amount FROM operation WHERE amount > 0 AND parent='") + id + wxT("'"); + req = QString("SELECT SUM(amount) as amount FROM operation WHERE amount > 0 AND parent='%1'").arg(id); - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(req, false); - if (set.NextRow()) - res = set.GetDouble(wxT("amount")); + if (query.next()) + { + set = query.record(); + res = set.value("amount").toDouble(); + } - set.Finalize(); + query.clear(); return res; } -void Database::SetAccountAmount(const wxString& accountId, int month, int year, double amount) +void Database::SetAccountAmount(int accountId, int month, int year, double amount) { - wxString req; - req = wxT("UPDATE account_amount SET ") ; - req += wxT("amount='") + DoubleToString(amount) + wxT("'"); - req += wxT(" WHERE account='") + accountId + wxT("'"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), year) + wxT("'"); - req += wxT(" AND month='") + wxString::Format(wxT("%d"), month) + wxT("'"); + QString req; + QSqlQuery query; - try + req = QString("UPDATE account_amount SET amount='%1' WHERE account='%2' AND month='%3' AND year='%4'"). + arg(DoubleToString(amount), accountId, month, year); + + if (!query.exec(req, _db)) { - if (!_db.ExecuteUpdate(req)) - { - req = wxT("INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES ('") ; - req += accountId + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), year) + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), month) + wxT("'"); - req += wxT(" ,'") + DoubleToString(amount) + wxT("'"); - req += wxT(")"); - EXECUTE_SQL_UPDATE(req, ); - } - } - catch (wxSQLite3Exception e) - { - std::cerr << req.mb_str() << "\n" ; - std::cerr << e.GetMessage().mb_str() << "\n" ; - return ; + req = "INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES ('%1', '%2', '%3', '%4')" ; + req = req.arg(accountId, year, month, DoubleToString(amount)); + EXECUTE_SQL_UPDATE(req, ); } } wxString Database::AddAccount(User* user, Account& ac) { - wxString req; + QString req; - req = wxT("INSERT INTO account ('user', 'name', 'number', 'shared', 'blocked', 'default_account', 'virtual') VALUES ('") ; - req += user->_id + wxT("'"); - req += wxT(", '") + ac.name + wxT("'"); - req += wxT(", '") + ac.number + wxT("'"); - if (ac.shared) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - if (ac.blocked) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - if (ac._default) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - if (ac._virtual) - req += wxT(", '1'") ; - else - req += wxT(", '0'") ; - req += wxT(")"); + req = "INSERT INTO account ('user', 'name', 'number', 'shared', 'blocked', 'default_account', 'virtual') VALUES " ; + req += "('%1', '%2', '%3', '%4', '%5', '%6', '%7')"; + req = req.arg(user->_id, ac.name, ac.number, ac.shared, ac.blocked, ac._default, ac._virtual); EXECUTE_SQL_UPDATE(req, wxT("0")); - return _db.GetLastRowId().ToString(); + return query.lastInsertId().toInt(); } void Database::UpdateAccount(Account& ac) { - wxString req; - req = wxT("UPDATE account SET ") ; - req += wxT("name='") + ac.name + wxT("'"); - req += wxT(", number='") + ac.number + wxT("'"); - if (ac.shared) - req += wxT(", shared='1'"); - else - req += wxT(", shared='0'"); - if (ac.blocked) - req += wxT(", blocked='1'"); - else - req += wxT(", blocked='0'"); - if (ac._default) - req += wxT(", default_account='1'"); - else - req += wxT(", default_account='0'"); - if (ac._virtual) - req += wxT(", virtual='1'"); - else - req += wxT(", virtual='0'"); - req += wxT(" WHERE id='") + ac.id + wxT("'"); + QString req; + + req = "UPDATE account SET name='%1', number='%2', shared='%3', blocked='%4', default_account='%5', virtual='%6' WHERE id='%7'" ; + req = req.arg(ac.name, ac.number, ac.shared, ac.blocked, ac._default, ac._virtual, ac.id); EXECUTE_SQL_UPDATE(req, ); + query.clear(); + if (!ac.shared && ac.is_owner) { - req = wxT("DELETE FROM shared_account WHERE account='") + ac.id + wxT("'"); + req = QString("DELETE FROM shared_account WHERE account='%1'").arg(ac.id); EXECUTE_SQL_UPDATE(req, ); } } -void Database::DeleteAccount(User* user, Account& ac, const wxString& replacement) +void Database::DeleteAccount(User* user, Account& ac, int replacement) { - wxString req; + QString req; if (ac.is_owner) { if (ac.shared) { - req = wxT("DELETE FROM shared_account WHERE account='") + ac.id + wxT("'"); + req = QString("DELETE FROM shared_account WHERE account='%1'").arg(ac.id); EXECUTE_SQL_UPDATE(req, ); + + query.clear(); } - req = wxT("DELETE FROM account WHERE id='") + ac.id + wxT("'"); + + req = QString("DELETE FROM account WHERE id='%1'").arg(ac.id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("DELETE FROM account_amount WHERE account='") + ac.id + wxT("'"); + req = QString("DELETE FROM account_amount WHERE account='%1'").arg(ac.id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("UPDATE operation SET account='") + replacement + wxT("'"); + req = QString("UPDATE operation SET account='%1' WHERE account='%2'").arg(replacement, ac.id); // req += wxT(", transfert='0'"); - req += wxT(" WHERE account='") + ac.id + wxT("'"); EXECUTE_SQL_UPDATE(req, ); } @@ -919,16 +816,21 @@ void Database::DeleteAccount(User* user, Account& ac, const wxString& replacemen RemoveSharedAccount(ac, user->_id); } -void Database::AddSharedAccount(Account& ac, const wxString& granted) +void Database::AddSharedAccount(Account& ac, const std::string& granted) { - wxString req; - wxSQLite3ResultSet set; + QString req; + QSqlRecord set; + QSqlQuery query; - req = wxT("SELECT id FROM user WHERE name='") + granted + wxT("'"); + req = QString("SELECT id FROM user WHERE name='%1'").arg(granted); - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - req = wxT("INSERT INTO shared_account ('account', 'user') VALUES ('") + ac.id + wxT("', '") + set.GetAsString(wxT("id")) + wxT("')"); + query.next(); + + set = query.record(); + + req = QString("INSERT INTO shared_account ('account', 'user') VALUES ('%1', '%2')").arg(ac.id, set.value("id").toString().toStdString()); EXECUTE_SQL_UPDATE(req, ); @@ -939,20 +841,25 @@ void Database::AddSharedAccount(Account& ac, const wxString& granted) } } -void Database::RemoveSharedAccount(Account& ac, const wxString& granted) +void Database::RemoveSharedAccount(Account& ac, const std::string& granted) { - wxString req; - wxSQLite3ResultSet set; + QString req; + QSqlRecord set; + QSqlQuery query; - req = wxT("DELETE FROM shared_account WHERE user='") + granted + wxT("' AND account='") + ac.id + wxT("'"); + req = QString("DELETE FROM shared_account WHERE user='%1' AND account='%2'").arg(granted, ac.id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("SELECT COUNT(user) AS cnt FROM shared_account WHERE account='") + ac.id + wxT("'"); + req = QString("SELECT COUNT(user) AS cnt FROM shared_account WHERE account='%1'").arg(ac.id); - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - if (!set.GetInt(wxT("cnt"))) + query.next(); + + set =query.record(); + + if (!set.value("cnt").toInt()) { ac.shared = false; UpdateAccount(ac); @@ -962,7 +869,7 @@ void Database::RemoveSharedAccount(Account& ac, const wxString& granted) wxString Database::AddCategory(User* user, Category& category) { - wxString req; + QString req; wxString backcolor, forecolor; backcolor = wxT("#") ; @@ -976,17 +883,17 @@ wxString Database::AddCategory(User* user, Category& category) forecolor += wxString::Format(wxT("%02X"), category.forecolor.Blue()); req = wxT("INSERT INTO category ('user', 'parent', 'name', 'backcolor', 'forecolor', 'font', 'fix_cost') VALUES ('") ; - req += user->_id + wxT("'"); - req += wxT(", '") + category.parent + wxT("'"); - req += wxT(", '") + category.name + wxT("'"); - req += wxT(", '") + backcolor + wxT("'"); - req += wxT(", '") + forecolor + wxT("'"); - req += wxT(", '") + category.font + wxT("'"); + req += user->_id + "'"; + req += ", '" + category.parent + "'"; + req += ", '" + category.name + "'"; + req += ", '" + backcolor + "'"; + req += ", '" + forecolor + "'"; + req += ", '" + category.font + "'"; if (category.fix_cost) - req += wxT(", '1'"); + req += ", '1'"; else - req += wxT(", '0'"); - req += wxT(")"); + req += ", '0'"; + req += ")"; EXECUTE_SQL_UPDATE(req, wxT("0")); @@ -995,7 +902,7 @@ wxString Database::AddCategory(User* user, Category& category) void Database::UpdateCategory(Category& category) { - wxString req; + QString req; wxString backcolor, forecolor; backcolor = wxT("#") ; @@ -1009,83 +916,75 @@ void Database::UpdateCategory(Category& category) forecolor += wxString::Format(wxT("%02X"), category.forecolor.Blue()); req = wxT("UPDATE category SET") ; - req += wxT(" parent='") + category.parent + wxT("'"); - req += wxT(", name='") + category.name + wxT("'"); - req += wxT(", backcolor='") + backcolor + wxT("'"); - req += wxT(", forecolor='") + forecolor + wxT("'"); - req += wxT(", font='") + category.font + wxT("'"); + req += wxT(" parent='") + category.parent + "'"; + req += wxT(", name='") + category.name + "'"; + req += wxT(", backcolor='") + backcolor + "'"; + req += wxT(", forecolor='") + forecolor + "'"; + req += wxT(", font='") + category.font + "'"; if (category.fix_cost) req += wxT(", fix_cost='1'"); else req += wxT(", fix_cost='0'"); - req += wxT(" WHERE id='") + category.id + wxT("'"); + req += wxT(" WHERE id='") + category.id + "'"; EXECUTE_SQL_UPDATE(req, ); } -void Database::DeleteCategory(User* user, Category& category, const wxString& replacement) +void Database::DeleteCategory(User* user, Category& category, int replacement) { - wxString req; + QString req; - req = wxT("DELETE FROM category WHERE id='") + category.id + wxT("'"); + req = QString("DELETE FROM category WHERE id='%1'").arg(category.id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("UPDATE category SET") ; - req += wxT(" parent='0'"); - req += wxT(" WHERE parent='") + category.id + wxT("'"); + req = QString("UPDATE category SET parent='' WHERE parent='%1'").arg(category.id) ; EXECUTE_SQL_UPDATE(req, ); - req = wxT("UPDATE operation SET category='") + replacement + wxT("'"); - req += wxT(" WHERE category='") + category.id + wxT("'"); - req += wxT(" AND user='") + user->_id + wxT("'"); + req = QString("UPDATE operation SET category='%1' WHERE category='%2' AND user='%3'").arg(replacement, category.id, user->_id); EXECUTE_SQL_UPDATE(req, ); if (replacement == user->_categories[0].id) { - req = wxT("UPDATE operation SET fix_cost='1'"); - req += wxT(" WHERE category='") + replacement + wxT("'"); + req = QString("UPDATE operation SET fix_cost='1' WHERE category='%1'").arg(replacement); EXECUTE_SQL_UPDATE(req, ); } } -bool Database::LoadCategory(const wxString& id, const wxString& name, Category& category) +bool Database::LoadCategory(int id, const std::string& name, Category& category) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; + QSqlQuery query; bool ret = false ; - if (id.Length()) - req = wxT("SELECT * FROM category WHERE id='") + id + wxT("'"); + if (id) + req = QString("SELECT * FROM category WHERE id='%1'").arg(id); else - req = wxT("SELECT * FROM category WHERE name='") + name + wxT("'"); + req = QString("SELECT * FROM category WHERE name='%1'").arg(name); - EXECUTE_SQL_QUERY(req, set, false); + EXECUTE_SQL_QUERY(req, false); - if (set.NextRow()) + if (query.next()) { - category.id = set.GetAsString(wxT("id")); - category.parent = set.GetAsString(wxT("parent")); - category.name = set.GetAsString(wxT("name")); - category.backcolor = wxColour(set.GetAsString(wxT("backcolor"))); - category.forecolor = wxColour(set.GetAsString(wxT("forecolor"))); - category.font = set.GetAsString(wxT("font")); - category.fix_cost = set.GetBool(wxT("fix_cost")); + set = query.record(); + fillCategory(&category, set); ret = true; } - set.Finalize(); + query.clear(); return ret; } std::map > Database::GetAllOperations(User* user) { - wxString req, req2, reqUnion; - wxSQLite3ResultSet set, set2; + QString req, req2, reqUnion; + QSqlRecord set; + QSqlQuery query; std::vector::iterator it; std::map > res; int year; @@ -1093,64 +992,69 @@ std::map > Database::GetAllOperations(User* user) if (!user->_accounts.empty()) { it = user->_accounts.begin(); - req = wxT("SELECT DISTINCT year FROM account_amount WHERE account IN('") + it->id; + req = "SELECT DISTINCT year FROM account_amount WHERE account IN('" + QString::Number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += "', '" + QString::Number(it->id) ; } - req += wxT("')"); + req += "')"; it = user->_accounts.begin(); - req2 = wxT("SELECT DISTINCT year FROM operation WHERE account IN('") + it->id; + req2 = "SELECT DISTINCT year FROM operation WHERE account IN('" + QString::Number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req2 += wxT("', '") + it->id ; + req2 += "', '" + QString::Number(it->id) ; } - req2 += wxT("')"); - req2 += wxT(" OR user='") + user->_id + wxT("'"); - req2 += wxT(" ORDER BY year ASC"); + req2 += "')"; + req2 += " OR user='" + QString::Number(user->_id) + "'"; + req2 += " ORDER BY year ASC"; - reqUnion = req + wxT(" UNION ") + req2; - EXECUTE_SQL_QUERY(reqUnion, set, res); + reqUnion = req + " UNION " + req2; + EXECUTE_SQL_QUERY(reqUnion, res); - while (set.NextRow()) + while (query.next()) { - year = set.GetInt(wxT("year")); + set = query.record(); + + year = set.value("year").toInt(); it = user->_accounts.begin(); - req = wxT("SELECT DISTINCT month FROM account_amount WHERE account IN('") + it->id; + req = "SELECT DISTINCT month FROM account_amount WHERE account IN('" + QString::Number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req += wxT("', '") + it->id ; + req += "', '" + QString::Number(it->id) ; } - req += wxT("')"); - req += wxT(" AND year='") + set.GetAsString(wxT("year")) + wxT("'"); + req += "')"; + req += " AND year='" + QString::Number(year) + "'"; it = user->_accounts.begin(); - req2 = wxT("SELECT DISTINCT month FROM operation WHERE (account IN('") + it->id; + req2 = "SELECT DISTINCT month FROM operation WHERE (account IN('" + QString::Number(it->id); it++; for (;it != user->_accounts.end(); it++) { - req2 += wxT("', '") + it->id ; + req2 += "', '" + QString::Number(it->id) ; } - req2 += wxT("')"); - req2 += wxT(" OR user='") + user->_id + wxT("')"); - req2 += wxT(" AND year='") + set.GetAsString(wxT("year")) + wxT("'"); - req2 += wxT(" ORDER BY month ASC"); + req2 += "')"; + req2 += " OR user='" + QString::Number(user->_id) + "')"; + req2 += " AND year='" + QString::Number(year) + "'"; + req2 += " ORDER BY month ASC"; - reqUnion = req + wxT(" UNION ") + req2; - EXECUTE_SQL_QUERY(reqUnion, set2, res); + reqUnion = req + " UNION " + req2; + query.clear(); - while (set2.NextRow()) + EXECUTE_SQL_QUERY(reqUnion, res); + + while (query.next()) { - res[year].push_back(set2.GetInt(wxT("monthpp"))); + set = query.record(); + res[year].push_back(set.value("month").toInt()); } - set2.Finalize(); + query.clear(); } - set.Finalize(); + query.clear(); } return res; @@ -1159,20 +1063,18 @@ std::map > Database::GetAllOperations(User* user) void Database::GenerateMonth(User* user, int monthFrom, int yearFrom, int monthTo, int yearTo) { std::vector::iterator it; - wxString req; - wxSQLite3ResultSet set; + QString req; + QSqlRecord set; double amount; + QSqlQuery query; if (monthFrom == -1 || yearFrom == -1) { for (it = user->_accounts.begin(); it != user->_accounts.end(); it++) { - req = wxT("INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES ('") ; - req += it->id + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), yearTo) + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), monthTo) + wxT("'"); - req += wxT(" ,'0.0'"); - req += wxT(")"); + req = "INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES " ; + req += "('%1', '%2', '%3', '%4')"; + req = req.arg(it->id, yearTo, monthTo, 0.0); EXECUTE_SQL_UPDATE(req, ); } @@ -1182,88 +1084,83 @@ void Database::GenerateMonth(User* user, int monthFrom, int yearFrom, int monthT for (it = user->_accounts.begin(); it != user->_accounts.end(); it++) { amount = 0.0; - req = wxT("SELECT SUM(amount) AS total FROM operation WHERE") ; - req += wxT(" account='") + it->id + wxT("'"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), yearFrom) + wxT("'"); - req += wxT(" AND month='") + wxString::Format(wxT("%d"), monthFrom) + wxT("'"); - req += wxT(" AND meta='0'"); + req = "SELECT SUM(amount) AS total FROM operation WHERE account='%1' AND year='%2' AND month='%3' AND meta='0'" ; + req = req.arg(it->id, yearFrom, monthFrom); - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - if (set.NextRow()) - amount += set.GetDouble(wxT("total")); + if (query.next()) + { + set = query.record(); + amount += set.value("total").toDouble(); + } - req = wxT("SELECT amount FROM account_amount WHERE") ; - req += wxT(" account='") + it->id + wxT("'"); - req += wxT(" AND year='") + wxString::Format(wxT("%d"), yearFrom) + wxT("'"); - req += wxT(" AND month='") + wxString::Format(wxT("%d"), monthFrom) + wxT("'"); + query.clear(); - EXECUTE_SQL_QUERY(req, set, ); + req = "SELECT amount FROM account_amount WHERE account='%1' AND year='%2' AND month='%3'" ; + req = req.arg(it->id, yearFrom, monthFrom); - if (set.NextRow()) - amount += set.GetDouble(wxT("amount")); + EXECUTE_SQL_QUERY(req, ); - req = wxT("INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES ('") ; - req += it->id + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), yearTo) + wxT("'"); - req += wxT(" ,'") + wxString::Format(wxT("%d"), monthTo) + wxT("'"); - req += wxT(" ,'") + DoubleToString(amount) + wxT("'"); - req += wxT(")"); + if (query.next()) + { + set = query.record(); + amount += set.value("amount").toDouble(); + } + + query.clear(); + + req = "INSERT INTO account_amount ('account', 'year', 'month', 'amount') VALUES " ; + req += "('%1', '%2', '%3', '%4')"; + req = req.arg(it->id, yearTo, monthTo, DoubleToString(amount)); EXECUTE_SQL_UPDATE(req, ); } } -void Database::ChangePassword(User* user, const wxString& password) +void Database::ChangePassword(User* user, const std::string& password) { - wxString req; + QString req; - req = wxT("UPDATE user SET ") ; - req += wxT("password='") + HashPassword(password) + wxT("'"); - req += wxT(" WHERE name='") + user->_name + wxT("'"); + req = QString("UPDATE user SET password='%1' WHERE name='%2'").arg(HashPassword(password), user->_name) ; EXECUTE_SQL_UPDATE(req, ); } -bool Database::UserExists(const wxString& name) +bool Database::UserExists(const std::string& name) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QString req; bool res=false; - req = wxT("SELECT name FROM user WHERE name='") + name + wxT("'") ; + req = QString("SELECT name FROM user WHERE name='%1'").arg(name); - EXECUTE_SQL_QUERY(req , set, false); + EXECUTE_SQL_QUERY(req, false); - if (set.NextRow()) + if (query.next()) res = true; else res = false; - set.Finalize(); + query.clear(); return res; } -void Database::ChangeName(User* user, const wxString& name) +void Database::ChangeName(User* user, const std::string& name) { - wxString req; + QString req; - req = wxT("UPDATE user SET ") ; - req += wxT("name='") + name + wxT("'"); - req += wxT(" WHERE name='") + user->_name + wxT("'"); + req = QString("UPDATE user SET name='%1' WHERE name='%2'").arg(name, user->_name) ; EXECUTE_SQL_UPDATE(req, ); } -void Database::NewUser(const wxString& name) +void Database::NewUser(const std::string& name) { - wxString req; + QString req; - req = wxT("INSERT INTO user ('name', 'password') VALUES ('") ; - req += name + wxT("'"); - req += wxT(", '") + HashPassword(wxT("")) + wxT("'"); - req += wxT(")"); + req = QString("INSERT INTO user ('name', 'password') VALUES ('%1', '%2')").arg(name, HashPassword("")) ; EXECUTE_SQL_UPDATE(req, ); } @@ -1273,102 +1170,89 @@ void Database::NewUser(const wxString& name) */ void Database::KillMe(User* user) { - wxString req; + QString req; std::vector::iterator it; - req = wxT("DELETE FROM preference WHERE user='") + user->_id + wxT("'"); + req = QString("DELETE FROM preference WHERE user='%1'").arg(user->_id); EXECUTE_SQL_UPDATE(req, ); if (!user->_accounts.empty()) { for (it = user->_accounts.begin(); it != user->_accounts.end(); it++) - DeleteAccount(user, *it, wxT("0")); + DeleteAccount(user, *it, 0); it = user->_accounts.begin(); if (it->is_owner) - req = wxT("DELETE FROM operation WHERE account IN('") + it->id; + req = wxT("DELETE FROM operation WHERE account IN('") + QString::Number(it->id); else req = wxT("DELETE FROM operation WHERE account IN('-1"); it++; for (;it != user->_accounts.end(); it++) { if (it->is_owner) - req += wxT("', '") + it->id ; + req += "', '" + QString::Number(it->id) ; } - req += wxT("')"); - req += wxT(" OR (user='") + user->_id + wxT("' AND account='')"); + req += "')"; + req += " OR (user='" + QString::Number(user->_id) + "' AND account='')"; EXECUTE_SQL_UPDATE(req, ); } - req = wxT("DELETE FROM category WHERE user='") + user->_id + wxT("'"); + req = QString("DELETE FROM category WHERE user='%1'").arg(user->_id); EXECUTE_SQL_UPDATE(req, ); - req = wxT("DELETE FROM user WHERE id='") + user->_id + wxT("'"); + req = QString("DELETE FROM user WHERE id='%1'").arg(user->_id); EXECUTE_SQL_UPDATE(req, ); } -void Database::UpdatePreference(User* user, const wxString& preference) +void Database::UpdatePreference(User* user, const std::string& preference) { - wxString req; + QString req; wxString value = user->_preferences[preference]; + QSqlQuery query; - req = wxT("UPDATE preference SET ") ; - req += wxT("name='") + preference + wxT("'"); - req += wxT(", value='") + value + wxT("'"); - req += wxT(" WHERE user='") + user->_id + wxT("'"); + req = QString("UPDATE preference SET name='%1', value='%2' WHERE user='%3'").arg(preference, value, user->_id) ; - try + if (!query.exec(req, _db)) { - if (!_db.ExecuteUpdate(req)) - { - req = wxT("INSERT INTO preference ('user', 'name', 'value') VALUES ('") ; - req += user->_id + wxT("'"); - req += wxT(" ,'") + preference + wxT("'"); - req += wxT(" ,'") + value + wxT("'"); - req += wxT(")"); - EXECUTE_SQL_UPDATE(req, ); - } - } - catch (wxSQLite3Exception e) - { - std::cerr << req.mb_str() << "\n" ; - std::cerr << e.GetMessage().mb_str() << "\n" ; - return ; + req = "INSERT INTO preference ('user', 'name', 'value') VALUES ('%1', '%2', '%3')" ; + req = req.arg(user->_id, preference, value); + EXECUTE_SQL_UPDATE(req, ); } } -std::vector* Database::Search(User* user, wxString* description, wxDateTime* dateFrom, wxDateTime* dateTo, - wxString* amountFrom, wxString* amountTo, - std::vector categories, int types, std::vector accounts, bool wildcards) +std::vector* Search(User* user, std::string* description, QDate* dateFrom, QDate* dateTo, + int* amountFrom, int* amountTo, + std::vector categories, int types, std::vector accounts, bool wildcards) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QSqlQuery query; + QString req; bool firstCond = false; std::vector::iterator it; std::vector::iterator accountIt; std::vector* res = new std::vector; int i; - wxString dayFrom, monthFrom, yearFrom; - wxString dayTo, monthTo, yearTo; - wxString desc; + QString dayFrom, monthFrom, yearFrom; + QString dayTo, monthTo, yearTo; + QString desc; if (dateFrom) { - dayFrom = wxString::Format(wxT("%d"), dateFrom->GetDay()-1); - monthFrom = wxString::Format(wxT("%d"), dateFrom->GetMonth()); - yearFrom = wxString::Format(wxT("%d"), dateFrom->GetYear()); + dayFrom = QString::Number(dateFrom->day()-1); + monthFrom = QString::Number(dateFrom->month()); + yearFrom = QString::Number(dateFrom->year()); } if (dateTo) { - dayTo = wxString::Format(wxT("%d"), dateTo->GetDay()-1); - monthTo = wxString::Format(wxT("%d"), dateTo->GetMonth()); - yearTo = wxString::Format(wxT("%d"), dateTo->GetYear()); + dayTo = QString::Number(dateTo->day()-1); + monthTo = QString::Number(dateTo->month()); + yearTo = QString::Number(dateTo->year()); } - req = wxT("SELECT * from operation WHERE "); + req = "SELECT * from operation WHERE "; if (description) { @@ -1377,56 +1261,56 @@ std::vector* Database::Search(User* user, wxString* description, wxDa ESCAPE_CHARS(desc); if (wildcards) - req += wxT("UPPER(description) LIKE UPPER('%") + desc + wxT("%')"); + req += "UPPER(description) LIKE UPPER('%" + desc + "%')"; else - req += wxT("description=\"") + desc + wxT("\""); + req += "description=\"" + desc + "\""; firstCond = true; } if (dateFrom) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; - req += wxT("("); - req += wxT("year >= ") + yearFrom ; - req += wxT(" AND (month > '") + monthFrom + wxT("' OR (month == '") + monthFrom + wxT("' AND day >= '") + dayFrom + wxT("')"); - req += wxT(" OR (month < '") + monthFrom + wxT("' AND year > '") + yearFrom + wxT("'))"); - req += wxT(")"); + if (firstCond) req += " AND " ; else firstCond = true; + req += "("; + req += "year >= " + yearFrom ; + req += " AND (month > '" + monthFrom + "' OR (month == '" + monthFrom + "' AND day >= '" + dayFrom + "')"; + req += " OR (month < '" + monthFrom + "' AND year > '" + yearFrom + "'))"; + req += ")"; } if (dateTo) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; - req += wxT("("); - req += wxT("year <= ") + yearTo ; - req += wxT(" AND (month < '") + monthTo + wxT("' OR (month == '") + monthTo + wxT("' AND day <= '") + dayTo + wxT("')"); - req += wxT(" OR (month > '") + monthTo + wxT("' AND year < '") + yearTo + wxT("'))"); - req += wxT(")"); + if (firstCond) req += " AND " ; else firstCond = true; + req += "("; + req += "year <= " + yearTo ; + req += " AND (month < '" + monthTo + "' OR (month == '" + monthTo + "' AND day <= '" + dayTo + "')"; + req += " OR (month > '" + monthTo + "' AND year < '" + yearTo + "'))"; + req += ")"; } if (amountFrom) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; - req += wxT("ABS(amount) >= ") + *amountFrom; + if (firstCond) req += " AND " ; else firstCond = true; + req += "ABS(amount) >= " + QString::Number(*amountFrom); } if (amountTo) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; - req += wxT("ABS(amount) <= ") + *amountTo; + if (firstCond) req += " AND " ; else firstCond = true; + req += "ABS(amount) <= " + QString::Number(*amountTo); } if (categories.size()) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; - req += wxT("category IN ('"); + if (firstCond) req += " AND " ; else firstCond = true; + req += "category IN ('"; it = categories.begin(); - req += *it; + req += QString::Number(*it); it++; for (; it != categories.end(); it++) - req += wxT("', '") + *it ; + req += "', '" + QString::Number(*it) ; - req += wxT("')"); + req += "')"; } if (types) @@ -1434,98 +1318,86 @@ std::vector* Database::Search(User* user, wxString* description, wxDa if (((types & FIX_OP) && !(types & NON_FIX_OP)) || (!(types & FIX_OP) && (types & NON_FIX_OP))) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; + if (firstCond) req += " AND " ; else firstCond = true; if (types & FIX_OP) - req += wxT(" fix_cost='1'"); + req += " fix_cost='1'"; else - req += wxT(" fix_cost='0'"); + req += " fix_cost='0'"; } if (((types & CHECKED_OP) && !(types & NOT_CHECKED_OP)) || (!(types & CHECKED_OP) && (types & NOT_CHECKED_OP))) { - if (firstCond) req += wxT(" AND ") ; else firstCond = true; + if (firstCond) req += " AND " ; else firstCond = true; if (types & CHECKED_OP) - req += wxT(" checked='1'"); + req += " checked='1'"; else - req += wxT(" checked='0'"); + req += " checked='0'"; } } - if (firstCond) req += wxT(" AND ") ; else firstCond = true; + if (firstCond) req += " AND " ; else firstCond = true; if (accounts.size()) { - req += wxT("(account IN ('"); + req += "(account IN ('"; it = accounts.begin(); - req += *it; + req += QString::Number(*it); it++; for (; it != accounts.end(); it++) - req += wxT("', '") + *it ; + req += "', '" + QString::Number(*it) ; - req += wxT("'))"); - // req += wxT(" OR user ='") + user->_id + wxT("')"); + req += "'))"; + // req += wxT(" OR user ='") + user->_id + "')"; } else { - req += wxT("(account IN ('"); + req += "(account IN ('"; accountIt = user->_accounts.begin(); - req += accountIt->id; + req += accountQString::Number(it->id); accountIt++; for (;accountIt != user->_accounts.end(); accountIt++) { - req += wxT("', '") + accountIt->id ; + req += "', '" + accountQString::Number(it->id) ; } - req += wxT("')"); - req += wxT(" OR user ='") + user->_id + wxT("')"); + req += "')"; + req += " OR user ='" + QString::Number(user->_id) + "')"; } - req += wxT(" ORDER BY year ") ; + req += " ORDER BY year " ; req += user->_preferences[wxT("operation_order")] ; - req += wxT(", month ") + user->_preferences[wxT("operation_order")] ; - req += wxT(", day ") + user->_preferences[wxT("operation_order")] ; + req += ", month " + user->_preferences[wxT("operation_order")] ; + req += ", day " + user->_preferences[wxT("operation_order")] ; // std::cout << req.mb_str() << "\n"; - EXECUTE_SQL_QUERY(req, set, res); + EXECUTE_SQL_QUERY(req, res); - while (set.NextRow()) + while (query.next()) { Operation op; - op.id = set.GetAsString(wxT("id")); - op.parent = set.GetAsString(wxT("parent")); - op.account = set.GetAsString(wxT("account")); - op.day = set.GetInt(wxT("day")); - op.month = set.GetInt(wxT("monthpp")); - op.year = set.GetInt(wxT("year")); - op.amount = set.GetDouble(wxT("amount")); - op.description = set.GetAsString(wxT("description")); - op.category = set.GetAsString(wxT("category")); - op.fix_cost = set.GetBool(wxT("fix_cost")); - op.checked = set.GetBool(wxT("checked")); - op.transfert = set.GetAsString(wxT("transfert")); - op.formula = set.GetAsString(wxT("formula")); - op.meta = set.GetBool(wxT("meta")); - op._virtual = set.GetBool(wxT("virtual")); + set = query.record(); + fillOperation(&op, set); res->push_back(op); } for(i=0; i < (int)res->size(); i++) - if ((*res)[i].parent.Length()) + if ((*res)[i].parent) user->Group(res, (*res)[i]); return res; } -void Database::GetStats(User* user, const wxString& monthFrom, const wxString& yearFrom, const wxString& monthTo, - const wxString& yearTo, std::map > >* accountAmounts, - std::map* categories) +void GetStats(User* user, int monthFrom, int yearFrom, int monthTo, + int yearTo, std::map > >* accountAmounts, + std::map* categories) { - wxSQLite3ResultSet set; - wxString req, req2; + QSqlRecord set; + QSqlQuery query; + QString req, req2; std::vector::iterator accountIt; std::vector::iterator categoryIt; @@ -1535,17 +1407,18 @@ void Database::GetStats(User* user, const wxString& monthFrom, const wxString& y { for (accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); accountIt++) { - req = wxT("SELECT month, year, amount FROM account_amount WHERE account ='") + accountIt->id + wxT("'"); - req += wxT(" AND (year > '") + yearFrom + wxT("' OR (year == '") + yearFrom + wxT("' AND month >= '") + monthFrom + wxT("'))"); - req += wxT(" AND (year < '") + yearTo + wxT("' OR (year == '") + yearTo + wxT("' AND month <= '") + monthTo + wxT("'))"); + req = "SELECT month, year, amount FROM account_amount WHERE account ='" + QString::Number(accountIt->id) + "'"; + req += " AND (year > '" + QString::Number(yearFrom) + "' OR (year == '" + QString::Number(yearFrom) + "' AND month >= '" + QString::Number(monthFrom) + "'))"; + req += " AND (year < '" + QString::Number(yearTo) + "' OR (year == '" + QString::Number(yearTo) + "' AND month <= '" + QString::Number(monthTo) + "'))"; - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - while (set.NextRow()) + while (query.next()) { - (*accountAmounts)[accountIt->id][set.GetInt(wxT("year"))][set.GetInt(wxT("monthpp"))] = set.GetInt(wxT("amount")); + set = query.record(); + (*accountAmounts)[accountIt->id][set.value("year").toInt()][set.value("month").toInt()] = set.value("amount").toDouble(); } - set.Finalize(); + query.clear(); } } @@ -1553,55 +1426,58 @@ void Database::GetStats(User* user, const wxString& monthFrom, const wxString& y { for (categoryIt = user->_categories.begin(); categoryIt != user->_categories.end(); categoryIt++) { - req = wxT("SELECT SUM(amount) as amount FROM operation AS o1 WHERE category='") + categoryIt->id + wxT("'"); + req = "SELECT SUM(amount) as amount FROM operation AS o1 WHERE category='" + QString::Number(categoryIt->id) + "'"; accountIt = user->_accounts.begin(); - req += wxT(" AND (account IN('") + accountIt->id; + req += " AND (account IN('" + QString::Number(accountIt->id); accountIt++; for (;accountIt != user->_accounts.end(); accountIt++) { - req += wxT("', '") + accountIt->id ; + req += "', '" + QString::Number(accountIt->id) ; } - req += wxT("')"); - req += wxT(" OR user='") + user->_id + wxT("')"); + req += "')"; + req += " OR user='" + QString::Number(user->_id) + "')"; - req += wxT(" AND (year > '") + yearFrom + wxT("' OR (year == '") + yearFrom + wxT("' AND month >= '") + monthFrom + wxT("'))"); - req += wxT(" AND (year < '") + yearTo + wxT("' OR (year == '") + yearTo + wxT("' AND month <= '") + monthTo + wxT("'))"); - req += wxT(" AND meta='0'"); + req += " AND (year > '" + QString::Number(yearFrom) + "' OR (year == '" + QString::Number(yearFrom) + "' AND month >= '" + QString::Number(monthFrom) + "'))"; + req += " AND (year < '" + QString::Number(yearTo) + "' OR (year == '" + QString::Number(yearTo) + "' AND month <= '" + QString::Number(monthTo) + "'))"; + req += " AND meta='0'"; - req2 = req + wxT(" AND (transfert='' OR transfert IS 0)"); - req2 += wxT(" AND amount < 0"); + req2 = req + " AND (transfert='' OR transfert IS 0)"; + req2 += " AND amount < 0"; - EXECUTE_SQL_QUERY(req2, set, ); + EXECUTE_SQL_QUERY(req2, ); - if (set.NextRow()) + if (query.next()) { - (*categories)[categoryIt->id] = -set.GetDouble(wxT("amount")); + set = query.record(); + (*categories)[categoryIt->id] = -set.value("amount").toDouble(); } - set.Finalize(); + query.clear(); // Transfert on blocked accounts must be computed - req2 = req + wxT(" AND transfert != ''"); - req2 = req + wxT(" AND (SELECT blocked FROM account WHERE id=o1.account)"); - req2 += wxT(" AND amount > 0"); + req2 = req + " AND transfert != ''"; + req2 += " AND (SELECT blocked FROM account WHERE id=o1.account)"; + req2 += " AND amount > 0"; - EXECUTE_SQL_QUERY(req2, set, ); + EXECUTE_SQL_QUERY(req2, ); - if (set.NextRow()) + if (query.next()) { - (*categories)[categoryIt->id] += set.GetDouble(wxT("amount")); + set = query.record(); + (*categories)[categoryIt->id] += set.value("amount").toDouble(); } - set.Finalize(); + query.clear(); } } } } -void Database::GetMonthStats(User* user, const wxString& month, const wxString& year, int nbDays, - std::map >* operations, - std::map* categories) +void GetMonthStats(User* user, int month, int year, int nbDays, + std::map >* operations, + std::map* categories) { - wxSQLite3ResultSet set; - wxString req; + QSqlRecord set; + QSqlQuery query; + QString req; std::vector::iterator accountIt; int previous_amount, previous_day, cur_day; @@ -1609,44 +1485,41 @@ void Database::GetMonthStats(User* user, const wxString& month, const wxString& { for (accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); accountIt++) { - req = wxT("SELECT amount FROM account_amount WHERE account ='") + accountIt->id + wxT("'"); - req += wxT(" AND year = '") + year + wxT("'"); - req += wxT(" AND month = '") + month + wxT("'"); + req = "SELECT amount FROM account_amount WHERE account ='%1' AND year='%2' AND month='%3'"; + req = req.arg(accountIt->id, year, month); - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); - while (set.NextRow()) + while (query.next()) { + set = query.record(); (*operations)[accountIt->id].clear(); - previous_amount = set.GetInt(wxT("amount")); + previous_amount = set.value("amount").toDouble(); } - set.Finalize(); + query.clear(); - req = wxT("SELECT day, amount FROM operation WHERE"); - req += wxT(" account = '") + accountIt->id + wxT("'"); - req += wxT(" AND year = '") + year + wxT("'"); - req += wxT(" AND month = '") + month + wxT("'"); - req += wxT(" AND meta='0'"); + req = "SELECT day, amount FROM operation WHERE account='%1' AND year='%2' AND month='%3' AND meta='0' ORDER BY day ASC"; + req = req.arg(accountIt->id, year, month); - req += wxT(" ORDER BY day ASC"); - - EXECUTE_SQL_QUERY(req, set, ); + EXECUTE_SQL_QUERY(req, ); cur_day = previous_day = -1; - while (set.NextRow()) + while (query.next()) { - cur_day = set.GetInt(wxT("day")); + set = query.record(); + + cur_day = set.value("day").toInt(); while (cur_day != previous_day) { (*operations)[accountIt->id].push_back(previous_amount); previous_day++; } - previous_amount += set.GetDouble(wxT("amount")); + previous_amount += set.value("amount").toDouble(); (*operations)[accountIt->id][cur_day] = previous_amount; } - set.Finalize(); + query.clear(); while (cur_day < nbDays) { @@ -1660,103 +1533,132 @@ void Database::GetMonthStats(User* user, const wxString& month, const wxString& GetStats(user, month, year, month, year, 0, categories) ; } -std::map* Database::GetNotChecked(User* user, int month, int year) +std::map* Database::GetNotChecked(User* user, int month, int year) { std::vector::iterator accountIt; - std::map* res = new std::map; - wxSQLite3ResultSet set; - wxString req; + std::map* res = new std::map; + QSqlRecord set; + QSqlQuery query; + QString req; for (accountIt = user->_accounts.begin() ;accountIt != user->_accounts.end(); accountIt++) { - req = wxT("SELECT SUM(amount) AS amount FROM operation WHERE account='") + accountIt->id + wxT("'"); - req += wxT(" AND checked='0'"); - req += wxT(" AND meta='0'"); - req += wxT(" AND (year < '") + wxString::Format(wxT("%d"), year) + wxT("'") ; - req += wxT(" OR (year == '") + wxString::Format(wxT("%d"), year) + wxT("'") ; - req += wxT(" AND month < '") + wxString::Format(wxT("%d"), month) + wxT("'") ; - req += wxT("))"); + req = "SELECT SUM(amount) AS amount FROM operation WHERE account='" + QString::Number(accountIt->id) + "'"; + req += " AND checked='0'"; + req += " AND meta='0'"; + req += " AND (year < '" + QString::Number(year) + "'" ; + req += " OR (year == '" + QString::Number(year) + "'" ; + req += " AND month < '" + QString::Number(month) + "'" ; + req += "))"; - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, delete res, delete res); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, delete res, delete res); - if (set.NextRow()) - (*res)[accountIt->id] = set.GetDouble(wxT("amount")); + if (query.next()) + { + set = query.record(); + (*res)[accountIt->id] = set.value("amount").toDouble(); + } + + query.clear(); } return res; } -std::map* Database::GetVirtualAmount(User* user, int month, int year) +std::map* Database::GetVirtualAmount(User* user, int month, int year) { std::vector::iterator accountIt; - std::map* res = new std::map; - wxSQLite3ResultSet set; - wxString req; + std::map* res = new std::map; + QSqlRecord set; + QSqlQuery query; + QString req; for (accountIt = user->_accounts.begin() ;accountIt != user->_accounts.end(); accountIt++) { - req = wxT("SELECT SUM(amount) AS amount FROM operation WHERE account='") + accountIt->id + wxT("'"); - req += wxT(" AND virtual='1'"); - req += wxT(" AND meta='0'"); - req += wxT(" AND (year < '") + wxString::Format(wxT("%d"), year) + wxT("'") ; - req += wxT(" OR (year == '") + wxString::Format(wxT("%d"), year) + wxT("'") ; - req += wxT(" AND month < '") + wxString::Format(wxT("%d"), month) + wxT("'") ; - req += wxT("))"); + req = "SELECT SUM(amount) AS amount FROM operation WHERE account='" + QString::Number(accountIt->id) + "'"; + req += " AND virtual='1'"; + req += " AND meta='0'"; + req += " AND (year < '" + QString::Number(year) + "'" ; + req += " OR (year == '" + QString::Number(year) + "'" ; + req += " AND month < '" + QString::Number(month) + "'" ; + req += "))"; - EXECUTE_SQL_QUERY_WITH_CODE(req, set, 0, delete res, delete res); + EXECUTE_SQL_QUERY_WITH_CODE(req, 0, delete res, delete res); - if (set.NextRow()) - (*res)[accountIt->id] = set.GetDouble(wxT("amount")); + if (query.next()) + { + set = query.record(); + (*res)[accountIt->id] = set.value("amount").toDouble(); + } + + query.clear(); } return res; } -std::map Database::getSharedAccountOwners(const wxString& account) +std::map Database::getSharedAccountOwners(int account) { - std::map res; - wxSQLite3ResultSet set, set2; - wxString req; + std::map res; + QSqlRecord set, set2; + QSqlQuery query; + QString req; - req = wxT("SELECT user FROM shared_account WHERE account='") + account + wxT("'"); + req = QString("SELECT user FROM shared_account WHERE account='%1'").arg(account); - EXECUTE_SQL_QUERY(req, set, res); + EXECUTE_SQL_QUERY(req, res); - while(set.NextRow()) + while(query.next()) { - req = wxT("SELECT name FROM user WHERE id='") + set.GetAsString(wxT("user")) + wxT("'"); + set = query.record(); - EXECUTE_SQL_QUERY(req, set2, res); + req = QString("SELECT name FROM user WHERE id='%1'").arg(set.value("user")); - res[set2.GetAsString(wxT("name"))] = set.GetAsString(wxT("user")); + query.clear(); + + EXECUTE_SQL_QUERY(req, res); + + set2 = query.record(); + + res[set2.value("name").toString().toStdString()] = set.value("user").toString().toStdString(); } return res; } -wxString Database::getSharedAccountOwner(const wxString& account) +std::string Database::getSharedAccountOwner(int account) { - wxSQLite3ResultSet set, set2; - wxString req; + QSqlRecord set ; + QSqlQuery query; + QString req; - req = wxT("SELECT user FROM account WHERE id='") + account + wxT("'"); + req = QString("SELECT user FROM account WHERE id='%1'").arg(account); - EXECUTE_SQL_QUERY(req, set, wxT("")); + EXECUTE_SQL_QUERY(req, ""); - while(set.NextRow()) + if (query.next()) { - req = wxT("SELECT name FROM user WHERE id='") + set.GetAsString(wxT("user")) + wxT("'"); + set = query.record(); - EXECUTE_SQL_QUERY(req, set2, wxT("")); + req = QString("SELECT name FROM user WHERE id='%1'").arg(set.value("user").toInt()); + + query.clear(); + + EXECUTE_SQL_QUERY(req, ""); + + set = query.record(); + + return set.value("name").toString().toStdString(); } - return set2.GetAsString(wxT("name")); + return ""; } void Database::UpdateImportPattern(User* user) { - std::map::iterator it; - wxString req, key; + std::map::iterator it; + QString req, key; + QSqlQuery query; for (it = user->_importPatterns.begin(); it != user->_importPatterns.end(); @@ -1766,31 +1668,15 @@ void Database::UpdateImportPattern(User* user) key = ImportEngine::RemoveUnused(it->first); - req = wxT("UPDATE import_pattern SET ") ; - req += wxT("pattern='") + it->second.pattern + wxT("'"); - req += wxT(", account='") + it->second.account + wxT("'"); - req += wxT(", category='") + it->second.category + wxT("'"); - req += wxT(" WHERE description='") + key + wxT("'"); + req = "UPDATE import_pattern SET pattern='%1', account='%2', category='%3' WHERE description='%4'" ; + req = req.arg(it->second.pattern, it->second.account, it->second.category, key); - try + if (!query.exec(req, _db)) { - if (!_db.ExecuteUpdate(req)) - { - req = wxT("INSERT INTO import_pattern ('user', 'description', 'pattern', 'account', 'category') VALUES ('") ; - req += user->_id + wxT("'"); - req += wxT(" ,'") + key + wxT("'"); - req += wxT(" ,'") + it->second.pattern + wxT("'"); - req += wxT(" ,'") + it->second.account + wxT("'"); - req += wxT(" ,'") + it->second.category + wxT("'"); - req += wxT(")"); - EXECUTE_SQL_UPDATE(req, ); - } - } - catch (wxSQLite3Exception e) - { - std::cerr << req.mb_str() << "\n" ; - std::cerr << e.GetMessage().mb_str() << "\n" ; - return ; + req = "INSERT INTO import_pattern ('user', 'description', 'pattern', 'account', 'category') VALUES " ; + req += "('%1', '%2', '%3', '%4', '%5')"; + req = req.arg(user->_id, key, it->second.pattern, it->second.account, it->second.category); + EXECUTE_SQL_UPDATE(req, ); } } } diff --git a/src/model/Database.hpp b/src/model/Database.hpp index 13113eb..79b114b 100644 --- a/src/model/Database.hpp +++ b/src/model/Database.hpp @@ -21,8 +21,9 @@ #define DATABASE_H #include -#include -#include + +#include +#include #include #include "model.hpp" @@ -40,40 +41,31 @@ // } #define EXECUTE_SQL_UPDATE_WITH_CODE(req, return_value, code_if_fail, code_if_syntax_fail) \ - do{ \ - try \ - { \ - _db.ExecuteUpdate(req); \ - } \ - catch (wxSQLite3Exception e) \ - { \ - wxMessageBox(_("Update failed !\n") + req, _("Error"), wxICON_ERROR | wxOK); \ - std::cerr << __FUNCTION__ << "\n" ; \ - std::cerr << req.mb_str() << "\n" ; \ - std::cerr << e.GetMessage().mb_str() << "\n" ; \ - code_if_fail; \ - return return_value; \ - } \ + do { \ + QSqlQuery query; \ + if (!query.exec(req)) \ + { \ + QMessageBox::critical(0, _("Error"), _("Update failed !\n") + req); \ + std::cerr << __FUNCTION__ << "\n" ; \ + std::cerr << req.toStdString() << "\n" ; \ + std::cerr << query.lastError().text().toStdString() << "\n" ; \ + code_if_fail; \ + return return_value; \ + } \ } while(0); -#define EXECUTE_SQL_QUERY_WITH_CODE(req, res, return_value, code_if_fail, code_if_syntax_fail) \ - do{ \ - try \ - { \ - res = _db.ExecuteQuery(req); \ - } \ - catch (wxSQLite3Exception e) \ - { \ - wxMessageBox(_("Query failed !\n") + req, _("Error"), wxICON_ERROR | wxOK); \ - std::cerr << __FUNCTION__ << "\n" ; \ - std::cerr << req.mb_str() << "\n" ; \ - std::cerr << e.GetMessage().mb_str() << "\n" ; \ - code_if_fail; \ - return return_value; \ - } \ - } while(0); +#define EXECUTE_SQL_QUERY_WITH_CODE(req, return_value, code_if_fail, code_if_syntax_fail) \ + if (!query.exec(req)) \ + { \ + QMessageBox::critical(0, _("Error"), _("Query failed !\n") + req); \ + std::cerr << __FUNCTION__ << "\n" ; \ + std::cerr << req.toStdString() << "\n" ; \ + std::cerr << query.lastError().text().toStdString() << "\n" ; \ + code_if_fail; \ + return return_value; \ + } \ -#define EXECUTE_SQL_QUERY(req, res, return_value) EXECUTE_SQL_QUERY_WITH_CODE(req, res, return_value, {}, {}) +#define EXECUTE_SQL_QUERY(req, return_value) EXECUTE_SQL_QUERY_WITH_CODE(req, return_value, {}, {}) #define EXECUTE_SQL_UPDATE(req, return_value) EXECUTE_SQL_UPDATE_WITH_CODE(req, return_value, {}, {}) @@ -83,8 +75,8 @@ class User; class Database { public: - static const int FIX_OP = 1;//(1 << 0); - static const int NON_FIX_OP = 2;//(1 << 1); + static const int FIX_OP = (1 << 0); + static const int NON_FIX_OP = (1 << 1); static const int CHECKED_OP = (1 << 2); static const int NOT_CHECKED_OP = (1 << 3); static const int ALL_OP = (~0); @@ -93,64 +85,64 @@ public: Database(const char* filename, KissCount* kiss); - std::list GetUsers(); - bool IsValidUser(const wxString& user, const wxString& password); + std::list GetUsers(); + bool IsValidUser(const QString& user, const QString& password); - User* LoadUser(const wxString& name); + User* LoadUser(const std::string& name); void LoadYear(User* user, int year); void UpdateOperation(User* user, Operation& op, bool checkTransfert=true); - wxString AddOperation(User* user, Operation& op, bool checkTransfert=true); + int AddOperation(User* user, Operation& op, bool checkTransfert=true); void DeleteOperation(User* user, Operation& op); void DeleteOperations(User* user, int month, int year); - bool LoadOperation(User* user, const wxString& id); - double MetaAmount(const wxString& id); - double MetaPositiveAmount(const wxString& id); + bool LoadOperation(User* user, int id); + double MetaAmount(int id); + double MetaPositiveAmount(int id); - double GetAccountAmount(const wxString& id, int month, int year); - void SetAccountAmount(const wxString& accountId, int month, int year, double amount); - double CalcAccountAmount(const wxString& id, int month, int year, bool* had_values); + double GetAccountAmount(int id, int month, int year); + void SetAccountAmount(int accountId, int month, int year, double amount); + double CalcAccountAmount(int id, int month, int year, bool* had_values); - wxString AddAccount(User* user, Account& ac); + int AddAccount(User* user, Account& ac); void UpdateAccount(Account& ac); - void DeleteAccount(User* user, Account& ac, const wxString& replacement); - void AddSharedAccount(Account& ac, const wxString& granted); - void RemoveSharedAccount(Account& ac, const wxString& granted); + void DeleteAccount(User* user, Account& ac, int replacement); + void AddSharedAccount(Account& ac, const std::string& granted); + void RemoveSharedAccount(Account& ac, const std::string& granted); - wxString AddCategory(User* user, Category& category); + int AddCategory(User* user, Category& category); void UpdateCategory(Category& category); - void DeleteCategory(User* user, Category& category, const wxString& replacement); - bool LoadCategory(const wxString& id, const wxString& name, Category& category); + void DeleteCategory(User* user, Category& category, int replacement); + bool LoadCategory(int id, const std::string& name, Category& category); std::map > GetAllOperations(User* user); void GenerateMonth(User* user, int monthFrom, int yearFrom, int monthTo, int yearTo); - void ChangePassword(User* user, const wxString& password); - bool UserExists(const wxString& name); - void ChangeName(User* user, const wxString& name); - void NewUser(const wxString& name); + void ChangePassword(User* user, const std::string& password); + bool UserExists(const std::string& name); + void ChangeName(User* user, const std::string& name); + void NewUser(const std::string& name); - void UpdatePreference(User* user, const wxString& preference); + void UpdatePreference(User* user, const std::string& preference); - std::vector* Search(User* user, wxString* description, wxDateTime* dateFrom, wxDateTime* dateTo, - wxString* amountFrom, wxString* amountTo, - std::vector categories, int types, std::vector accounts, bool wildcards); + std::vector* Search(User* user, std::string* description, QDate* dateFrom, QDate* dateTo, + int* amountFrom, int* amountTo, + std::vector categories, int types, std::vector accounts, bool wildcards); - void GetStats(User* user, const wxString& monthFrom, const wxString& yearFrom, const wxString& monthTo, - const wxString& yearTo, std::map > >* accountAmounts, - std::map* categories); + void GetStats(User* user, int monthFrom, int yearFrom, int monthTo, + int yearTo, std::map > >* accountAmounts, + std::map* categories); - void GetMonthStats(User* user, const wxString& month, const wxString& year, int nbDays, - std::map >* operations, - std::map* categories); + void GetMonthStats(User* user, int month, int year, int nbDays, + std::map >* operations, + std::map* categories); void KillMe(User* user); - bool GetOperation(const wxString& id, Operation* op); - std::map getSharedAccountOwners(const wxString& account); - wxString getSharedAccountOwner(const wxString& account); + bool GetOperation(int id, Operation* op); + std::map getSharedAccountOwners(int account); + int getSharedAccountOwner(int account); - std::map* GetNotChecked(User* user, int month, int year); - std::map* GetVirtualAmount(User* user, int month, int year); + std::map* GetNotChecked(User* user, int month, int year); + std::map* GetVirtualAmount(User* user, int month, int year); void UpdateImportPattern(User* user); @@ -160,10 +152,10 @@ public: private: KissCount* _kiss; - wxSQLite3Database _db; + QSqlDatabase _db; void CreateDatabase(); - wxString HashPassword(const wxString& password); + QString HashPassword(const QString& password); void LinkOrUnlinkOperation(User* user, Operation& op); }; diff --git a/src/model/Operation.cpp b/src/model/Operation.cpp index 020e0d9..6416eb1 100644 --- a/src/model/Operation.cpp +++ b/src/model/Operation.cpp @@ -35,7 +35,7 @@ bool sortOperations(const Operation& op1, const Operation& op2) if (op1.day < op2.day) return true; else if (op1.day == op2.day) - return (op1.description.Cmp(op2.description) < 0); + return (op1.description < op2.description); } } diff --git a/src/model/Operation.hpp b/src/model/Operation.hpp index bb4cb00..4a7fb64 100644 --- a/src/model/Operation.hpp +++ b/src/model/Operation.hpp @@ -20,28 +20,27 @@ #ifndef OPERATION_H #define OPERATION_H -#include #include struct Operation { - wxString id; - wxString parent; + int id; + int parent; unsigned int day; unsigned int month; unsigned int year; double amount; - wxString description; - wxString category; + std::string description; + int category; bool fix_cost; - wxString account; + int account; bool checked; - wxString transfert; - wxString formula; + int transfert; + std::string formula; bool meta; bool _virtual; - std::vector childs; + std::vector childs; - bool operator == (const wxString& opId) + bool operator == (int opId) { return id == opId; } diff --git a/src/model/User.cpp b/src/model/User.cpp index cfe38d8..f226323 100644 --- a/src/model/User.cpp +++ b/src/model/User.cpp @@ -44,64 +44,64 @@ void User::InvalidateOperations() _operations.clear(); } -Category User::GetCategory(const wxString& catId) +Category User::GetCategory(int catId) { Category cat; std::vector::iterator it = std::find(_categories.begin(), _categories.end(), catId); if (it !=_categories.end()) return *it; - if (_db->LoadCategory(catId, wxT(""), cat)) + if (_db->LoadCategory(catId, "", cat)) return cat; - cat.id = wxT("0"); - cat.parent = wxT("0"); + cat.id = 0; + cat.parent = 0; cat.name = _("Unknown"); - cat.font = wxT(""); + cat.font = ""; cat.backcolor = view::OWN_GREEN; cat.forecolor = wxColour(0x00, 0x00, 0x00); return cat; } -wxString User::GetCategoryName(const wxString& catId) +std::string User::GetCategoryName(int catId) { Category cat; std::vector::iterator it = std::find(_categories.begin(), _categories.end(), catId); if (it !=_categories.end()) return it->name; - if (_db->LoadCategory(catId, wxT(""), cat)) + if (_db->LoadCategory(catId, "", cat)) return cat.name; return _("Unknown") ; } -wxString User::GetCategoryId(const wxString& catName) +int User::GetCategoryId(const std::string& catName) { std::vector::iterator it; Category cat; for (it=_categories.begin(); it !=_categories.end(); it++) - if (wxGetTranslation(it->name) == catName) + if (_(it->name) == catName) return it->id; - if ( _db->LoadCategory(wxT(""), catName, cat)) + if ( _db->LoadCategory("", catName, cat)) return cat.id; - return wxT("0") ; + return 0 ; } -const wxFont User::GetCategoryFont(const wxString& catId) +const QFont User::GetCategoryFont(int catId) { - wxFont f; + QFont f; Category cat; for (unsigned int i=0; i<_categories.size(); i++) if (_categories[i].id == catId) return _categoriesFonts[i]; - if (_db->LoadCategory(catId, wxT(""), cat)) + if (_db->LoadCategory(catId, "", cat)) return KissCount::ExtractFont(cat.font); return f; @@ -110,7 +110,7 @@ const wxFont User::GetCategoryFont(const wxString& catId) void User::AddCategory(const Category& cat) { _categories.push_back(cat); - _categoriesFonts.push_back(KissCount::ExtractFont(wxT(""))); + _categoriesFonts.push_back(KissCount::ExtractFont("")); } void User::UpdateCategory(const Category& cat) @@ -136,7 +136,7 @@ void User::DeleteCategory(const Category& cat) } } -Account User::GetAccount(const wxString& accountId) throw (AccountNotFound) +Account User::GetAccount(int accountId) throw (AccountNotFound) { std::vector::iterator it = std::find(_accounts.begin(), _accounts.end(), accountId); @@ -146,7 +146,7 @@ Account User::GetAccount(const wxString& accountId) throw (AccountNotFound) throw AccountNotFound(); } -wxString User::GetAccountName(const wxString& accountId) +std::string User::GetAccountName(int accountId) { std::vector::iterator it = std::find(_accounts.begin(), _accounts.end(), accountId); @@ -155,14 +155,14 @@ wxString User::GetAccountName(const wxString& accountId) return _("Unknown") ; } -wxString User::GetAccountId(const wxString& accountName) +int User::GetAccountId(const std::string& accountName) { std::vector::iterator it; for (it=_accounts.begin(); it !=_accounts.end(); it++) if (it->name == accountName) return it->id; - return wxT("0") ; + return 0 ; } void User::AddAccount(Account& ac) @@ -201,17 +201,17 @@ int User::GetOperationsNumber(int month, int year) return (*_operations[year])[month].size(); } -wxLanguage User::GetLanguage() +std::string User::GetLanguage() { - wxString res = _preferences[wxT("language")]; - long val; + return _preferences["language"]; + // long val; - if (!res.Length()) - return wxLANGUAGE_ENGLISH ; + // if (!res.Length()) + // return wxLANGUAGE_ENGLISH ; - res.ToLong(&val); + // res.ToLong(&val); - return (wxLanguage)val; + // return (wxLanguage)val; } void User::LinkOrUnlinkOperation(Operation& op) @@ -226,13 +226,13 @@ void User::LinkOrUnlinkOperation(Operation& op) return; // Not Linked - if (!op.transfert.Length()) + if (!op.transfert) { for (it = (*_operations[op.year])[op.month].begin(); it != (*_operations[op.year])[op.month].end(); it++) { if (it->id != op.id && it->transfert == op.id) { - it->transfert = wxT(""); + it->transfert = 0; it->_virtual = false; return; } @@ -253,7 +253,7 @@ void User::LinkOrUnlinkOperation(Operation& op) return; } } - op.transfert = wxT(""); + op.transfert = 0; op._virtual = false; } } @@ -261,7 +261,7 @@ void User::LinkOrUnlinkOperation(Operation& op) bool User::Group(std::vector* ops, const Operation& op) { std::vector::iterator it; - std::vector::iterator it2; + std::vector::iterator it2; for (it = ops->begin(); it != ops->end(); it++) { @@ -280,9 +280,6 @@ bool User::Group(std::vector* ops, const Operation& op) void User::Group(const Operation& op) { - std::vector::iterator it; - std::vector::iterator it2; - if (!Group(&(*_operations[op.year])[op.month], op) && _db->LoadOperation(this, op.parent)) { @@ -293,7 +290,7 @@ void User::Group(const Operation& op) void User::UnGroup(const Operation& op) { std::vector::iterator it; - std::vector::iterator it2; + std::vector::iterator it2; for (it = (*_operations[op.year])[op.month].begin(); it != (*_operations[op.year])[op.month].end(); it++) { diff --git a/src/model/User.hpp b/src/model/User.hpp index ecee5b5..683cffa 100644 --- a/src/model/User.hpp +++ b/src/model/User.hpp @@ -22,7 +22,8 @@ #include #include -#include + +#include #include "Category.hpp" #include "Account.hpp" @@ -40,30 +41,30 @@ public: ~User(); void InvalidateOperations(); - wxString _id; - wxString _name; - wxString _password; + int _id; + std::string _name; + std::string _password; std::vector _accounts; std::map >* > _operations; std::vector _categories; - std::vector _categoriesFonts; - std::map _preferences; - std::map _importPatterns; + std::vector _categoriesFonts; + std::map _preferences; + std::map _importPatterns; class AccountNotFound {}; - Category GetCategory(const wxString& catId); - wxString GetCategoryName(const wxString& catId); - wxString GetCategoryId(const wxString& catName); - const wxFont GetCategoryFont(const wxString& catId); + Category GetCategory(int catId); + std::string GetCategoryName(int catId); + int GetCategoryId(const std::string& catName); + const QFont GetCategoryFont(int catId); void AddCategory(const Category& cat); void UpdateCategory(const Category& cat); void DeleteCategory(const Category& cat); - Account GetAccount(const wxString& accountId) throw (AccountNotFound); - wxString GetAccountName(const wxString& accountId); - wxString GetAccountId(const wxString& accountName); + Account GetAccount(int accountId) throw (AccountNotFound); + std::string GetAccountName(int accountId); + int GetAccountId(const std::string& accountName); void AddAccount(Account& ac); void UpdateAccount(Account& ac); void DeleteAccount(Account& ac); @@ -73,7 +74,7 @@ public: int GetAccountsNumber(); int GetOperationsNumber(int month, int year); - wxLanguage GetLanguage(); + std::string GetLanguage(); void LinkOrUnlinkOperation(Operation& op); diff --git a/src/model/export/ExportEngine.hpp b/src/model/export/ExportEngine.hpp index bed3a8e..775da0d 100644 --- a/src/model/export/ExportEngine.hpp +++ b/src/model/export/ExportEngine.hpp @@ -33,25 +33,25 @@ public: // Get supported file extension. Example : // "OFX files (*.ofx)|*.ofx" - virtual wxString GetFileExt(); + virtual std::string GetFileExt(); // Handle the file - virtual bool HandleFile(const wxString& path, User* user, Database* db, KissCount* kiss)=0; + virtual bool HandleFile(const std::string& path, User* user, Database* db, KissCount* kiss)=0; // Save operations (ExportEngin pre fill _accounts, _categories and _accountAmounts) virtual bool SaveFile(std::vector* operations)=0; protected: - wxString _path; + std::string _path; Database* _db; User* _user; KissCount* _kiss; - wxString _shortExt; - wxString _longExt; + std::string _shortExt; + std::string _longExt; - std::map _accounts; - std::map _categories; + std::map _accounts; + std::map _categories; std::map _accountAmounts; }; diff --git a/src/model/export/XMLExportEngine.cpp b/src/model/export/XMLExportEngine.cpp index 9dc9c31..490de6b 100644 --- a/src/model/export/XMLExportEngine.cpp +++ b/src/model/export/XMLExportEngine.cpp @@ -76,7 +76,7 @@ bool XMLExportEngine::SaveAccountAmounts() { xmlTextWriterStartElement(_writer, (const xmlChar*) "account_amount"); xmlTextWriterWriteAttribute(_writer, (const xmlChar*) "account", (const xmlChar*) it->first.account.utf8_str().data()); - xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "monthpp", "%d", it->first.month); + xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "month", "%d", it->first.month); xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "year", "%d", it->first.year); xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "amount", "%.2lf", it->second); xmlTextWriterEndElement(_writer); @@ -128,7 +128,7 @@ bool XMLExportEngine::SaveOperations(std::vector* operations) xmlTextWriterWriteAttribute(_writer, (const xmlChar*) "id", (const xmlChar*) it->id.utf8_str().data()); xmlTextWriterWriteAttribute(_writer, (const xmlChar*) "parent", (const xmlChar*) it->parent.utf8_str().data()); xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "day", "%d", it->day); - xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "monthpp", "%d", it->month); + xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "month", "%d", it->month); xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "year", "%d", it->year); xmlTextWriterWriteFormatAttribute(_writer, (const xmlChar*) "amount", "%.2lf", it->amount); xmlTextWriterWriteAttribute(_writer, (const xmlChar*) "description", (const xmlChar*) it->description.utf8_str().data()); diff --git a/src/model/import/ImportEngine.hpp b/src/model/import/ImportEngine.hpp index 0edd61c..cc4ef6d 100644 --- a/src/model/import/ImportEngine.hpp +++ b/src/model/import/ImportEngine.hpp @@ -28,57 +28,57 @@ class KissCount; class ImportPattern { public: - wxString pattern; - wxString account; - wxString category; + std::string pattern; + int account; + int category; } ; class ImportEngine { public: - static wxString NULL_IMPORT_PATTERN; + static std::string NULL_IMPORT_PATTERN; ImportEngine(); ~ImportEngine(); // Get supported file extension. Example : // "OFX files (*.ofx)|*.ofx" - virtual wxString GetFileExt(); + virtual std::string GetFileExt(); // Handle the file - virtual bool HandleFile(const wxString& path, User* user, Database* db, KissCount* kiss)=0; + virtual bool HandleFile(const std::string& path, User* user, Database* db, KissCount* kiss)=0; // Parse the file and return accounts that doesn't match virtual void ParseFile(std::vector& accounts, std::vector& categories); // Final Step - virtual std::vector* GetOperations(std::map& accounts, std::map& categories); + virtual std::vector* GetOperations(std::map& accounts, std::map& categories); const std::map& GetAccountAmounts(); - void MatchPattern(wxString& key, Operation& op); + void MatchPattern(std::string& key, Operation& op); int UpdatePattern(int pos); - static wxString RemoveUnused(const wxString& s); + static std::string RemoveUnused(const std::string& s); protected: Database* _db; User* _user; - wxString _path; + std::string _path; KissCount* _kiss; - wxString _shortExt; - wxString _longExt; + std::string _shortExt; + std::string _longExt; - std::map _accounts; - std::map _categories; + std::map _accounts; + std::map _categories; std::vector _unresolvedAccounts; std::vector _unresolvedCategories; std::vector _operations; - std::map _descriptions; + std::map _descriptions; std::map _accountAmounts; void ApplyPattern(ImportPattern& pattern, Operation& op); - wxString FindPattern(wxString& s1, wxString& s2); + std::string FindPattern(std::string& s1, std::string& s2); }; #endif diff --git a/src/model/import/XMLImportEngine.cpp b/src/model/import/XMLImportEngine.cpp index f702f25..412fa87 100644 --- a/src/model/import/XMLImportEngine.cpp +++ b/src/model/import/XMLImportEngine.cpp @@ -80,7 +80,7 @@ void XMLImportEngine::LoadAccountAmount(XMLImportEngine* _this, const char** att if (!strcmp(attrs[i], "account")) accountAmount.account = wxString(attrs[i+1], wxConvUTF8); - else if (!strcmp(attrs[i], "monthpp")) + else if (!strcmp(attrs[i], "month")) { wxString(attrs[i+1], wxConvUTF8).ToLong(&v); accountAmount.month = v; @@ -169,7 +169,7 @@ void XMLImportEngine::LoadOperation(XMLImportEngine* _this, const char** attrs) op.day = v; } - else if (!strcmp(attrs[i], "monthpp")) + else if (!strcmp(attrs[i], "month")) { wxString(attrs[i+1], wxConvUTF8).ToLong(&v); op.month = v; diff --git a/src/view/AccountPanel.cpp b/src/view/AccountPanel.cpp deleted file mode 100644 index b01985b..0000000 --- a/src/view/AccountPanel.cpp +++ /dev/null @@ -1,1121 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "grid/wxGridCellBitmapRenderer.hpp" -#include "GenerateDialog.hpp" - -#include "AccountPanel.hpp" - -enum {ACCOUNT_NUMBER, ACCOUNT_NAME, ACCOUNT_INIT, ACCOUNT_CUR, ACCOUNT_FINAL, NUMBER_COLS_ACCOUNTS}; -enum {CUR_CREDIT, CUR_DEBIT, TOTAL_CREDIT, TOTAL_DEBIT, BALANCE, STATS_ROW, CATS_STATS, NON_FIX}; -enum {CALENDAR_TREE_ID=1, OPS_GRID_ID, CALENDAR_ID, ACCOUNTS_GRID_ID, MENU_GENERATE_ID, MENU_DELETE_ID, DISPLAY_MODE_ID, GROUP_ID, UNGROUP_ID, UPDATE_NEXT_MONTHS_ID}; - -enum {VIRTUAL_MODE=0, REAL_MODE, CHECK_MODE}; - -BEGIN_EVENT_TABLE(AccountPanel, wxPanel) -EVT_GRID_CMD_CELL_CHANGE(OPS_GRID_ID, AccountPanel::OnOperationModified) -EVT_GRID_CMD_CELL_CHANGE(ACCOUNTS_GRID_ID, AccountPanel::OnAccountModified) -EVT_TREE_ITEM_RIGHT_CLICK(CALENDAR_TREE_ID, AccountPanel::OnTreeRightClick) -EVT_TREE_SEL_CHANGED(CALENDAR_TREE_ID, AccountPanel::OnTreeChange) -EVT_TREE_KEY_DOWN(CALENDAR_TREE_ID, AccountPanel::OnTreeChange) -EVT_MENU(MENU_GENERATE_ID, AccountPanel::OnMenuGenerate) -EVT_MENU(MENU_DELETE_ID, AccountPanel::OnMenuDelete) -EVT_SHOW(AccountPanel::OnShow) -EVT_CALENDAR_SEL_CHANGED(CALENDAR_ID, AccountPanel::OnCalendarChange) -EVT_RADIOBOX(DISPLAY_MODE_ID, AccountPanel::OnModeChange) -EVT_BUTTON(GROUP_ID, AccountPanel::OnGroup) -EVT_BUTTON(UNGROUP_ID, AccountPanel::OnUnGroup) -EVT_BUTTON(UPDATE_NEXT_MONTHS_ID, AccountPanel::OnUpdateNextMonths) -END_EVENT_TABLE() - -AccountPanel::AccountPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent), _curMonth(-1), _curYear(-1), _tree(this, CALENDAR_TREE_ID, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT) -{ - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *vbox2 = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *vbox3 = new wxBoxSizer(wxVERTICAL); - wxChartPanel* chart ; - int i ; - User* user = _kiss->GetUser(); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - DEFAULT_FONT(font); - wxRect rect = wxDisplay().GetGeometry(); - int nbCategories; - - SetSizer(hbox); - - ColorScheme* colorScheme = new ColorScheme(wxUI::categoryColors, WXSIZEOF(wxUI::categoryColors)); - - _pie = new PiePlot(); - _calendar = new wxCalendarCtrl(this, CALENDAR_ID, wxDefaultDateTime, wxDefaultPosition, wxDefaultSize, - wxCAL_MONDAY_FIRST | wxCAL_NO_MONTH_CHANGE | wxCAL_SEQUENTIAL_MONTH_SELECTION); - _calendar->EnableMonthChange(false); - _calendar->EnableYearChange(false); - _calendar->EnableHolidayDisplay(false); - _calendar->Enable(false); - - _accounts = new wxString[user->GetAccountsNumber()]; - for (i=0, - accountIt = user->_accounts.begin(); - accountIt != user->_accounts.end(); - accountIt++, i++) - _accounts[i] = accountIt->name; - - _categories = new wxString[user->GetCategoriesNumber()] ; - for(i=0, categoryIt = user->_categories.begin(); - categoryIt != user->_categories.end(); - categoryIt++, i++) - { - _categories[i] = wxGetTranslation(categoryIt->name) ; - _categoriesIndexes[categoryIt->name] = i; - } - - nbCategories = (user->GetCategoriesNumber() <= wxUI::MAX_CATEGORY) ? user->GetCategoriesNumber() : wxUI::MAX_CATEGORY; - - _categoriesValues = new double[user->GetCategoriesNumber()]; - for(i=0; iGetCategoriesNumber(); i++) - _categoriesValues[i] = 0.0; - - _dataset = new CategorySimpleDataset(_categories, nbCategories); - _dataset->AddSerie(_("Serie 1"), _categoriesValues, nbCategories); - - _dataset->SetRenderer(new CategoryRenderer(*colorScheme)); - _pie->SetDataset(_dataset); - _pie->SetColorScheme(colorScheme); - - _pie->SetLegend(new Legend(wxBOTTOM, wxCENTER)); - - _grid = new GridAccount(_kiss, this, OPS_GRID_ID, true, true, true); - - _accountsGrid = new wxGrid(this, ACCOUNTS_GRID_ID); - _accountsGrid->CreateGrid(0, NUMBER_COLS_ACCOUNTS); - _accountsGrid->SetRowLabelSize(0); - - _accountsGrid->SetDefaultCellFont(font); - - _accountsGrid->SetColLabelValue(ACCOUNT_NUMBER, _("Account number")); - _accountsGrid->SetColLabelValue(ACCOUNT_NAME, _("Account name")); - _accountsGrid->SetColLabelValue(ACCOUNT_INIT, _("Initial value")); - _accountsGrid->SetColLabelValue(ACCOUNT_CUR, _("Current value")); - _accountsGrid->SetColLabelValue(ACCOUNT_FINAL, _("Final value")); - - _accountsGrid->AutoSizeColumns(true); - - _statsGrid = new wxGrid(this, wxID_ANY); - - chart = new wxChartPanel(this); - chart->SetChart(new Chart(_pie, _("Cost repartition"))); - chart->Fit(); - chart->Layout(); - chart->SetMinSize(// chart->GetSize() - wxSize(200,300)); - - wxString modes[3] = {_("Virtual"), _("Real"), _("Check")}; - _radioMode = new wxRadioBox(this, DISPLAY_MODE_ID, _("Mode"), wxDefaultPosition, wxDefaultSize, - 3, modes); - - _tree.SetIndent(5); - - wxButton* buttonGroup = new wxButton(this, GROUP_ID, _("Group")); - wxButton* buttonUnGroup = new wxButton(this, UNGROUP_ID, _("UnGroup")); - wxButton* buttonUpdateNextMonths = new wxButton(this, UPDATE_NEXT_MONTHS_ID, _("Update next months")); - - vbox3->Add(&_tree, 0, wxGROW|wxALL, 2); - vbox3->Add(buttonUpdateNextMonths, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 10); - vbox3->Add(buttonGroup, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 10); - vbox3->Add(buttonUnGroup, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 10); - vbox3->Add(_radioMode, 0, wxALIGN_CENTER_HORIZONTAL|wxUP, 50); - - hbox->Add(vbox3, 0, wxALL, 2); - // hbox->Add(vbox3, 0, wxGROW|wxALL, 2); - hbox2->Add(_accountsGrid, 0, wxGROW|wxALL, 2); - hbox2->Add(_calendar, 0, wxALL, 2); - vbox2->Add(hbox2, 0); - vbox2->Add(_grid, 0, wxGROW|wxALL, 2); - hbox->Add(vbox2, 0, wxGROW|wxALL, 2); - vbox->Add(_statsGrid, 0, wxGROW); - vbox->Add(chart, 0, wxALIGN_CENTER_HORIZONTAL|wxUP, 10); - hbox->Add(vbox, 0, wxGROW|wxALL, 2); - - ChangeUser(); - - Fit(); - - SetMinSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetMaxSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetScrollbars(10, 10, 100/10, 100/10); -} - -AccountPanel::~AccountPanel() -{ - delete[] _categoriesValues; - delete[] _categories; - delete[] _accounts; -} - -KissPanel* AccountPanel::CreatePanel() -{ - return new AccountPanel(_kiss, _wxUI); -} - -wxBitmapButton* AccountPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(ACCOUNT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString AccountPanel::GetToolTip() -{ - return _("Operations"); -} - -void AccountPanel::InitStatsGrid(User* user) -{ - int i; - int nb_categories = user->GetCategoriesNumber(); - DEFAULT_FONT(font); - - if (!_statsGrid->GetNumberRows()) - { - _statsGrid->CreateGrid(nb_categories+CATS_STATS+1, 2); // Headers + blank + categories + non fix - _statsGrid->SetColLabelSize(0); - _statsGrid->SetRowLabelSize(0); - _statsGrid->EnableEditing(false); - } - else - { - _statsGrid->DeleteRows(0, _statsGrid->GetNumberRows()); - _statsGrid->InsertRows(0, nb_categories+CATS_STATS); - } - - _statsGrid->SetDefaultCellFont(font); - - _statsGrid->SetCellValue(TOTAL_CREDIT, 0, _("Total Credit")); - _statsGrid->SetCellValue(TOTAL_DEBIT, 0, _("Total Debit")); - - for(i=0; iSetCellValue(CATS_STATS+i+1, 0, _categories[i]); - _statsGrid->SetCellAlignment(CATS_STATS+i+1, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - } - else - { - _statsGrid->SetCellValue(CATS_STATS+i, 0, _categories[i]); - _statsGrid->SetCellAlignment(CATS_STATS+i, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - } - } - - _statsGrid->AutoSizeColumn(0, false); - font.SetWeight(wxFONTWEIGHT_BOLD); - _statsGrid->SetCellFont(CUR_CREDIT, 0, font); - _statsGrid->SetCellFont(CUR_DEBIT, 0, font); - _statsGrid->SetCellFont(BALANCE, 0, font); - _statsGrid->SetCellFont(BALANCE, 1, font); - - _statsGrid->SetCellValue(CUR_CREDIT, 0, _("Cur Credit")); - _statsGrid->SetCellValue(CUR_DEBIT, 0, _("Cur Debit")); - _statsGrid->SetCellValue(BALANCE, 0, _("Balance")); - _statsGrid->SetCellValue(NON_FIX, 0, _("Non fix")); - - _statsGrid->SetCellAlignment(CUR_DEBIT, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - _statsGrid->SetCellAlignment(CUR_CREDIT, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - _statsGrid->SetCellAlignment(TOTAL_DEBIT, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - _statsGrid->SetCellAlignment(TOTAL_CREDIT, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - _statsGrid->SetCellAlignment(BALANCE, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - _statsGrid->SetCellAlignment(NON_FIX, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); -} - -void AccountPanel::ChangeUser() -{ - User* user = _kiss->GetUser(); - int curYear = -1; - wxDateTime curDate; - wxTreeItemId rootNode, curNode; - std::map > ops; - std::map >::iterator it; - - ops = _kiss->GetAllOperations(); - - InitStatsGrid(user); - - _tree.DeleteAllItems(); - rootNode = _tree.AddRoot(wxT("")); - - curDate.SetToCurrent(); - if (ops.size()) - { - for(it = ops.begin(); it != ops.end(); it++) - { - if ((int)it->first <= curDate.GetYear()) - { - curYear = it->first; - curNode = _tree.AppendItem(rootNode, wxString::Format(wxT("%d"), it->first)); - } - else - _tree.AppendItem(rootNode, wxString::Format(wxT("%d"), it->first)); - } - Fit(); - if (curYear != -1) - { - _tree.SelectItem(curNode, true); - LoadYear(curYear); - } - } - else - { - curNode = _tree.AppendItem(rootNode, wxString::Format(wxT("%d"), curDate.GetYear())); - _tree.AppendItem(curNode, wxUI::months[(int)curDate.GetYear()]); - Fit(); - } -} - -void AccountPanel::LoadYear(int year, bool showMonth) -{ - User* user = _kiss->GetUser(); - int curMonth = -1; - wxDateTime curDate; - wxTreeItemId parentNode, curMonthNode; - std::map > ops ; - std::vector::iterator it; - - if (user->_operations[year] && _tree.GetChildrenCount(_tree.GetSelection(), true)) - { - if (showMonth) - ShowMonth(-1, year); - return; - } - - _curYear = year ; - _kiss->LoadYear(year); - ops = _kiss->GetAllOperations(); - - curDate.SetToCurrent(); - parentNode = _tree.GetSelection(); - - for (it = ops[year].begin(); it != ops[year].end(); it++) - { - if (curMonth == -1 || (year == curDate.GetYear() && *it <= curDate.GetMonth())) - { - curMonth = *it; - curMonthNode = _tree.AppendItem(parentNode, wxUI::months[*it]); - } - else - _tree.AppendItem(parentNode, wxUI::months[*it]); - } - - _tree.Expand(parentNode); - Fit(); - if (showMonth) - { - _tree.SelectItem(curMonthNode, true); - ShowMonth(curMonth, year); - } - - _wxUI->Layout(); -} - -void AccountPanel::ShowMonth(int month, int year) -{ - std::vector operations; - _fixCosts = 0; - User* user = _kiss->GetUser(); - DEFAULT_FONT(font); - std::vector::iterator categoryIt; - std::map >::iterator monthIt; - wxDateTime curDate; - curDate.SetToCurrent(); - - if (month == -1) - { - // Near month - if (year == curDate.GetYear()) - { - for (monthIt = user->_operations[year]->begin(); monthIt != user->_operations[year]->end(); monthIt++) - { - if ((int)monthIt->first <= curDate.GetMonth()) - { - month = monthIt->first; - } - } - } - - // First month - if (month == -1) - { - monthIt = user->_operations[year]->begin(); - if (user->_operations[year]->size() == 0 && year == curDate.GetYear()) - month = curDate.GetMonth(); - else - month = monthIt->first; - } - } - - _curYear = year; - _curMonth = month; - _wxUI->SetTitle(user->_name + wxT(" - ") + wxUI::months[month] + wxT(" ") + wxString::Format(wxT("%d"), year)); - _calendar->Enable(true); - - if (_grid->GetNumberRows() > 1) - _grid->DeleteRows(1, _grid->GetNumberRows()-1); - - // Operations are ordered - _curOperations = &((*user->_operations[year])[month]); - - _grid->LoadOperations(_curOperations, _curMonth, _curYear); - - InitAccountsGrid(user, month, year); - - _calendar->EnableMonthChange(true); - _calendar->EnableYearChange(true); - if (curDate.GetMonth() == month && curDate.GetYear() == year) - _calendar->SetDate(curDate) ; - else if (curDate.GetMonth() > month || curDate.GetYear() > year) - _calendar->SetDate(curDate.GetLastMonthDay((wxDateTime::Month)month, year)); - else if (curDate.GetMonth() < month || curDate.GetYear() < year) - _calendar->SetDate(wxDateTime(1, (wxDateTime::Month)month, year)); - - _calendar->EnableMonthChange(false); - _calendar->EnableYearChange(false); - _calendar->SetSize(_calendar->GetMinSize()); - - UpdateStats(); - - Fit(); - // SetMinSize(GetSize()); -} - -void AccountPanel::InitAccountsGrid(User* user, int month, int year) -{ - std::vector::iterator it; - int curLine = 0; - double value; - int i, a; - DEFAULT_FONT(font); - - if (_accountsGrid->GetNumberRows()) - _accountsGrid->DeleteRows(0, _accountsGrid->GetNumberRows()); - - font.SetWeight(wxFONTWEIGHT_BOLD); - - for (i=0, it = user->_accounts.begin(); it != user->_accounts.end(); i++, it++, curLine++) - { - _accountsGrid->AppendRows(); - - if (it->shared) - _accountsGrid->SetCellValue(curLine, ACCOUNT_NUMBER, it->number + wxT("*")); - else - _accountsGrid->SetCellValue(curLine, ACCOUNT_NUMBER, it->number); - - _accountsGrid->SetCellValue(curLine, ACCOUNT_NAME, it->name); - value = _kiss->GetAccountAmount(it->id, month, year); - _accountsGrid->SetCellEditor(curLine, ACCOUNT_INIT, new wxGridCellFloatEditor(-1, 2)); - _accountsGrid->SetCellValue(curLine, ACCOUNT_INIT, wxString::Format(wxT("%.2lf"), value)); - for (a=0; aSetReadOnly(curLine, a, a != ACCOUNT_INIT); - _accountsGrid->SetCellFont(curLine, ACCOUNT_CUR, font); - - _accountsInitValues[it->id] = value; - _accountsGrid->SetCellAlignment(curLine, ACCOUNT_INIT, wxALIGN_RIGHT, wxALIGN_CENTRE); - _accountsGrid->SetCellAlignment(curLine, ACCOUNT_CUR, wxALIGN_RIGHT, wxALIGN_CENTRE); - _accountsGrid->SetCellAlignment(curLine, ACCOUNT_FINAL, wxALIGN_RIGHT, wxALIGN_CENTRE); - } - - _accountsGrid->AutoSizeColumns(true); -} - -void AccountPanel::UpdateStats() -{ - int i; - User* user = _kiss->GetUser(); - std::vector::iterator it; - double curCredit, curDebit, totalCredit, totalDebit, balance, value, value2, percents; - std::map curAccountAmount, finalAccountAmount; - std::map::iterator doubleIt; - std::map::iterator intIt; - std::vector::iterator accountIt; - unsigned int day; - int mode; - std::map* notChecked = 0; - std::map* virtuals = 0; - Account account; - Operation op; - bool blocked_account ; - - mode = _radioMode->GetSelection(); - - curCredit = curDebit = totalCredit = totalDebit = percents = 0.0; - - if (mode == CHECK_MODE) - notChecked = _kiss->GetNotChecked(_curMonth, _curYear); - - if (mode == REAL_MODE || mode == CHECK_MODE) - virtuals = _kiss->GetVirtualAmount(_curMonth, _curYear); - - day = _calendar->GetDate().GetDay()-1; - - for (i=0; iGetCategoriesNumber(); i++) - _categoriesValues[i] = 0.0; - - for (doubleIt=_accountsInitValues.begin(); doubleIt!=_accountsInitValues.end(); doubleIt++) - { - curAccountAmount[doubleIt->first] = _accountsInitValues[doubleIt->first]; - finalAccountAmount[doubleIt->first] = _accountsInitValues[doubleIt->first]; - - if (mode == REAL_MODE || mode == CHECK_MODE) - { - curAccountAmount[doubleIt->first] += -(*virtuals)[doubleIt->first]; - finalAccountAmount[doubleIt->first] += -(*virtuals)[doubleIt->first]; - } - } - - for (it=_curOperations->begin(); it!=_curOperations->end(); it++) - { - if (it->meta) continue; - - op = *it; - blocked_account = false; - - // A credit on a blocked account must be considered as a debit - if (op.transfert.Length() && op.amount > 0) - { - account = user->GetAccount(op.account); - - if (account.blocked) - { - op.amount = -op.amount; - op.transfert = wxT(""); - blocked_account = true; - } - } - - - switch(mode) - { - case VIRTUAL_MODE: - if (op.amount >= 0) - { - if (!op.transfert.Length()) - totalCredit += op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length()) - curCredit += op.amount; - curAccountAmount[op.account] += op.amount; - } - finalAccountAmount[op.account] += op.amount; - } - else - { - if (!op.transfert.Length() && user->GetCategoryName(op.category) != _("Unknown")) - _categoriesValues[_categoriesIndexes[user->GetCategoryName(op.category)]] += -op.amount ; - - if (!op.transfert.Length()) - totalDebit += -op.amount; - - if (blocked_account) - op.amount = -op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length()) - curDebit += -op.amount; - curAccountAmount[op.account] += op.amount; - } - finalAccountAmount[op.account] += op.amount; - } - break; - case REAL_MODE: - if (op.amount >= 0) - { - if (!op.transfert.Length()) - totalCredit += op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length()) - curCredit += op.amount; - if (!op._virtual) - curAccountAmount[op.account] += op.amount; - } - if (!op._virtual) - finalAccountAmount[op.account] += op.amount; - } - else - { - if (!op.transfert.Length() && user->GetCategoryName(op.category) != _("Unknown")) - _categoriesValues[_categoriesIndexes[user->GetCategoryName(op.category)]] += -op.amount ; - - if (!op.transfert.Length() && !op._virtual) - totalDebit += -op.amount; - - if (blocked_account) - op.amount = -op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length() && !op._virtual) - curDebit += -op.amount; - if (!op._virtual) - curAccountAmount[op.account] += op.amount; - } - if (!op._virtual) - finalAccountAmount[op.account] += op.amount; - } - break; - case CHECK_MODE: - if (op.amount >= 0) - { - if (!op.transfert.Length() && !op._virtual) - totalCredit += op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length() && !op._virtual) - curCredit += op.amount; - if (op.checked && !op._virtual) - curAccountAmount[op.account] += op.amount; - } - if (op.checked && !op._virtual) - finalAccountAmount[op.account] += op.amount; - } - else - { - if (!op.transfert.Length() && user->GetCategoryName(op.category) != _("Unknown")) - _categoriesValues[_categoriesIndexes[user->GetCategoryName(op.category)]] += -op.amount ; - - if (!op.transfert.Length() && !op._virtual) - totalDebit += -op.amount; - - if (blocked_account) - op.amount = -op.amount; - - if (day >= op.day) - { - if (!op.transfert.Length() && !op._virtual) - curDebit += -op.amount; - if (op.checked && !op._virtual) - curAccountAmount[op.account] += op.amount; - } - if (op.checked && !op._virtual) - finalAccountAmount[op.account] += op.amount; - } - break; - } - } - - balance = totalCredit - totalDebit; - _statsGrid->SetCellValue(CUR_CREDIT, 1, wxString::Format(wxT("%.2lf"), curCredit)); - _statsGrid->SetCellValue(CUR_DEBIT, 1, wxString::Format(wxT("%.2lf"), curDebit)); - _statsGrid->SetCellValue(TOTAL_CREDIT, 1, wxString::Format(wxT("%.2lf"), totalCredit)); - _statsGrid->SetCellValue(TOTAL_DEBIT, 1, wxString::Format(wxT("%.2lf"), totalDebit)); - - _statsGrid->SetCellTextColour(BALANCE, 1, (balance >= 0) ? wxColor(0x00, 0xFF, 0x00) : wxColor(0xFF, 0x00, 0x00)); - _statsGrid->SetCellValue(BALANCE, 1, wxString::Format(wxT("%.2lf"), balance)); - - for(i=0; iGetCategoriesNumber()+1; i++) - { - if (totalDebit != 0) - percents = ((double) (_categoriesValues[i]*100))/totalDebit; - else - percents = 0.0; - if (i) - _statsGrid->SetCellValue(CATS_STATS+i+1, 1, wxString::Format(wxT("%.2lf (%02d %%)"), _categoriesValues[i], (int)percents)); - else - _statsGrid->SetCellValue(CATS_STATS+i, 1, wxString::Format(wxT("%.2lf (%02d %%)"), _categoriesValues[i], (int)percents)); - } - - value = totalDebit - _categoriesValues[0]; - if (totalDebit != 0) - percents = ((double) (value*100))/totalDebit; - else - percents = 0.0; - _statsGrid->SetCellValue(NON_FIX, 1, wxString::Format(wxT("%.2lf (%02d %%)"), value, (int)percents)); - - for (i=0, accountIt=user->_accounts.begin(); accountIt!=user->_accounts.end(); accountIt++, i++) - { - if (mode != CHECK_MODE) - { - value = _accountsInitValues[accountIt->id]; - if (mode == REAL_MODE) - value -= (*virtuals)[accountIt->id]; - _accountsGrid->SetCellValue(i, ACCOUNT_INIT, wxString::Format(wxT("%.2lf"), value)); - value = curAccountAmount[accountIt->id]; - _accountsGrid->SetCellValue(i, ACCOUNT_CUR, wxString::Format(wxT("%.2lf"), value)); - _accountsGrid->SetCellTextColour(i, ACCOUNT_CUR, (value >= 0.0) ? wxColor(0x00, 0x00, 0x00) : wxColor(0xFF, 0x00, 0x00)); - value = finalAccountAmount[accountIt->id]; - _accountsGrid->SetCellValue(i, ACCOUNT_FINAL, wxString::Format(wxT("%.2lf"), value)); - } - else - { - value = _accountsInitValues[accountIt->id] - (*virtuals)[accountIt->id]; - value2 = (*notChecked)[accountIt->id]; - - _accountsGrid->SetCellValue(i, ACCOUNT_INIT, wxString::Format(wxT("%.2lf (%.2lf)"), value, value-value2)); - value = curAccountAmount[accountIt->id]; - _accountsGrid->SetCellValue(i, ACCOUNT_CUR, wxString::Format(wxT("%.2lf (%.2lf)"), value, value-value2)); - _accountsGrid->SetCellTextColour(i, ACCOUNT_CUR, (value >= 0.0) ? wxColor(0x00, 0x00, 0x00) : wxColor(0xFF, 0x00, 0x00)); - value = finalAccountAmount[accountIt->id]; - _accountsGrid->SetCellValue(i, ACCOUNT_FINAL, wxString::Format(wxT("%.2lf (%.2lf)"), value, value-value2)); - } - } - - _accountsGrid->AutoSizeColumn(ACCOUNT_INIT, true); - _accountsGrid->AutoSizeColumn(ACCOUNT_CUR, true); - _accountsGrid->AutoSizeColumn(ACCOUNT_FINAL, true); - - if (notChecked) delete notChecked; - if (virtuals) delete virtuals; - - _statsGrid->AutoSizeColumn(1, true); - - _pie->DatasetChanged(_dataset); - - Layout(); -} - -void AccountPanel::OnOperationModified(wxGridEvent& event) -{ - UpdateStats(); - - Fit(); -} - -void AccountPanel::OnAccountModified(wxGridEvent& event) -{ - User* user = _kiss->GetUser(); - int row = event.GetRow(); - double amount; - wxString id = user->GetAccountId(_accounts[row]); - - static bool inModification = false; - - if (inModification) return ; - - inModification = true; - - _accountsGrid->GetCellValue(row, event.GetCol()).ToDouble(&amount); - - _kiss->SetAccountAmount(id, _curMonth, _curYear, amount); - _accountsInitValues[id] = amount; - - UpdateStats(); - - inModification = false; -} - -void AccountPanel::OnTreeRightClick(wxTreeEvent& event) -{ - wxMenu menu(0); - - menu.Append(MENU_GENERATE_ID, _("Generate monthpp")); - menu.AppendSeparator(); - if (_tree.GetCount() > 1) - menu.Append(MENU_DELETE_ID, _("Delete")); - - PopupMenu(&menu, event.GetPoint()); -} - -void AccountPanel::OnTreeChange(wxTreeEvent& event) -{ - int month=-1, year; - int i; - wxString monthString; - static bool inModification = false ; - - if (inModification) return; - - inModification = true; - - monthString = _tree.GetItemText(event.GetItem()); - for (i=0; i<12; i++) - if (monthString == wxUI::months[i]) - { - month = i; - break; - } - - if (month == -1) - { - year = wxAtoi(monthString); - - // Error - if (year == 0) - { - inModification = false; - return; - } - - if (year == _curYear) - { - inModification = false; - return; - } - - // _tree.CollapseAll(); - // _tree.Expand(event.GetItem()); - LoadYear(year, false); - } - else - { - year = wxAtoi(_tree.GetItemText(_tree.GetItemParent(event.GetItem()))); - - // Error - if (year == 0) - { - inModification = false; - return; - } - - if (year != _curYear || month != _curMonth) - { - ShowMonth(month, year); - } - } - - inModification = false; -} - -void AccountPanel::GetTreeSelection(int* month, int* year) -{ - wxString monthString; - int i; - - *month = -1; *year = -1; - - monthString = _tree.GetItemText(_tree.GetSelection()); - for (i=0; i<12; i++) - if (monthString == wxUI::months[i]) - { - *month = i; - break; - } - - if (*month == -1) - { - *year = wxAtoi(monthString); - - // Error - if (year == 0) - { - *month = -1; - *year = -1; - return; - } - } - else - { - *year = wxAtoi(_tree.GetItemText(_tree.GetItemParent(_tree.GetSelection()))); - - // Error - if (year == 0) - { - *month = -1; - *year = -1; - return; - } - } -} - -void AccountPanel::OnMenuGenerate(wxCommandEvent& event) -{ - int month, year; - wxDateTime curDate; - - curDate.SetToCurrent(); - - GetTreeSelection(&month, &year); - - if (month == -1 && year == curDate.GetYear()) - { - month = _curMonth; - } - - GenerateDialog g(_kiss, _wxUI, month, year); - g.ShowModal(); -} - -void AccountPanel::OnMenuDelete(wxCommandEvent& event) -{ - int month, year; - wxString message; - wxTreeItemId curNode, node ; - std::map > ops ; - - GetTreeSelection(&month, &year); - - ops = _kiss->GetAllOperations(); - - if (ops.size() == 1 && (ops[year].size() == 1 || month == -1)) - { - wxMessageBox(_("It must be at least one month !"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - message = _("Are you sure want to delete "); - if (month != -1) - message += wxUI::months[month] + wxT(" "); - message += wxString::Format(wxT("%d"), year); - - message += _(" operations ?"); - - wxMessageDialog dialog(_wxUI, message, wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - return; - - curNode = _tree.GetSelection(); - - if (ops[year].size() == 1 && month != -1) - curNode = _tree.GetItemParent(curNode); - - _kiss->DeleteOperations(month, year); - - node = _tree.GetNextSibling(curNode); - - if (!node.IsOk()) - node = _tree.GetPrevSibling(curNode); - - _tree.Delete(curNode); - - if (!node.IsOk()) - ChangeUser(); - else - { - _tree.SelectItem(node); - GetTreeSelection(&month, &year); - if (month == -1) - month = ops[year][0]; - ShowMonth(month, year); - } - _wxUI->NeedReload(); -} - -void AccountPanel::GenerateMonth(int month, int year) -{ - wxTreeItemId root, years, node ; - wxTreeItemIdValue cookie; - wxString monthString, yearString; - std::map > ops ; - std::vector::iterator it ; - int i; - - root = _tree.GetRootItem(); - yearString = wxString::Format(wxT("%d"), year); - monthString = wxUI::months[month]; - - ops = _kiss->GetAllOperations(); - - if (_tree.GetChildrenCount(root, true) < 1) - { - node = _tree.AppendItem(root, yearString); - node = _tree.AppendItem(node, monthString); - - _tree.SelectItem(node, true); - ShowMonth(month, year); - return ; - } - - years = _tree.GetFirstChild(root, cookie); - while (years.IsOk()) - { - if (_tree.GetItemText(years) == yearString) - break; - if (wxAtoi(_tree.GetItemText(years)) > year) - { - years = _tree.GetPrevSibling(years); - if (!years.IsOk()) - years = _tree.PrependItem(root, yearString); - else - years = _tree.InsertItem(root, years, yearString); - break; - } - years = _tree.GetNextSibling(years); - } - - if (!years.IsOk()) - { - years = _tree.GetFirstChild(root, cookie); - if (wxAtoi(_tree.GetItemText(years)) > year) - years = _tree.PrependItem(root, yearString); - else - years = _tree.AppendItem(root, yearString); - } - - if (!_tree.GetChildrenCount(years, true)) - node = _tree.AppendItem(years, monthString); - else - { - for(i=0, it = ops[year].begin(); - it != ops[year].end(); - it++, i++) - { - if (*it > month) - break; - } - if (it == ops[year].end()) - years = _tree.AppendItem(years, monthString); - else - years = _tree.InsertItem(years, i-1, monthString); - } - - _tree.SelectItem(node, true); - ShowMonth(month, year); - _wxUI->NeedReload(); -} - -void AccountPanel::OnShow(wxShowEvent& event) -{ - if (_curMonth != -1) - _wxUI->SetTitle(_kiss->GetUser()->_name + wxT(" - ") + wxUI::months[_curMonth] + wxT(" ") + wxString::Format(wxT("%d"), _curYear)); - else - _wxUI->SetTitle(_kiss->GetUser()->_name); -} - -void AccountPanel::OnCalendarChange(wxCalendarEvent& event) -{ - UpdateStats(); -} - -void AccountPanel::OnModeChange(wxCommandEvent& event) -{ - UpdateStats(); -} - -void AccountPanel::OnGroup(wxCommandEvent& event) -{ - _grid->Group(); -} - -void AccountPanel::OnUnGroup(wxCommandEvent& event) -{ - _grid->UnGroup(); -} - -void AccountPanel::OnUpdateNextMonths(wxCommandEvent& event) -{ - double* deltas, *cur_amounts, amount; - int i, a; - User* user = _kiss->GetUser(); - bool had_values, accounts_updated = false; - int last_month = 0, last_year = 0, account_updated = 0; - std::map > operations; - - deltas = new double[user->_accounts.size()] ; - cur_amounts = new double[user->_accounts.size()] ; - - operations = _kiss->GetAllOperations(); - - if (_curMonth == 11) - { - last_month = 0; - last_year = _curYear+1; - } - else - { - last_month = _curMonth+1; - last_year = _curYear; - } - - for (i=0; i<(int)user->_accounts.size(); i++) - { - deltas[i] = _kiss->GetAccountAmount(user->_accounts[i].id, _curMonth, _curYear); - cur_amounts[i] = deltas[i] += _kiss->CalcAccountAmount(user->_accounts[i].id, _curMonth, _curYear, &had_values); - - for (a=0; a<(int)operations[last_year].size(); a++) - if (operations[last_year][a] == last_month) break; - - if (a == (int)operations[last_year].size()) - { - deltas[i] = 0; - continue; - } - - amount = _kiss->GetAccountAmount(user->_accounts[i].id, last_month, last_year); - - deltas[i] -= amount; - - account_updated++; - } - - if (!account_updated) - goto end; - - last_month = _curMonth; - last_year = _curYear; - - while (1) - { - account_updated = 0; - - if (last_month == 11) - { - last_month = 0; - last_year = last_year+1; - } - else - last_month++; - - for (i=0; i<(int)user->_accounts.size(); i++) - { - if (deltas[i] == 0.0) continue; - - amount = _kiss->GetAccountAmount(user->_accounts[i].id, last_month, last_year); - if ((cur_amounts[i] - amount) != deltas[i]) continue; - - cur_amounts[i] = amount + deltas[i]; - _kiss->SetAccountAmount(user->_accounts[i].id, last_month, last_year, cur_amounts[i]); - cur_amounts[i] += _kiss->CalcAccountAmount(user->_accounts[i].id, last_month, last_year, &had_values); - - account_updated++; - } - - if (!account_updated) break; - - accounts_updated = true; - } - - if (last_month == 0) - { - last_month = 11; - last_year--; - } - else - last_month--; - -end: - if (accounts_updated) - { - wxString message = _("Accounts updated until ") + wxUI::months[last_month]; - - message += wxT(" ") + wxString::Format(wxT("%d"), last_year); - - wxMessageBox(message, wxT("KissCount"), wxICON_INFORMATION | wxOK); - } - else - wxMessageBox(_("Any account updated !"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - - delete[] deltas; - delete[] cur_amounts; -} diff --git a/src/view/AccountPanel.hpp b/src/view/AccountPanel.hpp deleted file mode 100644 index fc55281..0000000 --- a/src/view/AccountPanel.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef ACCOUNTPANEL_H -#define ACCOUNTPANEL_H - -#include -#include -#include -#include -#include -#include - -#include "view.hpp" - -#include -#include "grid/GridAccount.hpp" -#include "grid/CalendarEditor.hpp" -#include - -class GridAccount; - -class AccountPanel: public KissPanel -{ -public: - AccountPanel(KissCount* kiss, wxUI *parent); - ~AccountPanel(); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - - void ChangeUser(); - void LoadYear(int year, bool showMonth=true); - void ShowMonth(int month, int year); - void GenerateMonth(int month, int year); - - void OnOperationModified(wxGridEvent& event); - void OnAccountModified(wxGridEvent& event); - void OnTreeRightClick(wxTreeEvent& event); - void OnTreeChange(wxTreeEvent& event); - void OnMenuGenerate(wxCommandEvent& event); - void OnMenuDelete(wxCommandEvent& event); - void OnCalendarChange(wxCalendarEvent& event); - void OnModeChange(wxCommandEvent& event); - void OnGroup(wxCommandEvent& event); - void OnUnGroup(wxCommandEvent& event); - void OnUpdateNextMonths(wxCommandEvent& event); - - int _curMonth, _curYear; - -private: - wxTreeCtrl _tree; - wxCalendarCtrl* _calendar; - GridAccount* _grid; - wxGrid *_statsGrid, *_accountsGrid; - PiePlot* _pie; - double *_categoriesValues; - wxRadioBox *_radioMode; - std::map _categoriesIndexes; - std::vector* _curOperations; - wxString* _categories, *_accounts; - std::map _accountsInitValues; - CategorySimpleDataset* _dataset; - int _fixCosts; - - void InitStatsGrid(User* user); - void InitAccountsGrid(User* user, int month, int year); - void UpdateStats(); - void InsertOperation(User* user, Operation* op, int line, bool fix); - void GetTreeSelection(int* month, int* year); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/ExportPanel.cpp b/src/view/ExportPanel.cpp deleted file mode 100644 index 4fb4f07..0000000 --- a/src/view/ExportPanel.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "grid/CalendarEditor.hpp" -#include "grid/wxGridCellBitmapRenderer.hpp" -#include "ExportPanel.hpp" - -enum {EXPORT_ID=1, SEARCH_ID, GRID_ID}; - -BEGIN_EVENT_TABLE(ExportPanel, wxPanel) -EVT_BUTTON(EXPORT_ID, ExportPanel::OnButtonExport) -EVT_BUTTON(SEARCH_ID, ExportPanel::OnButtonSearch) -EVT_SHOW(ExportPanel::OnShow) -END_EVENT_TABLE() - -ExportPanel::ExportPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent), _operations(0) -{ - DEFAULT_FONT(font); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - wxDateTime firstOfMonth; - wxRect rect = wxDisplay().GetGeometry(); - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *vbox2 = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - - SetSizer(vbox); - - _searchButton = new wxButton(this, SEARCH_ID, _("Searchpp")); - - _banner = new SearchBanner(kiss, this, this, OnEnter); - - vbox->Add(_banner, 0, wxGROW|wxALL, 5); - vbox->Add(_searchButton, 0, wxALL, 5); - - _grid = new GridAccount(_kiss, this, GRID_ID, false, false, false); - - hbox->Add(_grid, 0, wxGROW|wxALL, 5); - - _exportButton = new wxButton(this, EXPORT_ID, _("Export")); - - vbox2->Add(_exportButton, wxALL, 15); - - hbox->Add(vbox2, 0, wxALL, 15); - - vbox->Add(hbox, 0, wxGROW|wxALL, 5); - - Fit(); - - SetMinSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetMaxSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetScrollbars(10, 10, 100/10, 100/10); -} - -ExportPanel::~ExportPanel() -{ -} - -KissPanel* ExportPanel::CreatePanel() -{ - return new ExportPanel(_kiss, _wxUI); -} - -wxBitmapButton* ExportPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(EXPORT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString ExportPanel::GetToolTip() -{ - return _("Export"); -} - -void ExportPanel::OnEnter(void* caller, wxCommandEvent& event) -{ - ExportPanel* _this = (ExportPanel*) caller; - - _this->OnButtonExport(event); -} - -void ExportPanel::OnButtonSearch(wxCommandEvent& event) -{ - _operations = _banner->Search(); - - if (!_operations) return; - - if (_operations->size() > 1) - wxMessageBox(wxString::Format(wxT("%d"), _operations->size()) + _(" entries found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - else if (_operations->size() == 1) - wxMessageBox(_("1 entry found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - else - { - wxMessageBox(_("No entry found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - return; - } - - _grid->LoadOperations(_operations, 0, 0); - - _wxUI->Layout(); -} - -void ExportPanel::OnButtonExport(wxCommandEvent& event) -{ - if (!_operations || !_operations->size()) - { - wxMessageBox(_("No operation to save"), wxT("Error"), wxICON_ERROR | wxOK); - return; - } - - wxFileDialog saveFileDialog(this, _("Save as"), wxT(""), wxT(""), - _kiss->GetExportEngineExtensions(), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); - - if (saveFileDialog.ShowModal() == wxID_CANCEL) - return; - - _exportEngine = _kiss->GetExportEngine(saveFileDialog.GetPath()); - - if (!_exportEngine) - { - wxMessageBox(_("Any engine can process this file !"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - - return ; - } - - if (_exportEngine->SaveFile(_operations)) - wxMessageBox(_("Operations successfuly saved"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - else - wxMessageBox(_("Failed to save operations"), wxT("Error"), wxICON_ERROR | wxOK); - -} - -void ExportPanel::OnShow(wxShowEvent& event) -{ - _wxUI->SetTitle(_("KissCount - Export")); -} diff --git a/src/view/ExportPanel.hpp b/src/view/ExportPanel.hpp deleted file mode 100644 index 2b87dcc..0000000 --- a/src/view/ExportPanel.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef EXPORTPANEL_H -#define EXPORTPANEL_H - -#include -#include -#include -#include -#include "view.hpp" -#include "grid/GridAccount.hpp" -#include "SearchBanner.hpp" -#include -#include - -class GridAccount; -class SearchBanner; -class ExportEngine; - -class ExportPanel: public KissPanel -{ -public: - ExportPanel(KissCount* kiss, wxUI *parent); - ~ExportPanel(); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - - void OnButtonSearch(wxCommandEvent& event); - void OnButtonExport(wxCommandEvent& event); - -private: - std::vector *_operations; - SearchBanner* _banner; - GridAccount *_grid; - wxButton* _searchButton, *_exportButton; - ExportEngine* _exportEngine; - - static void OnEnter(void* caller, wxCommandEvent& event); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/GenerateDialog.cpp b/src/view/GenerateDialog.cpp deleted file mode 100644 index 0404cee..0000000 --- a/src/view/GenerateDialog.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include - -#include "GenerateDialog.hpp" - -enum {BUTTON_OK_ID=1, BUTTON_CANCEL_ID, YEAR_FROM_ID, MONTH_FROM_ID, YEAR_TO_ID, MONTH_TO_ID}; - -BEGIN_EVENT_TABLE(GenerateDialog, wxDialog) -EVT_BUTTON(BUTTON_OK_ID, GenerateDialog::OnOK) -EVT_BUTTON(BUTTON_CANCEL_ID, GenerateDialog::OnCancel) -EVT_CHOICE(YEAR_FROM_ID, GenerateDialog::OnYearFromChange) -EVT_CHOICE(YEAR_TO_ID, GenerateDialog::OnYearToChange) -END_EVENT_TABLE() - -GenerateDialog::GenerateDialog(KissCount* kiss, wxUI *parent, int month, int year) : wxDialog(&(*parent), wxID_ANY, _("Generate monthpp")), _kiss(kiss), _wxUI(parent) -{ - wxGridBagSizer *gridBagSizer; - wxStaticText* label; - std::map >::iterator it; - int i, a, toSelect=-1; - wxDateTime curDate; - wxCommandEvent event; - std::vector::iterator monthIt; - - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - gridBagSizer = new wxGridBagSizer(4, 5); - - curDate.SetToCurrent(); - - label = new wxStaticText(this, wxID_ANY, _("From ")); - gridBagSizer->Add(label, wxGBPosition(0, 0)); - _yearFrom = new wxChoice(this, YEAR_FROM_ID); - gridBagSizer->Add(_yearFrom, wxGBPosition(0, 1)); - _monthFrom = new wxChoice(this, MONTH_FROM_ID); - gridBagSizer->Add(_monthFrom, wxGBPosition(0, 2)); - - label = new wxStaticText(this, wxID_ANY, _("To ")); - gridBagSizer->Add(label, wxGBPosition(1, 0)); - _yearTo = new wxChoice(this, YEAR_TO_ID); - gridBagSizer->Add(_yearTo, wxGBPosition(1, 1)); - _monthTo = new wxChoice(this, MONTH_TO_ID); - gridBagSizer->Add(_monthTo, wxGBPosition(1, 2)); - - wxButton* ok = new wxButton(this, BUTTON_OK_ID, _("OK")); - wxButton* cancel = new wxButton(this, BUTTON_CANCEL_ID, _("Cancel")); - gridBagSizer->Add(ok, wxGBPosition(3, 3)); - gridBagSizer->Add(cancel, wxGBPosition(3, 4)); - - _ops = _kiss->GetAllOperations(); - - _yearFrom->Append(wxT("")); - _monthFrom->Append(wxT("")); - - for(i=1, it = _ops.begin(); it != _ops.end(); it++, i++) - { - _yearFrom->Append(wxString::Format(wxT("%d"), it->first)); - if (year == it->first) - toSelect = i; - } - - if (toSelect != -1) - { - _yearFrom->Select(toSelect); - OnYearFromChange(event); - toSelect=0; - if (month != -1) - { - for(i=0; i<(int)_monthFrom->GetCount(); i++) - { - if (_monthFrom->GetString(i) == wxUI::months[month]) - { - toSelect = i; - break; - } - } - } - _monthFrom->Select(toSelect); - } - else - { - _yearFrom->Select(0); - OnYearFromChange(event); - } - - for(i=2000; i<=2050; i++) - _yearTo->Append(wxString::Format(wxT("%d"), i)); - - if (year == -1) - { - _yearTo->Select(curDate.GetYear()-2000); - OnYearToChange(event); - _monthTo->Select(curDate.GetMonth()-1); - } - else - { - if (month == 11) - year++; - - _yearTo->Select(year-2000); - OnYearToChange(event); - - if (month == -1) - _monthTo->Select(0); - else - { - for(a=0, i=0, monthIt=_ops[year].begin(); monthIt!=_ops[year].end() && i<12; i++) - { - if (i != *monthIt) - { - a++; - continue; - } - if (*monthIt > month) - break; - monthIt++; - } - _monthTo->Select(a); - } - } - - hbox->Add(gridBagSizer, 0, wxGROW|wxALL, 10); - SetSizer(hbox); - - Fit(); - Center(); -} - -void GenerateDialog::OnYearFromChange(wxCommandEvent& event) -{ - wxString years = _yearFrom->GetString(_yearFrom->GetCurrentSelection()); - int year; - std::vector::iterator it; - - _monthFrom->Clear(); - - if (!years.Length()) - { - _monthFrom->Append(wxT("")); - return; - } - - year = wxAtoi(years); - - for(it=_ops[year].begin(); it!=_ops[year].end(); it++) - _monthFrom->Append(wxUI::months[*it]); - _monthFrom->Select(0); - - Layout(); -} - -void GenerateDialog::OnYearToChange(wxCommandEvent& event) -{ - int year, i, ok; - std::vector::iterator it; - - _monthTo->Clear(); - - year = wxAtoi(_yearTo->GetString(_yearTo->GetCurrentSelection())); - - for (i=0; i<12; i++) - { - ok = 1; - for(it=_ops[year].begin(); it!=_ops[year].end(); it++) - { - if (*it == i) - { - ok=0; break; - } - } - if (ok) - _monthTo->Append(wxUI::months[i]); - } - - _monthTo->Select(0); - - Layout(); -} - -void GenerateDialog::OnOK(wxCommandEvent& event) -{ - int monthFrom, yearFrom, monthTo, yearTo, i; - - if (!_yearFrom->GetString(_yearFrom->GetCurrentSelection()).Length()) - { - monthFrom = -1; - yearFrom = -1; - } - else - { - for (i=0; i<12; i++) - { - if (wxUI::months[i] == _monthFrom->GetString(_monthFrom->GetCurrentSelection())) - { - monthFrom = i; - break; - } - } - yearFrom = wxAtoi(_yearFrom->GetString(_yearFrom->GetCurrentSelection())); - } - - for (i=0; i<12; i++) - { - if (wxUI::months[i] == _monthTo->GetString(_monthTo->GetCurrentSelection())) - { - monthTo = i; - break; - } - } - yearTo = wxAtoi(_yearTo->GetString(_yearTo->GetCurrentSelection())); - - Close(); - _kiss->GenerateMonth(monthFrom, yearFrom, monthTo, yearTo); -} - -void GenerateDialog::OnCancel(wxCommandEvent& event) -{ - Close(); -} diff --git a/src/view/GenerateDialog.hpp b/src/view/GenerateDialog.hpp deleted file mode 100644 index 63b879d..0000000 --- a/src/view/GenerateDialog.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef GENERATEDIALOG_H -#define GENERATEDIALOG_H - -#include - -#include -#include -#include - -#include "wxUI.hpp" - -class wxUI; -class KissCount; - -class GenerateDialog : public wxDialog -{ -public: - GenerateDialog(KissCount* kiss, wxUI *parent, int month, int year); - - void OnYearFromChange(wxCommandEvent& event); - void OnYearToChange(wxCommandEvent& event); - void OnOK(wxCommandEvent& event); - void OnCancel(wxCommandEvent& event); - -private: - KissCount* _kiss; - wxUI* _wxUI; - wxChoice* _yearFrom, *_monthFrom, *_yearTo, *_monthTo; - std::map > _ops; - - DECLARE_EVENT_TABLE(); - -}; -#endif diff --git a/src/view/ImportPanel.cpp b/src/view/ImportPanel.cpp deleted file mode 100644 index 5ebd355..0000000 --- a/src/view/ImportPanel.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "ImportPanel.hpp" - -enum {OPEN_FILE_ID=1, BUTTON_OPEN_ID, NAME_ID, BUTTON_LOAD_ID, BUTTON_INTEGRATE_ID, CHECK_SAVE_ID, OPS_GRID_ID}; - -BEGIN_EVENT_TABLE(ImportPanel, wxPanel) -EVT_GRID_CMD_CELL_CHANGE(OPS_GRID_ID, ImportPanel::OnOperationModified) -EVT_BUTTON(BUTTON_OPEN_ID, ImportPanel::OnFile) -EVT_BUTTON(BUTTON_INTEGRATE_ID, ImportPanel::OnIntegrate) -EVT_TEXT_ENTER(OPEN_FILE_ID, ImportPanel::OnFileEnter) -EVT_BUTTON(BUTTON_LOAD_ID, ImportPanel::OnLoadOperations) -EVT_SHOW(ImportPanel::OnShow) -END_EVENT_TABLE() - -ImportPanel::ImportPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent) -{ - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *vbox2 = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - _hbox = new wxBoxSizer(wxHORIZONTAL); - wxButton* buttonOpen; - wxRect rect = wxDisplay().GetGeometry(); - int w, h; - wxStaticBox* staticAccount = new wxStaticBox(this, wxID_ANY, _("Unresolved accounts")); - wxStaticBox* staticCategory = new wxStaticBox(this, wxID_ANY, _("Unresolved categories")); - - SetSizer(vbox); - - _fileTxt = new wxTextCtrl(this, OPEN_FILE_ID); - _fileTxt->SetWindowStyle(_fileTxt->GetWindowStyle() | wxTE_PROCESS_ENTER); - _fileTxt->GetSize(&w, &h); - wxSize size(rect.width/3, h); - _fileTxt->SetMinSize(size); - buttonOpen = new wxButton(this, BUTTON_OPEN_ID, wxT("...")); - - _buttonLoadOperations = new wxButton(this, BUTTON_LOAD_ID, _("Load operations")); - _buttonLoadOperations->Disable(); - - _buttonIntegrate = new wxButton(this, BUTTON_INTEGRATE_ID, _("Integrate operations")); - _buttonIntegrate->Disable(); - - _checkSaveImportPatterns = new wxCheckBox(this, CHECK_SAVE_ID, _("Save import patterns")); - - hbox->Add(_fileTxt, 0, wxGROW|wxALL, 5); - hbox->Add(buttonOpen, 0, wxALL, 5); - hbox->Add(_buttonLoadOperations, 0, wxALL, 5); - hbox->Add(_buttonIntegrate, 0, wxALL, 5); - hbox->Add(_checkSaveImportPatterns, 0, wxALL, 5); - - vbox->Add(hbox, 0); - - _accountsGrid = new wxGrid(this, wxID_ANY); - _accountsGrid->CreateGrid(0, 3); - _accountsGrid->SetRowLabelSize(0); - _accountsGrid->SetColLabelValue(0, _("File account")); - _accountsGrid->SetColLabelValue(1, _("Account name")); - _accountsGrid->SetColLabelValue(2, _("Internal account")); - _accountsGrid->Fit(); - - _categoriesGrid = new wxGrid(this, wxID_ANY); - _categoriesGrid->CreateGrid(0, 3); - _categoriesGrid->SetRowLabelSize(0); - _categoriesGrid->SetColLabelValue(0, _("File category")); - _categoriesGrid->SetColLabelValue(1, _("Category name")); - _categoriesGrid->SetColLabelValue(2, _("Internal category")); - _categoriesGrid->Fit(); - - wxStaticBoxSizer* staticBoxSizer = new wxStaticBoxSizer (staticAccount, wxVERTICAL); - staticBoxSizer->Add(_accountsGrid, 0, wxGROW|wxALL, 2); - vbox2->Add(staticBoxSizer, wxGROW|wxALL); - - staticBoxSizer = new wxStaticBoxSizer (staticCategory, wxVERTICAL); - staticBoxSizer->Add(_categoriesGrid, 0, wxGROW|wxALL, 2); - vbox2->Add(staticBoxSizer, wxGROW|wxALL); - - _operationsGrid = new GridAccount(kiss, this, OPS_GRID_ID, false, false, false); - - _hbox->Add(vbox2, 0, wxGROW|wxALL, 15); - _hbox->Add(_operationsGrid, 0, wxGROW|wxALL, 15); - - vbox->Add(_hbox, wxGROW); - - Fit(); - - SetMinSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetMaxSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetScrollbars(10, 10, 100/10, 100/10); -} - -KissPanel* ImportPanel::CreatePanel() -{ - return new ImportPanel(_kiss, _wxUI); -} - -wxBitmapButton* ImportPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(IMPORT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString ImportPanel::GetToolTip() -{ - return _("Import"); -} - -void ImportPanel::OnShow(wxShowEvent& event) -{ - _wxUI->SetTitle(_("KissCount - Import")); -} - -void ImportPanel::OnFile(wxCommandEvent& WXUNUSED(event)) -{ - wxFileDialog openFileDialog(this, _("Choose a database to open"), wxT(""), wxT(""), - _kiss->GetImportEngineExtensions(), wxFD_OPEN|wxFD_FILE_MUST_EXIST); - - if (openFileDialog.ShowModal() == wxID_CANCEL) - return; - - _fileTxt->Clear(); - - *_fileTxt << openFileDialog.GetPath(); - - ProcessFile(); -} - -void ImportPanel::OnFileEnter(wxCommandEvent& WXUNUSED(event)) -{ - ProcessFile(); -} - -void ImportPanel::ProcessFile() -{ - User* user = _kiss->GetUser(); - int i; - wxGridCellChoiceEditor* accountEditor; - wxString* userAccounts; - std::map resolvedAccounts; - wxGridCellChoiceEditor* categoryEditor; - wxString* userCategories; - std::map resolvedCategories; - wxCommandEvent event; - - wxString path = _fileTxt->GetLineText(0); - - _buttonLoadOperations->Disable(); - _buttonIntegrate->Disable(); - _accountsGrid->ClearGrid(); - _categoriesGrid->ClearGrid(); - _operationsGrid->ClearGrid(); - - _importEngine = _kiss->GetImportEngine(path); - - if (!_importEngine) - { - wxMessageBox(_("Any engine can process this file !"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - - return ; - } - - _importEngine->ParseFile(_unresolvedAccounts, _unresolvedCategories); - - if (_unresolvedAccounts.size()) - { - int nb_accounts = user->GetAccountsNumber(); - userAccounts = new wxString[nb_accounts+1]; - - userAccounts[0] = _("Create one"); - - for(i=0; i_accounts[i].name; - - accountEditor = new wxGridCellChoiceEditor(nb_accounts+1, userAccounts, false); - - _buttonLoadOperations->Enable(); - - _accountsGrid->AppendRows(_unresolvedAccounts.size()); - - for (i=0; i<(int)_unresolvedAccounts.size(); i++) - { - _accountsGrid->SetCellValue(i, 0, _unresolvedAccounts[i].number); - _accountsGrid->SetReadOnly(i, 0); - _accountsGrid->SetCellValue(i, 1, _unresolvedAccounts[i].name); - _accountsGrid->SetCellValue(i, 2, userAccounts[0]); - - _accountsGrid->SetCellEditor(i, 2, accountEditor); - } - - _accountsGrid->AutoSize(); - _accountsGrid->Layout(); - } - - if (_unresolvedCategories.size()) - { - int nb_categories = user->GetCategoriesNumber(); - userCategories = new wxString[nb_categories+1]; - - userCategories[0] = _("Create one"); - - for(i=0; i_categories[i].name; - - categoryEditor = new wxGridCellChoiceEditor(nb_categories+1, userCategories, false); - - _buttonLoadOperations->Enable(); - - _categoriesGrid->AppendRows(_unresolvedCategories.size()); - - for (i=0; i<(int)_unresolvedCategories.size(); i++) - { - _categoriesGrid->SetCellValue(i, 0, _unresolvedCategories[i].name); - _categoriesGrid->SetReadOnly(i, 0); - _categoriesGrid->SetCellValue(i, 2, userCategories[0]); - - _categoriesGrid->SetCellEditor(i, 2, categoryEditor); - } - - _categoriesGrid->AutoSize(); - _categoriesGrid->Layout(); - } - - if (!_unresolvedAccounts.size() && !_unresolvedCategories.size()) - { - OnLoadOperations(event); - } - Layout(); -} - -void ImportPanel::OnLoadOperations(wxCommandEvent& WXUNUSED(event)) -{ - int i, nbAccounts=0, nbCategories=0; - User* user = _kiss->GetUser(); - Account account; - Category category; - std::map accounts; - std::map categories; - wxString oldid; - - for(i=0; i<_accountsGrid->GetNumberRows(); i++) - { - if (_accountsGrid->GetCellValue(i, 2) == _("Create one")) - nbAccounts++; - else - accounts[_accountsGrid->GetCellValue(i, 0)] = - user->GetAccountId(_accountsGrid->GetCellValue(i, 1)); - } - - for(i=0; i<_categoriesGrid->GetNumberRows(); i++) - { - if (_categoriesGrid->GetCellValue(i, 2) == _("Create one")) - nbCategories++; - else - categories[_categoriesGrid->GetCellValue(i, 0)] = - user->GetAccountId(_categoriesGrid->GetCellValue(i, 1)); - } - - if (nbAccounts || nbCategories) - { - wxString message; - - if (nbAccounts) - { - message += wxString::Format(_("%d accounts"), nbAccounts); - if (nbCategories) message += _(" and "); - } - - if (nbCategories) - message += wxString::Format(_("%d categories"), nbCategories); - - message += _(" will be created, is it ok ?"); - - wxMessageDialog dialog(_wxUI, message, wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - return; - - for(i=0; i<_accountsGrid->GetNumberRows(); i++) - { - if (_accountsGrid->GetCellValue(i, 2) == _("Create one")) - { - account = _unresolvedAccounts[i] ; - if (_accountsGrid->GetCellValue(i, 1).Length()) - account.name = _accountsGrid->GetCellValue(i, 1); - else - account.name = _accountsGrid->GetCellValue(i, 0); - account.number = _accountsGrid->GetCellValue(i, 0); - - oldid = account.id; - _resolvedAccounts[oldid] = accounts[_accountsGrid->GetCellValue(i, 0)] = _kiss->AddAccount(account); - } - } - - _accountsGrid->DeleteRows(0, _accountsGrid->GetNumberRows ()); - - for(i=0; i<_categoriesGrid->GetNumberRows(); i++) - { - if (_categoriesGrid->GetCellValue(i, 2) == _("Create one")) - { - category = _unresolvedCategories[i] ; - if (_categoriesGrid->GetCellValue(i, 1).Length()) - category.name = _categoriesGrid->GetCellValue(i, 1); - else - category.name = _categoriesGrid->GetCellValue(i, 0); - - oldid = category.id; - _resolvedCategories[oldid] = categories[_categoriesGrid->GetCellValue(i, 0)] = category.id = _kiss->AddCategory(category); - } - } - - _categoriesGrid->DeleteRows(0, _categoriesGrid->GetNumberRows ()); - - _wxUI->NeedReload(); - } - - _operations = _importEngine->GetOperations(accounts, categories); - - if (_operations->size()) - { - _hbox->Detach(_operationsGrid); - delete _operationsGrid; - _operationsGrid = new GridAccount(_kiss, this, OPS_GRID_ID, false, false, false); - _hbox->Add(_operationsGrid, 0, wxGROW|wxALL, 15); - - _operationsGrid->LoadOperations(_operations, 0, 0); - _buttonIntegrate->Enable(); - - _buttonLoadOperations->Disable(); - - Fit(); - } - else - { - wxMessageBox(_("No operation found into this file"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - } -} - -void ImportPanel::OnIntegrate(wxCommandEvent& WXUNUSED(event)) -{ - int i; - std::map mapid; - wxString oldid, account; - bool update; - std::map accountAmounts; - std::map::iterator it; - double amount; - - if (!_operations->size()) return; - - wxMessageDialog dialog(_wxUI, _("Are you sure want to integrate these operations ?"), wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - return; - - _buttonIntegrate->Disable(); - - for(i=0; i<(int)_operations->size(); i++) - { - oldid = (*_operations)[i].id; - _kiss->AddOperation((*_operations)[i], false); - mapid[oldid] = (*_operations)[i].id; - } - - for(i=0; i<(int)_operations->size(); i++) - { - update = false; - - if ((*_operations)[i].parent.Length()) - { - (*_operations)[i].parent = mapid[(*_operations)[i].parent]; - update = true; - } - - if ((*_operations)[i].transfert.Length()) - { - (*_operations)[i].transfert = mapid[(*_operations)[i].transfert]; - update = true; - } - - if (update) - _kiss->UpdateOperation((*_operations)[i], false); - } - - accountAmounts = _importEngine->GetAccountAmounts(); - - for(it=accountAmounts.begin(); it!=accountAmounts.end(); it++) - { - account = it->first.account; - - if (_resolvedAccounts.count(account)) - account = _resolvedAccounts[account]; - - amount = _kiss->GetAccountAmount(account, it->first.month, it->first.year); - - if (!amount) - _kiss->SetAccountAmount(account, it->first.month, it->first.year, it->second); - } - - if (_checkSaveImportPatterns->IsChecked()) - _kiss->UpdateImportPattern(); - - _operations->clear(); - _operationsGrid->ClearGrid(); - - wxMessageBox(_("Operations successfully imported"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - - _wxUI->NeedReload(); -} - -void ImportPanel::OnOperationModified(wxGridEvent& event) -{ - int col = event.GetCol(); - int row; - static bool update = false; - - if (col != DESCRIPTION && col != CATEGORY && col != ACCOUNT) return ; - - if (update) return; - - update = true; - - row = event.GetRow(); - - _operationsGrid->ClearGrid(); - - if (_importEngine->UpdatePattern(row-1) > 1) - _operationsGrid->LoadOperations(_operations, 0, 0); - - Fit(); - - update = false; -} diff --git a/src/view/ImportPanel.hpp b/src/view/ImportPanel.hpp deleted file mode 100644 index 388c505..0000000 --- a/src/view/ImportPanel.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef IMPORTPANEL_H -#define IMPORTPANEL_H - -#include - -#include "view.hpp" -#include -#include - -#include "grid/GridAccount.hpp" - -class ImportPanel: public KissPanel -{ -public: - ImportPanel(KissCount* kiss, wxUI *parent); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - - void OnFile(wxCommandEvent& WXUNUSED(event)); - void OnFileEnter(wxCommandEvent& WXUNUSED(event)); - void OnLoadOperations(wxCommandEvent& WXUNUSED(event)); - void OnIntegrate(wxCommandEvent& WXUNUSED(event)); - void OnOperationModified(wxGridEvent& event); - -private: - wxBoxSizer *_hbox; - wxGrid* _accountsGrid, *_categoriesGrid; - wxTextCtrl* _fileTxt; - GridAccount* _operationsGrid; - ImportEngine* _importEngine; - wxButton* _buttonLoadOperations, *_buttonIntegrate; - wxCheckBox *_checkSaveImportPatterns; - std::vector* _operations; - - std::vector _unresolvedAccounts; - std::vector _unresolvedCategories; - std::map _resolvedAccounts; - std::map _resolvedCategories; - - void ProcessFile(); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/KissPanel.hpp b/src/view/KissPanel.hpp index af5bdd8..8c83aba 100644 --- a/src/view/KissPanel.hpp +++ b/src/view/KissPanel.hpp @@ -20,34 +20,5 @@ #ifndef KISSPANEL_H #define KISSPANEL_H -#include -#include -#include - -#include "wxUI.hpp" - -class wxUI; -class KissCount; - -class KissPanel: public wxScrolledWindow -{ -public: - KissPanel(KissCount* kiss, wxUI* parent) : - wxScrolledWindow((wxFrame*)parent), - _kiss(kiss), - _wxUI(parent), - _KissButton(0) - {Hide();} - - virtual void OnShow(wxShowEvent& event)=0; - virtual KissPanel* CreatePanel()=0; - virtual wxBitmapButton* GetButton(int id) {return 0;} - virtual wxString GetToolTip() {return wxT("");} - -protected: - KissCount* _kiss; - wxUI* _wxUI; - wxBitmapButton* _KissButton; -}; #endif diff --git a/src/view/PasswordDialog.cpp b/src/view/PasswordDialog.cpp deleted file mode 100644 index 7311892..0000000 --- a/src/view/PasswordDialog.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include - -#include "PasswordDialog.hpp" - -enum {BUTTON_OK_ID=1, BUTTON_CANCEL_ID, OLD_PASSWORD_ID, NEW_PASSWORD_ID, CONFIRM_PASSWORD_ID}; - -BEGIN_EVENT_TABLE(PasswordDialog, wxDialog) -EVT_BUTTON(BUTTON_OK_ID, PasswordDialog::OnOK) -EVT_BUTTON(BUTTON_CANCEL_ID, PasswordDialog::OnCancel) -END_EVENT_TABLE() - -PasswordDialog::PasswordDialog(KissCount* kiss, wxUI *parent) : wxDialog(&(*parent), wxID_ANY, _("Change password")), _kiss(kiss), _wxUI(parent) -{ - wxGridBagSizer *gridBagSizer; - wxStaticText* label; - - gridBagSizer = new wxGridBagSizer(5, 3); - - label = new wxStaticText(this, wxID_ANY, _("Old password ")); - gridBagSizer->Add(label, wxGBPosition(0, 0)); - _oldPassword = new wxTextCtrl(this, OLD_PASSWORD_ID); - gridBagSizer->Add(_oldPassword, wxGBPosition(0, 1)); - - label = new wxStaticText(this, wxID_ANY, _("New password ")); - gridBagSizer->Add(label, wxGBPosition(1, 0)); - _newPassword = new wxTextCtrl(this, NEW_PASSWORD_ID); - gridBagSizer->Add(_newPassword, wxGBPosition(1, 1)); - - label = new wxStaticText(this, wxID_ANY, _("Confirm password ")); - gridBagSizer->Add(label, wxGBPosition(2, 0)); - _confirmPassword = new wxTextCtrl(this, CONFIRM_PASSWORD_ID); - gridBagSizer->Add(_confirmPassword, wxGBPosition(2, 1)); - - _oldPassword->SetWindowStyle(wxTE_PASSWORD); - _newPassword->SetWindowStyle(wxTE_PASSWORD); - _confirmPassword->SetWindowStyle(wxTE_PASSWORD); - - wxButton* ok = new wxButton(this, BUTTON_OK_ID, _("OK")); - wxButton* cancel = new wxButton(this, BUTTON_CANCEL_ID, _("Cancel")); - gridBagSizer->Add(ok, wxGBPosition(4, 1)); - gridBagSizer->Add(cancel, wxGBPosition(4, 2)); - - SetSizer(gridBagSizer); - - Layout(); - Center(); -} - -void PasswordDialog::OnOK(wxCommandEvent& event) -{ - User* user = _kiss->GetUser(); - - if (!_kiss->IsValidUser(user->_name, _oldPassword->GetLineText(0))) - { - wxMessageBox(_("Invalid old password"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - if (_newPassword->GetLineText(0) != _confirmPassword->GetLineText(0)) - { - wxMessageBox(_("Please retype new password"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - _kiss->ChangePassword(_newPassword->GetLineText(0)); - - wxMessageBox(_("Password changed"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - Close(); -} - -void PasswordDialog::OnCancel(wxCommandEvent& event) -{ - Close(); -} diff --git a/src/view/PasswordDialog.hpp b/src/view/PasswordDialog.hpp deleted file mode 100644 index d589715..0000000 --- a/src/view/PasswordDialog.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef PASSWORDDIALOG_H -#define PASSWORDDIALOG_H - -#include -#include "wxUI.hpp" -#include - -class wxUI; -class KissCount; - -class PasswordDialog : public wxDialog -{ -public: - PasswordDialog(KissCount* kiss, wxUI *parent); - - void OnOK(wxCommandEvent& event); - void OnCancel(wxCommandEvent& event); - -private: - KissCount* _kiss; - wxUI* _wxUI; - wxTextCtrl* _oldPassword, *_newPassword, *_confirmPassword; - - DECLARE_EVENT_TABLE(); -}; -#endif diff --git a/src/view/PreferencesPanel.cpp b/src/view/PreferencesPanel.cpp deleted file mode 100644 index ba2b5c2..0000000 --- a/src/view/PreferencesPanel.cpp +++ /dev/null @@ -1,863 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "grid/wxMyGrid.hpp" -#include "grid/wxGridCellStarEditor.hpp" -#include "grid/wxGridCellFastBoolEditor.hpp" -#include "grid/wxGridCellButtonRenderer.hpp" -#include "grid/wxGridCellButtonEditor.hpp" -#include "PasswordDialog.hpp" - -#include "PreferencesPanel.hpp" - -enum {ACCOUNT_NAME, ACCOUNT_NUMBER, ACCOUNT_DEFAULT, ACCOUNT_VIRTUAL, ACCOUNT_BLOCKED, ACCOUNT_DELETE, NUMBER_COLS_ACCOUNT}; -enum {CATEGORY_NAME, CATEGORY_BACKGROUND_COLOR, CATEGORY_FOREGROUND_COLOR, CATEGORY_FONT, CATEGORY_DELETE, NUMBER_COLS_CATEGORY}; - -enum {CATEGORIES_GRID_ID=1, ACCOUNTS_GRID_ID, NAME_ID, CHANGE_NAME_ID, CHANGE_PASSWORD_ID, KILL_ME_ID, LANGUAGE_ID, - OPERATION_ORDER_ID, SHARED_WITH_ID}; - -BEGIN_EVENT_TABLE(PreferencesPanel, wxPanel) -EVT_BUTTON(CHANGE_NAME_ID, PreferencesPanel::OnChangeName) -EVT_BUTTON(CHANGE_PASSWORD_ID, PreferencesPanel::OnChangePassword) -EVT_BUTTON(KILL_ME_ID, PreferencesPanel::OnKillMe) -EVT_GRID_CMD_CELL_CHANGE(CATEGORIES_GRID_ID, PreferencesPanel::OnCategoryModified) -EVT_GRID_CMD_CELL_CHANGE(ACCOUNTS_GRID_ID, PreferencesPanel::OnAccountModified) -EVT_GRID_CMD_SELECT_CELL(ACCOUNTS_GRID_ID, PreferencesPanel::OnAccountCellChanged) -EVT_COMBOBOX(OPERATION_ORDER_ID, PreferencesPanel::OnOperationOrderChange) -EVT_COMBOBOX(LANGUAGE_ID, PreferencesPanel::OnLanguageChange) -EVT_CHECKLISTBOX(SHARED_WITH_ID, PreferencesPanel::OnSharedChange) -EVT_SHOW(PreferencesPanel::OnShow) -END_EVENT_TABLE() - -PreferencesPanel::PreferencesPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent), _sharedWith(0), _curAccountRow(-1) -{ - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); - //wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - wxStaticBox* staticUser, *staticAccount, *staticCategories, *staticLanguage, *staticOperationOrder, *staticSharedWith; - User* user = _kiss->GetUser(); - wxGridBagSizer *gridBagSizer; - wxStaticText* label; - wxButton* buttonChangeName, *buttonChangePassword, *killMe; - wxStaticBoxSizer * staticBoxSizer; - std::list users; - std::list::iterator it; - wxRect rect = wxDisplay().GetGeometry(); - - SetSizer(vbox); - - staticUser = new wxStaticBox(this, wxID_ANY, _("User")); - staticAccount = new wxStaticBox(this, wxID_ANY, _("Accounts")); - staticCategories = new wxStaticBox(this, wxID_ANY, _("Categories")); - staticLanguage = new wxStaticBox(this, wxID_ANY, _("Language")); - staticOperationOrder = new wxStaticBox(this, wxID_ANY, _("Operation order")); - staticSharedWith = new wxStaticBox(this, wxID_ANY, _("Shared withpp")); - - // User - staticBoxSizer = new wxStaticBoxSizer (staticUser, wxVERTICAL); - - gridBagSizer = new wxGridBagSizer(2, 3); - staticBoxSizer->Add(gridBagSizer, 0, wxGROW|wxALL, 2); - - label = new wxStaticText(this, wxID_ANY, _("Name")); - gridBagSizer->Add(label, wxGBPosition(0, 0)); - - _name = new wxTextCtrl(this, NAME_ID, user->_name); - gridBagSizer->Add(_name, wxGBPosition(0, 1)); - - buttonChangeName = new wxButton(this, CHANGE_NAME_ID, _("Change Name")); - buttonChangePassword = new wxButton(this, CHANGE_PASSWORD_ID, _("Change Password")); - killMe = new wxButton(this, KILL_ME_ID, _("Kill me")); - - gridBagSizer->Add(buttonChangeName, wxGBPosition(1, 0)); - gridBagSizer->Add(buttonChangePassword, wxGBPosition(1, 1)); - gridBagSizer->Add(killMe, wxGBPosition(1, 2)); - - vbox->Add(staticBoxSizer, 0, wxALL, 10); - - // Account - staticBoxSizer = new wxStaticBoxSizer (staticAccount, wxVERTICAL); - - { - int clicks[] = {ACCOUNT_DEFAULT, ACCOUNT_DELETE}; - - _accountsGrid = new wxMyGrid(this, ACCOUNTS_GRID_ID, clicks, 2); - } - - InitAccounts(user); - - staticBoxSizer->Add(_accountsGrid, 0, wxGROW|wxALL, 2); - - hbox1->Add(staticBoxSizer, 0, wxALL); - - staticBoxSizer = new wxStaticBoxSizer (staticSharedWith, wxVERTICAL); - _sharedWith = new wxCheckListBox(this, SHARED_WITH_ID); - - staticBoxSizer->Add(_sharedWith, 0, wxGROW); - - users = _kiss->GetUsers(); - - for(it=users.begin(); it!=users.end(); it++) - if (*it != user->_name) - _sharedWith->Append(*it); - - _sharedWith->Enable(false); - - hbox1->Add(staticBoxSizer, 0, wxLEFT, 5); - vbox->Add(hbox1, 0, wxGROW|wxALL, 10); - - // Categories - staticBoxSizer = new wxStaticBoxSizer (staticCategories, wxVERTICAL); - - { - int clicks[] = {CATEGORY_BACKGROUND_COLOR, CATEGORY_FOREGROUND_COLOR, CATEGORY_FONT, CATEGORY_DELETE}; - - _categoriesGrid = new wxMyGrid(this, CATEGORIES_GRID_ID, clicks, 4); - } - - staticBoxSizer->Add(_categoriesGrid, 0, wxGROW|wxALL, 2); - - InitCategories(user); - - vbox->Add(staticBoxSizer, 0, wxALL, 10); - - // Operation Order - staticBoxSizer = new wxStaticBoxSizer (staticOperationOrder, wxVERTICAL); - - _operationOrder = new wxComboBox(this, OPERATION_ORDER_ID); - _operationOrder->SetWindowStyle(wxCB_READONLY); - - staticBoxSizer->Add(_operationOrder, 0, wxGROW|wxALL, 2); - - hbox2->Add(staticBoxSizer, 0); - - InitOperationOrder(user); - - // Language - staticBoxSizer = new wxStaticBoxSizer (staticLanguage, wxVERTICAL); - - _language = new wxBitmapComboBox(this, LANGUAGE_ID); - _language->SetWindowStyle(wxCB_READONLY); - - staticBoxSizer->Add(_language, 0, wxGROW|wxALL, 2); - - hbox2->Add(staticBoxSizer, 0, wxLEFT, 10); - - InitLanguage(user); - - _language->Fit(); - - vbox->Add(hbox2, 0, wxALL, 10); - - Fit(); - - SetMinSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetMaxSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetScrollbars(10, 10, 100/10, 100/10); -} - -KissPanel* PreferencesPanel::CreatePanel() -{ - return new PreferencesPanel(_kiss, _wxUI); -} - -wxBitmapButton* PreferencesPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(PREFS_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString PreferencesPanel::GetToolTip() -{ - return _("Preferences"); -} - -void PreferencesPanel::InitAccounts(User* user) -{ - std::vector::iterator it; - int curLine = 0; - Account account ; - DEFAULT_FONT(font); - - _accountsGrid->CreateGrid(0, NUMBER_COLS_ACCOUNT); - _accountsGrid->SetRowLabelSize(0); - _accountsGrid->SetColLabelValue(ACCOUNT_NAME, _("Name")); - _accountsGrid->SetColLabelValue(ACCOUNT_NUMBER, _("Number")); - _accountsGrid->SetColLabelValue(ACCOUNT_DEFAULT, _("Default")); - _accountsGrid->SetColLabelValue(ACCOUNT_VIRTUAL, _("Virtual")); - _accountsGrid->SetColLabelValue(ACCOUNT_BLOCKED, _("Blocked")); - _accountsGrid->SetColLabelValue(ACCOUNT_DELETE, _("Delete")); - _accountsGrid->SetDefaultCellFont(font); - - for (it = user->_accounts.begin(); it != user->_accounts.end(); it++, curLine++) - { - _accountsGrid->AppendRows(); - AddAccount(curLine, *it); - } - - _accountsGrid->AppendRows(); - account.id = wxT("0"); - AddAccount(curLine, account); -} - -void PreferencesPanel::AddAccount(int line, Account ac) -{ - if (ac.id != wxT("0")) - { - _accountsGrid->SetCellValue(line, ACCOUNT_NAME, ac.name); - if (ac.shared) - _accountsGrid->SetCellValue(line, ACCOUNT_NUMBER, ac.number + wxT("*")); - else - _accountsGrid->SetCellValue(line, ACCOUNT_NUMBER, ac.number); - - _accountsGrid->SetCellEditor(line, ACCOUNT_NUMBER, new wxGridCellStarEditor ()); - _accountsGrid->SetCellRenderer(line, ACCOUNT_DEFAULT, new wxGridCellBoolRenderer ()); - _accountsGrid->SetCellEditor(line, ACCOUNT_DEFAULT, new wxGridCellFastBoolEditor ()); - _accountsGrid->SetCellRenderer(line, ACCOUNT_VIRTUAL, new wxGridCellBoolRenderer ()); - _accountsGrid->SetCellEditor(line, ACCOUNT_VIRTUAL, new wxGridCellFastBoolEditor ()); - _accountsGrid->SetCellRenderer(line, ACCOUNT_BLOCKED, new wxGridCellBoolRenderer ()); - _accountsGrid->SetCellEditor(line, ACCOUNT_BLOCKED, new wxGridCellFastBoolEditor ()); - _accountsGrid->SetCellRenderer(line, ACCOUNT_DELETE, new wxGridCellBoolRenderer ()); - _accountsGrid->SetCellEditor(line, ACCOUNT_DELETE, new wxGridCellBoolEditor ()); - _accountsGrid->SetCellValue(line, ACCOUNT_DEFAULT, (ac._default)?wxT("1"):wxT("0")); - _accountsGrid->SetCellValue(line, ACCOUNT_VIRTUAL, (ac._virtual)?wxT("1"):wxT("0")); - _accountsGrid->SetCellValue(line, ACCOUNT_BLOCKED, (ac.blocked)?wxT("1"):wxT("0")); - - _accountsGrid->SetCellAlignment(line, ACCOUNT_DEFAULT, wxALIGN_CENTRE, wxALIGN_CENTRE); - _accountsGrid->SetCellAlignment(line, ACCOUNT_VIRTUAL, wxALIGN_CENTRE, wxALIGN_CENTRE); - _accountsGrid->SetCellAlignment(line, ACCOUNT_BLOCKED, wxALIGN_CENTRE, wxALIGN_CENTRE); - _accountsGrid->SetCellAlignment(line, ACCOUNT_DELETE, wxALIGN_CENTRE, wxALIGN_CENTRE); - - if (!ac.is_owner) - { - _accountsGrid->SetReadOnly(line, ACCOUNT_NAME, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_NUMBER, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_DEFAULT, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_VIRTUAL, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_BLOCKED, true); - } - else - { - _accountsGrid->SetReadOnly(line, ACCOUNT_DEFAULT, false); - _accountsGrid->SetReadOnly(line, ACCOUNT_VIRTUAL, false); - _accountsGrid->SetReadOnly(line, ACCOUNT_BLOCKED, false); - _accountsGrid->SetReadOnly(line, ACCOUNT_DELETE, false); - } - } - else - { - _accountsGrid->SetReadOnly(line, ACCOUNT_DEFAULT, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_VIRTUAL, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_BLOCKED, true); - _accountsGrid->SetReadOnly(line, ACCOUNT_DELETE, true); - - _accountsGrid->AutoSizeColumns(true); - } -} - -#define SET_ROW_COLOR(row, backcolor, forecolor) for(int i=0; iSetCellBackgroundColour(row, i, backcolor); \ - _categoriesGrid->SetCellTextColour(row, i, forecolor); \ - } - -#define SET_ROW_FONT(row, font) for(int i=0; iSetCellFont(row, i, font); \ - } - -void PreferencesPanel::InitCategories(User* user) -{ - std::vector::iterator it; - int curLine = 0; - DEFAULT_FONT(font); - Category cat; - - _categoriesGrid->CreateGrid(0, NUMBER_COLS_CATEGORY); - _categoriesGrid->SetRowLabelSize(0); - _categoriesGrid->SetDefaultCellFont(font); - - _categoriesGrid->SetColLabelValue(CATEGORY_NAME, _("Name")); - _categoriesGrid->SetColLabelValue(CATEGORY_BACKGROUND_COLOR, _("Background color")); - _categoriesGrid->SetColLabelValue(CATEGORY_FOREGROUND_COLOR, _("Foreground color")); - _categoriesGrid->SetColLabelValue(CATEGORY_FONT, _("Font")); - _categoriesGrid->SetColLabelValue(CATEGORY_DELETE, _("Delete")); - - for (it=user->_categories.begin(); it!=user->_categories.end(); it++, curLine++) - { - _categoriesGrid->AppendRows(); - AddCategory(curLine, *it); - } - - _categoriesGrid->SetReadOnly(0, CATEGORY_NAME, true); - _categoriesGrid->SetReadOnly(0, CATEGORY_DELETE, true); - - cat.id = wxT("0"); - _categoriesGrid->AppendRows(); - AddCategory(curLine, cat); -} - -void PreferencesPanel::AddCategory(int line, Category cat) -{ - User* user = _kiss->GetUser(); - - if (cat.id != wxT("0")) - { - _categoriesGrid->SetCellValue(line, CATEGORY_NAME, wxGetTranslation(cat.name)); - SET_ROW_COLOR(line, cat.backcolor, cat.forecolor); - if (line) - { - _categoriesGrid->SetCellRenderer(line, CATEGORY_DELETE, new wxGridCellBoolRenderer ()); - _categoriesGrid->SetCellEditor(line, CATEGORY_DELETE, new wxGridCellBoolEditor ()); - } - - _categoriesGrid->SetCellRenderer(line, CATEGORY_BACKGROUND_COLOR, new wxGridCellButtonRenderer (wxT("..."))); - _categoriesGrid->SetCellRenderer(line, CATEGORY_FOREGROUND_COLOR, new wxGridCellButtonRenderer (wxT("..."))); - _categoriesGrid->SetCellRenderer(line, CATEGORY_FONT, new wxGridCellButtonRenderer (wxT("..."))); - _categoriesGrid->SetCellEditor(line, CATEGORY_BACKGROUND_COLOR, new wxGridCellButtonEditor (wxT("..."))); - _categoriesGrid->SetCellEditor(line, CATEGORY_FOREGROUND_COLOR, new wxGridCellButtonEditor (wxT("..."))); - _categoriesGrid->SetCellEditor(line, CATEGORY_FONT, new wxGridCellButtonEditor (wxT("..."))); - - if (cat.font.Length()) - { - wxFont font = user->GetCategoryFont(cat.id); - SET_ROW_FONT(line, font); - } - - _categoriesGrid->SetCellAlignment(line, CATEGORY_DELETE, wxALIGN_CENTRE, wxALIGN_CENTRE); - } - else - { - _categoriesGrid->SetReadOnly(line, CATEGORY_BACKGROUND_COLOR, true); - _categoriesGrid->SetReadOnly(line, CATEGORY_FOREGROUND_COLOR, true); - _categoriesGrid->SetReadOnly(line, CATEGORY_FONT, true); - _categoriesGrid->SetReadOnly(line, CATEGORY_DELETE, true); - SET_ROW_COLOR(line, view::OWN_GREEN, *wxBLACK); - - _categoriesGrid->AutoSizeColumns(true); - } -} - -void PreferencesPanel::InitLanguage(User* user) -{ - int i, select=0; - - for (i=0; iAppend(SupportedLanguages::languages[i].name, wxBitmap(SupportedLanguages::languages[i].icon, wxBITMAP_TYPE_PNG)); - if (SupportedLanguages::languages[i].language == _wxUI->_language) - select = i; - } - - _language->Select(select); -} - -void PreferencesPanel::InitOperationOrder(User* user) -{ - _operationOrder->Append(_("Ascending")); - _operationOrder->Append(_("Descending")); - - if (user->_preferences[wxT("operation_order")] == wxT("ASC")) - _operationOrder->Select(0); - else - _operationOrder->Select(1); -} - -void PreferencesPanel::OnAccountModified(wxGridEvent& event) -{ - int op_complete = 1; - wxString value ; - Account new_account, account; - User* user = _kiss->GetUser(); - int row = event.GetRow(); - int col = event.GetCol(); - static bool inModification = false ; - int i, a; - - if (inModification) return; - - inModification = true; - - value = _accountsGrid->GetCellValue(row, ACCOUNT_NAME); - if (value.Length()) - { - new_account.name = value; - op_complete--; - } - - value = _accountsGrid->GetCellValue(row, ACCOUNT_NUMBER); - if (value.Length()) - { - new_account.number = value; - op_complete--; - } - - value = _accountsGrid->GetCellValue(row, ACCOUNT_DEFAULT); - if (value.Length() && value != wxT("0")) - new_account._default = true; - else - new_account._default = false; - - value = _accountsGrid->GetCellValue(row, ACCOUNT_VIRTUAL); - if (value.Length() && value != wxT("0")) - new_account._virtual = true; - else - new_account._virtual = false; - - value = _accountsGrid->GetCellValue(row, ACCOUNT_BLOCKED); - if (value.Length() && value != wxT("0")) - new_account.blocked = true; - else - new_account.blocked = false; - - // Account modification - if (user->GetAccountsNumber() && row < user->GetAccountsNumber()) - { - new_account.id = user->_accounts[row].id; - new_account.shared = user->_accounts[row].shared; - new_account.is_owner = user->_accounts[row].is_owner; - - if (col == ACCOUNT_DELETE) - { - if (user->_accounts.size() == 1) - { - wxMessageBox(_("It must be at least one account !"), _("Error"), wxICON_ERROR | wxOK); - _accountsGrid->SetCellValue(row, col, wxT("0")); - return; - } - wxString *accounts = new wxString[user->GetAccountsNumber()]; - accounts[0] = _("None"); - a = 0; - for(i=0; i < user->GetAccountsNumber(); i++) - if (user->_accounts[i].id != new_account.id) - accounts[++a] = user->_accounts[i].name; - wxSingleChoiceDialog dialog(_wxUI, _("Wich account will replace this one ?"), wxT("KissCount"), user->GetAccountsNumber(), accounts); - - if (dialog.ShowModal() == wxID_CANCEL) - { - _accountsGrid->SetCellValue(row, col, wxT("0")); - } - else - { - _accountsGrid->DeleteRows(row, 1); - i = dialog.GetSelection(); - _kiss->DeleteAccount(new_account, (!i) ? wxT("0") : user->GetAccountId(accounts[i])); - } - - if (user->_accounts.size() == 1) - { - user->_accounts[0]._default = true; - _kiss->UpdateAccount(user->_accounts[0]); - _accountsGrid->SetCellValue(0, ACCOUNT_DEFAULT, wxT("1")); - } - - Fit(); - inModification = false; - _wxUI->NeedReload(); - return; - } - - if (col == ACCOUNT_DEFAULT) - { - for (i=0; iGetAccountsNumber(); i++) - { - if (i != row) - { - account = user->_accounts[i]; - if (account._default) - { - account._default = false; - _kiss->UpdateAccount(account); - _accountsGrid->SetCellValue(i, ACCOUNT_DEFAULT, wxT("")); - break; - } - } - } - } - - - if (col == ACCOUNT_NAME) - { - value = user->GetAccountId(new_account.name); - if (value != wxT("0") && value != new_account.id) - { - wxMessageBox(_("Account ")+new_account.name+_(" already exists"), _("Error"), wxICON_ERROR | wxOK ); - _accountsGrid->SetCellValue(row, ACCOUNT_NAME, user->_accounts[row].name); - inModification = false; - return ; - } - } - - _kiss->UpdateAccount(new_account); - } - // New account - else - { - if (op_complete) - { - inModification = false; - return ; - } - - if (user->GetAccountId(new_account.name) != wxT("0")) - { - wxMessageBox(_("Account ")+new_account.name+_(" already exists"), _("Error"), wxICON_ERROR | wxOK ); - inModification = false; - return ; - } - - new_account.shared = false; - new_account.blocked = false; - new_account.is_owner = true; - new_account._virtual = false; - - AddAccount(row, new_account); - _kiss->AddAccount(new_account); - - _accountsGrid->AppendRows(); - new_account.id = wxT("0"); - - AddAccount(row+1, new_account); - } - - Fit(); - _wxUI->NeedReload(); - inModification = false; -} - -void PreferencesPanel::OnAccountCellChanged(wxGridEvent& event) -{ - User* user = _kiss->GetUser(); - int row = event.GetRow(); - std::map::iterator it; - int i; - bool own; - wxString owner; - - if (!_sharedWith || _curAccountRow == row) - { - event.Skip(); - return ; - } - - _curAccountRow = row ; - - if (row >= (int) user->_accounts.size()) - { - for(i=0; i<(int)_sharedWith->GetCount(); i++) - _sharedWith->Check(i, false); - own = false; - } - else - { - _sharedOwners = _kiss->getSharedAccountOwners(user->_accounts[row].id); - owner = _kiss->getSharedAccountOwner(user->_accounts[row].id); - for(i=0; i<(int)_sharedWith->GetCount(); i++) - { - _sharedWith->Check(i, _sharedOwners[_sharedWith->GetString(i)].Length() > 0 || - _sharedWith->GetString(i) == owner); - } - own = user->_accounts[row].is_owner; - } - - _sharedWith->Enable(own); - event.Skip(); -} - -void PreferencesPanel::OnSharedChange(wxCommandEvent& event) -{ - User* user = _kiss->GetUser(); - - // Event is fired before change - if (_sharedWith->IsChecked(event.GetSelection())) - { - if (!user->_accounts[_curAccountRow].shared) - _accountsGrid->SetCellValue(_curAccountRow, ACCOUNT_NUMBER, - user->_accounts[_curAccountRow].number + wxT("*")); - - _kiss->AddSharedAccount(user->_accounts[_curAccountRow], - _sharedWith->GetString(event.GetSelection())); - } - else - { - _kiss->RemoveSharedAccount(user->_accounts[_curAccountRow], - _sharedOwners[_sharedWith->GetString( - event.GetSelection())]); - - if (!user->_accounts[_curAccountRow].shared) - _accountsGrid->SetCellValue(_curAccountRow, ACCOUNT_NUMBER, user->_accounts[_curAccountRow].number); - } - - _wxUI->NeedReload(); - - event.Skip(); -} - -void PreferencesPanel::OnCategoryModified(wxGridEvent& event) -{ - int op_complete = 1; - wxString value; - User* user = _kiss->GetUser(); - int row = event.GetRow(); - int col = event.GetCol(); - static bool inModification = false ; - Category new_cat, cat_tmp; - int i, a; - - if (inModification) return; - - inModification = true; - - if (event.GetCol() == CATEGORY_BACKGROUND_COLOR) - { - wxColourData color; - color.SetColour(wxColor(user->_categories[row].backcolor)); - wxColourDialog dial(this, &color); - - if (dial.ShowModal() == wxID_OK) - { - user->_categories[row].backcolor = dial.GetColourData().GetColour(); - _kiss->UpdateCategory(user->_categories[row]); - - SET_ROW_COLOR(row, user->_categories[row].backcolor, user->_categories[row].forecolor); - _wxUI->NeedReload(); - } - - inModification = false ; - return ; - } - - if (event.GetCol() == CATEGORY_FOREGROUND_COLOR) - { - wxColourData color; - color.SetColour(wxColor(user->_categories[row].forecolor)); - wxColourDialog dial(this, &color); - - if (dial.ShowModal() == wxID_OK) - { - user->_categories[row].forecolor = dial.GetColourData().GetColour(); - _kiss->UpdateCategory(user->_categories[row]); - - SET_ROW_COLOR(row, user->_categories[row].backcolor, user->_categories[row].forecolor); - _wxUI->NeedReload(); - } - - inModification = false ; - return ; - } - - if (event.GetCol() == CATEGORY_FONT) - { - wxFontData font; - font.SetInitialFont(_kiss->ExtractFont(user->_categories[row].font)); - wxFontDialog dial(this, font); - - if (dial.ShowModal() == wxID_OK) - { - font = dial.GetFontData(); - - user->_categories[row].font = _kiss->CompactFont(font.GetChosenFont()); - _kiss->UpdateCategory(user->_categories[row]); - - SET_ROW_FONT(row, font.GetChosenFont()); - _wxUI->NeedReload(); - } - - inModification = false ; - return ; - } - - value = _categoriesGrid->GetCellValue(row, CATEGORY_NAME); - if (value.Length()) - { - new_cat.name = value; - op_complete--; - } - - new_cat.backcolor = _categoriesGrid->GetCellBackgroundColour(row, col); - new_cat.forecolor = _categoriesGrid->GetCellTextColour(row, col); - new_cat.font = wxT(""); - new_cat.parent = wxT("0"); - - // Categories modification - if (user->GetCategoriesNumber() && row < user->GetCategoriesNumber()) - { - new_cat.id = user->_categories[row].id; - new_cat.fix_cost = user->_categories[row].fix_cost; - if (col == CATEGORY_DELETE) - { - wxString *categories = new wxString[user->GetCategoriesNumber()]; - categories[0] = _("None"); - a = 0; - for(i=0; i < user->GetCategoriesNumber(); i++) - if (user->_categories[i].id != new_cat.id) - categories[++a] = wxGetTranslation(user->_categories[i].name); - wxSingleChoiceDialog dialog(_wxUI, _("Wich category will replace this one ?"), wxT("KissCount"), user->GetCategoriesNumber(), categories); - if (dialog.ShowModal() == wxID_CANCEL) - { - _categoriesGrid->SetCellValue(row, col, wxT("0")); - } - else - { - _categoriesGrid->DeleteRows(row, 1); - i = dialog.GetSelection(); - _kiss->DeleteCategory(user->_categories[row], (!i) ? wxT("0") : user->GetCategoryId(categories[i])); - Fit(); - _wxUI->NeedReload(); - } - inModification = false; - return; - } - - value = user->GetCategoryId(new_cat.name); - if (value != wxT("0") && value != new_cat.id) - { - wxMessageBox(_("Category ")+new_cat.name+_(" already exists"), _("Error"), wxICON_ERROR | wxOK ); - _categoriesGrid->SetCellValue(row, CATEGORY_NAME, user->_categories[row].name); - inModification = false; - return ; - } - - _kiss->UpdateCategory(new_cat); - } - // New category - else - { - if (op_complete) - { - inModification = false; - return ; - } - - if (user->GetCategoryId(new_cat.name) != wxT("0")) - { - wxMessageBox(_("Category ")+new_cat.name+_(" already exists"), _("Error"), wxICON_ERROR | wxOK ); - inModification = false; - return ; - } - - new_cat.fix_cost = false; - - _kiss->AddCategory(new_cat); - AddCategory(row, new_cat); - - _categoriesGrid->SetReadOnly(row, CATEGORY_BACKGROUND_COLOR, false); - _categoriesGrid->SetReadOnly(row, CATEGORY_FOREGROUND_COLOR, false); - _categoriesGrid->SetReadOnly(row, CATEGORY_FONT, false); - _categoriesGrid->SetReadOnly(row, CATEGORY_DELETE, false); - - new_cat.id = wxT("0"); - _categoriesGrid->AppendRows(); - AddCategory(++row, new_cat); - } - - Fit(); - _wxUI->NeedReload(); - - inModification = false; - - return; -} - -void PreferencesPanel::OnChangeName(wxCommandEvent& event) -{ - User* user = _kiss->GetUser(); - wxString name = _name->GetLineText(0); - - if (name == user->_name) - return; - - if (!name.size()) - { - wxMessageBox(_("Invalid name"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - if (_kiss->UserExists(name)) - { - wxMessageBox(_("User ") + name + _(" already exists"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - _kiss->ChangeName(name); - - wxMessageBox(_("Name changed"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - _wxUI->NeedReload(); - _wxUI->SetTitle(_kiss->GetUser()->_name + wxT(" - ") +_("Preferences")); -} - -void PreferencesPanel::OnChangePassword(wxCommandEvent& event) -{ - PasswordDialog p(_kiss, _wxUI); - p.ShowModal(); -} - -void PreferencesPanel::OnOperationOrderChange(wxCommandEvent& event) -{ - if (_operationOrder->GetCurrentSelection() == 0) - _kiss->SetOperationOrder(wxT("ASC")); - else - _kiss->SetOperationOrder(wxT("DESC")); - - _wxUI->NeedReload(); -} - -void PreferencesPanel::OnLanguageChange(wxCommandEvent& event) -{ - wxLanguage language = SupportedLanguages::languages[_language->GetSelection()].language; - if (_wxUI->SetLanguage(language) || language == wxLANGUAGE_ENGLISH) - { - _wxUI->NeedReload(); - _kiss->SetLanguage(language); - wxMessageBox(_("Language successfully changed, please go to another panel"), _("KissCount"), wxICON_INFORMATION | wxOK); - } - else - wxMessageBox(_("Language not changed"), _("KissCount"), wxICON_ERROR | wxOK); -} - -void PreferencesPanel::OnShow(wxShowEvent& event) -{ - _wxUI->SetTitle(_kiss->GetUser()->_name + _(" - ") + _("Preferences")); -} - -void PreferencesPanel::OnKillMe(wxCommandEvent& event) -{ - User* user = _kiss->GetUser(); - - wxMessageDialog dialog(_wxUI, _("Are you sure want to delete ")+user->_name+_(" profil ?"), wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - { - return; - } - - _kiss->KillMe(); -} diff --git a/src/view/PreferencesPanel.hpp b/src/view/PreferencesPanel.hpp deleted file mode 100644 index 791c34b..0000000 --- a/src/view/PreferencesPanel.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef PREFERENCESPANEL_H -#define PREFERENCESPANEL_H - -#include -#include - -#include "view.hpp" -#include -#include "SupportedLanguages.hpp" - -class PreferencesPanel: public KissPanel -{ -public: - PreferencesPanel(KissCount* kiss, wxUI *parent); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - - void ChangeUser(); - - void OnAccountModified(wxGridEvent& event); - void OnAccountCellChanged(wxGridEvent& event); - void OnSharedChange(wxCommandEvent& event); - void OnCategoryModified(wxGridEvent& event); - void OnChangeName(wxCommandEvent& event); - void OnChangePassword(wxCommandEvent& event); - void OnOperationOrderChange(wxCommandEvent& event); - void OnLanguageChange(wxCommandEvent& event); - void OnKillMe(wxCommandEvent& event); - -private: - wxGrid* _accountsGrid; - wxGrid* _categoriesGrid; - wxTextCtrl* _name; - wxBitmapComboBox* _language; - wxComboBox* _operationOrder; - wxCheckListBox* _sharedWith; - int _curAccountRow; - std::map _sharedOwners; - - void InitAccounts(User* user); - void InitCategories(User* user); - void InitLanguage(User* user); - void InitOperationOrder(User* user); - - void AddAccount(int line, Account ac); - void AddCategory(int line, Category cat); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/SearchBanner.cpp b/src/view/SearchBanner.cpp deleted file mode 100644 index 3d15323..0000000 --- a/src/view/SearchBanner.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "SearchBanner.hpp" - -enum {DESCRIPTION_ID=1, CALENDAR_FROM_ID, CALENDAR_TO_ID}; - -BEGIN_EVENT_TABLE(SearchBanner, wxPanel) -EVT_CALENDAR_SEL_CHANGED(CALENDAR_TO_ID, SearchBanner::OnCalendarToChange) -EVT_TEXT_ENTER(DESCRIPTION_ID, SearchBanner::OnEnter) -END_EVENT_TABLE() - -SearchBanner::SearchBanner(KissCount* kiss, wxPanel *parent, void* caller, OnButtonEnter enterCallback) : wxPanel(parent), _kiss(kiss), _caller(caller), _enterCallback(enterCallback), _operations(0) -{ - DEFAULT_FONT(font); - User* user = _kiss->GetUser(); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - wxDateTime firstOfMonth; - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - - SetSizer(vbox); - - _checkDateFrom = new wxCheckBox(this, wxID_ANY, _("Date from")); - _checkDateTo = new wxCheckBox(this, wxID_ANY, _("Date to")); - - _checkDateFrom->SetValue(wxT("1")); - _checkDateTo->SetValue(wxT("1")); - - wxGridBagSizer *gridBagSizer = new wxGridBagSizer(3, 10); - - firstOfMonth.SetToCurrent(); - firstOfMonth.SetDay(1); - _calendarFrom = new wxCalendarCtrl(this, CALENDAR_FROM_ID, firstOfMonth, wxDefaultPosition, wxDefaultSize, - wxCAL_MONDAY_FIRST); - _calendarTo = new wxCalendarCtrl(this, CALENDAR_TO_ID, wxDefaultDateTime, wxDefaultPosition, wxDefaultSize, - wxCAL_MONDAY_FIRST); - - - _description = new wxTextCtrl(this, DESCRIPTION_ID); - _description->SetWindowStyle(_description->GetWindowStyle() | wxTE_PROCESS_ENTER); - wxSize size = _description->GetSize(); - size.SetWidth(size.GetWidth()*2); - _description->SetMinSize(size); - _amountFrom = new wxTextCtrl(this, wxID_ANY); - _amountTo = new wxTextCtrl(this, wxID_ANY); - - _category = new wxCheckListBox(this, wxID_ANY); - _category->Append(_("Unknown")); - for(categoryIt = user->_categories.begin(); categoryIt != user->_categories.end(); categoryIt++) - _category->Append(wxGetTranslation(categoryIt->name)); - - wxString stypes[] = {_("Fix"), _("Non fix"), _("Checked"), _("Not checked")}; - _optype = new wxCheckListBox(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 4, stypes); - - _account = new wxCheckListBox(this, wxID_ANY); - _account->Append(_("Unknown")); - for(accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); accountIt++) - _account->Append(accountIt->name); - - wxStaticText* labelDescription = new wxStaticText(this, wxID_ANY, _("Description")); - wxStaticText* labelAmountFrom = new wxStaticText(this, wxID_ANY, _("Amount from")); - wxStaticText* labelAmountTo = new wxStaticText(this, wxID_ANY, _("Amount to")); - wxStaticText* labelCategory = new wxStaticText(this, wxID_ANY, _("Category")); - wxStaticText* labelOperations = new wxStaticText(this, wxID_ANY, _("Operations")); - wxStaticText* labelAccount = new wxStaticText(this, wxID_ANY, _("Account")); - - gridBagSizer->Add(labelDescription, wxGBPosition(0, 0)); - gridBagSizer->Add(_description, wxGBPosition(1, 0)); - gridBagSizer->Add(_checkDateFrom, wxGBPosition(0, 1)); - gridBagSizer->Add(_calendarFrom, wxGBPosition(1, 1)); - gridBagSizer->Add(_checkDateTo, wxGBPosition(0, 2)); - gridBagSizer->Add(_calendarTo, wxGBPosition(1, 2)); - gridBagSizer->Add(labelAmountFrom, wxGBPosition(0, 3)); - gridBagSizer->Add(_amountFrom, wxGBPosition(1, 3)); - gridBagSizer->Add(labelAmountTo, wxGBPosition(0, 4)); - gridBagSizer->Add(_amountTo, wxGBPosition(1, 4)); - gridBagSizer->Add(labelCategory, wxGBPosition(0, 5)); - gridBagSizer->Add(_category, wxGBPosition(1, 5)); - gridBagSizer->Add(labelOperations, wxGBPosition(0, 6)); - gridBagSizer->Add(_optype, wxGBPosition(1, 6)); - gridBagSizer->Add(labelAccount, wxGBPosition(0, 7)); - gridBagSizer->Add(_account, wxGBPosition(1, 7)); - - vbox->Add(gridBagSizer, 0, wxGROW|wxALL, 5); -} - -SearchBanner::~SearchBanner() -{ - if (_operations) delete _operations; -} - -std::vector * SearchBanner::Search() -{ - wxString *description=0, *amountFrom=0, *amountTo=0; - std::vector categories, accounts; - wxDateTime *dateFrom=0, *dateTo=0; - User* user= _kiss->GetUser(); - int i, types=0; - std::vector::iterator it; - double af, at; - - if (_operations) - { - delete _operations; - _operations = 0; - } - - if (_checkDateFrom->IsChecked()) - { - dateFrom = new wxDateTime; - *dateFrom = _calendarFrom->GetDate(); - } - - if (_checkDateTo->IsChecked()) - { - dateTo = new wxDateTime; - *dateTo = _calendarTo->GetDate(); - } - - if (dateFrom && dateTo && *dateFrom > *dateTo) - { - wxMessageBox(_("Invalid date range"), _("Error"), wxICON_ERROR | wxOK); - goto end; - } - - if (_amountFrom->GetLineText(0).Length()) - { - amountFrom = new wxString; - *amountFrom = _amountFrom->GetLineText(0); - if (!amountFrom->ToDouble(&af)) - { - wxMessageBox(_("Invalid amount from"), _("Error"), wxICON_ERROR | wxOK); - goto end; - } - - if (af < 0) af *= -1; - } - - if (_amountTo->GetLineText(0).Length()) - { - amountTo = new wxString; - *amountTo = _amountTo->GetLineText(0); - if (!amountTo->ToDouble(&at)) - { - wxMessageBox(_("Invalid amount to"), _("Error"), wxICON_ERROR | wxOK); - goto end; - } - - if (at < 0) at *= -1; - } - - if (amountFrom && amountTo && af > at) - { - wxMessageBox(_("Invalid amount range"), _("Error"), wxICON_ERROR | wxOK); - goto end; - } - - if (_description->GetLineText(0).Length()) - { - description = new wxString; - *description = _description->GetLineText(0); - } - - for(i=0; iGetCategoriesNumber()+1; i++) - if (_category->IsChecked(i)) - categories.push_back((i) ? user->_categories[i-1].id : wxT("0")); - - types |= (_optype->IsChecked(0)) ? Database::FIX_OP : 0; - types |= (_optype->IsChecked(1)) ? Database::NON_FIX_OP : 0; - types |= (_optype->IsChecked(2)) ? Database::CHECKED_OP : 0; - types |= (_optype->IsChecked(3)) ? Database::NOT_CHECKED_OP : 0; - - for(i=0; iGetAccountsNumber()+1; i++) - if (_account->IsChecked(i)) - accounts.push_back((i) ? user->_accounts[i-1].id : wxT("0")); - - _operations = _kiss->Search(description, dateFrom, dateTo, amountFrom, amountTo, categories,types, accounts); - -end: - delete dateFrom; - delete dateTo; - delete amountFrom; - delete amountTo; - - return _operations; -} - -void SearchBanner::OnEnter(wxCommandEvent& event) -{ - if (_enterCallback) - _enterCallback(_caller, event); -} - -void SearchBanner::OnCalendarFromChange(wxCalendarEvent& event) -{ - _checkDateFrom->SetValue(true); -} - -void SearchBanner::OnCalendarToChange(wxCalendarEvent& event) -{ - _checkDateTo->SetValue(true); -} diff --git a/src/view/SearchBanner.hpp b/src/view/SearchBanner.hpp deleted file mode 100644 index a35cfe4..0000000 --- a/src/view/SearchBanner.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef SEARCHBANNER_H -#define SEARCHBANNER_H - -#include -#include -#include -#include -#include -#include "view.hpp" -#include "grid/CalendarEditor.hpp" - -#include - -typedef void (*OnButtonEnter)(void* caller, wxCommandEvent& event); - -class SearchBanner: public wxPanel -{ -public: - SearchBanner(KissCount* kiss, wxPanel* parent, void* caller=0, OnButtonEnter enterCallback=0); - ~SearchBanner(); - - void OnEnter(wxCommandEvent& event); - void OnButtonSearch(wxCommandEvent& event); - void OnCalendarFromChange(wxCalendarEvent& event); - void OnCalendarToChange(wxCalendarEvent& event); - - std::vector * Search(); - -private: - KissCount* _kiss; - void* _caller; - OnButtonEnter _enterCallback; - - std::vector *_operations; - wxCalendarCtrl* _calendarFrom, *_calendarTo; - wxCheckBox *_checkDateFrom, *_checkDateTo; - wxTextCtrl* _description, *_amountFrom, *_amountTo; - wxCheckListBox* _category, *_account, *_optype; - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/SearchPanel.cpp b/src/view/SearchPanel.cpp deleted file mode 100644 index f370372..0000000 --- a/src/view/SearchPanel.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include "grid/CalendarEditor.hpp" -#include "grid/wxGridCellBitmapRenderer.hpp" - -#include "SearchPanel.hpp" - -enum {SEARCH_ID=1, GRID_ID, - CHANGE_ACCOUNT_ID, CHANGE_CATEGORY_ID, RENAME_ID}; - -BEGIN_EVENT_TABLE(SearchPanel, wxPanel) -EVT_BUTTON(SEARCH_ID, SearchPanel::OnButtonSearch) -EVT_GRID_CMD_CELL_CHANGE(GRID_ID, SearchPanel::OnOperationModified) -EVT_BUTTON(CHANGE_ACCOUNT_ID, SearchPanel::OnButtonChangeAccount) -EVT_BUTTON(CHANGE_CATEGORY_ID, SearchPanel::OnButtonChangeCategory) -EVT_BUTTON(RENAME_ID, SearchPanel::OnButtonRename) -EVT_SHOW(SearchPanel::OnShow) -END_EVENT_TABLE() - -SearchPanel::SearchPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent), _operations(0) -{ - DEFAULT_FONT(font); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - wxDateTime firstOfMonth; - wxRect rect = wxDisplay().GetGeometry(); - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *vbox2 = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - - SetSizer(vbox); - - _searchButton = new wxButton(this, SEARCH_ID, _("Searchpp")); - - _banner = new SearchBanner(kiss, this, this, OnEnter); - - vbox->Add(_banner, 0, wxGROW|wxALL, 5); - vbox->Add(_searchButton, 0, wxALL, 5); - - _grid = new GridAccount(_kiss, this, GRID_ID, false, false, true); - - hbox->Add(_grid, 0, wxGROW|wxALL, 5); - - _changeAccountButton = new wxButton(this, CHANGE_ACCOUNT_ID, _("Change account")); - _changeCategoryButton = new wxButton(this, CHANGE_CATEGORY_ID, _("Change category")); - _renameButton = new wxButton(this, RENAME_ID, _("Rename")); - - vbox2->Add(_changeAccountButton, wxALL, 15); - vbox2->Add(_changeCategoryButton, wxALL, 15); - vbox2->Add(_renameButton, wxALL, 15); - - hbox->Add(vbox2, 0, wxALL, 15); - - vbox->Add(hbox, 0, wxGROW|wxALL, 5); - - Fit(); - - SetMinSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetMaxSize(wxSize(rect.width-rect.x-15, rect.height-rect.y-128-25)); - SetScrollbars(10, 10, 100/10, 100/10); -} - -SearchPanel::~SearchPanel() -{ -} - -KissPanel* SearchPanel::CreatePanel() -{ - return new SearchPanel(_kiss, _wxUI); -} - -wxBitmapButton* SearchPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(SEARCH_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString SearchPanel::GetToolTip() -{ - return _("Searchpp"); -} - -void SearchPanel::OnEnter(void* caller, wxCommandEvent& event) -{ - SearchPanel* _this = (SearchPanel*) caller; - - _this->OnButtonSearch(event); -} - -void SearchPanel::OnButtonSearch(wxCommandEvent& event) -{ - _operations = _banner->Search(); - - if (!_operations) return; - - if (_operations->size() > 1) - wxMessageBox(wxString::Format(wxT("%d"), _operations->size()) + _(" entries found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - else if (_operations->size() == 1) - wxMessageBox(_("1 entry found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - else - { - wxMessageBox(_("No entry found"), wxT("KissCount"), wxICON_INFORMATION | wxOK); - return; - } - - _grid->LoadOperations(_operations, 0, 0); - - _wxUI->Layout(); -} - -static void ChangeAccount(Operation* op, void** params) -{ - wxString* account = (wxString*) params[0]; - - op->account = *account; -} - -void SearchPanel::OnButtonChangeAccount(wxCommandEvent& event) -{ - int i, a; - std::vector rows; - User* user = _kiss->GetUser(); - wxString *accounts = new wxString[user->GetAccountsNumber()+1]; - std::vector::iterator it; - wxString account; - void * params[] = {&account}; - - if (!_operations) return; - - _grid->GetSelectedOperations(&rows); - - accounts[0] = _("None"); - a = 0; - for(i=0; i < user->GetAccountsNumber(); i++) - accounts[++a] = user->_accounts[i].name; - - wxSingleChoiceDialog dialog(_wxUI, _("Choose a new account"), wxT("KissCount"), user->GetAccountsNumber()+1, accounts); - - if (dialog.ShowModal() == wxID_CANCEL) - return; - - a = dialog.GetSelection(); - account = (a) ? user->_accounts[a-1].id : wxT("0"); - - _grid->MassUpdate(rows, ChangeAccount, params); - - _wxUI->NeedReload(); -} - -static void ChangeCategory(Operation* op, void** params) -{ - wxString* category = (wxString*) params[0]; - bool* fix = (bool*) params[1]; - - op->category = *category; - op->fix_cost = * fix; -} - -void SearchPanel::OnButtonChangeCategory(wxCommandEvent& event) -{ - int i, a; - std::vector rows; - User* user = _kiss->GetUser(); - wxString *categories = new wxString[user->GetCategoriesNumber()+1]; - std::vector::iterator it; - wxString category; - bool fix; - void * params[] = {&category, &fix}; - - if (!_operations) return; - - _grid->GetSelectedOperations(&rows); - - categories[0] = _("None"); - a = 0; - for(i=0; i < user->GetCategoriesNumber(); i++) - categories[++a] = wxGetTranslation(user->_categories[i].name); - - wxSingleChoiceDialog dialog(_wxUI, _("Choose a new category"), wxT("KissCount"), user->GetCategoriesNumber()+1, categories); - - if (dialog.ShowModal() == wxID_CANCEL) - return; - - a = dialog.GetSelection(); - - if (a) - { - category = user->_categories[a-1].id ; - fix = user->_categories[a-1].fix_cost; - } - else - { - category = wxT("0"); - fix = false; - } - - _grid->MassUpdate(rows, ChangeCategory, params); - - _wxUI->NeedReload(); -} - -static void ChangeName(Operation* op, void** params) -{ - wxString* description = (wxString*) params[0]; - - op->description = *description; -} - -void SearchPanel::OnButtonRename(wxCommandEvent& event) -{ - std::vector rows; - std::vector::iterator it; - wxString category; - wxString description; - void * params[] = {&description}; - - if (!_operations) return; - - _grid->GetSelectedOperations(&rows); - - wxTextEntryDialog u(this, wxT(""), _("Enter a new description")); - - if (u.ShowModal() == wxID_CANCEL) - return; - - description = u.GetValue(); - - if (!description.size()) return; - - _grid->MassUpdate(rows, ChangeName, params); - - _wxUI->NeedReload(); -} - -void SearchPanel::OnShow(wxShowEvent& event) -{ - _wxUI->SetTitle(_kiss->GetUser()->_name + wxT(" - ") + _("Searchpp")); -} - -void SearchPanel::OnOperationModified(wxGridEvent& event) -{ - _wxUI->NeedReload(); -} diff --git a/src/view/SearchPanel.hpp b/src/view/SearchPanel.hpp deleted file mode 100644 index a523fb9..0000000 --- a/src/view/SearchPanel.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef SEARCHPANEL_H -#define SEARCHPANEL_H - -#include -#include -#include "view.hpp" -#include "grid/GridAccount.hpp" -#include "AccountPanel.hpp" -#include "SearchBanner.hpp" - -#include - -class GridAccount; - -class SearchPanel: public KissPanel -{ -public: - SearchPanel(KissCount* kiss, wxUI *parent); - ~SearchPanel(); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - - /* void OnEnter(wxCommandEvent& event); */ - void OnButtonSearch(wxCommandEvent& event); - void OnOperationModified(wxGridEvent& event); - - void OnButtonChangeAccount(wxCommandEvent& event); - void OnButtonChangeCategory(wxCommandEvent& event); - void OnButtonRename(wxCommandEvent& event); - -private: - std::vector *_operations; - SearchBanner* _banner; - GridAccount *_grid; - wxButton* _searchButton, *_renameButton, *_changeAccountButton, *_changeCategoryButton; - - static void OnEnter(void* caller, wxCommandEvent& event); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/StatsPanel.cpp b/src/view/StatsPanel.cpp deleted file mode 100644 index 7225ff7..0000000 --- a/src/view/StatsPanel.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include - -#include "StatsPanel.hpp" - -enum {RANGE_ID=1, ACCOUNTS_ID}; - -BEGIN_EVENT_TABLE(StatsPanel, wxPanel) -EVT_CHOICE(RANGE_ID, StatsPanel::OnRangeChange) -EVT_CHECKLISTBOX(ACCOUNTS_ID, StatsPanel::OnAccountsChange) -END_EVENT_TABLE() - -StatsPanel::StatsPanel(KissCount* kiss, wxUI *parent) : KissPanel(kiss, parent), _plot(0), _chart(0) -{ - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - _hbox2 = new wxBoxSizer(wxHORIZONTAL); - _vbox2 = new wxBoxSizer(wxVERTICAL); - int i; - User* user = _kiss->GetUser(); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - std::map > operations; - std::map >::iterator it; - int nbCategories; - - SetSizer(vbox); - - _monthFrom = new wxChoice (this, RANGE_ID, wxDefaultPosition, wxDefaultSize, 12, wxUI::months); - _yearFrom = new wxChoice (this, RANGE_ID); - _monthTo = new wxChoice (this, RANGE_ID, wxDefaultPosition, wxDefaultSize, 12, wxUI::months); - _yearTo = new wxChoice (this, RANGE_ID); - - operations = _kiss->GetAllOperations(); - - for(i=0, it = operations.begin(); it != operations.end(); it++, i++) - { - _yearFrom->Append(wxString::Format(wxT("%d"), it->first)); - _yearTo->Append(wxString::Format(wxT("%d"), it->first)); - } - - if (i) i--; - - _yearFrom->Select(i); - _yearTo->Select(i); - _monthFrom->Select(0); - _monthTo->Select(11); - - wxStaticText* label = new wxStaticText(this, wxID_ANY, _("From")); - hbox->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 5); - hbox->Add(_monthFrom, 0, wxRIGHT, 5); - hbox->Add(_yearFrom, 0, wxRIGHT, 20); - - label = new wxStaticText(this, wxID_ANY, _("To")); - hbox->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 5); - hbox->Add(_monthTo, 0, wxRIGHT, 5); - hbox->Add(_yearTo); - - _account = new wxCheckListBox(this, ACCOUNTS_ID); - for(i=0, accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); accountIt++, i++) - { - _account->Append(accountIt->name); - _account->Check(i); - } - - _categories = new wxString[user->GetCategoriesNumber()] ; - for(i=0, categoryIt = user->_categories.begin(); - categoryIt != user->_categories.end(); - categoryIt++, i++) - { - _categoriesIndexes[categoryIt->id] = i; - _categories[i] = wxGetTranslation(categoryIt->name) ; - } - - DEFAULT_FONT(font); - - _statsGrid = new wxGrid(this, wxID_ANY); - - _statsGrid->CreateGrid(user->GetCategoriesNumber()+1, 2); - _statsGrid->SetColLabelSize(0); - _statsGrid->SetRowLabelSize(0); - _statsGrid->EnableEditing(false); - - _statsGrid->SetDefaultCellFont(font); - _statsGrid->AutoSizeColumn(0, true); - - for(i=0; iGetCategoriesNumber(); i++) - { - if (i) - { - _statsGrid->SetCellValue(i+1, 0, _categories[i]); - _statsGrid->SetCellAlignment(i+1, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - } - else - { - _statsGrid->SetCellValue(i, 0, _categories[i]); - _statsGrid->SetCellAlignment(i, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - } - } - - _statsGrid->SetCellValue(1, 0, _("Non fix")); - _statsGrid->SetCellAlignment(1, 1, wxALIGN_RIGHT, wxALIGN_CENTRE); - - _vbox2->Add(_account, 0, wxGROW|wxALL, 5); - _vbox2->Add(_statsGrid, 0, wxALIGN_CENTER_HORIZONTAL|wxGROW|wxALL, 5); - - _pie = new PiePlot(); - - nbCategories = (user->GetCategoriesNumber() <= wxUI::MAX_CATEGORY) ? user->GetCategoriesNumber() : wxUI::MAX_CATEGORY; - - _dataset = new CategorySimpleDataset(_categories, nbCategories); - ColorScheme* colorScheme = new ColorScheme(wxUI::categoryColors, WXSIZEOF(wxUI::categoryColors)); - - _categoriesValues = new double[user->GetCategoriesNumber()]; - for(i=0; iGetCategoriesNumber(); i++) - _categoriesValues[i] = 0.0; - - _dataset->AddSerie(_("Serie 1"), _categoriesValues, nbCategories); - _dataset->SetRenderer(new CategoryRenderer(*colorScheme)); - _pie->SetDataset(_dataset); - _pie->SetColorScheme(colorScheme); - - _pie->SetLegend(new Legend(wxBOTTOM, wxCENTER)); - - _chartCategories = new wxChartPanel(this); - _chartCategories->SetChart(new Chart(_pie, _("Cost repartition"))); - _chartCategories->Fit(); - _chartCategories->Layout(); - _chartCategories->SetMinSize(// chart->GetSize() - wxSize(200,250)); - - vbox->Add(hbox, 0, wxALIGN_CENTER_VERTICAL|wxGROW|wxALL, 5); - vbox->Add(_hbox2, 0, wxGROW|wxALL, 5); - - wxCommandEvent event ; - OnRangeChange(event); - - Fit(); -} - -KissPanel* StatsPanel::CreatePanel() -{ - return new StatsPanel(_kiss, _wxUI); -} - -wxBitmapButton* StatsPanel::GetButton(int id) -{ - if (!_KissButton) - _KissButton = new wxBitmapButton(_wxUI, id, wxBitmap(wxT(STATS_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128)); - - return _KissButton; -} - -wxString StatsPanel::GetToolTip() -{ - return _("Statistics"); -} - -void StatsPanel::UpdateStats(int monthFrom, int yearFrom, int monthTo, int yearTo) -{ - std::map > > accountAmounts; - std::map categories; - std::map > operations; - std::vector::iterator accountIt; - std::map::iterator categoriesIt; - std::map >::iterator accountYearIt; - double total, non_fix; - int account, size, i, a, b, percents, nbDays; - double *amounts; - wxString value; - User* user = _kiss->GetUser(); - wxDateTime date; - bool failed; - - if (_chart) - { - _hbox2->Detach(_chart); - _hbox2->Detach(_vbox2); - _hbox2->Detach(_chartCategories); - delete _chart; - } - - // first step: create plot - _plot = new XYPlot(); - - // create dataset - XYSimpleDataset *dataset = new XYSimpleDataset(); - - if (monthFrom == monthTo && yearFrom == yearTo) - { - nbDays = date.GetLastMonthDay((wxDateTime::Month)monthFrom, yearFrom).GetDay(); - - _kiss->GetMonthStats(monthFrom, yearFrom, nbDays, &operations, &categories); - - // Line on 0 all over the years - amounts = new double[nbDays*2]; - for (a=0; aAddSerie((double *) amounts, nbDays); - delete[] amounts; - - for (account = 0, i = 0, accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); - account++, accountIt++, i++) - { - if (!_account->IsChecked(account)) - { - i-- ; - continue; - } - - amounts = new double[nbDays*2]; - size = 0; - for (a=0; aid][a]; - } - dataset->AddSerie((double *) amounts, nbDays); - // set serie names to be displayed on legend - dataset->SetSerieName(i+1, user->GetAccountName(accountIt->id)); - delete[] amounts; - } - } - else - { - _kiss->GetStats(monthFrom, yearFrom, monthTo, yearTo, &accountAmounts, &categories); - - // Line on 0 all over the years - size = ((yearTo - yearFrom) + 1) * 12; - amounts = new double[size*2]; - for (a=0; a<(size/12); a++) - { - for(b=0; b<12; b++) - { - amounts[a*12*2+b*2+0] = a*12+b; - amounts[a*12*2+b*2+1] = 0; - } - } - - dataset->AddSerie((double *) amounts, size); - delete[] amounts; - - for (account = 0, i = 0, accountIt = user->_accounts.begin(); accountIt != user->_accounts.end(); - account++, accountIt++, i++) - { - if (!_account->IsChecked(account)) - { - i-- ; - continue; - } - - size = accountAmounts[accountIt->id].size(); - amounts = new double[size*13*2]; - size = 0; - for(a = 0, accountYearIt = accountAmounts[accountIt->id].begin(); - accountYearIt != accountAmounts[accountIt->id].end(); - accountYearIt++, a++) - { - for(b = 0; b<=12; b++) - { - amounts[size*2+0] = a*12+b; - if (!accountAmounts[accountIt->id][accountYearIt->first].count(b)) - { - /* - If previously afiled, continue to avoid to set - account to 0 (only for display) - */ - if (!b || failed) continue; - /* - Compute cur month value (if there are operations) - as next month value - */ - amounts[size*2+1] = - accountAmounts[accountIt->id][accountYearIt->first][b-1] - + _kiss->CalcAccountAmount(accountIt->id, b-1, accountYearIt->first, 0); - failed = true; - } - else - { - amounts[size*2+1] = accountAmounts[accountIt->id][accountYearIt->first][b]; - failed = false; - } - size++; - } - } - dataset->AddSerie((double *) amounts, size); - // set serie names to be displayed on legend - dataset->SetSerieName(i+1, user->GetAccountName(accountIt->id)); - delete[] amounts; - } - } - - // create line renderer and set it to dataset - XYLineRenderer *renderer = new XYLineRenderer(true, true); - dataset->SetRenderer(renderer); - - // add our dataset to plot - _plot->AddDataset(dataset); - - // create left and bottom number axes - NumberAxis *leftAxis = new NumberAxis(AXIS_LEFT); - NumberAxis *bottomAxis = new NumberAxis(AXIS_BOTTOM); - - // add axes to plot - _plot->AddAxis(leftAxis); - _plot->AddAxis(bottomAxis); - - // link axes and dataset - _plot->LinkDataVerticalAxis(0, 0); - _plot->LinkDataHorizontalAxis(0, 0); - - // set legend - _plot->SetLegend(new Legend(wxCENTER, wxRIGHT)); - - _chart = new wxChartPanel(this); - _chart->SetChart(new Chart(_plot, _("Accounts"))); - _chart->Fit(); - _chart->Layout(); - _chart->SetMinSize(// chart->GetSize() - wxSize(750,550)); - - _hbox2->Add(_chart, 0, wxGROW|wxALL, 5); - - total = 0.0; - for(categoriesIt = categories.begin(); categoriesIt != categories.end(); categoriesIt++) - total += categoriesIt->second; - - for(i=0, categoriesIt = categories.begin(); categoriesIt != categories.end(); categoriesIt++, i++) - { - _categoriesValues[_categoriesIndexes[categoriesIt->first]] = categoriesIt->second; - if (total) - percents = ((double) (categoriesIt->second*100))/total; - else - percents = 0; - value = wxString::Format(wxT("%0.2lf (%02d%%)"), categoriesIt->second, percents); - if (i) - _statsGrid->SetCellValue(_categoriesIndexes[categoriesIt->first]+1, 1, value); - else - _statsGrid->SetCellValue(_categoriesIndexes[categoriesIt->first], 1, value); - } - - non_fix = total - _categoriesValues[0]; - - if (total) - percents = ((double) (non_fix*100))/total; - else - percents = 0; - value = wxString::Format(wxT("%0.2lf (%02d%%)"), non_fix, percents); - _statsGrid->SetCellValue(1, 1, value); - - _statsGrid->AutoSizeColumn(0, true); - _statsGrid->AutoSizeColumn(1, true); - - _pie->DatasetChanged(_dataset); - - _hbox2->Add(_vbox2, 0, wxGROW|wxALL, 5); - _hbox2->Add(_chartCategories, 0, wxGROW|wxALL, 10); - - Layout(); -} - -void StatsPanel::OnShow(wxShowEvent& event) -{ - _wxUI->SetTitle(_kiss->GetUser()->_name + _(" - ") + _("Statistics")); -} - -void StatsPanel::OnRangeChange(wxCommandEvent& event) -{ - long monthFrom, monthTo, yearFrom, yearTo; - - if (!_yearFrom->GetStringSelection().Length() || - !_yearTo->GetStringSelection().Length()) - return; - - monthFrom = _monthFrom->GetCurrentSelection(); - _yearFrom->GetStringSelection().ToLong(&yearFrom); - monthTo = _monthTo->GetCurrentSelection(); - _yearTo->GetStringSelection().ToLong(&yearTo); - - if (yearTo < yearFrom || - (yearFrom == yearTo && monthFrom > monthTo)) - { - wxMessageBox(_("Invalide date range"), _("KissCount"), wxICON_ERROR | wxOK); - return; - } - - UpdateStats(monthFrom, yearFrom, monthTo, yearTo); -} - -void StatsPanel::OnAccountsChange(wxCommandEvent& event) -{ - OnRangeChange(event); -} diff --git a/src/view/StatsPanel.hpp b/src/view/StatsPanel.hpp deleted file mode 100644 index 9cc303c..0000000 --- a/src/view/StatsPanel.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef STATSPANEL_H -#define STATSPANEL_H - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "view.hpp" -#include - -class StatsPanel: public KissPanel -{ -public: - StatsPanel(KissCount* kiss, wxUI *parent); - - KissPanel* CreatePanel(); - wxBitmapButton* GetButton(int id); - wxString GetToolTip(); - void OnShow(wxShowEvent& event); - -private: - wxCalendarCtrl* _calendarFrom, *_calendarTo; - wxChoice* _monthFrom, *_yearFrom, *_monthTo, *_yearTo; - wxGrid *_statsGrid; - PiePlot* _pie; - double *_categoriesValues; - CategorySimpleDataset* _dataset; - XYPlot *_plot ; - wxString* _categories; - std::map _categoriesIndexes; - wxBoxSizer *_hbox2, *_vbox2; - wxChartPanel* _chart, *_chartCategories; - wxCheckListBox* _account; - - void UpdateStats(int monthFrom, int yearFrom, int monthTo, int yearTo); - - void OnRangeChange(wxCommandEvent& event); - void OnAccountsChange(wxCommandEvent& event); - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/UsersDialog.cpp b/src/view/UsersDialog.cpp deleted file mode 100644 index 0ae9f71..0000000 --- a/src/view/UsersDialog.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include -#include -#include -#include - -#include "UsersDialog.hpp" - -enum {TEXT_PASSWORD_ID=1, BUTTON_OK_ID, BUTTON_CANCEL_ID, BUTTON_NEW_USER_ID}; - -BEGIN_EVENT_TABLE(UsersDialog, wxDialog) -EVT_BUTTON(BUTTON_OK_ID, UsersDialog::OnOK) -EVT_BUTTON(BUTTON_CANCEL_ID, UsersDialog::OnCancel) -EVT_BUTTON(BUTTON_NEW_USER_ID, UsersDialog::OnNewUser) -EVT_TEXT_ENTER(TEXT_PASSWORD_ID, UsersDialog::OnEnter) -END_EVENT_TABLE() - -UsersDialog::UsersDialog(KissCount* kiss, wxUI *parent) : wxDialog(&(*parent), -1, _("Users")), _kiss(kiss), _wxUI(parent) -{ - wxGridBagSizer *gridBagSizer; - wxStaticText* label; - wxCommandEvent event; - - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - gridBagSizer = new wxGridBagSizer(4, 4); - - label = new wxStaticText(this, wxID_ANY, _("User ")); - gridBagSizer->Add(label, wxGBPosition(0, 0)); - _users = new wxChoice(this, wxID_ANY); - gridBagSizer->Add(_users, wxGBPosition(0, 1)); - - label = new wxStaticText(this, wxID_ANY, _("Password ")); - gridBagSizer->Add(label, wxGBPosition(1, 0)); - _password = new wxTextCtrl(this, TEXT_PASSWORD_ID); - _password->SetWindowStyle(_password->GetWindowStyle() | wxTE_PASSWORD | wxTE_PROCESS_ENTER); - gridBagSizer->Add(_password, wxGBPosition(1, 1)); - - wxButton* ok = new wxButton(this, BUTTON_OK_ID, _("OK")); - wxButton* cancel = new wxButton(this, BUTTON_CANCEL_ID, _("Cancel")); - wxButton* newUser = new wxButton(this, BUTTON_NEW_USER_ID, _("New User")); - gridBagSizer->Add(ok, wxGBPosition(3, 1)); - gridBagSizer->Add(cancel, wxGBPosition(3, 2)); - gridBagSizer->Add(newUser, wxGBPosition(3, 3)); - - std::list users_list = _kiss->GetUsers(); - - for(std::list::iterator i = users_list.begin(); i != users_list.end(); i++) - { - _users->Append(*i); - } - - _users->Select(0); - - hbox->Add(gridBagSizer, 0, wxGROW|wxALL, 10); - SetSizer(hbox); - - _users->SetFocus(); - Fit(); - Center(); - - if (users_list.size() == 0) - OnNewUser(event); - else - ShowModal(); -} - -void UsersDialog::OnEnter(wxCommandEvent& event) -{ - OnOK(event); -} - -void UsersDialog::OnOK(wxCommandEvent& event) -{ - // No users in database - if (!_users->GetStringSelection().Length()) - { - return; - } - - if (!_kiss->IsValidUser(_users->GetStringSelection(), _password->GetLineText(0))) - { - wxMessageBox(_("Invalid password"), _("Error"), wxICON_ERROR | wxOK); - _password->Clear(); - _password->SetFocus(); - } - else - { - _kiss->LoadUser(_users->GetStringSelection()); - Close(); - } -} - -void UsersDialog::OnCancel(wxCommandEvent& event) -{ - Close(); -} - -void UsersDialog::OnNewUser(wxCommandEvent& event) -{ - wxString name; - wxTextEntryDialog u(this, wxT(""), _("New User")); - - if (u.ShowModal() == wxID_CANCEL) - return; - - name = u.GetValue(); - - if (!name.size()) return; - - if (_kiss->UserExists(name)) - { - wxMessageBox(_("User ") + name + _(" already exists"), _("Error"), wxICON_ERROR | wxOK); - return; - } - - _kiss->NewUser(name); - _kiss->LoadUser(name); - - Close(); -} diff --git a/src/view/UsersDialog.hpp b/src/view/UsersDialog.hpp deleted file mode 100644 index 8f02303..0000000 --- a/src/view/UsersDialog.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef USERSDIALOG_H -#define USERSDIALOG_H - -#include - -#include -#include "wxUI.hpp" - -class wxUI; -class KissCount; - -class UsersDialog : public wxDialog -{ -public: - UsersDialog(KissCount* kiss, wxUI *parent); - - void OnEnter(wxCommandEvent& event); - void OnOK(wxCommandEvent& event); - void OnCancel(wxCommandEvent& event); - void OnNewUser(wxCommandEvent& event); - -private: - KissCount* _kiss; - wxUI* _wxUI; - wxChoice* _users; - wxTextCtrl* _password; - - DECLARE_EVENT_TABLE(); - -}; -#endif diff --git a/src/view/grid/CalendarEditor.cpp b/src/view/grid/CalendarEditor.cpp deleted file mode 100644 index 41fab4e..0000000 --- a/src/view/grid/CalendarEditor.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "CalendarEditor.hpp" - -CalendarEditor::CalendarEditor(int day, int month, int year) : _day(day), _month(month), _year(year), _parent(0), _days(0), _editor(0) -{ - wxDateTime date; - int i; - - _maxDay = date.GetLastMonthDay ((wxDateTime::Month) month, year).GetDay(); - - _days = new wxString[_maxDay]; - - for (i=0; i<_maxDay; i++) - _days[i] = wxString::Format(wxT("%d"), i+1) ; - - _editor = new wxChoice(); -} - -CalendarEditor::~CalendarEditor() -{ - delete _editor; - delete[] _days; -} - -void CalendarEditor::BeginEdit(int row, int col, wxGrid *grid) -{ - // wxDateTime date, dateDef; - - // if (!grid->GetCellValue(row, col).Len()) return; - - // if (date.ParseFormat(grid->GetCellValue(row, col), wxT("%d/%m/%Y"), dateDef)) - // _calendar->SetDate(wxDateTime(_day, _month, _year)); -} - -wxGridCellEditor* CalendarEditor::Clone() const -{ - return new CalendarEditor(_day, _month, _year); -} - -void CalendarEditor::Create(wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler) -{ - _parent = parent; - _editor->Create(parent, id, wxDefaultPosition, wxDefaultSize, _maxDay, _days); - _editor->Select(_day); - _editor->Connect((int)id, (int)wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(CalendarEditor::OnDateChanged), 0, this); -} - -bool CalendarEditor::EndEdit (int row, int col, wxGrid *grid) -{ - grid->SetCellValue(row, col, wxString::Format(wxT("%02d/%02d/%d"), _day+1, _month+1, _year)) ; - - return true; -} - -void CalendarEditor::ApplyEdit (int row, int col, wxGrid *grid) -{ - grid->SetCellValue(row, col, wxString::Format(wxT("%02d/%02d/%d"), _day+1, _month+1, _year)) ; -} - -wxString CalendarEditor::GetValue() const -{ - return wxString::Format(wxT("%02d/%02d/%d"), _day+1, _month+1, _year); -} - -void CalendarEditor::Reset() -{ - _editor->Select(_day); -} - -void CalendarEditor::Show (bool show, wxGridCellAttr *attr) -{ - _editor->Show(show); -} - -void CalendarEditor::SetSize (const wxRect &rect) -{ - _editor->SetSize(rect); -} - -void CalendarEditor::StartingClick() -{ - Show(true, 0); -} - -bool CalendarEditor::IsAcceptedKey(wxKeyEvent &event) -{ - return true; -} - -void CalendarEditor::OnDateChanged(wxCommandEvent& event) -{ - _day = _editor->GetSelection(); -} diff --git a/src/view/grid/CalendarEditor.hpp b/src/view/grid/CalendarEditor.hpp deleted file mode 100644 index d043db9..0000000 --- a/src/view/grid/CalendarEditor.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef CALENDAREDITOR_H -#define CALENDAREDITOR_H - -#include -#include -#include -#include -#include -#include - -class CalendarEditor : public wxGridCellChoiceEditor, public wxEvtHandler -{ -public: - - CalendarEditor(int day, int month, int year); - ~CalendarEditor(); - - void BeginEdit(int row, int col, wxGrid *grid); - wxGridCellEditor* Clone () const; - void Create(wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler); - bool EndEdit(int row, int col, wxGrid *grid); - void ApplyEdit(int row, int col, wxGrid *grid); - wxString GetValue() const; - void Reset(); - void Show(bool show, wxGridCellAttr *attr=0); - void SetSize (const wxRect &rect); - /* void OnCalendarChange(wxCommandEvent& event); */ - void OnDateChanged(wxCommandEvent& event); - void StartingClick(); - bool IsAcceptedKey(wxKeyEvent &event); - -private: - int _day; - int _month; - int _year; - wxWindow *_parent; - wxString* _days; - int _maxDay; - wxChoice* _editor; -}; - -#endif diff --git a/src/view/grid/GridAccount.cpp b/src/view/grid/GridAccount.cpp deleted file mode 100644 index 1944012..0000000 --- a/src/view/grid/GridAccount.cpp +++ /dev/null @@ -1,1553 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "GridAccount.hpp" - -#define SET_ROW_COLOR(row, backcolor, forecolor) for(int i=0; iGetUser(); - std::vector::iterator accountIt; - std::vector::iterator categoryIt; - - CreateGrid(1, NUMBER_COLS_OPS); - SetColLabelSize(0); - SetRowLabelSize(0); - - SetColSize (DESCRIPTION, GetColSize(DESCRIPTION)*5); - SetDefaultCellFont(font); - - font.SetWeight(wxFONTWEIGHT_BOLD); - wxString colsName[] = {wxT(""), _("Description"), _("Date"), _("Debit"), _("Credit"), _("Category"), _("Account"), wxT(""), wxT("")}; - for(i=0; iGetAccountsNumber()]; - for (i=0, - accountIt = user->_accounts.begin(); - accountIt != user->_accounts.end(); - accountIt++, i++) - _accounts[i] = accountIt->name; - - _categories = new wxString[user->GetCategoriesNumber()] ; - for(i=0, categoryIt = user->_categories.begin(); - categoryIt != user->_categories.end(); - categoryIt++, i++) - { - _categories[i] = wxGetTranslation(categoryIt->name) ; - } - - Connect(id, wxEVT_GRID_CELL_CHANGE, wxGridEventHandler(GridAccount::OnOperationModified), 0, this); - - AutoSizeColumn(TREE, false); - AutoSizeColumn(CATEGORY, false); - AutoSizeColumn(OP_DATE, false); - AutoSizeColumn(ACCOUNT, false); - AutoSizeColumn(OP_DELETE, false); - AutoSizeColumn(CHECKED, false); -} - -GridAccount::~GridAccount() -{ - delete[] _categories; - delete[] _accounts; -} - -wxPen GridAccount::GetColGridLinePen (int col) -{return wxPen(*wxBLACK, 1, wxSOLID);} - -wxPen GridAccount::GetRowGridLinePen (int row) { - if (_canAddOperation) - { - if (row == 0 || row == _fixCosts || - row == _week1 || - row == _week2 || - row == _week3 || - row == _week4) - return wxPen(*wxBLACK, 1, wxSOLID); - } - else - if (row == 0) - return wxPen(*wxBLACK, 1, wxSOLID); - - return GetCellBackgroundColour(row, 0); -} - -void GridAccount::ResetWeeks() -{ - _week1 = _week2 = _week3 = _week4 = 0; -} - -void GridAccount::SetWeek(int week, int line) { - switch (week) { - case 1: _week1 = line; break; - case 2: _week2 = line; break; - case 3: _week3 = line; break; - case 4: _week4 = line; break; - } -} - -Operation& GridAccount::GetOperation(const wxString& id) throw (OperationNotFound) -{ - std::vector::iterator it = std::find(_operations->begin(), _operations->end(), id); - - if (it != _operations->end()) return *it; - - throw OperationNotFound(); -} - -void GridAccount::UpdateOperation(Operation& op) -{ - std::vector::iterator it = std::find(_operations->begin(), _operations->end(), op.id); - - if (it != _operations->end()) - { - if (_databaseSynchronization) - _kiss->UpdateOperation(op); - *it = op; - } -} - -int GridAccount::GetDisplayedRow(const wxString& id) -{ - std::vector::iterator it = std::find(_displayedOperations.begin(), _displayedOperations.end(), id); - - if (it != _displayedOperations.end()) return it-_displayedOperations.begin(); - - return -1; -} - -void GridAccount::ClearGrid() -{ - std::vector operations; - - LoadOperations(&operations, 0, 0); -} - -void GridAccount::LoadOperations(std::vector* operations, int month, int year) -{ - std::vector::iterator it; - User* user = _kiss->GetUser(); - int curLine = 0; - Operation NULLop; - - NULLop.id = wxT(""); - - _loadOperations = true; - _operations = operations; - _curMonth = month; - _curYear = year; - _displayedOperations.clear(); - _displayedOperations.push_back(NULLop); // Header - _fixCosts = 0; - it = _operations->begin(); - - if (GetNumberRows () > 1) - DeleteRows(1, GetNumberRows ()-1); - - if (_canAddOperation) - { - for (;it != _operations->end() && it->fix_cost; it++) - { - if (it->parent.Length()) continue; - - if (_setWeek) - InsertOperationWithWeek(user, *it, ++curLine, true, it->month, it->year); - else - InsertOperation(user, *it, ++curLine, true, it->month, it->year); - } - - InsertOperation(user, NULLop, ++curLine, true, month, year); - - for (; it != _operations->end(); it++) - { - if (it->parent.Length()) continue; - - if (_setWeek) - InsertOperationWithWeek(user, *it, ++curLine, false, it->month, it->year); - else - InsertOperation(user, *it, ++curLine, false, it->month, it->year); - } - - InsertOperation(user, NULLop, ++curLine, false, month, year); - } - else - { - for (;it != _operations->end(); it++) - { - if (it->parent.Length()) continue; - - InsertOperation(user, *it, ++curLine, it->fix_cost, it->month, it->year); - } - } - - AutoSizeColumn(TREE, false); - AutoSizeColumn(CATEGORY, false); - AutoSizeColumn(OP_DATE, false); - AutoSizeColumn(ACCOUNT, false); - AutoSizeColumn(OP_DELETE, false); - AutoSizeColumn(CHECKED, false); - - _loadOperations = false; -} - -void GridAccount::ComputeWeeks() -{ - std::vector::iterator it; - int curLine, curWeek, week, i; - - if (!_canAddOperation) return; - - for (it = _displayedOperations.begin(), curLine=0; - it != _displayedOperations.end(); - it++, curLine++) - { - if (it->id.Length() && !it->fix_cost) break; - } - - if (it == _displayedOperations.end()) return; - - ResetWeeks(); - - curWeek = wxDateTime(it->day+1, (wxDateTime::Month)it->month, it->year).GetWeekOfMonth(); - it++; - for (i=1; it != _displayedOperations.end(); it++, curLine++) - { - if (!it->id.Length() || it->parent.Length()) continue; - week = wxDateTime(it->day+1, (wxDateTime::Month)it->month, it->year).GetWeekOfMonth(); - if (week != curWeek) - { - SetWeek(i++, curLine); - curWeek = week; - } - } -} - -void GridAccount::InsertOperationWithWeek(User* user, Operation& op, int line, bool fix, int month, int year) -{ - InsertOperation(user, op, line, fix, month, year); - - if (op.id.Length() && !fix) - ComputeWeeks(); -} - -void GridAccount::InsertOperation(User* user, Operation& op, int line, bool fix, int month, int year) -{ - std::vector::iterator it; - std::vector::iterator it2; - int r, g, b; - double amount; - wxColour color; - wxDateTime curDate; - wxString description; - wxFont font; - Category cat ; - Operation op2; - - curDate.SetToCurrent(); - - // // First is header - // if (op) - _displayedOperations.insert(_displayedOperations.begin()+line, op); - - if (!user->_accounts.size()) return; - - InsertRows(line, 1); - - if (op.id.Length() && op.meta) - { - SetCellRenderer(line, TREE, new wxGridCellTreeButtonRenderer()); - SetCellEditor(line, TREE, new wxGridCellTreeButtonEditor()); - - SetReadOnly(line, OP_DATE, true); - SetReadOnly(line, CREDIT, true); - SetReadOnly(line, DEBIT, true); - SetReadOnly(line, CATEGORY, true); - SetReadOnly(line, ACCOUNT, true); - } - else - SetReadOnly(line, TREE, true); - - SetCellEditor(line, DEBIT, new wxGridCellFloatEditor(wxID_ANY, 2)); - SetCellEditor(line, CREDIT, new wxGridCellFloatEditor(wxID_ANY, 2)); - wxGridCellChoiceEditor* accountEditor = new wxGridCellChoiceEditor(user->GetAccountsNumber(), _accounts, false); - SetCellEditor(line, ACCOUNT, accountEditor); - wxGridCellChoiceEditor* categoryEditor ; - - if (_canAddOperation) - categoryEditor = new wxGridCellChoiceEditor(user->GetCategoriesNumber()-1, _categories+1, false); - else - categoryEditor = new wxGridCellChoiceEditor(user->GetCategoriesNumber(), _categories, false); - - SetCellEditor(line, CATEGORY, categoryEditor); - - if (fix) - { - SetCellValue(line, CATEGORY, _("Fix")); - SetReadOnly(line, CATEGORY); - _fixCosts++; - } - - SetCellEditor(line, DEBIT, new wxGridCellFormulaEditor(op.formula)); - SetCellEditor(line, CREDIT, new wxGridCellFormulaEditor(op.formula)); - - if (op.id.Length()) - { - cat = user->GetCategory(op.category); - - SetCellEditor(line, OP_DATE, new CalendarEditor(op.day, month, year)); - description = op.description; - UNESCAPE_CHARS(description); - SetCellValue(line, DESCRIPTION, description); - SetCellRenderer(line, DESCRIPTION, new wxGridCellTabStringRenderer ()); - SetCellValue(line, OP_DATE, wxString::Format(wxT("%02d/%02d/%d"), op.day+1, month+1, year)); - if (op.amount < 0) - SetCellValue(line, DEBIT, wxString::Format(wxT("%.2lf"), -op.amount)); - else - SetCellValue(line, CREDIT, wxString::Format(wxT("%.2lf"), op.amount)); - - if (!op.meta) - SetCellValue(line, ACCOUNT, user->GetAccountName(op.account)); - if (!fix && !op.meta) - SetCellValue(line, CATEGORY, wxGetTranslation(cat.name)); - SetCellRenderer(line, OP_DELETE, new wxGridCellBoolRenderer ()); - SetCellEditor(line, OP_DELETE, new wxGridCellBoolEditor ()); - SetCellRenderer(line, CHECKED, new wxGridCellBoolRenderer ()); - SetCellEditor(line, CHECKED, new wxGridCellFastBoolEditor ()); - - if (op.category.Length()) - color = cat.backcolor; - else - color = view::OWN_GREEN; - - if (op.checked) - { - r = ((color.Red()*1.5) >= 0xFF) ? 0xFF : color.Red()*1.5 ; - g = ((color.Green()*1.5) >= 0xFF) ? 0xFF : color.Green()*1.5 ; - b = ((color.Blue()*1.5) >= 0xFF) ? 0xFF : color.Blue()*1.5 ; - color.Set(r, g, b, color.Alpha()); - SetCellValue(line, CHECKED, wxT("1")); - } - - SET_ROW_COLOR(line, color, cat.forecolor); - if (op.category.Length() && cat.font.Length()) - { - font = user->GetCategoryFont(cat.id); - SET_ROW_FONT(line, font); - } - - if (op.meta && !op.amount) - { - amount = _kiss->MetaPositiveAmount(op.id); - - SetCellValue(line, DEBIT, wxString::Format(wxT("%.2lf"), amount)); - SetCellValue(line, CREDIT, wxString::Format(wxT("%.2lf"), amount)); - } - - if (!_loadOperations) - { - if (op.meta) - AutoSizeColumn(TREE, false); - AutoSizeColumn(CATEGORY, false); - AutoSizeColumn(ACCOUNT, false); - } - } - else - { - SetCellEditor(line, OP_DATE, new CalendarEditor(0, month, year)); - if (curDate.GetMonth() == month && - curDate.GetYear() == year) - { - if (!fix) - SetCellValue(line, OP_DATE, wxString::Format(wxT("%02d/%02d/%d"), curDate.GetDay(), month+1, year)); - SetCellEditor(line, OP_DATE, new CalendarEditor(curDate.GetDay()-1, month, year)); - } - else - SetCellEditor(line, OP_DATE, new CalendarEditor(0, month, year)); - - if (fix) - { - SET_ROW_COLOR(line, view::OWN_YELLOW, *wxBLACK); - } - else - { - SET_ROW_COLOR(line, view::OWN_GREEN, *wxBLACK); - } - - SetReadOnly(line, CHECKED, true); - SetReadOnly(line, OP_DELETE, true); - } - - SetCellAlignment(line, OP_DATE, wxALIGN_CENTRE, wxALIGN_CENTRE); - SetCellAlignment(line, DEBIT, wxALIGN_RIGHT, wxALIGN_CENTRE); - SetCellAlignment(line, CREDIT, wxALIGN_RIGHT, wxALIGN_CENTRE); - SetCellAlignment(line, OP_DELETE, wxALIGN_CENTRE, wxALIGN_CENTRE); - SetCellAlignment(line, CHECKED, wxALIGN_CENTRE, wxALIGN_CENTRE); - - AutoSizeRow(line); - - Layout(); - SetMinSize(GetMinSize()); -} - -// From http://nomadsync.cvs.sourceforge.net/nomadsync/nomadsync/src/ -void GridAccount::OnCellLeftClick(wxGridEvent& evt) -{ - if (evt.GetCol() != TREE && evt.GetCol() != OP_DELETE && evt.GetCol() != CHECKED) { evt.Skip() ; return;} - - // This forces the cell to go into edit mode directly - //m_waitForSlowClick = TRUE; - SetGridCursor(evt.GetRow(), evt.GetCol()); - // Store the click co-ordinates in the editor if possible - // if an editor has created a ClientData area, we presume it's - // a wxPoint and we store the click co-ordinates - wxGridCellEditor* pEditor = GetCellEditor(evt.GetRow(), evt.GetCol()); - wxPoint* pClickPoint = (wxPoint*)pEditor->GetClientData(); - if (pClickPoint) - { - *pClickPoint = ClientToScreen(evt.GetPosition()); -#ifndef __WINDOWS__ - EnableCellEditControl(true); -#endif - } - // hack to prevent selection from being lost when click combobox - if (/*evt.GetCol() == 0 && */IsInSelection(evt.GetRow(), evt.GetCol())) - { - //m_selTemp = m_selection; - m_selection = 0; - } - pEditor->DecRef(); - evt.Skip(); -} - -void GridAccount::DeleteOperation(const Operation& op) -{ - std::vector::iterator it = std::find(_operations->begin(), _operations->end(), op.id); - - if (it != _operations->end()) _operations->erase(it); -} - -void GridAccount::InsertIntoGrid(Operation& op) -{ - int i, a, start; - User* user = _kiss->GetUser(); - Operation parent; - - // No previous fix operations - if (op.fix_cost && !_displayedOperations[1].id.Length()) - i = 1; - else - { - if (op.parent.Length()) - start = GetDisplayedRow(op.parent); - else - start = 0; - - for(i=start; i<(int)_displayedOperations.size(); i++) - { - if (!_displayedOperations[i].id.Length()) continue; - if (_displayedOperations[i].parent.Length()) continue; - if ((_displayedOperations)[i].fix_cost && !op.fix_cost) continue; - if (!(_displayedOperations)[i].fix_cost && op.fix_cost) break; - if (user->_preferences[wxT("operation_order")] == wxT("ASC")) - { - if ((_displayedOperations)[i].day > op.day) - break; - } - else - { - if ((_displayedOperations)[i].day < op.day) - break; - } - } - - if (op.parent.Length()) - { - parent = GetOperation(op.parent); - if ((i-start) > (int)(parent.childs.size())) - i = start + parent.childs.size(); - if (parent.day >= op.day) - i = start + 1; - } - else if (i == (int)_displayedOperations.size() || - i == _fixCosts) - i--; - else if (!(_displayedOperations)[i].fix_cost && op.fix_cost) - i --; - } - - for (a=0; a<(int)_operations->size(); a++) - { - if ((*_operations)[a].fix_cost && !op.fix_cost) continue; - if (!(*_operations)[a].fix_cost && op.fix_cost) - { - a--; - break; - } - if ((*_operations)[a].day > op.day) - { - a--; - break; - } - } - - if (a < 0) a = 0; - _operations->insert(_operations->begin()+a, op); - - InsertOperationWithWeek(user, (*_operations)[a], i, op.fix_cost, _curMonth, _curYear); -} - -int GridAccount::RemoveMeta(Operation op, int line, bool removeRoot, bool deleteOp) -{ - std::vector::iterator it, it2; - wxGridCellTreeButtonRenderer* treeRenderer; - int i, deletedOperations = 0; - Operation op2; - - treeRenderer = (wxGridCellTreeButtonRenderer*) GetCellRenderer(line, TREE); - - for(i=0; i<(int)op.childs.size(); i++) - { - op2 = GetOperation(op.childs[i]); - if (op2.meta) - RemoveMeta(op2, line+1, true, deleteOp); - else - { - if (treeRenderer->IsCollapsed()) - { - DeleteRows(line+1, 1); - deletedOperations++; - if (op2.fix_cost) _fixCosts--; - _displayedOperations.erase(_displayedOperations.begin()+line+1); - } - - if (deleteOp) - { - DeleteOperation(op2); - if (_databaseSynchronization) - _kiss->DeleteOperation(op2); - } - } - } - - op.childs.clear(); - - if (removeRoot) - { - DeleteRows(line, 1); - _displayedOperations.erase(_displayedOperations.begin()+line); - if (op.fix_cost) _fixCosts--; - if (deleteOp) - { - DeleteOperation(op); - if (_databaseSynchronization) - _kiss->DeleteOperation(op); - } - deletedOperations++; - } - - treeRenderer->DecRef(); - - return deletedOperations; -} - -void GridAccount::CheckMeta(Operation& op, int line, bool check) -{ - std::vector::iterator it, it2; - wxGridCellTreeButtonRenderer* treeRenderer; - int i; - Operation op2; - wxColour color ; - unsigned char r, g, b; - User* user = _kiss->GetUser(); - - treeRenderer = (wxGridCellTreeButtonRenderer*) GetCellRenderer(line, TREE); - - for(i=0; i<(int)op.childs.size(); i++) - { - op2 = GetOperation(op.childs[i]); - op2.checked = check; - UpdateOperation(op2); - - if (op2.meta) - CheckMeta(op2, line+1, check); - - if (treeRenderer->IsCollapsed()) - { - SetCellValue(line+i+1, CHECKED, check ? wxT("1") : wxT("0")); - color = user->GetCategory(op2.category).backcolor; - - if (check) - { - r = ((color.Red()*1.5) >= 0xFF) ? 0xFF : color.Red()*1.5 ; - g = ((color.Green()*1.5) >= 0xFF) ? 0xFF : color.Green()*1.5 ; - b = ((color.Blue()*1.5) >= 0xFF) ? 0xFF : color.Blue()*1.5 ; - color.Set(r, g, b, color.Alpha()); - } - - SET_ROW_COLOR(line+i+1, color, user->GetCategory(op2.category).forecolor); - } - } - - treeRenderer->DecRef(); -} - -void GridAccount::OnOperationModified(wxGridEvent& event) -{ - User* user = _kiss->GetUser(); - int row = event.GetRow(); - int col = event.GetCol(); - Operation new_op, cur_op, op_tmp, op_tmp2; - int op_complete = 6, i, last_day; - wxString value ; - wxDateTime date; - bool need_insertion = false; - static bool inModification = false ; - wxColour color ; - unsigned char r, g, b; - wxGridCellTreeButtonRenderer* treeRenderer; - std::vector::iterator it; - Operation op, op2; - double amount; - wxFont font; - Category cat ; - - // Avoid recursives calls - if (inModification || _loadOperations) return; - - inModification = true ; - - if (col == TREE) - { - treeRenderer = (wxGridCellTreeButtonRenderer*) GetCellRenderer(row, col); - - op = _displayedOperations[row]; - - if (!treeRenderer->IsCollapsed()) - { - for (i=1, it=op.childs.begin(); it!=op.childs.end(); it++, i++) - { - op2 = GetOperation(*it); - InsertOperationWithWeek(user, op2, row+i, op2.fix_cost, op2.month, op2.year); - } - } - else - { - RemoveMeta(op, row, false, false); - } - - treeRenderer->DecRef(); - - ComputeWeeks(); - inModification = false; - _parent->Fit(); - return; - } - - if (col == DEBIT) - SetCellValue(row, CREDIT, wxT("")); - else if (col == CREDIT) - SetCellValue(row, DEBIT, wxT("")); - - value = GetCellValue(row, DESCRIPTION); - if (value.Length()) - { - new_op.description = value; - op_complete--; - } - - value = GetCellValue(row, OP_DATE); - if (value.Length()) - { - date.ParseFormat(value, wxT("%d/%m/%Y")); - new_op.day = date.GetDay()-1; - new_op.month = date.GetMonth(); - new_op.year = date.GetYear(); - op_complete--; - } - - if (col == DESCRIPTION && - (!GetCellValue(row, CATEGORY).Length() || - !GetCellValue(row, ACCOUNT).Length())) - { - new_op.fix_cost = (row <= _fixCosts); - if (_kiss->SearchPreviousOperation(&op_tmp, new_op, _curMonth, _curYear, _canAddOperation)) - { - if (!GetCellValue(row, CATEGORY).Length()) - { - new_op.category = op_tmp.category; - SetCellValue(row, CATEGORY, wxGetTranslation(user->GetCategoryName(new_op.category))); - op_complete--; - } - - if (!GetCellValue(row, ACCOUNT).Length()) - { - new_op.account = op_tmp.account; - SetCellValue(row, ACCOUNT, user->GetAccountName(new_op.account)); - op_complete--; - } - - col = CATEGORY; - new_op.fix_cost = (new_op.category == user->GetCategoryId(wxT("Fix"))); - } - } - - value = GetCellValue(row, DEBIT); - if (value.Length()) - { - value.ToDouble(&new_op.amount); - if (new_op.amount < 0) - { - new_op.amount *= -1.0; - SetCellValue(row, DEBIT, wxString::Format(wxT("%.2lf"), new_op.amount)); - } - if (new_op.amount != 0.0) new_op.amount *= -1.0; - op_complete--; - wxGridCellFormulaEditor* pEditor = (wxGridCellFormulaEditor*) GetCellEditor(row, DEBIT); - new_op.formula = pEditor->GetFormula(); - pEditor->DecRef(); - } - - value = GetCellValue(row, CREDIT); - if (value.Length()) - { - value.ToDouble(&new_op.amount); - if (new_op.amount < 0) - { - new_op.amount *= -1.0; - SetCellValue(row, CREDIT, wxString::Format(wxT("%.2lf"), new_op.amount)); - } - op_complete--; - wxGridCellFormulaEditor* pEditor = (wxGridCellFormulaEditor*) GetCellEditor(row, CREDIT); - new_op.formula = pEditor->GetFormula(); - pEditor->DecRef(); - } - - value = GetCellValue(row, CATEGORY); - if (value.Length()) - { - new_op.category = user->GetCategoryId(value); - op_complete--; - } - - value = GetCellValue(row, ACCOUNT); - if (value.Length()) - { - new_op.account = user->GetAccountId(value); - op_complete--; - } - - value = GetCellValue(row, CHECKED); - if (value.Length() && value != wxT("0")) - new_op.checked = true; - else - new_op.checked = false; - op_complete--; - - cur_op = (_displayedOperations)[row] ; - - if (col == CHECKED || col == CATEGORY) - { - color = user->GetCategory(new_op.category).backcolor; - - if (new_op.checked) - { - r = ((color.Red()*1.5) >= 0xFF) ? 0xFF : color.Red()*1.5 ; - g = ((color.Green()*1.5) >= 0xFF) ? 0xFF : color.Green()*1.5 ; - b = ((color.Blue()*1.5) >= 0xFF) ? 0xFF : color.Blue()*1.5 ; - color.Set(r, g, b, color.Alpha()); - } - - SET_ROW_COLOR(row, color, user->GetCategory(new_op.category).forecolor); - SET_ROW_FONT(row, user->GetCategoryFont(new_op.category)); - - if (col == CHECKED) - { - cur_op.checked = new_op.checked; - UpdateOperation(cur_op); - inModification = false; - if (cur_op.meta) - CheckMeta(cur_op, row, cur_op.checked); - else - { - if (cur_op.parent.Length()) - { - op2 = GetOperation(cur_op.parent); - UpdateMeta(op2); - int row2 = GetDisplayedRow(op2.id); - SetCellValue(row2, CHECKED, op2.checked ? wxT("1") : wxT("0")); - - color = user->GetCategory(op2.category).backcolor; - - if (op2.checked) - { - r = ((color.Red()*1.5) >= 0xFF) ? 0xFF : color.Red()*1.5 ; - g = ((color.Green()*1.5) >= 0xFF) ? 0xFF : color.Green()*1.5 ; - b = ((color.Blue()*1.5) >= 0xFF) ? 0xFF : color.Blue()*1.5 ; - color.Set(r, g, b, color.Alpha()); - } - - SET_ROW_COLOR(row2, color, user->GetCategory(op2.category).forecolor); - } - } - event.Skip(); - return; - } - } - - if (col == OP_DELETE) - { - wxMessageDialog dialog(this, _("Are you sure want to delete : \n")+new_op.description, wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - { - SetCellValue(row, col, wxT("0")); - inModification = false; - return; - } - } - - // Modify a fix operation - if (row < _fixCosts || !_canAddOperation) - { - if (col == OP_DELETE) - { - if (cur_op.parent.Length()) - user->UnGroup(_displayedOperations[row]); - - if (cur_op.meta) - RemoveMeta(_displayedOperations[row], row, true, true); - else - { - if (cur_op.parent.Length()) - { - op_tmp = GetOperation(cur_op.parent); - for (int a=0; a<(int)op_tmp.childs.size(); a++) - if (op_tmp.childs[a] == op.id) - { - op2.childs.erase(op_tmp.childs.begin()+a); - break; - } - } - - DeleteRows(row, 1); - DeleteOperation(cur_op); - if (_databaseSynchronization) - _kiss->DeleteOperation(cur_op); - _displayedOperations.erase(_displayedOperations.begin()+row); - - if (cur_op.parent.Length() && op_tmp.childs.size() < 2) - { - if (op_tmp.childs.size() == 1) - { - op_tmp2 = GetOperation(op_tmp.childs[0]); - op_tmp2.parent = wxT(""); - UpdateOperation(op_tmp2); - row = GetDisplayedRow(op_tmp2.id); - _displayedOperations[row] = op_tmp2; - } - row = GetDisplayedRow(cur_op.parent); - DeleteRows(row, 1); - DeleteOperation(op_tmp); - if (_databaseSynchronization) - _kiss->DeleteOperation(op_tmp); - _displayedOperations.erase(_displayedOperations.begin()+row); - _fixCosts--; - } - _fixCosts--; - ComputeWeeks(); - } - inModification = false ; - event.Skip(); - return ; - } - - new_op.id = cur_op.id; - new_op.fix_cost = true; - new_op.transfert = cur_op.transfert; - new_op.meta = cur_op.meta; - new_op.parent = cur_op.parent; - new_op.childs = cur_op.childs; - new_op._virtual = cur_op._virtual; - - if (cur_op.day != new_op.day) - { - need_insertion = true; - DeleteRows(row, 1); - DeleteOperation(cur_op); - _displayedOperations.erase(_displayedOperations.begin()+row); - _fixCosts--; - } - else - { - UpdateOperation(new_op); - (_displayedOperations)[row] = new_op; - } - } - // Add a fixCost - else if (row == _fixCosts) - { - if (op_complete) { - inModification = false ; - return ; - } - need_insertion = true; - new_op.fix_cost = true; - new_op.meta = false; - new_op._virtual = false; - - for(i=0; iAddOperation(new_op); - } - // Modify an operation - else if (row < (int)(_displayedOperations.size()-1)) - { - new_op.id = cur_op.id; - new_op.fix_cost = false; - new_op.transfert = cur_op.transfert; - new_op.meta = cur_op.meta; - new_op.parent = cur_op.parent; - new_op.childs = cur_op.childs; - new_op._virtual = cur_op._virtual; - - if (col == OP_DELETE) - { - if (cur_op.parent.Length()) - user->UnGroup(_displayedOperations[row]); - - if (cur_op.meta) - RemoveMeta(_displayedOperations[row], row, true, true); - else - { - if (cur_op.parent.Length()) - { - op_tmp = GetOperation(cur_op.parent); - for (int a=0; a<(int)op_tmp.childs.size(); a++) - if (op_tmp.childs[a] == op.id) - { - op2.childs.erase(op_tmp.childs.begin()+a); - break; - } - } - - DeleteRows(row, 1); - DeleteOperation(cur_op); - _displayedOperations.erase(_displayedOperations.begin()+row); - if (_databaseSynchronization) - _kiss->DeleteOperation(cur_op); - - if (cur_op.parent.Length() && op_tmp.childs.size() <= 1) - { - if (op_tmp.childs.size() == 1) - { - op_tmp2 = GetOperation(op_tmp.childs[0]); - op_tmp2.parent = wxT(""); - UpdateOperation(op_tmp2); - row = GetDisplayedRow(op_tmp2.id); - _displayedOperations[row] = op_tmp2; - } - row = GetDisplayedRow(cur_op.parent); - DeleteRows(row, 1); - DeleteOperation(op_tmp); - if (_databaseSynchronization) - _kiss->DeleteOperation(op_tmp); - _displayedOperations.erase(_displayedOperations.begin()+row); - } - - ComputeWeeks(); - } - inModification = false ; - event.Skip(); - return ; - } - - if (cur_op.day != new_op.day) - { - need_insertion = true; - DeleteRows(row, 1); - DeleteOperation(cur_op); - _displayedOperations.erase(_displayedOperations.begin()+row); - } - else - { - UpdateOperation(new_op); - (_displayedOperations)[row] = new_op; - } - } - // Add an operation - else - { - if (op_complete) { - inModification = false ; - return ; - } - need_insertion = true; - new_op.fix_cost = false; - new_op.meta = false; - new_op._virtual = false; - - for(i=0; iAddOperation(new_op); - } - - if (user->GetAccount(new_op.account).blocked && new_op.amount < 0) - wxMessageBox(_("You made a debit on a blocked account"), _("Warning"), wxICON_WARNING | wxOK); - - if (need_insertion) - { - InsertIntoGrid(new_op); - UpdateOperation(new_op); - } - - if (new_op.parent.Length()) - { - row = GetDisplayedRow(new_op.parent); - - new_op = _displayedOperations[row]; - - last_day = new_op.day; - - UpdateMeta(new_op); - - _displayedOperations[row] = new_op; - - cat = user->GetCategory(new_op.category); - - if (new_op.category.Length()) - color = cat.backcolor; - else - color = view::OWN_GREEN; - - if (new_op.checked) - { - r = ((color.Red()*1.5) >= 0xFF) ? 0xFF : color.Red()*1.5 ; - g = ((color.Green()*1.5) >= 0xFF) ? 0xFF : color.Green()*1.5 ; - b = ((color.Blue()*1.5) >= 0xFF) ? 0xFF : color.Blue()*1.5 ; - color.Set(r, g, b, color.Alpha()); - SetCellValue(row, CHECKED, wxT("1")); - } - else - SetCellValue(row, CHECKED, wxT("0")); - - - SET_ROW_COLOR(row, color, cat.forecolor); - - if (new_op.category.Length() && cat.font.Length()) - { - font = user->GetCategoryFont(cat.id); - SET_ROW_FONT(row, font); - } - - SetCellValue(row, OP_DATE, wxString::Format(wxT("%02d/%02d/%d"), new_op.day+1, _curMonth+1, _curYear)); - - if (!_displayedOperations[row].amount) - { - amount = _kiss->MetaPositiveAmount(new_op.id); - - SetCellValue(row, DEBIT, wxString::Format(wxT("%.2lf"), amount)); - SetCellValue(row, CREDIT, wxString::Format(wxT("%.2lf"), amount)); - } - else - { - if (_displayedOperations[row].amount < 0) - { - SetCellValue(row, DEBIT, wxString::Format(wxT("%.2lf"), -new_op.amount)); - SetCellValue(row, CREDIT, wxT("")); - } - else - { - SetCellValue(row, DEBIT, wxT("")); - SetCellValue(row, CREDIT, wxString::Format(wxT("%.2lf"), new_op.amount)); - } - } - - // Move updated meta - if ((int)new_op.day != last_day) - { - int i; - RemoveMeta(new_op, row, true, false); - InsertIntoGrid(new_op); - row = GetDisplayedRow(new_op.id); - for (i=1, it=new_op.childs.begin(); it!=new_op.childs.end(); it++, i++) - { - op2 = GetOperation(*it); - InsertOperationWithWeek(user, op2, row+i, op2.fix_cost, _curMonth, _curYear); - } - treeRenderer = (wxGridCellTreeButtonRenderer*) GetCellRenderer(row, 0); - treeRenderer->Invert(); - treeRenderer->DecRef(); - } - } - - inModification = false ; - - event.Skip(); -} - -void GridAccount::UpdateMeta(Operation& meta) -{ - std::vector::iterator it; - Operation op ; - wxString category = wxT(""); - bool updateCat = false ; - - if (!meta.childs.size()) return ; - - meta.category = wxT(""); - meta.checked = true; - meta.amount = 0; - - for(it=meta.childs.begin(); it!=meta.childs.end(); it++) - { - op = GetOperation(*it); - if (op.year <= meta.year && op.month <= meta.month && op.day < meta.day) - { - meta.year = op.year; - meta.month = op.month; - meta.day = op.day; - } - meta.checked &= op.checked; - if (!meta.description.Length() && op.description.Length()) - meta.description = op.description; - if (!category.Length()) - { - if (op.category.Length()) - { - category = op.category; - updateCat = true; - } - } - else - { - if (op.category.Length() && op.category != category) - updateCat = false; - } - op.parent = meta.id; - } - - if (updateCat) - meta.category = category; - - meta.amount = _kiss->MetaAmount(meta.id); - - UpdateOperation(meta); -} - - -void GridAccount::GetSelectedOperations(std::vector* rows) -{ - std::vector::iterator it; - - rows->clear(); - - // Blocks. We always expect btl and bbr to have the same size, since their - // entries are supposed to correspond. - const wxGridCellCoordsArray& btl(GetSelectionBlockTopLeft()); - const wxGridCellCoordsArray& bbr(GetSelectionBlockBottomRight()); - size_t blockCount = btl.size(); - - if (blockCount == bbr.size()) - { - for (size_t i = 0; i < blockCount; ++i) - { - const wxGridCellCoords& tl = btl[i]; - const wxGridCellCoords& br = bbr[i]; - for (int row = tl.GetRow(); row <= br.GetRow(); ++row) - { - it = std::find(rows->begin(), rows->end(), row); - - if (it != rows->end() || !row) continue; - - rows->push_back(row); - } - } - } - - // Singly selected cells. - const wxGridCellCoordsArray& cells(GetSelectedCells()); - for (size_t i = 0; i < cells.size(); ++i) - { - int row = cells[i].GetRow(); - - if (!row) continue; - - it = std::find(rows->begin(), rows->end(), row); - - if (it != rows->end()) continue; - - rows->push_back(row); - } -} - -void GridAccount::Group() -{ - std::vector selected, rows; - std::vector::iterator it; - std::vector ops; - std::vector::iterator it2; - std::vector::iterator it3; - wxString parent = wxT(""); - Operation op, op2; - int fix = -1, i, a, row; - - GetSelectedOperations(&selected); - - for (size_t i = 0; i < selected.size(); ++i) - { - op = _displayedOperations[selected[i]] ; - - if (op.id.Length()) - { - if (!parent.Length()) - { - if (op.parent.Length()) - { - parent = op.parent; - continue; - } - else if(op.meta) - parent = op.id; - } - else - { - if ((parent.Length() && op.parent.Length() && op.parent != parent)) - { - wxMessageBox(_("Cannot group these operations"), _("Error"), wxICON_ERROR | wxOK); - return ; - } - } - - if (fix != -1 && ((!fix && op.fix_cost) || (fix && !op.fix_cost))) - { - wxMessageBox(_("Cannot group these operations"), _("Error"), wxICON_ERROR | wxOK); - return ; - } - - if (fix == -1) - fix = op.fix_cost ? 1 : 0; - - ops.push_back(op); - rows.push_back(selected[i]); - } - } - - if (!ops.size()) return; - - if (!parent.Length()) - { - if (rows.size() < 2) return; - - op.parent = wxT(""); - op.day = ops[0].day; - op.month = ops[0].month; - op.year = ops[0].year; - op.amount = 0; - op.description = wxT(""); - op.category = wxT(""); - op.fix_cost = fix; - op.account = wxT(""); - op.checked = false; - op.transfert = wxT(""); - op.formula = wxT(""); - op.meta = true; - op.childs.clear(); - - op.id = _kiss->AddOperation(op); - } - else - { - if (rows.size() < 1) return; - - row = GetDisplayedRow(parent); - op = _displayedOperations[row]; - - //if (op.id.Length()) return; - } - - std::sort(rows.begin(), rows.end()); - - for(i=0; i<(int)rows.size(); i++) - { - if (ops[i].meta) - RemoveMeta(ops[i], rows[i], true, false); - else - { - if (ops[i].fix_cost) _fixCosts--; - DeleteRows(rows[i], 1); - _displayedOperations.erase(_displayedOperations.begin()+rows[i]); - - for(a=i+1; a<(int)rows.size(); a++) - if (rows[a] >= rows[i]) - rows[a]--; - } - } - - for(it2=ops.begin(); it2!=ops.end(); it2++) - { - if (it2->id == parent) continue; - - for (i=0, it3=op.childs.begin(); it3!=op.childs.end(); it3++, i++) - { - op2 = GetOperation(*it3); - if (*it3 == it2->id || - op2.day > it2->day) - break; - } - - if (i) i--; - - if (it3 == op.childs.end()) - op.childs.push_back(it2->id); - else if (*it3 == it2->id) - continue; - else - op.childs.insert(op.childs.begin()+i, it2->id); - - it2->parent = op.id; - UpdateOperation(*it2); - } - - UpdateMeta(op); - - InsertIntoGrid(op); - - UpdateOperation(op); -} - - -void GridAccount::UnGroup() -{ - std::vector rows, selected; - std::vector::iterator it; - std::vector ops; - std::vector ops2; - std::vector::iterator it2; - std::vector::iterator it3; - wxString parent = wxT(""); - Operation op, op2; - int fix = -1, i, a, line; - - GetSelectedOperations(&selected); - - for (size_t i = 0; i < selected.size(); ++i) - { - op = _displayedOperations[selected[i]] ; - - if (op.id.Length()) - { - if ((parent.Length() && op.parent != parent) - || (!op.parent.Length() && !op.meta)) - { - wxMessageBox(_("Cannot ungroup these operations"), _("Error"), wxICON_ERROR | wxOK); - return ; - } - - if (fix != -1 && ((!fix && op.fix_cost) || (fix && !op.fix_cost))) - { - wxMessageBox(_("Cannot ungroup these operations"), _("Error"), wxICON_ERROR | wxOK); - return ; - } - - if (fix == -1) - fix = op.fix_cost ? 1 : 0; - - if(op.meta) - { - parent = op.id; - continue; - } - - if (!parent.Length() && op.parent.Length()) - parent = op.parent; - - ops.push_back(op); - rows.push_back(selected[i]); - } - } - - if (!ops.size() && !parent.Length()) return; - -removeLastGroup: - // Only one meta is selected - if (!ops.size()) - { - line = GetDisplayedRow(parent); - op = _displayedOperations[line]; - ops2 = op.childs; - RemoveMeta(op, line, true, false); - - for(i=0; i<(int)ops2.size(); i++) - { - op2 = GetOperation(ops2[i]); - op2.parent = wxT(""); - UpdateOperation(op2); - InsertIntoGrid(op2); - } - - _kiss->DeleteOperation(op); - DeleteOperation(op); - } - else - { - if (!parent.Length()) return; - - line = GetDisplayedRow(parent); - op2 = _displayedOperations[line]; - - for(i=0; i<(int)ops.size(); i++) - { - op = ops[i]; - op.parent = wxT(""); - UpdateOperation(op); - line = GetDisplayedRow(op.id); - DeleteRows(line, 1); - _displayedOperations.erase(_displayedOperations.begin()+line); - InsertIntoGrid(GetOperation(op.id)); - if (op.fix_cost) _fixCosts--; - for (a=0; a<(int)op2.childs.size(); a++) - if (op2.childs[a] == op.id) - { - op2.childs.erase(op2.childs.begin()+a); - break; - } - UpdateMeta(op2); - UpdateOperation(op2); - } - - line = GetDisplayedRow(parent); - _displayedOperations[line] = op2; - - if (op2.childs.size() < 2) - { - ops.clear(); - // Sorry ... - goto removeLastGroup; - } - - UpdateOperation(op2); - } - - ComputeWeeks(); -} - -void GridAccount::MassUpdate(std::vector& rows, updateOperationFunc func, void** params) -{ - int i, b; - std::vector::iterator it; - Operation op, op2; - - _parent->Disable(); - - _parent->SetCursor(wxCursor(wxCURSOR_WAIT)); - - _parent->Update(); - - if (rows.size()) - { - for(i=0; i<(int)rows.size(); i++) - { - op = _displayedOperations[rows[i]]; - - func (&op, params); - - UpdateOperation(op); - - if (op.meta) - { - for(b=0; b<(int)op.childs.size(); b++) - { - op2 = GetOperation(op.childs[b]); - func (&op2, params); - UpdateOperation(op2); - } - } - } - } - else - { - for(it=_operations->begin(); it!=_operations->end(); it++) - { - func (&(*it), params); - if (_databaseSynchronization) - _kiss->UpdateOperation(*it); - } - } - - ClearGrid(); - - LoadOperations(_operations, 0, 0); - - Layout(); - - _parent->Enable(); - - _parent->SetCursor(wxNullCursor); -} diff --git a/src/view/grid/GridAccount.hpp b/src/view/grid/GridAccount.hpp deleted file mode 100644 index a0914b9..0000000 --- a/src/view/grid/GridAccount.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef GRIDACCOUNT_H -#define GRIDACCOUNT_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include "wxGridCellFastBoolEditor.hpp" -#include "wxGridCellTreeButtonRenderer.hpp" -#include "wxGridCellTreeButtonEditor.hpp" -#include "wxGridCellBitmapRenderer.hpp" -#include "wxGridCellFormulaEditor.hpp" -#include "wxGridCellTabStringRenderer.hpp" - -class KissCount; - -enum {TREE, DESCRIPTION, OP_DATE, DEBIT, CREDIT, CATEGORY, ACCOUNT, OP_DELETE, CHECKED, NUMBER_COLS_OPS}; - -typedef void (*updateOperationFunc)(Operation* op, void** params); - -class GridAccount : public wxGrid -{ -public: - class OperationNotFound {}; - - GridAccount(KissCount* kiss, wxWindow *parent, wxWindowID id, - bool canAddOperation, bool setWeek, bool synchronizeWithDatabase); - ~GridAccount(); - - wxPen GetColGridLinePen (int col); - wxPen GetRowGridLinePen (int row); - - virtual void ClearGrid(); - void LoadOperations(std::vector* operations, int month, int year); - void InsertOperationWithWeek(User* user, Operation& op, int line, bool fix, int month, int year) ; - void InsertOperation(User* user, Operation& op, int line, bool fix, int month, int year) ; - - void GetSelectedOperations(std::vector* rows); - - void MassUpdate(std::vector& rows, updateOperationFunc func, void** params); - - void Group(); - void UnGroup(); - - void OnCellLeftClick(wxGridEvent& evt); - void OnOperationModified(wxGridEvent& event); - - int _fixCosts; - int _week1, _week2, _week3, _week4; - std::vector _displayedOperations; - -private: - wxWindow* _parent; - KissCount* _kiss; - bool _displayLines; - bool _canAddOperation, _setWeek; - bool _databaseSynchronization; - wxString* _categories, *_accounts; - std::vector* _operations; - bool _loadOperations; - int _curMonth, _curYear; - - void SetWeek(int week, int line); - void ResetWeeks(); - void ComputeWeeks(); - - void InsertIntoGrid(Operation& op); - void DeleteOperation(const Operation& op); - void UpdateMeta(Operation& op); - int RemoveMeta(Operation op, int line, bool removeRoot, bool deleteOp); - void CheckMeta(Operation& op, int line, bool check); - - Operation& GetOperation(const wxString& id) throw(OperationNotFound); - void UpdateOperation(Operation& op); - int GetDisplayedRow(const wxString& id); - - DECLARE_EVENT_TABLE(); -}; -#endif diff --git a/src/view/grid/wxGridCellBitmapRenderer.cpp b/src/view/grid/wxGridCellBitmapRenderer.cpp deleted file mode 100644 index b1bf2be..0000000 --- a/src/view/grid/wxGridCellBitmapRenderer.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellBitmapRenderer.hpp" - -wxGridCellBitmapRenderer::wxGridCellBitmapRenderer(wxBitmap& bitmap) : _bitmap(bitmap) -{ - -} - -wxGridCellRenderer* wxGridCellBitmapRenderer::Clone () const -{ - wxBitmap bitmap(_bitmap); - return new wxGridCellBitmapRenderer(bitmap); -} - -void wxGridCellBitmapRenderer::Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected) -{ - dc.SetBrush(wxBrush(grid.GetCellBackgroundColour(row, col))); - dc.DrawRectangle(rect); - dc.DrawBitmap (_bitmap, rect.x + (rect.width-_bitmap.GetWidth())/2, rect.y + (rect.height-_bitmap.GetHeight())/2, true); -} - -wxSize wxGridCellBitmapRenderer::GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col) -{ - return wxSize(_bitmap.GetWidth(), _bitmap.GetHeight()); -} diff --git a/src/view/grid/wxGridCellBitmapRenderer.hpp b/src/view/grid/wxGridCellBitmapRenderer.hpp deleted file mode 100644 index 782c9ce..0000000 --- a/src/view/grid/wxGridCellBitmapRenderer.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLBITMAPRENDERER_H -#define WXGRIDCELLBITMAPRENDERER_H - -#include -#include -#include - -class wxGridCellBitmapRenderer : public wxGridCellRenderer -{ -public: - wxGridCellBitmapRenderer(wxBitmap& bitmap); - - virtual wxGridCellRenderer* Clone () const; - virtual void Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected); - virtual wxSize GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col); - -private: - wxBitmap _bitmap; -}; - -#endif diff --git a/src/view/grid/wxGridCellButtonEditor.cpp b/src/view/grid/wxGridCellButtonEditor.cpp deleted file mode 100644 index 7e1f290..0000000 --- a/src/view/grid/wxGridCellButtonEditor.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellButtonEditor.hpp" - -enum {BUTTON_ID = 1} ; - -// BEGIN_EVENT_TABLE(wxGridCellButtonEditor, wxEvtHandler) -// EVT_BUTTON(BUTTON_ID, wxGridCellButtonEditor::OnButton) -// END_EVENT_TABLE() - -wxGridCellButtonEditor::wxGridCellButtonEditor(const wxString& text) : _text(text), _button(0) -{} - -wxGridCellButtonEditor::~wxGridCellButtonEditor() -{ - if (_button) delete _button; -} - -wxGridCellEditor* wxGridCellButtonEditor::Clone () const -{ - return new wxGridCellButtonEditor(_text); -} - -void wxGridCellButtonEditor::BeginEdit (int row, int col, wxGrid *grid) -{ - _row = row; - _col = col; - _grid = grid; - - if (_grid) - { - wxGridEvent event (_grid->GetId(), wxEVT_GRID_CELL_CHANGE, this, _row, _col); - _grid->GetEventHandler()->AddPendingEvent(event); - } -} - -void wxGridCellButtonEditor::Create (wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler) -{ - if (_button) return; - _button = new wxButton(parent, id, _text); - _button->Connect(id, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxGridCellButtonEditor::OnButton), 0, this); -} - -bool wxGridCellButtonEditor::EndEdit (int row, int col, /*const*/ wxGrid *grid/*, const wxString &oldval, wxString *newval*/) -{ - return false; -} - -void wxGridCellButtonEditor::ApplyEdit (int row, int col, wxGrid *grid) -{} - -void wxGridCellButtonEditor::Reset () -{} - -wxString wxGridCellButtonEditor::GetValue() const -{ - return wxT(""); -} - -void wxGridCellButtonEditor::SetSize (const wxRect &rect) -{ - if (_button) _button->SetSize(rect); -} - -void wxGridCellButtonEditor::Show (bool show, wxGridCellAttr *attr=0) -{ - if (_button) _button->Show(show); -} - -void wxGridCellButtonEditor::OnButton(wxCommandEvent& evt) -{ - if (_grid) - { - wxGridEvent event (_grid->GetId(), wxEVT_GRID_CELL_CHANGE, this, _row, _col); - _grid->GetEventHandler()->AddPendingEvent(event); - } -} diff --git a/src/view/grid/wxGridCellButtonEditor.hpp b/src/view/grid/wxGridCellButtonEditor.hpp deleted file mode 100644 index 21c6b6b..0000000 --- a/src/view/grid/wxGridCellButtonEditor.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLBUTTONEDITOR_H -#define WXGRIDCELLBUTTONEDITOR_H - -#include -#include -#include - -class wxGridCellButtonEditor : public wxGridCellEditor, public wxEvtHandler -{ -public: - wxGridCellButtonEditor(const wxString& text); - ~wxGridCellButtonEditor(); - - wxGridCellEditor* Clone () const; - - void BeginEdit (int row, int col, wxGrid *grid); - void Create (wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler); - bool EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/); - void ApplyEdit (int row, int col, wxGrid *grid); - void Reset () ; - wxString GetValue() const ; - void SetSize (const wxRect &rect); - void Show (bool show, wxGridCellAttr *attr); - - void OnButton(wxCommandEvent& event); -private: - wxString _text; - wxButton* _button; - int _row, _col; - wxGrid* _grid; - - /* DECLARE_EVENT_TABLE(); */ -}; - -#endif diff --git a/src/view/grid/wxGridCellButtonRenderer.cpp b/src/view/grid/wxGridCellButtonRenderer.cpp deleted file mode 100644 index 2f32f75..0000000 --- a/src/view/grid/wxGridCellButtonRenderer.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellButtonRenderer.hpp" - -wxGridCellButtonRenderer::wxGridCellButtonRenderer(const wxString& text) : _text(text) -{ - -} - -wxGridCellRenderer* wxGridCellButtonRenderer::Clone () const -{ - return new wxGridCellButtonRenderer(_text); -} - -void wxGridCellButtonRenderer::Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &_rect, int row, int col, bool isSelected) -{ - wxRect rect = _rect; - wxCoord w, h, descent, external_leading; - - wxBrush originalBrush = dc.GetBrush(); - wxPen originalPen = dc.GetPen(); - - dc.SetPen(wxPen(*wxLIGHT_GREY)); - dc.SetBrush(wxBrush(grid.GetCellBackgroundColour(row, col))); - dc.DrawRectangle(rect); - - rect.x += 2 ; - rect.y += 2 ; - rect.width -= 6 ; - rect.height -= 6 ; - - dc.SetPen(wxPen(*wxWHITE)); - dc.DrawLine(rect.x, rect.y, rect.x + rect.width, rect.y); - dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height); - - dc.SetPen(wxPen(*wxBLACK)); - dc.DrawLine(rect.x, rect.y + rect.height, rect.x + rect.width + 1, rect.y + rect.height); - dc.DrawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); - - dc.SetPen(wxPen(wxColor(0x80, 0x80, 0x80))); - dc.DrawLine(rect.x + 1, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1); - dc.DrawLine(rect.x + rect.width - 1, rect.y + 1, rect.x + rect.width - 1, rect.y + rect.height); - - rect.x += 1 ; - rect.y += 1 ; - rect.width -= 2 ; - rect.height -= 2 ; - - dc.SetPen(wxPen(*wxLIGHT_GREY)); - dc.SetBrush(wxBrush(*wxLIGHT_GREY)); - dc.DrawRectangle(rect); - - dc.GetTextExtent(_text, &w, &h, &descent, &external_leading); - - if (w < rect.width) - rect.x += (rect.width - w) / 2; - - if (h < rect.height) - rect.y += (rect.height - h) / 2; - - rect.y -= (external_leading + descent); - - dc.SetTextForeground(*wxBLACK); - // dc.SetTextBackground(wxColor(128, 128, 128, 255)); - dc.SetTextBackground(*wxLIGHT_GREY); - - dc.DrawText(_text, rect.x, rect.y); - - dc.SetBrush(originalBrush); - dc.SetPen(originalPen); -} - -wxSize wxGridCellButtonRenderer::GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col) -{ - wxCoord w, h; - - dc.GetTextExtent(_text, &w, &h); - return wxSize(w+14, h+14); // (2 + 2 + 3) * 2 -} diff --git a/src/view/grid/wxGridCellButtonRenderer.hpp b/src/view/grid/wxGridCellButtonRenderer.hpp deleted file mode 100644 index 4a41a23..0000000 --- a/src/view/grid/wxGridCellButtonRenderer.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLBUTTONRENDERER_H -#define WXGRIDCELLBUTTONRENDERER_H - -#include -#include - -class wxGridCellButtonRenderer : public wxGridCellRenderer -{ -public: - wxGridCellButtonRenderer(const wxString& text); - - virtual wxGridCellRenderer* Clone () const; - virtual void Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected); - virtual wxSize GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col); - -private: - wxString _text; -}; - -#endif diff --git a/src/view/grid/wxGridCellFastBoolEditor.hpp b/src/view/grid/wxGridCellFastBoolEditor.hpp deleted file mode 100644 index 4795eea..0000000 --- a/src/view/grid/wxGridCellFastBoolEditor.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef WXGRIDCELLFASTBOOLEDITOR_H -#define WXGRIDCELLFASTBOOLEDITOR_H - -#include -#include - -// From http://wiki.wxwidgets.org/WxGrid -class wxGridCellFastBoolEditor : public wxGridCellBoolEditor -{ -public: - - void BeginEdit (int row, int col, wxGrid* grid) - { - wxGridCellBoolEditor::BeginEdit(row, col, grid); - - wxFocusEvent event (wxEVT_KILL_FOCUS); - if (m_control) - { - m_control->GetEventHandler()->AddPendingEvent(event); - } - } -}; - -#endif diff --git a/src/view/grid/wxGridCellFormulaEditor.cpp b/src/view/grid/wxGridCellFormulaEditor.cpp deleted file mode 100644 index 6e144a3..0000000 --- a/src/view/grid/wxGridCellFormulaEditor.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellFormulaEditor.hpp" - -wxGridCellFormulaEditor::wxGridCellFormulaEditor(const wxString& formula) : _formula(formula) -{} - -void wxGridCellFormulaEditor::BeginEdit (int row, int col, wxGrid *grid) { - static bool inModification = false; - Operation op; - - if (inModification) return ; - - inModification = true; - - op = ((GridAccount*) grid)->_displayedOperations[row]; - - if (op.formula.Length()) - { - grid->SetCellValue(row, col, op.formula); - _formula = op.formula; - } - - wxGridCellTextEditor::BeginEdit(row, col, grid); - - inModification = false; -} - -bool wxGridCellFormulaEditor::EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/) -{ - wxString res = GetValue(); - Operation op; - char* str, *str2; - struct ParseExp::parse_opt opt, *r; - bool ret; - - res = res.Trim(); - res.Replace(wxT(","), wxT("."), true); - - if (res.StartsWith(wxT("="))) - { - str = (char*) std::string(res.mb_str()).c_str(); - str2 = new char[strlen(str)]; - strcpy(str2, str+1); - r = &opt; - str = str2; - try { - ParseExp::ParseExp(&str2, r, false); - } - catch(...) - { - wxMessageBox(_("Invalid formula !"), _("Error"), wxICON_ERROR | wxOK); - delete str; - return false; - } - - delete str; - _formula = res; - - ret = wxGridCellTextEditor::EndEdit(row, col, grid); - - grid->SetCellValue(row, col, wxString::Format(wxT("%.2lf"), ParseExp::EvaluateExpr(&opt, true))); - } - else - { - _formula = wxT(""); - ret = wxGridCellTextEditor::EndEdit(row, col, grid); - } - - return ret; -} - -wxString wxGridCellFormulaEditor::GetFormula() -{ - return _formula; -} diff --git a/src/view/grid/wxGridCellFormulaEditor.hpp b/src/view/grid/wxGridCellFormulaEditor.hpp deleted file mode 100644 index 28d7ad9..0000000 --- a/src/view/grid/wxGridCellFormulaEditor.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLFORMULAEDITOR_H -#define WXGRIDCELLFORMULAEDITOR_H - -#include -#include -#include -#include "GridAccount.hpp" -#include "../../ParseExp.hpp" -class wxGridCellFormulaEditor : public wxGridCellTextEditor -{ -public: - wxGridCellFormulaEditor(const wxString& formula); - /* ~wxGridCellFormulEeditor(); */ - - /* wxGridCellEditor* Clone () const; */ - - void BeginEdit (int row, int col, wxGrid *grid); - /* void Create (wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler); */ - bool EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/); - /* void ApplyEdit (int row, int col, wxGrid *grid); */ - /* void Reset () ; */ - /* wxString GetValue() const ; */ - /* void SetSize (const wxRect &rect); */ - /* void Show (bool show, wxGridCellAttr *attr); */ - - wxString GetFormula(); - -private: - wxString _formula; - wxButton* _button; - int _row, _col; - wxGrid* _grid; - - /* DECLARE_EVENT_TABLE(); */ -}; - -#endif diff --git a/src/view/grid/wxGridCellStarEditor.cpp b/src/view/grid/wxGridCellStarEditor.cpp deleted file mode 100644 index 61af891..0000000 --- a/src/view/grid/wxGridCellStarEditor.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellStarEditor.hpp" - -void wxGridCellStarEditor::BeginEdit (int row, int col, wxGrid *grid) { - static bool inModification = false; - wxString value; - - if (inModification) return ; - - inModification = true; - - value = grid->GetCellValue(row, col); - _has_star = (value[value.Length()-1] == '*'); - - if (_has_star) - grid->SetCellValue(row, col, value.RemoveLast()); - - wxGridCellTextEditor::BeginEdit(row, col, grid); - - inModification = false; -} - -bool wxGridCellStarEditor::EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/) -{ - wxString res = GetValue(); - bool ret; - - ret = wxGridCellTextEditor::EndEdit(row, col, grid); - - if (_has_star) - grid->SetCellValue(row, col, res + wxT("*")); - - return ret; -} - diff --git a/src/view/grid/wxGridCellStarEditor.hpp b/src/view/grid/wxGridCellStarEditor.hpp deleted file mode 100644 index 9709c4e..0000000 --- a/src/view/grid/wxGridCellStarEditor.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLSTAREDITOR_H -#define WXGRIDCELLSTAREDITOR_H - -#include -#include -#include - -class wxGridCellStarEditor : public wxGridCellTextEditor -{ -public: - void BeginEdit (int row, int col, wxGrid *grid); - bool EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/); - -private: - bool _has_star; -}; - -#endif diff --git a/src/view/grid/wxGridCellTabStringRenderer.cpp b/src/view/grid/wxGridCellTabStringRenderer.cpp deleted file mode 100644 index 44bbced..0000000 --- a/src/view/grid/wxGridCellTabStringRenderer.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellTabStringRenderer.hpp" - -void wxGridCellTabStringRenderer::Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected) -{ - wxString d; - wxGridTableBase * table ; - - if (!((GridAccount*) &grid)->_displayedOperations[row].parent.Length()) - { - wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected); - return; - } - - table = grid.GetTable(); - - d = table->GetValue(row, col).Trim(); - - table->SetValue(row, col, wxT(" ") + d); - wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected); - table->SetValue(row, col, d); -} diff --git a/src/view/grid/wxGridCellTabStringRenderer.hpp b/src/view/grid/wxGridCellTabStringRenderer.hpp deleted file mode 100644 index 7293d57..0000000 --- a/src/view/grid/wxGridCellTabStringRenderer.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLTABSTRINGRENDERER_H -#define WXGRIDCELLTABSTRINGRENDERER_H - -#include -#include -#include - -#include "GridAccount.hpp" - -class wxGridCellTabStringRenderer : public wxGridCellStringRenderer -{ -public: - virtual void Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected); -}; - -#endif diff --git a/src/view/grid/wxGridCellTreeButtonEditor.cpp b/src/view/grid/wxGridCellTreeButtonEditor.cpp deleted file mode 100644 index a371515..0000000 --- a/src/view/grid/wxGridCellTreeButtonEditor.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellTreeButtonEditor.hpp" - -wxGridCellEditor* wxGridCellTreeButtonEditor::Clone () const -{ - return new wxGridCellTreeButtonEditor(); -} - -void wxGridCellTreeButtonEditor::BeginEdit (int row, int col, wxGrid *grid) -{ - wxGridEvent evt(0, 0, 0, row, col); - - _row = row; - _col = col; - _grid = grid; - - wxGridCellRenderer* pRenderer = _grid->GetCellRenderer(_row, _col); - - ((GridAccount*)_grid)->OnCellLeftClick(evt); - - ((wxGridCellTreeButtonRenderer*) pRenderer)->Invert(); - - pRenderer->DecRef(); -} - - -void wxGridCellTreeButtonEditor::Create (wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler) -{ -} - -bool wxGridCellTreeButtonEditor::EndEdit (int row, int col, /*const*/ wxGrid *grid/*, const wxString &oldval, wxString *newval*/) -{ - return true; -} - -void wxGridCellTreeButtonEditor::ApplyEdit (int row, int col, wxGrid *grid) -{} - -void wxGridCellTreeButtonEditor::Reset () -{} - -wxString wxGridCellTreeButtonEditor::GetValue() const -{ - wxGridCellRenderer* pRenderer = _grid->GetCellRenderer(_row, _col); - wxString res = ((wxGridCellTreeButtonRenderer*) pRenderer)->IsCollapsed() ? wxT("1") : wxT("0"); - - pRenderer->DecRef(); - - return res; -} - -void wxGridCellTreeButtonEditor::SetSize (const wxRect &rect) -{ -} - -void wxGridCellTreeButtonEditor::Show (bool show, wxGridCellAttr *attr=0) -{ -} diff --git a/src/view/grid/wxGridCellTreeButtonEditor.hpp b/src/view/grid/wxGridCellTreeButtonEditor.hpp deleted file mode 100644 index 617852a..0000000 --- a/src/view/grid/wxGridCellTreeButtonEditor.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLTREEBUTTONEDITOR_H -#define WXGRIDCELLTREEBUTTONEDITOR_H - -#include -#include -#include - -#include "GridAccount.hpp" -#include "wxGridCellTreeButtonRenderer.hpp" - -class wxGridCellTreeButtonEditor : public wxGridCellEditor -{ -public: - - wxGridCellEditor* Clone () const; - - void BeginEdit (int row, int col, wxGrid *grid); - void Create (wxWindow *parent, wxWindowID id, wxEvtHandler *evtHandler); - bool EndEdit (int row, int col, wxGrid *grid/*, const wxString &oldval, wxString *newval*/); - void ApplyEdit (int row, int col, wxGrid *grid); - void Reset () ; - wxString GetValue() const ; - void SetSize (const wxRect &rect); - void Show (bool show, wxGridCellAttr *attr); - -private: - int _row, _col; - wxGrid* _grid; -}; - -#endif diff --git a/src/view/grid/wxGridCellTreeButtonRenderer.cpp b/src/view/grid/wxGridCellTreeButtonRenderer.cpp deleted file mode 100644 index 7ac783b..0000000 --- a/src/view/grid/wxGridCellTreeButtonRenderer.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#include "wxGridCellTreeButtonRenderer.hpp" - -wxGridCellTreeButtonRenderer::wxGridCellTreeButtonRenderer(bool collapsed) : _collapsed(collapsed) -{ - -} - -wxGridCellRenderer* wxGridCellTreeButtonRenderer::Clone () const -{ - return new wxGridCellTreeButtonRenderer(_collapsed); -} - -bool wxGridCellTreeButtonRenderer::IsCollapsed() -{ - return _collapsed; -} - -void wxGridCellTreeButtonRenderer::Invert() -{ - _collapsed = !_collapsed; -} - -void wxGridCellTreeButtonRenderer::Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &_rect, int row, int col, bool isSelected) -{ - wxRect rect = _rect; - - wxBrush originalBrush = dc.GetBrush(); - wxPen originalPen = dc.GetPen(); - - dc.SetPen(wxPen(grid.GetCellBackgroundColour(row, col))); - dc.SetBrush(wxBrush(grid.GetCellBackgroundColour(row, col))); - dc.DrawRectangle(rect); - - rect.x += 4 ; - rect.y += 4 ; - rect.width -= 8 ; - rect.height -= 8 ; - - if (rect.width > rect.height) - rect.width = rect.height; - else if (rect.height > rect.width) - rect.height = rect.width; - - dc.SetPen(wxPen(*wxBLACK)); - - dc.DrawLine(rect.x, rect.y, rect.x + rect.width, rect.y); - dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height); - - dc.DrawLine(rect.x, rect.y + rect.height, rect.x + rect.width + 1, rect.y + rect.height); - dc.DrawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); - - rect.x += 2 ; - rect.y += 2 ; - rect.width -= 4 ; - rect.height -= 4 ; - - dc.DrawLine(rect.x+1, rect.y + rect.height/2, rect.x + rect.width + 1, rect.y + rect.height/2); - - if (!_collapsed) - dc.DrawLine(rect.x + rect.width/2 + 1, rect.y, rect.x + rect.width/2 + 1, rect.y + rect.height); -} - -wxSize wxGridCellTreeButtonRenderer::GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col) -{ - return wxSize(8, 8); -} diff --git a/src/view/grid/wxGridCellTreeButtonRenderer.hpp b/src/view/grid/wxGridCellTreeButtonRenderer.hpp deleted file mode 100644 index 33c4f6a..0000000 --- a/src/view/grid/wxGridCellTreeButtonRenderer.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright 2010-2011 Grégory Soutadé - - This file is part of KissCount. - - KissCount is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - KissCount is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY 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 KissCount. If not, see . -*/ - -#ifndef WXGRIDCELLTREEBUTTONRENDERER_H -#define WXGRIDCELLTREEBUTTONRENDERER_H - -#include -#include - -class wxGridCellTreeButtonRenderer : public wxGridCellRenderer -{ -public: - wxGridCellTreeButtonRenderer(bool collapsed=false); - - virtual wxGridCellRenderer* Clone () const; - virtual void Draw (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected); - virtual wxSize GetBestSize (wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col); - - bool IsCollapsed(); - void Invert(); -private: - bool _collapsed; -}; - -#endif diff --git a/src/view/grid/wxMyGrid.cpp b/src/view/grid/wxMyGrid.cpp deleted file mode 100644 index 30150fc..0000000 --- a/src/view/grid/wxMyGrid.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include "wxMyGrid.hpp" - -BEGIN_EVENT_TABLE(wxMyGrid, wxGrid) -EVT_GRID_CELL_LEFT_CLICK(wxMyGrid::OnCellLeftClick ) -END_EVENT_TABLE() - -wxMyGrid::wxMyGrid(wxWindow* parent, int id, int* clicks, int size) : wxGrid(parent, id) -{ - for(int i=0; i::iterator it; - - for(it = _clicks.begin(); it != _clicks.end(); it++) - { - if (*it == evt.GetCol()) - { - // This forces the cell to go into edit mode directly - //m_waitForSlowClick = TRUE; - SetGridCursor(evt.GetRow(), evt.GetCol()); - // Store the click co-ordinates in the editor if possible - // if an editor has created a ClientData area, we presume it's - // a wxPoint and we store the click co-ordinates - wxGridCellEditor* pEditor = GetCellEditor(evt.GetRow(), evt.GetCol()); - wxPoint* pClickPoint = (wxPoint*)pEditor->GetClientData(); - if (pClickPoint) - { - *pClickPoint = ClientToScreen(evt.GetPosition()); -#ifndef __WINDOWS__ - EnableCellEditControl(true); -#endif - } - // hack to prevent selection from being lost when click combobox - if (evt.GetCol() == 0 && IsInSelection(evt.GetRow(), evt.GetCol())) - { - //m_selTemp = m_selection; - m_selection = 0; - } - pEditor->DecRef(); - break; - } - } - evt.Skip(); -} diff --git a/src/view/grid/wxMyGrid.hpp b/src/view/grid/wxMyGrid.hpp deleted file mode 100644 index d5a3432..0000000 --- a/src/view/grid/wxMyGrid.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef WXMYGRID_H -#define WXMYGRID_H - -#include -#include -#include - -// From http://wiki.wxwidgets.org/WxGrid -class wxMyGrid : public wxGrid -{ -public: - wxMyGrid(wxWindow* parent, int id, int* clicks, int size); - - void OnCellLeftClick(wxGridEvent& ev); - -private: - std::vector _clicks; - - DECLARE_EVENT_TABLE(); -}; - -#endif diff --git a/src/view/view.hpp b/src/view/view.hpp index b40054d..a9756d7 100644 --- a/src/view/view.hpp +++ b/src/view/view.hpp @@ -20,16 +20,14 @@ #ifndef VIEW_H #define VIEW_H -#include - namespace view { - const wxColour OWN_CYAN(0x99, 0xCC, 0xFF); - const wxColour OWN_YELLOW(0xFF, 0xFF, 0x99); - const wxColour OWN_GREEN(0x3D, 0xEB, 0x3D); - const wxString DEFAULT_FONT_NAME(wxT("Liberation Sans")); + const QColor OWN_CYAN(0x99, 0xCC, 0xFF); + const QColor OWN_YELLOW(0xFF, 0xFF, 0x99); + const QColor OWN_GREEN(0x3D, 0xEB, 0x3D); + const std::string DEFAULT_FONT_NAME("Liberation Sans"); const int DEFAULT_FONT_SIZE = 12; -#define DEFAULT_FONT(font_name) wxFont font_name(view::DEFAULT_FONT_SIZE, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, view::DEFAULT_FONT_NAME); +#define DEFAULT_FONT(font_name) QFont font_name(view::DEFAULT_FONT_NAME, view::DEFAULT_FONT_SIZE); }; #define DELETE_ICON RESSOURCES_ROOT "icons/process-stop.png" diff --git a/src/view/wxUI.cpp b/src/view/wxUI.cpp index a8daa2d..1957bff 100644 --- a/src/view/wxUI.cpp +++ b/src/view/wxUI.cpp @@ -17,7 +17,7 @@ along with KissCount. If not, see . */ -#include "AccountPanel.hpp" +/*#include "AccountPanel.hpp" #include "PreferencesPanel.hpp" #include "UsersDialog.hpp" #include "GenerateDialog.hpp" @@ -30,121 +30,115 @@ #include "grid/wxGridCellFastBoolEditor.hpp" #include "grid/wxGridCellButtonRenderer.hpp" #include "grid/wxGridCellButtonEditor.hpp" - +*/ #include "wxUI.hpp" enum {BUTTON_CHANGE_USER_ID=-4, BUTTON_ABOUT_ID=-5, BUTTON_QUIT_ID=-6}; -BEGIN_EVENT_TABLE(wxUI, wxFrame) -EVT_BUTTON(BUTTON_CHANGE_USER_ID, wxUI::OnButtonChangeUser) -EVT_BUTTON(BUTTON_ABOUT_ID, wxUI::OnButtonAbout) -EVT_BUTTON(BUTTON_QUIT_ID, wxUI::OnButtonQuit) -END_EVENT_TABLE() +std::string wxUI::months[12] ; +QColor wxUI::categoryColors[MAX_CATEGORY] = {QColor(0x00, 0x45, 0x86), + QColor(0xFF, 0x3E, 0x0E), + QColor(0xFF, 0xD3, 0x20), + QColor(0x58, 0x9D, 0x1B), + QColor(0x7E, 0x00, 0x21), + QColor(0x83, 0xCC, 0xFF), + QColor(0x31, 0x40, 0x04), + QColor(0xB0, 0xCF, 0x00), + QColor(0x4B, 0x1F, 0x6F), + QColor(0xFF, 0x93, 0x0E), + QColor(0xC5, 0x00, 0x0D), + QColor(0x00, 0x84, 0xD1)}; -wxString wxUI::months[12] ; -wxColour wxUI::categoryColors[MAX_CATEGORY] = {wxColour(0x00, 0x45, 0x86), - wxColour(0xFF, 0x3E, 0x0E), - wxColour(0xFF, 0xD3, 0x20), - wxColour(0x58, 0x9D, 0x1B), - wxColour(0x7E, 0x00, 0x21), - wxColour(0x83, 0xCC, 0xFF), - wxColour(0x31, 0x40, 0x04), - wxColour(0xB0, 0xCF, 0x00), - wxColour(0x4B, 0x1F, 0x6F), - wxColour(0xFF, 0x93, 0x0E), - wxColour(0xC5, 0x00, 0x0D), - wxColour(0x00, 0x84, 0xD1)}; - -wxUI::wxUI(KissCount* kiss, const wxString& title, const wxPoint& pos, const wxSize& size) - : wxFrame(0, -1, title, pos, size), _kiss(kiss), +wxUI::wxUI(KissCount* kiss, const QString& title) + : QFrame(0), _kiss(kiss), _curPanel(0), _locale(0), _needReload(false) { - wxInitAllImageHandlers(); + setWindowTitle(title); - _vbox = new wxBoxSizer(wxVERTICAL); - _buttonsBox = new wxBoxSizer(wxHORIZONTAL); - // ButtonPanel* buttons = new ButtonPanel(_kiss, this); - // wxMenu *menuFile = new wxMenu; + // _vbox = new wxBoxSizer(wxVERTICAL); + // _buttonsBox = new wxBoxSizer(wxHORIZONTAL); + // // ButtonPanel* buttons = new ButtonPanel(_kiss, this); + // // wxMenu *menuFile = new wxMenu; - // menuFile->Append( ID_About, wxT("&About...") ); - // menuFile->AppendSeparator(); - // menuFile->Append( ID_Quit, wxT("E&xit") ); + // // menuFile->Append( ID_About, wxT("&About...") ); + // // menuFile->AppendSeparator(); + // // menuFile->Append( ID_Quit, wxT("E&xit") ); - // wxMenuBar *menuBar = new wxMenuBar; - // menuBar->Append( menuFile, wxT("&File") ); + // // wxMenuBar *menuBar = new wxMenuBar; + // // menuBar->Append( menuFile, wxT("&File") ); - // SetMenuBar( menuBar ); + // // SetMenuBar( menuBar ); - // CreateStatusBar(); - // SetStatusText( wxT("Welcome to wxWidgets!") ); - _buttonsBox->Add(new wxBitmapButton(this, BUTTON_CHANGE_USER_ID, wxBitmap(wxT(CHANGE_USER_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); - _buttonsBox->Add(new wxBitmapButton(this, BUTTON_ABOUT_ID, wxBitmap(wxT(ABOUT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); - _buttonsBox->Add(new wxBitmapButton(this, BUTTON_QUIT_ID, wxBitmap(wxT(QUIT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); + // // CreateStatusBar(); + // // SetStatusText( wxT("Welcome to wxWidgets!") ); + // _buttonsBox->Add(new wxBitmapButton(this, BUTTON_CHANGE_USER_ID, wxBitmap(wxT(CHANGE_USER_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); + // _buttonsBox->Add(new wxBitmapButton(this, BUTTON_ABOUT_ID, wxBitmap(wxT(ABOUT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); + // _buttonsBox->Add(new wxBitmapButton(this, BUTTON_QUIT_ID, wxBitmap(wxT(QUIT_ICON), wxBITMAP_TYPE_PNG), wxDefaultPosition, wxSize(128, 128))); - SetSizer(_vbox); + // SetSizer(_vbox); - _vbox->Add(_buttonsBox, 0, wxGROW); + // _vbox->Add(_buttonsBox, 0, wxGROW); } wxUI::~wxUI() { int i; - for (i=0; i<(int)_panels.size(); i++) - Disconnect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), _panels[i], this); + // for (i=0; i<(int)_panels.size(); i++) + // Disconnect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), _panels[i], this); if (_locale) delete _locale; } -bool wxUI::SetLanguage(long language) +bool wxUI::SetLanguage(std::string language) { bool res = true; - if (_locale) delete _locale; - _locale = 0; +// if (_locale) delete _locale; +// _locale = 0; - // load language if possible, fall back to english otherwise - if(wxLocale::IsAvailable(language)) - { - _locale = new wxLocale( language, wxLOCALE_CONV_ENCODING ); +// // load language if possible, fall back to english otherwise +// if(wxLocale::IsAvailable(language)) +// { +// _locale = new wxLocale( language, wxLOCALE_CONV_ENCODING ); -#ifdef __WXGTK__ - _locale->AddCatalogLookupPathPrefix(wxT(LANG_ROOT)); -#endif +// #ifdef __WXGTK__ +// _locale->AddCatalogLookupPathPrefix(wxT(LANG_ROOT)); +// #endif - _locale->AddCatalog(wxT("frenchpp")); - _locale->AddCatalog(wxT("kisscount")); +// _locale->AddCatalog(wxT("frenchpp")); +// _locale->AddCatalog(wxT("kisscount")); - _language = (wxLanguage) language; - } +// _language = (wxLanguage) language; +// } - if (_locale == 0 || !_locale->IsOk()) - { - if (_locale) delete _locale; - _locale = new wxLocale(); +// if (_locale == 0 || !_locale->IsOk()) +// { +// if (_locale) delete _locale; +// _locale = new wxLocale(); -#ifdef __WXGTK__ - _locale->AddCatalogLookupPathPrefix(wxT(LANG_ROOT)); -#endif +// #ifdef __WXGTK__ +// _locale->AddCatalogLookupPathPrefix(wxT(LANG_ROOT)); +// #endif - _locale->AddCatalog(wxT("kisscount")); +// _locale->AddCatalog(wxT("kisscount")); - _language = wxLANGUAGE_ENGLISH; - res = false; - } +// _language = wxLANGUAGE_ENGLISH; +// res = false; +// } - months[0] = _("january"); - months[1] = _("february"); - months[2] = _("marchpp"); - months[3] = _("april"); - months[4] = _("may"); - months[5] = _("june"); - months[6] = _("july"); - months[7] = _("august"); - months[8] = _("september"); - months[9] = _("october"); - months[10] = _("november"); - months[11] = _("december") ; +// months[0] = _("january"); +// months[1] = _("february"); +// months[2] = _("marchpp"); +// months[3] = _("april"); +// months[4] = _("may"); +// months[5] = _("june"); +// months[6] = _("july"); +// months[7] = _("august"); +// months[8] = _("september"); +// months[9] = _("october"); +// months[10] = _("november"); +// months[11] = _("december") ; return res; } @@ -160,50 +154,50 @@ bool wxUI::SetLanguage(long language) void wxUI::InitPanels() { - KissPanel* panel; - wxBitmapButton* button; - _panels.clear(); + // KissPanel* panel; + // wxBitmapButton* button; + // _panels.clear(); - ADD_PANEL(AccountPanel, 0); - ADD_PANEL(StatsPanel, 1); - ADD_PANEL(SearchPanel, 2); - ADD_PANEL(PreferencesPanel, 3); - ADD_PANEL(ImportPanel, 4); - ADD_PANEL(ExportPanel, 5); + // ADD_PANEL(AccountPanel, 0); + // ADD_PANEL(StatsPanel, 1); + // ADD_PANEL(SearchPanel, 2); + // ADD_PANEL(PreferencesPanel, 3); + // ADD_PANEL(ImportPanel, 4); + // ADD_PANEL(ExportPanel, 5); } void wxUI::LoadPanels() { - std::vector::iterator it; - KissPanel* temp; - int i; + // std::vector::iterator it; + // KissPanel* temp; + // int i; - if (_curPanel) - { - _vbox->Detach(_curPanel); - _curPanel = 0; - } + // if (_curPanel) + // { + // _vbox->Detach(_curPanel); + // _curPanel = 0; + // } - if (_panels.size()) - { - for (i=0; i<(int)_panels.size(); i++) - { - temp = _panels[i]->CreatePanel(); - Disconnect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), _panels[i], this); - _panels[i] = temp; - Connect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), temp, this); - _buttons[i]->SetToolTip(temp->GetToolTip()); - } - } - else - InitPanels(); + // if (_panels.size()) + // { + // for (i=0; i<(int)_panels.size(); i++) + // { + // temp = _panels[i]->CreatePanel(); + // Disconnect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), _panels[i], this); + // _panels[i] = temp; + // Connect(i, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(wxUI::OnButtonClicked), temp, this); + // _buttons[i]->SetToolTip(temp->GetToolTip()); + // } + // } + // else + // InitPanels(); } void wxUI::LoadUser() { User* user = _kiss->GetUser(); - if (user->_preferences[wxT("language")] != wxT("")) + if (user->_preferences["language"].size()) SetLanguage(user->GetLanguage()); LoadPanels(); @@ -214,92 +208,92 @@ void wxUI::LoadUser() void wxUI::ShowPanel(KissPanel* panel) { - wxShowEvent event; - int i; - User* user = _kiss->GetUser(); + // wxShowEvent event; + // int i; + // User* user = _kiss->GetUser(); - if (!panel) return; + // if (!panel) return; - if (_curPanel) - { - _vbox->Detach(_curPanel); - _curPanel->Hide(); - } + // if (_curPanel) + // { + // _vbox->Detach(_curPanel); + // _curPanel->Hide(); + // } - if (_needReload) - { - user->InvalidateOperations(); - for(i=0; i<(int)_panels.size(); i++) - if (_panels[i] == panel) break; - LoadPanels(); - _needReload = false; - _curPanel = _panels[i]; - } - else - _curPanel = panel; + // if (_needReload) + // { + // user->InvalidateOperations(); + // for(i=0; i<(int)_panels.size(); i++) + // if (_panels[i] == panel) break; + // LoadPanels(); + // _needReload = false; + // _curPanel = _panels[i]; + // } + // else + // _curPanel = panel; - _curPanel->OnShow(event); - _vbox->Add(_curPanel); - _curPanel->Show(); - Layout(); + // _curPanel->OnShow(event); + // _vbox->Add(_curPanel); + // _curPanel->Show(); + // Layout(); } -void wxUI::OnButtonClicked(wxCommandEvent& event) +void wxUI::OnButtonClicked(QEvent& event) { - ShowPanel(_panels[event.GetId()]); + // ShowPanel(_panels[event.GetId()]); } -void wxUI::OnButtonChangeUser(wxCommandEvent& event) +void wxUI::OnButtonChangeUser(QEvent& event) { ChangeUser(); } void wxUI::ChangeUser() { - UsersDialog u(_kiss, this); + // UsersDialog u(_kiss, this); } -void wxUI::OnButtonAbout(wxCommandEvent& event) +void wxUI::OnButtonAbout(QEvent& event) { - wxMessageBox( _("Personal accounting software\n\nhttp://indefero.soutade.fr/p/kisscount/\n\nLicenced under GNU GPL v3\n\nCopyright (C) 2010-2011 Grégory Soutadé"), - wxT("KissCount " APP_VERSION "\n\n"), - wxOK | wxICON_INFORMATION, this ); + // wxMessageBox( _("Personal accounting software\n\nhttp://indefero.soutade.fr/p/kisscount/\n\nLicenced under GNU GPL v3\n\nCopyright (C) 2010-2011 Grégory Soutadé"), + // wxT("KissCount " APP_VERSION "\n\n"), + // wxOK | wxICON_INFORMATION, this ); } -void wxUI::OnButtonQuit(wxCommandEvent& event) +void wxUI::OnButtonQuit(QEvent& event) { - wxMessageDialog dialog(this, _("Quit KissCount ?"), wxT("KissCount"), wxYES_NO); - if (dialog.ShowModal() == wxID_NO) - { - return; - } + // wxMessageDialog dialog(this, _("Quit KissCount ?"), wxT("KissCount"), wxYES_NO); + // if (dialog.ShowModal() == wxID_NO) + // { + // return; + // } - Close(true); + // Close(true); } void wxUI::GenerateMonth(int month, int year) { - ((AccountPanel*)_panels[0])->GenerateMonth(month, year); + // ((AccountPanel*)_panels[0])->GenerateMonth(month, year); } void wxUI::KillMe() { - std::vector::iterator it; + // std::vector::iterator it; - if (_curPanel) - { - _vbox->Detach(_curPanel); - _curPanel = 0; - } + // if (_curPanel) + // { + // _vbox->Detach(_curPanel); + // _curPanel = 0; + // } - for (it=_panels.begin(); it!= _panels.end(); it++) - { - if (*it) delete *it; - _buttonsBox->Remove(0); - _buttons.erase(_buttons.begin()); - } + // for (it=_panels.begin(); it!= _panels.end(); it++) + // { + // if (*it) delete *it; + // _buttonsBox->Remove(0); + // _buttons.erase(_buttons.begin()); + // } - _panels.clear(); + // _panels.clear(); } void wxUI::NeedReload() diff --git a/src/view/wxUI.hpp b/src/view/wxUI.hpp index 9b934c6..5ed9a9d 100644 --- a/src/view/wxUI.hpp +++ b/src/view/wxUI.hpp @@ -22,32 +22,35 @@ class ImportEngine; -#include +#include +#include +#include +#include +#include + #include -#include "KissPanel.hpp" +#include +#include -#ifdef WIN32 -#undef _ -#define _(s) wxString(wxGetTranslation(s)) -#endif +#define _(s) QObject::tr(s) class KissCount; class KissPanel; class AccountPanel; class PreferencesPanel; -class wxUI: public wxFrame +class wxUI: public QFrame { public: static const int MAX_CATEGORY = 12; - static wxString months[MAX_CATEGORY]; - static wxColour categoryColors[MAX_CATEGORY]; + static std::string months[MAX_CATEGORY]; + static QColor categoryColors[MAX_CATEGORY]; - wxUI(KissCount* kiss, const wxString& title, const wxPoint& pos, const wxSize& size); + wxUI(KissCount* kiss, const QString& title); ~wxUI(); - bool SetLanguage(long language); + bool SetLanguage(std::string language); void ChangeUser(); void LoadUser(); @@ -62,26 +65,45 @@ public: void ShowPanel(KissPanel* panel); void NeedReload(); - wxLanguage _language; + int _language; - void OnButtonClicked(wxCommandEvent& event); - void OnButtonChangeUser(wxCommandEvent& event); - void OnButtonAbout(wxCommandEvent& event); - void OnButtonQuit(wxCommandEvent& event); + void OnButtonClicked(QEvent& event); + void OnButtonChangeUser(QEvent& event); + void OnButtonAbout(QEvent& event); + void OnButtonQuit(QEvent& event); private: KissCount *_kiss; - wxBoxSizer *_vbox, *_buttonsBox; + QVBoxLayout *_vbox, *_buttonsBox; KissPanel *_curPanel; std::vector _panels; - std::vector _buttons; - wxLocale *_locale; + std::vector _buttons; + QLocale *_locale; bool _needReload; void InitPanels(); void LoadPanels(); +}; - DECLARE_EVENT_TABLE(); +class KissPanel: public QScrollArea +{ +public: + KissPanel(KissCount* kiss, wxUI* parent) : + QScrollArea(static_cast(parent)), + _kiss(kiss), + _wxUI(parent), + _KissButton(0) + {hide();} + + virtual void OnShow(QShowEvent * event)=0; + virtual KissPanel* CreatePanel()=0; + virtual QPushButton* GetButton(int id) {return 0;} + virtual std::string GetToolTip() {return "";} + +protected: + KissCount* _kiss; + wxUI* _wxUI; + QPushButton* _KissButton; }; #endif